how to use a keyboard macro in a lisp function until it fails
right now I have a keyboard macro defined and named, and i want to make a lisp function which goes to the top of the buffer, an开发者_StackOverflow中文版d does:
i = 1
do{
run macro
if macro hit the end of the buffer, break out of the loop
insert i
i++
}while(true)
here's what's in my .emacs
(fset 'next-id
(lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item (quote ([19 73 68 61 34 13 67108896 19 34 13 2 23] 0 "%d")) arg)))
(global-set-key (kbd "C-x n") 'next-id)
how would I go about this?
Srsly. Here's how to do it: C-u 0 F4
This should do the trick:
(defun apply-macro-to-buffer (&optional macro)
"Apply last keyboard macro to the buffer"
(interactive "CEnter the name of the macro to apply: ")
(or macro
(progn
(if (null last-kbd-macro)
(error "No keyboard macro has been defined"))
(setq macro last-kbd-macro)))
(let ((end-marker (copy-marker (point-max)))
(i 1))
(save-excursion
(goto-char (point-min))
(while (and (< (point) end-marker))
(let ((mark-active nil))
(execute-kbd-macro macro))
(insert (format "%d\n" i))
(setq i (1+ i))))))
To do the same for a regular command, try this:
(defun apply-command-to-buffer (command)
"Apply a command to the buffer"
(interactive "CEnter the name of the command to apply: ")
(let ((end-marker (copy-marker (point-max)))
(i 1))
(save-excursion
(goto-char (point-min))
(while (and (< (point) end-marker))
(call-interactively command)
(insert (format "%d\n" i))
(setq i (1+ i))))))
精彩评论