user2366158
user2366158

Reputation: 231

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) 

Upvotes: 2

Views: 561

Answers (1)

Drew
Drew

Reputation: 30708

One answer:

  1. Define a function that runs the macro: Write this in an Emacs-Lisp buffer leaving the cursor at the end:: (defun foo ()

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

  3. Replace setq last-kbd-macro by execute-kbd-macro, and add a final ):

    (defun foo () (execute-kbd-macro XXXXX)

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

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

Upvotes: 1

Related Questions