1;;; macros.el --- non-primitive commands for keyboard macros -*- lexical-binding:t -*-
2
3;; Copyright (C) 1985-1987, 1992, 1994-1995, 2001-2021 Free Software
4;; Foundation, Inc.
5
6;; Maintainer: emacs-devel@gnu.org
7;; Keywords: abbrev
8;; Package: emacs
9
10;; This file is part of GNU Emacs.
11
12;; GNU Emacs is free software: you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
23;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
24
25;;; Commentary:
26
27;; Extension commands for keyboard macros.  These permit you to assign
28;; a name to the last-defined keyboard macro, expand and insert the
29;; lisp corresponding to a macro, query the user from within a macro,
30;; or apply a macro to each line in the reason.
31
32;;; Code:
33
34(require 'kmacro)
35
36;;;###autoload
37(defalias 'name-last-kbd-macro #'kmacro-name-last-macro)
38
39(defun macros--insert-vector-macro (definition)
40  "Print DEFINITION, a vector, into the current buffer."
41  (insert ?\[
42          (mapconcat (lambda (event)
43                       (or (prin1-char event)
44                           (prin1-to-string event)))
45                     definition
46                     " ")
47          ?\]))
48
49;;;###autoload
50(defun insert-kbd-macro (macroname &optional keys)
51  "Insert in buffer the definition of kbd macro MACRONAME, as Lisp code.
52MACRONAME should be a symbol.
53Optional second arg KEYS means also record the keys it is on
54\(this is the prefix argument, when calling interactively).
55
56This Lisp code will, when executed, define the kbd macro with the same
57definition it has now.  If you say to record the keys, the Lisp code
58will also rebind those keys to the macro.  Only global key bindings
59are recorded since executing this Lisp code always makes global
60bindings.
61
62To save a kbd macro, visit a file of Lisp code such as your `~/.emacs',
63use this command, and then save the file."
64  (interactive (list (intern (completing-read "Insert kbd macro (name): "
65					      obarray
66                                              #'kmacro-keyboard-macro-p
67					      t))
68		     current-prefix-arg))
69  (let (definition)
70    (if (string= (symbol-name macroname) "")
71	(progn
72	  (setq macroname 'last-kbd-macro definition last-kbd-macro)
73	  (insert "(setq "))
74      (setq definition (symbol-function macroname))
75      (insert "(fset '"))
76    (prin1 macroname (current-buffer))
77    (insert "\n   ")
78    (if (stringp definition)
79	(let ((beg (point)) end)
80	  (prin1 definition (current-buffer))
81	  (setq end (point-marker))
82	  (goto-char beg)
83	  (while (< (point) end)
84	    (let ((char (following-char)))
85	      (cond ((= char 0)
86		     (delete-region (point) (1+ (point)))
87		     (insert "\\C-@"))
88		    ((< char 27)
89		     (delete-region (point) (1+ (point)))
90		     (insert "\\C-" (+ 96 char)))
91		    ((= char ?\C-\\)
92		     (delete-region (point) (1+ (point)))
93		     (insert "\\C-\\\\"))
94		    ((< char 32)
95		     (delete-region (point) (1+ (point)))
96		     (insert "\\C-" (+ 64 char)))
97		    ((< char 127)
98		     (forward-char 1))
99		    ((= char 127)
100		     (delete-region (point) (1+ (point)))
101		     (insert "\\C-?"))
102		    ((= char 128)
103		     (delete-region (point) (1+ (point)))
104		     (insert "\\M-\\C-@"))
105		    ((= char (aref "\M-\C-\\" 0))
106		     (delete-region (point) (1+ (point)))
107		     (insert "\\M-\\C-\\\\"))
108		    ((< char 155)
109		     (delete-region (point) (1+ (point)))
110		     (insert "\\M-\\C-" (- char 32)))
111		    ((< char 160)
112		     (delete-region (point) (1+ (point)))
113		     (insert "\\M-\\C-" (- char 64)))
114		    ((= char (aref "\M-\\" 0))
115		     (delete-region (point) (1+ (point)))
116		     (insert "\\M-\\\\"))
117		    ((< char 255)
118		     (delete-region (point) (1+ (point)))
119		     (insert "\\M-" (- char 128)))
120		    ((= char 255)
121		     (delete-region (point) (1+ (point)))
122		     (insert "\\M-\\C-?"))))))
123      (if (vectorp definition)
124          (macros--insert-vector-macro definition)
125        (pcase (kmacro-extract-lambda definition)
126          (`(,vecdef ,counter ,format)
127           (insert "(kmacro-lambda-form ")
128           (macros--insert-vector-macro vecdef)
129           (insert " ")
130           (prin1 counter (current-buffer))
131           (insert " ")
132           (prin1 format (current-buffer))
133           (insert ")"))
134          (_ (prin1 definition (current-buffer))))))
135    (insert ")\n")
136    (if keys
137        (let ((keys (or (where-is-internal (symbol-function macroname)
138                                           '(keymap))
139                        (where-is-internal macroname '(keymap)))))
140	  (while keys
141	    (insert "(global-set-key ")
142	    (prin1 (car keys) (current-buffer))
143	    (insert " '")
144	    (prin1 macroname (current-buffer))
145	    (insert ")\n")
146	    (setq keys (cdr keys)))))))
147
148;;;###autoload
149(defun kbd-macro-query (flag)
150  "Query user during kbd macro execution.
151  With prefix argument, enters recursive edit, reading keyboard
152commands even within a kbd macro.  You can give different commands
153each time the macro executes.
154  Without prefix argument, asks whether to continue running the macro.
155Your options are: \\<query-replace-map>
156\\[act]	Finish this iteration normally and continue with the next.
157\\[skip]	Skip the rest of this iteration, and start the next.
158\\[exit]	Stop the macro entirely right now.
159\\[recenter]	Redisplay the screen, then ask again.
160\\[edit]	Enter recursive edit; ask again when you exit from that."
161  (interactive "P")
162  (or executing-kbd-macro
163      defining-kbd-macro
164      (user-error "Not defining or executing kbd macro"))
165  (if flag
166      (let (executing-kbd-macro defining-kbd-macro)
167	(recursive-edit))
168    (if (not executing-kbd-macro)
169	nil
170      (let ((loop t)
171	    (msg (substitute-command-keys
172		  "Proceed with macro?\\<query-replace-map>\
173 (\\[act], \\[skip], \\[exit], \\[recenter], \\[edit]) ")))
174	(while loop
175	  (let ((key (let ((executing-kbd-macro nil)
176			   (defining-kbd-macro nil))
177		       (message "%s" msg)
178		       (read-event)))
179		def)
180	    (setq key (vector key))
181	    (setq def (lookup-key query-replace-map key))
182	    (cond ((eq def 'act)
183		   (setq loop nil))
184		  ((eq def 'skip)
185		   (setq loop nil)
186		   (setq executing-kbd-macro ""))
187		  ((eq def 'exit)
188		   (setq loop nil)
189		   (setq executing-kbd-macro t))
190		  ((eq def 'recenter)
191		   (recenter nil))
192		  ((eq def 'edit)
193		   (let (executing-kbd-macro defining-kbd-macro)
194		     (recursive-edit)))
195		  ((eq def 'quit)
196		   (setq quit-flag t))
197		  (t
198		   (or (eq def 'help)
199		       (ding))
200		   (with-output-to-temp-buffer "*Help*"
201		     (princ
202		      (substitute-command-keys
203		       "Specify how to proceed with keyboard macro execution.
204Possibilities: \\<query-replace-map>
205\\[act]	Finish this iteration normally and continue with the next.
206\\[skip]	Skip the rest of this iteration, and start the next.
207\\[exit]	Stop the macro entirely right now.
208\\[recenter]	Redisplay the screen, then ask again.
209\\[edit]	Enter recursive edit; ask again when you exit from that."))
210		     (with-current-buffer standard-output
211		       (help-mode)))))))))))
212
213;;;###autoload
214(defun apply-macro-to-region-lines (top bottom &optional macro)
215  "Apply last keyboard macro to all lines in the region.
216For each line that begins in the region, move to the beginning of
217the line, and run the last keyboard macro.
218
219When called from lisp, this function takes two arguments TOP and
220BOTTOM, describing the current region.  TOP must be before BOTTOM.
221The optional third argument MACRO specifies a keyboard macro to
222execute.
223
224This is useful for quoting or unquoting included text, adding and
225removing comments, or producing tables where the entries are regular.
226
227For example, in Usenet articles, sections of text quoted from another
228author are indented, or have each line start with `>'.  To quote a
229section of text, define a keyboard macro which inserts `>', put point
230and mark at opposite ends of the quoted section, and use
231`\\[apply-macro-to-region-lines]' to mark the entire section.
232
233Suppose you wanted to build a keyword table in C where each entry
234looked like this:
235
236    { \"foo\", foo_data, foo_function },
237    { \"bar\", bar_data, bar_function },
238    { \"baz\", baz_data, baz_function },
239
240You could enter the names in this format:
241
242    foo
243    bar
244    baz
245
246and write a macro to massage a word into a table entry:
247
248    \\C-x (
249       \\M-d { \"\\C-y\", \\C-y_data, \\C-y_function },
250    \\C-x )
251
252and then select the region of un-tablified names and use
253`\\[apply-macro-to-region-lines]' to build the table from the names."
254  (interactive "r")
255  (or macro
256      (progn
257	(if (null last-kbd-macro)
258	    (user-error "No keyboard macro has been defined"))
259	(setq macro last-kbd-macro)))
260  (save-excursion
261    (let ((end-marker (copy-marker bottom))
262	  next-line-marker)
263      (goto-char top)
264      (if (not (bolp))
265	  (forward-line 1))
266      (setq next-line-marker (point-marker))
267      (while (< next-line-marker end-marker)
268	(goto-char next-line-marker)
269	(save-excursion
270	  (forward-line 1)
271	  (set-marker next-line-marker (point)))
272	(save-excursion
273	  (let ((mark-active nil))
274	    (execute-kbd-macro macro))))
275      (set-marker end-marker nil)
276      (set-marker next-line-marker nil))))
277
278;;;###autoload (define-key ctl-x-map "q" 'kbd-macro-query)
279
280(provide 'macros)
281
282;;; macros.el ends here
283