Assume I have a text file with content
1
123
12
12345
If I want to add an 'a' in the beginning of each line I can simply use string-rectangle (C-x r t), but what if I want to append an 'a' to the end of each line, after which the file should become
1a
123a
12a
12345a
Thanks.
You could use replace-regexp for this purpose, with the $ regexp metacharacter that matches end-of-line. Go to the start of the buffer, and then do M-x replace-regexp, and answer $ and (your text) to the two prompts.
Or, in emacs-speak, for your specific example of adding a:
M-< M-x replace-regexp RET $ RET a RET
Emacs keyboard macros are your friend.
C-x ( C-e a C-n C-x )
Which just sets up the keyboard macro by: starting the keyboard macro (C-x (), go to the end of the line (C-e), insert an a, go to the next line (C-n), and then end the macro recording (C-x )).
Now you can either execute it (C-x e), and keep pressing e for each line you want to have it run on, or you can run it on a region with C-x C-k r.
If you do this a lot, you can save the macro, or you can write a function. This would be one such function:
(defun add-string-to-end-of-lines-in-region (str b e)
"prompt for string, add it to end of lines in the region"
(interactive "sWhat shall we append? \nr")
(goto-char e)
(forward-line -1)
(while (> (point) b)
(end-of-line)
(insert str)
(forward-line -1)))
Related
I have the following code that attempts to create a new line and then jump to it. The idea is that move-end-of-line will jump to the end of the current line, and ["C-m"] would act as return/enter. Yet executing this command gives the error: "wrong number of arguments". How do I fix this?
(global-set-key (kbd "C-.") 'new-line)
(defun new-line ()
(interactive)
(move-end-of-line)
["C-m"]
)
I think you need to read the Emacs & elisp manuals: these questions are pretty easy to answer. Here's one way to do it.
(defun insert-line-after-line (&optional n)
(interactive "p")
(end-of-line 1) ;end of current line
(open-line n) ;open n new lines
(forward-line 1)) ;go to start of first of them
But seriously: Emacs has very extensive self-documentation, it is easy to find out how to do these things.
An option is to record a macro and use that.
M-x kmacro-start-macro
C-e
C-m
M-x kmacro-end-macro
If you don't care about the macro persisting, just run it:
C-x e
But if you want it to persist you would save it:
M-x name-last-kbd-macro new-line
M-x insert-kbd-macro new-line
and paste the output into your initialisation file (with your shortcut definition):
(global-set-key (kbd "C-.") 'new-line)
(fset 'new-line
[end return])
["C-m"] is like the way you specify a key for doing a key binding, but this is not the same as how you programmatically tell Emacs to insert a character into a document. You could use (insert-char ?\^M) (see ref here), but that would result in a literal ^M character (try it; another way to do the same thing interactively is Ctrl-Q followed by Ctrl-M). (insert "\n") seems to be what you're looking for.
Also, the reason you're getting the message "wrong number of arguments" is because (move-end-of-line) requires an argument when called out of interactive context. (move-end-of-line 1) works.
That said, possibly an easier way to achieve the result you're looking for is with the following setting:
(setq next-line-add-newlines t)
This will allow you to just do C-n at the end of the file and not worry about the distinction between moving and inserting.
I have a problem for execute a personal macro in another session in Emacs. I succeeded to create macro and execute then but, after I want to save it for execute them in another time.
For this I write this code in ~/.emacs
(fset 'psTest
(lambda (&optional arg) "Keyboard macro."
(interactive "p")
(kmacro-exec-ring-item (quote ("^X2^X2^X2^X2" 0 "%d")) arg)))
but when I call my macro in another file [ M- x psTest ], Emacs doesn't execute my macro but writes key in my file
^X2^X2^X2^X2
all my commands:
In terminal:
user#PC $ emacs ~/.emacs
In emacs:
C-x (
C-x 2
C-x )
C-x C-k n psTest
M-x insert-kbd-macro [ENTER] psTest [ENTER]
C-x C-c
In terminal:
user#PC $ cat ~/.emacs :
(fset 'psTest
(lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item (quote ("^X2" 0 "%d")) arg)))
user#PC $ emacs ~/test
In emacs:
M- psTest
Now my macro [M- psTest] write ^X2 in my file instead of execute [^X2] which split the screen.
Where is my error?
Thanks
The problem lies in the sequence "^X2" in your macro definition. It contains two characters ^ and X rather than the single character 0x18 in the charset ascii (ASCII (ISO646 IRV)) which is used by emacs to refer to C-x but is displayed the same, though probably in a different color. If you replace the former two-letter-sequence with the latter character and evaluate the definition again, it should work.
You can insert the character with
C-x8RET #x18 RET.
PS: To display information about a specific character at point you can use
M-x desribe-char or what-cursor-position, which is bound to C-x = by default.
I agree with Simon Fromme.
To insert the C-x character, you may omit the #x prefix from his answer and type:
C-x8RET18RET
But you may also simply type C-qC-x in case you don't know the hexadecimal value of the ascii code of this or any other character!
Nevertheless, in your case, I would rather search for the function associated to the C-x 2 sequence. You'll easily find it is split-window-below using either:
C-h k C-x 2 RET
or M-x edit-last-kbd-macro RET
Then you can write some code easier to copy/paste/save like:
(fset 'psTest #'split-window-below)
or
(defun psTest ()
(interactive)
(split-window-below))
This might be a good way to start learning emacs-lisp!
I have a block of code like this:
ec2_shell_exec(tag: "ls /
ec2_shell_exec(tag: "sudo yum install git-core
ec2_shell_exec(tag: "pwd
Whats the easiest way to add a ") to this block of code?
Please note, emacs runs in terminal mode aka -nw mode.
Interactively
C-M-% $ RET ") RET
don't forget to press 4 keys at the same time: Ctrl for C, Alt for M, and Shift-5 for %
if the above still does not work (e.g., you are in a terminal with emacs -nw), you can do M-x query-replace-regexp RET $ RET ") RET
Programmatically
(while (not (eobp)) ; you have to edit the condition!
(goto-char (line-end-position))
(insert "\")")
(forward-line))
A keyboard macro should be easy to type on most terminals:
Move to your first line
Start recording a keyboard macro with C-x (
Go to end of line with C-e
Type ")
Move down with C-n
Stop recording macro with C-x )
Type C-x e to replay once
Type e for each successive time you need to repeat it
Summarizing the two solutions here (for folks running emacs in terminal):
M-x query-replace-regexp RET $ RET ") RET
And
first highlight ec2_shell_exec(tag. And call mc/mark-all-like-this which is from multiple-cursor. You will see all ec2_shell_exec(tag being hightlighted. Now call end-of-line to move every cursor to the end. Finally, you can insert anything you want. Press C-g to end operation
video demo: https://www.youtube.com/watch?v=jNa3axo40qM
Thanks adobe and tom!
I often want to make a multiline function call and reduce it down to one line. For example, convert...
function_call(
'first_arg',
'second')
to
function_call('first_arg', 'second')
Does emacs have some commands to help with this. Specifically, is there a command that will delete all whitespace from the point to the first non-whitespace character?
You might try delete-indentation, my favorite command for joining multiple lines into one line. In your example, put the cursor on the line with "second" and hit M-^ twice. Here are the docs:
M-^ runs the command delete-indentation, which is an interactive compiled Lisp function in simple.el.
It is bound to M-^.
(delete-indentation &optional arg)
Join this line to previous and fix up whitespace at join. If there is a fill prefix, delete it from the beginning of this line. With argument, join this line to following line.
Take a look at the fixup-whitespace function. It comes with Emacs, in simple.el. Its docs are:
Fixup white space between objects around point.
Leave one space or none, according to the context.
A similar function, just-one-space, that
Deletes all spaces and tabs around point, leaving one space
is typically bound to M-SPC.
Specifically, is there a command that will delete all whitespace from the point to the first non-whitespace character?
There's a command that does almost that:
M-\ runs the command delete-horizontal-space
which is an interactive compiled Lisp function in `simple.el'.
It is bound to M-\.
(delete-horizontal-space &optional backward-only)
Delete all spaces and tabs around point.
If backward-only is non-nil, only delete them before point.
You can always use M-z to delete upto a character.
For eg in your case:
M-z ' to delete upto the single quote (unfortunately this will delete the single quote as well, but that is a minor inconvenience).
I use the following macro to "pull" the next line onto the end of the current line, compressing whitespace.
(defun pull-next-line()
(interactive)
(move-end-of-line 1)
(kill-line)
(just-one-space))
This is exactly the opposite of #jrockway's move-line-up and of delete-indentation, which I find more natural. The just-one-space command in the macro is exactly #Mike's M-SPACE.
I bind pull-next-line to M-J (in analogy with Vim's J, for "join", command) using the following in my .emacs.
(global-set-key (kbd "M-J") 'pull-next-line)
Example. Calling pull-next-line on the first line of
function_call(
'first_arg',
'second')
yields
function_call( 'first_arg',
'second')
Calling it a second time yields
function_call( 'first_arg', 'second')
Alt-space will reduce a string of whitespace to a single space character, but it won't delete the newline. Still, that should help a little.
To delete everything from point to the first non-whitespace (or newline), type a non-whitespace char, Alt-space, backspace (to remove final whitespace char), then backspace (to delete the char you added.
To turn the multi-line function declaration into a single-line declaration, use a combination of Alt-space, backspace, and Alt-E (goto-endofline) commands.
A rather drastic way of doing this is Hungry-Delete mode:
Hungry-Delete is a minor-mode that causes deletion to delete all whitespace in the direction you are deleting.
A slightly different approach would be creating a keyboard macro to do the job for you.
so, for creating the macro stage a general scenario like so:
foo
bar
[a line with "foo" then a couple of lines later and with some white spaces, write "bar"]
then standing anywhere between foo and bar, do the following:
C-x ( ; start recording macro
M-b ; move backwards to the beginning of foo
END ; move to the end of foo
C-space ; place mark
C-M-f ; move to the end of bar
HOME ; move to the beginning of the line
C-w ; yank out all the white space
M-SPACE ; leave only one space
C-x ) ; end recording the macro
M-x name-last-kbd-macro ; name it, call it jline or something
Now you can always remove all whitespace between two words with M-x one-line
Make sure you remember to save your keyboard macro by issuing M-x insert-kbd-macro somewhere in your .emacs file - this is how it looks:
(fset 'jline
[?\M-b end ?\C- ?\C-\M-f home ?\C-w escape ? ])
I do this:
(defun move-line-up ()
"Removes leading spaces from the current line, and then moves
the current line to the end of the previous line."
(interactive)
(let (start end)
(save-excursion
(beginning-of-line)
; get first non-space character, only look on this line
(let ((search-end (save-excursion (end-of-line) (point))))
(re-search-forward "[^[:space:]]" search-end))
(setq end (1- (point)))
(previous-line)
(end-of-line)
(setq start (point))
(delete-region start end))
(goto-char start)))
(defun move-next-line-up ()
"Moves the next line to the end of the current line"
(interactive)
(next-line)
(move-line-up))
And bind these as:
(global-set-key (kbd "C-x ,") 'move-line-up)
(global-set-key (kbd "C-x .") 'move-next-line-up)
So to solve your problem, on the line that says "second)", just run C-x , C-x ,
If you want all of your deletes to act that way, you might check out greedy-delete.
How can I copy a line 10 times easily in Emacs? I can't find a copy-line shortcut or function. I can use C-aC-spcC-eM-w to laboriously copy the line but how can I then paste it more than once?
Any ideas before I go and write my own functions.
you can use a keyboard macro for that:-
C-a C-k C-x ( C-y C-j C-x ) C-u 9 C-x e
Explanation:-
C-a : Go to start of line
C-k : Kill line
C-x ( : Start recording keyboard macro
C-y : Yank killed line
C-j : Move to next line
C-x ) : Stop recording keyboard macro
C-u 9 : Repeat 9 times
C-x e : Execute keyboard macro
Copying:
If you frequently work with lines, you might want to make copy (kill-ring-save) and cut (kill-region) work on lines when no region is selected:
(defadvice kill-ring-save (before slickcopy activate compile)
"When called interactively with no active region, copy a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(list (line-beginning-position)
(line-beginning-position 2)))))
(defadvice kill-region (before slickcut activate compile)
"When called interactively with no active region, kill a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(list (line-beginning-position)
(line-beginning-position 2)))))
Then you can copy the line with just M-w.
Pasting:
Often a prefix argument just performs an action multiple times, so you'd expect C-u 10 C-y to work, but in this case C-y uses its argument to mean which element of the kill-ring to "yank" (paste). The only solution I can think of is what kronoz says: record a macro with C-x ( C-y C-x ) and then let the argument of C-u go to kmacro-end-and-call-macro instead (that's C-u 9 C-x e or even just C-9 C-x e or M-9 C-x e).
Another way:
You can also just stay in M-x viper-mode and use yy10p :)
You may know this, but for many commands a "C-u 10" prefix will do the trick. Unfortunately for the C-y yank command, "C-u" is redefined to mean "go back that many items in the kill ring, and yank that item".
I thought you might be able to use the copy-to-register and insert-register commands with the C-u prefix command, but apparently that doesn't work either.
Also C-x z, "repeat last command" seems to be immune to C-u.
Another thought would be to use M-: to get an Eval prompt and type in a bit of elisp. I thought something like (dotimes '10 'yank) might do it, but it doesn't seem to.
So it looks like using C-u on a macro may indeed be the best you can do short of writing your own little function.
Had I a vote, I'd vote for kronoz answer.
You don't need both C-x ) and C-x e in this example.
You can just give the repeat argument straight to C-x ). This stops recording and repeats the macro, in one step. Or you can skip C-x ) and go straight to C-x e, since C-x e will end the recording before doing the repeats.
Which way to choose depends on how you like your repeat count to work. For C-x ) you say how many repeats you wanted in total (so 10 in this case). For C-x e you need to say how many more repeats are left (i.e. 9).
C-a C-k C-k will also kill the trailing newline, so you don't have to put it back yourself later. It's quicker than using the mark, and doesn't need you to change any variables.
Even better (unless you're in a terminal), you can use C-S-Backspace* to kill the entire line, regardless of where you are in it.
[* If you're using X windows, make sure to type shift (not alt) or you may terminate your session!]
Speaking of terminals, M-9 is a nice alternative if you find you can't type C-9.
In Emacs 22 and higher, by default F3 starts a macro and F4 end/repeats a macro. You just hit F3 to start recording, hit F4 when you're done, and hit F4 again to repeat the macro. (F4 also takes an argument.)
Putting this all together, to get 10 copies of the current line:
C-S-Backspace : kill this line
F3 : start macro
C-y : yank the line
C-1 C-0 F4 : make that 10 yanks
Not quite as short as y y 10 p, but pretty close. :)
Here's a function I took from an OS/2 port of Emacs. (Yes, I've been using Emacs for a while.)
;; Author: Eberhard Mattes <mattes#azu.informatik.uni-stuttgart.de>
(defun emx-dup-line (arg)
"Duplicate current line.
Set mark to the beginning of the new line.
With argument, do this that many times."
(interactive "*p")
(setq last-command 'identity) ; Don't append to kill ring
(let ((s (point)))
(beginning-of-line)
(let ((b (point)))
(forward-line)
(if (not (eq (preceding-char) ?\n)) (insert ?\n))
(copy-region-as-kill b (point))
(while (> arg 0)
(yank)
(setq arg (1- arg)))
(goto-char s))))
I have that bound to F9 d:
(global-set-key [f9 ?d] 'emx-dup-line)
Then I'd use C-u 10 F9 d to duplicate a line 10 times.
The only way I know to repeat arbitrary commands is to use the "repeat by argument" feature of keyboard macros.
C-a C-space down M-w C-x ( C-y C-x ) C-9 C-x e
C-a : Go to start of line
C-space : Set mark
down : Go to start of following line
M-w : Copy region
C-x ( : Start keyboard macro
C-y : Yank copied line
C-x ) : End keyboard macro
C-9 C-x e : Execute keyboard macro nine times.
That's kind of weak compared to vim. But only because vim is amazingly efficient at this sort of thing.
If you are really pining for modal vi-like interaction, you could use one of the vi emulation modes, such as viper-mode. Check in the section "Emulation" of online emacs manual.
You will want to kill the line: C-a C-k, and then C-y or ?
I don't know of a direct equivalent (C-y 10 times is the best I know), but you may be interested in Viper, which is a vi emulation package for emacs. It's part of the standard emacs distribution.
Based on Baxissimo's answer I defuned this:
(defun yank-n-times (arg)
"yank prefix-arg number of times. Not safe in any way."
(interactive "*p")
(dotimes 'arg (yank)))
Set that to some key, call it with a prefix argument, and off you go.
edit (also modified the interactive call above to be less lousy)
Or, here's a version that can sort of replace yank-pop:
(defun yank-n-times (&optional arg)
"yank prefix-arg number of times. Call yank-pop if last command was yank."
(interactive "*p")
(if (or (string= last-command "yank")
(string= last-command "yank-pop"))
(yank-pop arg)
(if (> arg 1)
(dotimes 'arg (yank))
(message "Previous arg was not a yank, and called without a prefix."))))
the message is kind of a lie, but you shouldn't call it without a prefix of greater than 1 anyway, so.
Not sure if it's a good idea, but I replaced M-y with this, I'll see how that goes.
First you need this key binding in your .emacs:
;; yank n times
(global-set-key "\C-y" (lambda (n) (interactive "*p") (dotimes (i n) (clipboard-yank))))
Then you can do:
C-a C-SPC C-n M-w C-u 10 C-y
C-a C-SPC C-n M-w - select whole line
C-u 10 C-y - repeat "clipboard-yank" 10 times
You get the line with C-k, you make the next command happen ten times with C-u 10, then you paste the line with C-y. Pretty simple.
If you always want C-k to do the whole line, you can set kill-whole-line to t. No more fiddling with C-a or C-e.
There's a lot you can do with fancy kill rings, registers, and macros, and I encourage you to learn them, but yanking a line ten times doesn't have to be tough or strange.