Swapping 2 columns with Emacs - emacs

I have 2 columns, separated by comma. How can I swap those columns with Emacs?
I have the following:
column 1,column2
x1,x2
y1,y2
f1,f2
and I want it like this:
column2,column 1
x2,x1
y2,y1
f2,f1

Use M-x query-replace-regexp and then:
\(.+\),\(.+\)
as replace regexp and
\2,\1
for replacement.
In Emacs, you need to escape grouping parentheses with \. So, above regexp would be usually written as
(.+),(.+)
which means that you want everything before comma in first group and everything after comma in second group.
\2,\1
means: write second group, then comma, then first group.

While you can apply techniques given by other people, you can also use the org-mode tables.
Once you convert the data into org-mode table, it is very easy to swap the columns by simple keystrokes. You can have M-x org-mode, select the region then do M-x org-table-convert-region, and then M- on the right most column. I am not sure, how to export the data as CSV, but that should be very easy for you with replace-regexp. This can be helpful: http://www.gnu.org/software/emacs/manual/html_node/org/Tables.html#Tables

Similar to the answer given by #darioo, type the following into the top of your buffer:
(query-replace-regexp "\\(.*?\\),\\(.*\\)" "\\2,\\1")
Then, put your cursor at the end of this line and press ctrl-x, ctrl-e.
You will have an interactive search-and-replace for which you press the space bar to make the change, and press ctrl-g to quit. If you press ! (exclamation mark) then the search will cease being interactive and take place on all matching text.
If you want to reverse the changes then press M-x (usually ESC followed by x) and type undo and press enter.

Emacs has a rectangular selection mode, see for example: http://emacs-fu.blogspot.com/2008/12/working-with-rectangular-selections.html
Even better, if you enable cua-mode, entering Ctrl-Enter will put you in rectangle selection mode that is very easy to use.
http://trey-jackson.blogspot.com/2008/10/emacs-tip-26-cua-mode-specifically.html

Use a macro !
Go to the first line of the buffer
Start recording a macro (F3)
Move to the beginning of the line (^a)
Search for comma (^s ,)
Transpose (M-t)
Move cursor down one line
Stop recording macro (F4)
Select the rest of the lines and:
M-x apply-macro-to-region-lines
UPDATE: This doesn't work properly if you have multiple words in a column. Looking for a more general solution...

Related

How to put cursor on every other line (on alternate lines)

How can I put cursor on every other line (on alternate lines).
For example, I want to put cursor on line 1,3,5,7....
How can I do that?
I know I can do that by AltClick. But there are too many lines and an easier way will be very helpful.
You can do this with a regex:
Find: ^(.*\n){1}.*$
With focus on the find input, hit Alt+Enter. It will select all those matches - every two lines. Or if focus is in the editor, hit Ctrl+Shift+L - it'll do the same thing.
Home to put cursor at beginning of those selections. (If you have spaces or tabs at the beginning of a line, just hit Home until you are at the beginning.)
UpArrow or DownArrow to move those cursors where you want.
Obviously this scales pretty easily:
Find: ^(.*\n){2}.*$ for every third line, ^(.*\n){3}.*$ for every fourth line, etc.
You can use the extension Select By and use the command Place cursor based on line number, uses boolean expression (selectby.lineNr)
In the expression box of the command type
(n-1)%2==0
If you want to limit the number of cursors add an extra criterion
(n-1)%2==0 && n<100
If you place the cursor on line 1 you can use
c+2k
Read the extension page for other possibilities
You can set key binding for often use expressions.
Edit
Feature suggestion by #blueray
In v1.8.0 I have added inselection.
If you want to limit the cursors to the current selection(s) you can use the expression
c+2k && inselection

Retaining tab-to-tab-stop with Emacs replace-regexp

I have a very large text file with nearly 20 columns. Unfortunately the program which produced the file did not properly handle columns which began with a -10 (it only properly spaced data which had a total of 5 characters, not 6). Essentially I ended up with something that looks like this:
-10.072-10.179-10.2190.002
I want it to look like:
-10.072 -10.179 -10.219 0.002
and was almost able to do so with:
M-x replace-regexp RET -10\.... RET \&TAB RET
When I use TAB however, it only replaces with a space rather than tab- ideally a tab-to-tab-stop. If I manually go to one of these situations in the file and type TAB it properly does a tab-to-tab-stop to align the data with the proper column. How do I retain the tab-to-stop function within the replace-regexp?
The search and replace certainly ought to be inserting a tab. The apparent size of a tab can vary, of course, which is the only reason I can think of for it appearing to be a space. You could use whitespace-mode to make the difference more obvious.
As for tab-to-tab-stop, that's a dynamic function rather than a special kind of tab character, so you can't do that with a search and replace1. I would suggest using a keyboard macro instead, to get the same dynamic behaviour as manual typing.
F3
M-C-s -10.... RET
M-x tab-to-tab-stop RET
F4
or perhaps just: F3M-C-s -10.... RETTABF4
Then you can run the macro until it fails with C-0F4
(If you only want to run it on a portion of the buffer, you can simply narrow to the relevant region first.)
1 Not strictly true, as Emacs lets you evaluate arbitrary elisp as part of a replacement pattern; but it's not just a case of calling the tab-to-tab-stop function, so the macro is really much simpler.

How can I modify emacs' Search and Replace to perform a more complicated task?

total Emacs noob here. So right now I'm working on a fairly big LaTeX project in Emacs in which there are couple of places where I need to index some words, using the makeidx package. Because I also wanted indexed words to be bold, I created my own command \ind{} which would make the argument go bold and indexed. But right now I'm dissatisifed with this command so I'd like to change every instance of \ind{whatever} in my text by \textbf{whatever}\index{whatever by default}.
The thing is I know exactly what I want :
Go through the text, look for any instance of \ind{ and replace by \textbf{ using search-and-replace
Save the argument of \ind ("whatever" in this case) in memory
Ask me the user what should the argument of \index be. By default (by striking enter), it should be the first argument, but I can also change my mind and enter something different ("whatever by default" in this case). If there's no input (only a space " " for example) stop the program.
Write down \index{, the new argument and }.
Go to next occurance in the text.
But, alas!, I know not how to achieve this, so I need someone's help. If it should take too much time to explain how to do such a thing, would you please send me some tutorial about writing my own functions?
I hope I'm being clear, and thanks for your patience!
This approach seems vaguely unorthodox to me, but it works and seems sufficient for a one-off job...
In the replacement text for replace-regexp and query-replace-regexp (C-M-%), one newer escape sequence is \,(...), where ... can be any Lisp expression. There's a Lisp function read-from-minibuffer which reads arbitrary text typed by the user, with an optional default. Therefore:
C-M-%: Start query-replace-regexp.
\\ind{\([^}]+?\)}: The pattern to search for.
\\textbf{\1}\\index{\,(read-from-minibuffer "index content? " \1)}: The replacement text. The user will be prompted for the text to put in the braces following the \index{} element, using the original text between the braces following the \ind{} element as a default.
Note that when using query-replace-regexp, you'll have to confirm each choice by typing y after each. Use M-x replace-regexp if you want to avoid this step.
Vlad give you the LaTeX answer to your problem. An Emacs solution is the key-macro: start with
C-x (
to define a new macro, then do one step of your change, say:
C-s \ind{
<left>ex
Then copy and paste the argument in the \textbf macro... You have to be careful to move in a way that will be repeatable. Once the standard modification is done, you let the cursor after the whatever by default and end the definition by
C-x )
now C-x e will call the macro you just define, letting your cursor at the correct place to change the part you want to change You can also repeat the e to call the macro several time at once.
Why not just redefine the \ind so that it can get an optional argument?
For example:
\newcommand{\ind}[2][]{%
\def\first{#1}%
\ifx\first\empty
\textbf{#2}\index{#2}%
\else
\textbf{#2}\index{#1}%
\fi
}
This way you can use \ind{whatever} or \ind[whatever-else]{whatever}.

Emacs remember text selection

I decided that I was ready to try something new, after a few years of using gEdit for most of my coding needs, and try to learn using Emacs. I knew this would be difficult, as I have heard how complex Emacs can be, but I was lured by its power. The hardest thing has been getting used to writing ELisp in the .emacs file to change things about the editor. I can't currently do it myself, but I have found a few helpful snippets here and there to change some options.
One thing I have been having a lot of problems with is getting Emacs to remember the text I have selected after a command. For instance, I commonly highlight a section of code to mass indent it. However, if I do this in Emacs, it will move the selected text only once before unselecting all of the text. Does anyone know a way around this?
Anyway, I apologize for what seems to me to be an easy question, but after an hour of Google searching and looking around here on SO, I thought it was worth asking. I have a few more questions about Emacs, but I will save them and ask separately after I get this straightened out. Thanks!
UPDATE
A few people have asked about what mod I am using and what type of text I am entering. While I don't know much about Emacs modes, I am editing a pure text file at the moment. Something like this:
Hello, I am a simple text file
that is made up of three separate
lines.
If I highlight all three lines and hit TAB, I get this:
Hello, I am a simple text file
that is made up of three separate
lines.
This is great, however, if I use C-x C-x like some suggest below to reselect the text and hit TAB again, I get this:
Hello, I am a simple text file
that is made up of three separate
lines.
I hope this helps!
FWIW, here is the reason for the behaviour of your newly-added example. (I'm not 'solving' the issue here, but I'm posting it to demystify what you're seeing.)
This was determined with emacs -q which disables my customisations, so the following is default behaviour for emacs 23.2.
You are in text-mode. You should see (Text) or similar in the mode line at the bottom of the screen, and C-h m will tell you (under the list of minor modes) "Text mode: Major mode for editing text written for humans to read." Emacs decides (by way of the auto-mode-alist variable) that it should switch to text-mode if you visit a filename matching certain extensions (such as .txt).
In text-mode pressing TAB with a region highlighted causes indent-according-to-mode to be called on each line of the region in sequence. The slightly convoluted path to finding this out starts at C-h k TAB, which tells us that TAB is bound to indent-for-tab-command, which in this instance calls indent-region -- that function name is not stated explicitly in the help, but can be seen in the code -- which checks the buffer-local indent-region-function variable, which is nil, and: "A value of nil means really run indent-according-to-mode on each line."
indent-according-to-mode checks the indent-line-function variable, which has the buffer-local value indent-relative.
Use C-h f indent-relative RET to see the help for this function. (Read this).
Although you probably won't yet have had the experience to know how to check all that (or necessarily even want to!), and fully understand everything it tells you, this is an example of how the self-documenting aspect of Emacs enables a user to figure out what is going on (which then makes it feasible to change things). I essentially just used C-h k (describe-key), C-h f (describe-function), and C-h v (describe-variable) to follow the documentation. Looking at the source code for indent-for-tab-command was as simple as clicking the file name shown as part of its help page.
I suggest doing the following to help see what is happening when indent-relative runs on each line:
M-x set-variable x-stretch-cursor t
M-x set-variable ruler-mode-show-tab-stops t
M-x ruler-mode
Now for each line in turn, put the cursor at the very start of the line and press TAB. You'll end up with all three lines indented to the first tab-stop ('T' in the ruler).
Now repeat this -- again, ensure you are at the very start of each line, in front of the existing indentation.
The first character of the first line (which is currently a tab) is once again indented to the first tab-stop, as there is no preceding line for it to examine.
Next, the first character of the second line is indented to match the position of the first non-white-space character of the preceding line. Because the first character of the second line is also a tab, the actual text of the second line is pushed one tab further along.
The third line follows suit. Its first tab character is lined up with the first non-white-space character of the second line, with the same relative effect as before, giving you the final state in your example.
To emphasise, note what happens if you now put enter the line "a b c" above the existing lines, then move back to the start of the next line (what was previously the first line) and press TAB. The first tab character will now be indented in line with the 'b'. Provided that the indent-tabs-mode variable is true (meaning you have actual tab characters), then this will have no practical effect on the position of the words in the line, as 'indenting' a tab with spaces will not have an effect until the number of spaces exceeds the width of the tab (but that's another kettle of fish entirely!)
All this really means is that text-mode in Emacs doesn't behave the way you'd like it to in this situation. Other major modes can do completely different things when you press TAB, of course.
As is invariably the case with Emacs, things you don't like can be changed or circumvented with elisp. Some searching (especially at the Emacs Wiki) will frequently turn up useful solutions to problems you encounter.
Try typing C-x C-x after Emacs unselects it.
Then, instead of hitting tab (I never knew that tab does what you said! That's totally whacked.), do M-8 C-x C-i. Pity it's so many keys, but it ought to do what you want -- namely, shove everything over 8 columns. Obviously replace the M-8 with something else if you want some other number of columns.
What I usually do is simply type C-x C-x (exchange-point-and-mark) after a command that deactives the region.
How are you indenting, and in which mode?
The indentation rules in any programming mode should generally just get it right. (If they don't, that's probably more indicative that you want to configure the rules for that mode differently, but I suspect that's a different question which has been asked already).
If you're in text-mode or similar and just using TAB, then I can see the problem.
Note that if you're using indent-rigidly (C-x C-i, or C-x TAB which is the same thing) then you can repeatedly indent the same region simply by repeating the command, even if the highlighting has disappeared from view.
You can also use a prefix arg to indent-rigidly to make it indent many times. e.g. C-u C-u C-x C-i (easier to type than it looks) will indent 16 spaces (4 x 4, as the prefix arg defaults to 4, and it multiplies on each repeat). Similarly, M-8 C-x C-i indents 8 spaces. This is fine in some circumstances, and way too cumbersome in others.
Personally I suggest putting (cua-selection-mode 1) into your .emacs and using that for rigid indentation. Trey Jackson made a handy blog about it. With this, you can C-RET to start rectangle selection, down as many lines as you need, TAB repeatedly to indent the lines, and C-RET to exit the mode.
While the rectangle is active, RET cycles through the corners. For left-hand corners, typing inserts in front. For right-hand corners, typing inserts after. For the single-column rectangle, bottom counts as 'left' and top counts as 'right' for this purpose.
Trey's blog lists all the available features (or look in the source file: cua-base.el)
Be warned that indentation in Emacs is generally an unexpectedly complicated topic.
You can do this with something like the following:
(add-hook 'text-mode-hook (lambda ()
(set (make-local-variable 'indent-region-function)
(lambda (s e)
(indent-rigidly s e tab-width)))))
Then selecting a region and hitting TAB. will indent the region by a tab-width. You can then exchange point and mark with C-x C-x and hit TAB again to repeat.
I do, however, agree with the previous answers that suggest using indent-rigidly directly.

Multiline sentence in emacs

If I have a multiline sentence in Emacs it naturally overflows onto the the following lines. Now, if my cursor is at the beginning of such a sentence and I press the DOWN ARROW key, the cursor is placed at the beginning of the next sentence (which might be at 4-5 lines down), rather than on the next line itself (which other editors do). Same is the behavior of the END and HOME keys.
Is there a way in which I can change this behavior and get the cursor on the next line instead of the next sentence?
I haven't yet tried it myself, but I think what you are asking for is the default behavior for emacs 23. What version are you running?
You might want to check out the page Move By Visible Lines page on the emacswiki.
You might want to try auto-fill-mode or longlines-mode. To get either use M-X then type the command you want. Toggle them off the same way.
If that doesn't work you may want to examine the binding that is being applied to your down arrow. Type C-h k then hit the down arrow key.
It sounds as though the text is wrapping, so by definition (a line being a group of characters separated by a carriage return), it is moving down to the next line.
I agree it is a pain, however a lot of other editors also have this behaviour.
One way is to turn off wrapping:
M-x toggle-truncate-lines
You wont be able to see all of the text in the editor, however it will move down to the next line.