Save and execute an Emacs keyboard macro - emacs

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!

Related

How to set a keybinding to create and jump to the next line in emacs?

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.

Running emacs keyboard macros in batch mode

I want to be able to save a keyboard macro in emacs and apply it to a file repeatedly in batch mode. To give a simple example, I made the following file paren-delete.el which is supposed to delete all parentheses and their contents. When I run emacs --batch target.txt --load paren-delete.el, nothing seems to have changed. It appears that only the first kbd function does what it's supposed to, so clearly I don't understand how that command works.
I know that it would be preferable to avoid keyboard macros and write my functions in proper elisp, but I'd prefer a quick-and-dirty solution, and I feel like I'm close.
(kbd "M-x load-library kmacro")
(fset 'delete-paren
(lambda (&optional arg) "Keyboard macro." (interactive "p")
(kmacro-exec-ring-item (quote ("^S(^M^B^#^[^N^W" 0 "%d")) arg)))
(start-kbd-macro nil)
(kbd "M-x delete-paren")
(end-kbd-macro)
(kbd "C-u 0 C-x e")
(save-buffer)
One answer:
Define a function that runs the macro: Write this in an Emacs-Lisp buffer leaving the cursor at the end::
(defun foo ()
M-x insert-kbd-macro RET
Now you have this text, but with the definition of your keyboard macro in place of XXXXX:
(defun foo () (setq last-kbd-macro XXXXX)
Replace setq last-kbd-macro by execute-kbd-macro, and add a final ):
(defun foo () (execute-kbd-macro XXXXX)
Then use C-x C-e after the definition or C-M-x anywhere inside it.
That defines function foo, which does just what your keyboard macro did (in the same context, e.g., same mode, so same key bindings).
Save the definition to your init file. You can use it with Emacs in batch mode. You can also add (interactive) after () to make it a command, so you can use it with M-x.
Another answer:
With Bookmark+, use C-u M-x bmkp-make-function-bookmark to create a bookmark from the last keyboard macro. You are prompted for the bookmark name.
Bookmarks are persistent. To use a bookmark in batch mode, call it as an argument of bookmark-jump, like so: (bookmark-jump THE-BOOKMARK-NAME).

Appending characters to the end of each line in Emacs

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)))

Convert Emacs macro into Elisp

Is there a way to convert an emacs macro into elisp, not like what M-x insert-kbd-macro does, the actual activity becoming elisp statements.
Thanks for your help.
Nope, sorry. There is no trivial way to convert an emacs macro into elisp.
Update: There's been some work on Emacs to start down this path. See this thread as a starting point. It's still not possible (June 2010), but there's activity.
The first reason I can think of is dealing with interactive commands and translating keystrokes into proper arguments for functions.
Think of the following sequence:
C-x b .em TAB RET
This begins the command to switch to a buffer, types three characters, uses TAB completion to complete it and RET to accept. The equivalent lisp for the end result (in an emacs session where the TAB completion is unique) is:
(switch-to-buffer ".emacs")
Thinking of completion, there are also interactions with expansion of all types (dabbrev, hippie-expand, etc.).
A starting point can be M-x edit-last-kbd-macro which (in my case) shows this:
;; Keyboard Macro Editor. Press C-c C-c to finish; press C-x k RET to cancel.
;; Original keys: C-x b .em <tab> RET
Command: last-kbd-macro
Key: none
Macro:
C-x b ;; switch-to-buffer
.em ;; self-insert-command * 3
<tab> ;; pabbrev-expand-maybe
RET ;; newline-and-indent
Which at least gives you some of the function names. But you'll see that RET is labeled as 'newline-and-indent which is incorrect because at the time of the macro execution, the minibuffer is active and the binding is in fact 'minibuffer-complete-and-exit. Similarly, the proper binding for TAB is 'minibuffer-complete.
I made a package that allows pretty much exactly this at https://github.com/Silex/elmacro
It has some quirks but it works pretty well... for example, the following macro:
F3 C-e M-b M-u C-a C-n F4
Generates the following elisp:
(defun upcase-last-word ()
"Change me!"
(interactive)
(move-end-of-line 1)
(backward-word 1)
(upcase-word 1)
(move-beginning-of-line 1)
(next-line 1 1))

Emacs equivalent of Vim's yy10p?

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.