d.braitain
d.braitain

Reputation: 11

Save and execute an Emacs keyboard macro

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

Upvotes: 1

Views: 313

Answers (2)

duthen
duthen

Reputation: 908

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!

Upvotes: 1

Simon Fromme
Simon Fromme

Reputation: 3174

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.

Upvotes: 1

Related Questions