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
152With prefix argument FLAG, enter recursive edit, reading
153keyboard commands even within a kbd macro.  You can give
154different commands each time the macro executes.
155
156Without prefix argument, ask whether to continue running the
157macro.
158
159Your options are: \\<query-replace-map>
160
161\\[act]	Finish this iteration normally and continue with the next.
162\\[skip]	Skip the rest of this iteration, and start the next.
163\\[exit]	Stop the macro entirely right now.
164\\[recenter]	Redisplay the screen, then ask again.
165\\[edit]	Enter recursive edit; ask again when you exit from that."
166  (interactive "P")
167  (or executing-kbd-macro
168      defining-kbd-macro
169      (user-error "Not defining or executing kbd macro"))
170  (if flag
171      (let (executing-kbd-macro defining-kbd-macro)
172	(recursive-edit))
173    (if (not executing-kbd-macro)
174	nil
175      (let ((loop t)
176	    (msg (substitute-command-keys
177		  "Proceed with macro?\\<query-replace-map>\
178 (\\[act], \\[skip], \\[exit], \\[recenter], \\[edit]) ")))
179	(while loop
180	  (let ((key (let ((executing-kbd-macro nil)
181			   (defining-kbd-macro nil))
182		       (message "%s" msg)
183		       (read-event)))
184		def)
185	    (setq key (vector key))
186	    (setq def (lookup-key query-replace-map key))
187	    (cond ((eq def 'act)
188		   (setq loop nil))
189		  ((eq def 'skip)
190		   (setq loop nil)
191		   (setq executing-kbd-macro ""))
192		  ((eq def 'exit)
193		   (setq loop nil)
194		   (setq executing-kbd-macro t))
195		  ((eq def 'recenter)
196		   (recenter nil))
197		  ((eq def 'edit)
198		   (let (executing-kbd-macro defining-kbd-macro)
199		     (recursive-edit)))
200		  ((eq def 'quit)
201		   (setq quit-flag t))
202		  (t
203		   (or (eq def 'help)
204		       (ding))
205		   (with-output-to-temp-buffer "*Help*"
206		     (princ
207		      (substitute-command-keys
208		       "Specify how to proceed with keyboard macro execution.
209Possibilities: \\<query-replace-map>
210\\[act]	Finish this iteration normally and continue with the next.
211\\[skip]	Skip the rest of this iteration, and start the next.
212\\[exit]	Stop the macro entirely right now.
213\\[recenter]	Redisplay the screen, then ask again.
214\\[edit]	Enter recursive edit; ask again when you exit from that."))
215		     (with-current-buffer standard-output
216		       (help-mode)))))))))))
217
218;;;###autoload
219(defun apply-macro-to-region-lines (top bottom &optional macro)
220  "Apply last keyboard macro to all lines in the region.
221For each line that begins in the region, move to the beginning of
222the line, and run the last keyboard macro.
223
224When called from lisp, this function takes two arguments TOP and
225BOTTOM, describing the current region.  TOP must be before BOTTOM.
226The optional third argument MACRO specifies a keyboard macro to
227execute.
228
229This is useful for quoting or unquoting included text, adding and
230removing comments, or producing tables where the entries are regular.
231
232For example, in Usenet articles, sections of text quoted from another
233author are indented, or have each line start with `>'.  To quote a
234section of text, define a keyboard macro which inserts `>', put point
235and mark at opposite ends of the quoted section, and use
236`\\[apply-macro-to-region-lines]' to mark the entire section.
237
238Suppose you wanted to build a keyword table in C where each entry
239looked like this:
240
241    { \"foo\", foo_data, foo_function },
242    { \"bar\", bar_data, bar_function },
243    { \"baz\", baz_data, baz_function },
244
245You could enter the names in this format:
246
247    foo
248    bar
249    baz
250
251and write a macro to massage a word into a table entry:
252
253    \\C-x (
254       \\M-d { \"\\C-y\", \\C-y_data, \\C-y_function },
255    \\C-x )
256
257and then select the region of un-tablified names and use
258`\\[apply-macro-to-region-lines]' to build the table from the names."
259  (interactive "r")
260  (or macro
261      (progn
262	(if (null last-kbd-macro)
263	    (user-error "No keyboard macro has been defined"))
264	(setq macro last-kbd-macro)))
265  (save-excursion
266    (let ((end-marker (copy-marker bottom))
267	  next-line-marker)
268      (goto-char top)
269      (if (not (bolp))
270	  (forward-line 1))
271      (setq next-line-marker (point-marker))
272      (while (< next-line-marker end-marker)
273	(goto-char next-line-marker)
274	(save-excursion
275	  (forward-line 1)
276	  (set-marker next-line-marker (point)))
277	(save-excursion
278	  (let ((mark-active nil))
279	    (execute-kbd-macro macro))))
280      (set-marker end-marker nil)
281      (set-marker next-line-marker nil))))
282
283;;;###autoload (define-key ctl-x-map "q" 'kbd-macro-query)
284
285(provide 'macros)
286
287;;; macros.el ends here
288