Fixes: debbugs:18939
[emacs.git] / lisp / skeleton.el
blob9074268890eeff005ce30f1e1beee35527db312d
1 ;;; skeleton.el --- Lisp language extension for writing statement skeletons -*- coding: utf-8 -*-
3 ;; Copyright (C) 1993-1996, 2001-2015 Free Software Foundation, Inc.
5 ;; Author: Daniel Pfeiffer <occitan@esperanto.org>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: extensions, abbrev, languages, tools
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; A very concise language extension for writing structured statement
27 ;; skeleton insertion commands for programming language modes. This
28 ;; originated in shell-script mode and was applied to ada-mode's
29 ;; commands which shrunk to one third. And these commands are now
30 ;; user configurable.
32 ;;; Code:
34 (eval-when-compile (require 'cl-lib))
36 ;; page 1: statement skeleton language definition & interpreter
37 ;; page 2: paired insertion
38 ;; page 3: mirror-mode, an example for setting up paired insertion
41 (defvar skeleton-transformation-function 'identity
42 "If non-nil, function applied to literal strings before they are inserted.
43 It should take strings and characters and return them transformed, or nil
44 which means no transformation.
45 Typical examples might be `upcase' or `capitalize'.")
46 (defvaralias 'skeleton-transformation 'skeleton-transformation-function)
48 ; this should be a fourth argument to defvar
49 (put 'skeleton-transformation-function 'variable-interactive
50 "aTransformation function: ")
53 (defvar skeleton-autowrap t
54 "Controls wrapping behavior of functions created with `define-skeleton'.
55 When the region is visible (due to `transient-mark-mode' or marking a region
56 with the mouse) and this is non-nil and the function was called without an
57 explicit ARG, then the ARG defaults to -1, i.e. wrapping around the visible
58 region.")
59 (make-obsolete-variable 'skeleton-autowrap nil "24.5")
61 (defvar skeleton-end-newline t
62 "If non-nil, make sure that the skeleton inserted ends with a newline.
63 This just influences the way the default `skeleton-end-hook' behaves.")
65 (defvar skeleton-end-hook
66 (lambda ()
67 (or (eolp) (not skeleton-end-newline) (newline-and-indent)))
68 "Hook called at end of skeleton but before going to point of interest.
69 By default this moves out anything following to next line,
70 unless `skeleton-end-newline' is set to nil.
71 The variables `v1' and `v2' are still set when calling this.")
74 ;;;###autoload
75 (defvar skeleton-filter-function 'identity
76 "Function for transforming a skeleton proxy's aliases' variable value.")
77 (defvaralias 'skeleton-filter 'skeleton-filter-function)
79 (defvar skeleton-untabify nil ; bug#12223
80 "When non-nil untabifies when deleting backwards with element -ARG.")
82 (defvar skeleton-newline-indent-rigidly nil
83 "When non-nil, indent rigidly under current line for element `\\n'.
84 Else use mode's `indent-line-function'.")
86 (defvar-local skeleton-further-elements ()
87 "A buffer-local varlist (see `let') of mode specific skeleton elements.
88 These variables are bound while interpreting a skeleton. Their value may
89 in turn be any valid skeleton element if they are themselves to be used as
90 skeleton elements.")
92 (defvar skeleton-subprompt
93 (substitute-command-keys
94 "RET, \\<minibuffer-local-map>\\[abort-recursive-edit] or \\[help-command]")
95 "Replacement for %s in prompts of recursive subskeletons.")
98 (defvar skeleton-debug nil
99 "If non-nil `define-skeleton' will override previous definition.")
101 (defvar skeleton-positions nil
102 "List of positions marked with @, after skeleton insertion.
103 The list describes the most recent skeleton insertion, and its elements
104 are integer buffer positions in the reverse order of the insertion order.")
106 ;; reduce the number of compiler warnings
107 (defvar skeleton-il)
108 (defvar skeleton-modified)
109 (defvar skeleton-point)
110 (defvar skeleton-regions)
112 (def-edebug-spec skeleton-edebug-spec
113 ([&or null stringp (stringp &rest stringp) [[&not atom] def-form]]
114 &rest &or "n" "_" "-" ">" "@" "&" "!" "resume:"
115 ("quote" def-form) skeleton-edebug-spec def-form))
116 ;;;###autoload
117 (defmacro define-skeleton (command documentation &rest skeleton)
118 "Define a user-configurable COMMAND that enters a statement skeleton.
119 DOCUMENTATION is that of the command.
120 SKELETON is as defined under `skeleton-insert'."
121 (declare (doc-string 2) (debug (&define name stringp skeleton-edebug-spec)))
122 (if skeleton-debug
123 (set command skeleton))
124 `(progn
125 ;; Tell self-insert-command that this function, if called by an
126 ;; abbrev, should cause the self-insert to be skipped.
127 (put ',command 'no-self-insert t)
128 (defun ,command (&optional str arg)
129 ,(concat documentation
130 (if (string-match "\n\\'" documentation)
131 "" "\n")
132 "\n"
133 "This is a skeleton command (see `skeleton-insert').
134 Normally the skeleton text is inserted at point, with nothing \"inside\".
135 If there is a highlighted region, the skeleton text is wrapped
136 around the region text.
138 A prefix argument ARG says to wrap the skeleton around the next ARG words.
139 A prefix argument of -1 says to wrap around region, even if not highlighted.
140 A prefix argument of zero says to wrap around zero words---that is, nothing.
141 This is a way of overriding the use of a highlighted region.")
142 (interactive "*P\nP")
143 (skeleton-proxy-new ',skeleton str arg))))
145 ;;;###autoload
146 (defun skeleton-proxy-new (skeleton &optional str arg)
147 "Insert SKELETON.
148 Prefix ARG allows wrapping around words or regions (see `skeleton-insert').
149 If no ARG was given, but the region is visible, ARG defaults to -1 depending
150 on `skeleton-autowrap'. An ARG of M-0 will prevent this just for once.
151 This command can also be an abbrev expansion (3rd and 4th columns in
152 \\[edit-abbrevs] buffer: \"\" command-name).
154 Optional second argument STR may also be a string which will be the value
155 of `str' whereas the skeleton's interactor is then ignored."
156 (skeleton-insert (funcall skeleton-filter-function skeleton)
157 ;; Pretend C-x a e passed its prefix arg to us
158 (if (or arg current-prefix-arg)
159 (prefix-numeric-value (or arg
160 current-prefix-arg))
161 (and skeleton-autowrap
162 (or (eq last-command 'mouse-drag-region)
163 (and transient-mark-mode mark-active))
164 ;; Deactivate the mark, in case one of the
165 ;; elements of the skeleton is sensitive
166 ;; to such situations (e.g. it is itself a
167 ;; skeleton).
168 (progn (deactivate-mark)
169 -1)))
170 (if (stringp str)
171 str))
172 ;; Return non-nil to tell expand-abbrev that expansion has happened.
173 ;; Otherwise the no-self-insert is ignored.
176 ;;;###autoload
177 (defun skeleton-insert (skeleton &optional regions str)
178 "Insert the complex statement skeleton SKELETON describes very concisely.
180 With optional second argument REGIONS, wrap first interesting point
181 \(`_') in skeleton around next REGIONS words, if REGIONS is positive.
182 If REGIONS is negative, wrap REGIONS preceding interregions into first
183 REGIONS interesting positions (successive `_'s) in skeleton.
185 An interregion is the stretch of text between two contiguous marked
186 points. If you marked A B C [] (where [] is the cursor) in
187 alphabetical order, the 3 interregions are simply the last 3 regions.
188 But if you marked B A [] C, the interregions are B-A, A-[], []-C.
190 The optional third argument STR, if specified, is the value for the
191 variable `str' within the skeleton. When this is non-nil, the
192 interactor gets ignored, and this should be a valid skeleton element.
194 SKELETON is made up as (INTERACTOR ELEMENT ...). INTERACTOR may be nil if
195 not needed, a prompt-string or an expression for complex read functions.
197 If ELEMENT is a string or a character it gets inserted (see also
198 `skeleton-transformation-function'). Other possibilities are:
200 \\n go to next line and indent according to mode, unless
201 this is the first/last element of a skeleton and point
202 is at bol/eol
203 _ interesting point, interregion here
204 - interesting point, no interregion interaction, overrides
205 interesting point set by _
206 > indent line (or interregion if > _) according to major mode
207 @ add position to `skeleton-positions'
208 & do next ELEMENT if previous moved point
209 | do next ELEMENT if previous didn't move point
210 -NUM delete NUM preceding characters (see `skeleton-untabify')
211 resume: skipped, continue here if quit is signaled
212 nil skipped
214 After termination, point will be positioned at the last occurrence of -
215 or at the first occurrence of _ or at the end of the inserted text.
217 Note that \\n as the last element of the skeleton only inserts a
218 newline if not at eol. If you want to unconditionally insert a newline
219 at the end of the skeleton, use \"\\n\" instead. Likewise with \\n
220 as the first element when at bol.
222 Further elements can be defined via `skeleton-further-elements'.
223 ELEMENT may itself be a SKELETON with an INTERACTOR. The user is prompted
224 repeatedly for different inputs. The SKELETON is processed as often as
225 the user enters a non-empty string. \\[keyboard-quit] terminates skeleton insertion, but
226 continues after `resume:' and positions at `_' if any. If INTERACTOR in
227 such a subskeleton is a prompt-string which contains a \".. %s ..\" it is
228 formatted with `skeleton-subprompt'. Such an INTERACTOR may also be a list
229 of strings with the subskeleton being repeated once for each string.
231 Quoted Lisp expressions are evaluated for their side-effects.
232 Other Lisp expressions are evaluated and the value treated as above.
233 Note that expressions may not return t since this implies an
234 endless loop. Modes can define other symbols by locally setting them
235 to any valid skeleton element. The following local variables are
236 available:
238 str first time: read a string according to INTERACTOR
239 then: insert previously read string once more
240 help help-form during interaction with the user or nil
241 input initial input (string or cons with index) while reading str
242 v1, v2 local variables for memorizing anything you want
244 When done with skeleton, but before going back to `_'-point call
245 `skeleton-end-hook' if that is non-nil."
246 (let ((skeleton-regions regions))
247 (and skeleton-regions
248 (setq skeleton-regions
249 (if (> skeleton-regions 0)
250 (list (copy-marker (point) t)
251 (save-excursion (forward-word skeleton-regions)
252 (point-marker)))
253 (setq skeleton-regions (- skeleton-regions))
254 ;; copy skeleton-regions - 1 elements from `mark-ring'
255 (let ((l1 (cons (mark-marker) mark-ring))
256 (l2 (list (copy-marker (point) t))))
257 (while (and l1 (> skeleton-regions 0))
258 (push (copy-marker (pop l1) t) l2)
259 (setq skeleton-regions (1- skeleton-regions)))
260 (sort l2 '<))))
261 (goto-char (car skeleton-regions))
262 (setq skeleton-regions (cdr skeleton-regions)))
263 (let ((beg (point))
264 skeleton-modified skeleton-point resume: help input v1 v2)
265 (setq skeleton-positions nil)
266 (unwind-protect
267 (cl-progv
268 (mapcar #'car skeleton-further-elements)
269 (mapcar (lambda (x) (eval (cadr x))) skeleton-further-elements)
270 (skeleton-internal-list skeleton str))
271 (run-hooks 'skeleton-end-hook)
272 (sit-for 0)
273 (or (pos-visible-in-window-p beg)
274 (progn
275 (goto-char beg)
276 (recenter 0)))
277 (if skeleton-point
278 (goto-char skeleton-point))))))
280 (defun skeleton-read (prompt &optional initial-input recursive)
281 "Function for reading a string from the minibuffer within skeletons.
283 PROMPT must be a string or a form that evaluates to a string.
284 It may contain a `%s' which will be replaced by `skeleton-subprompt'.
285 If non-nil second arg INITIAL-INPUT or variable `input' is a string or
286 cons with index to insert before reading. If third arg RECURSIVE is non-nil
287 i.e. we are handling the iterator of a subskeleton, returns empty string if
288 user didn't modify input.
289 While reading, the value of `minibuffer-help-form' is variable `help' if that
290 is non-nil or a default string."
291 (let ((minibuffer-help-form (or (if (boundp 'help) (symbol-value 'help))
292 (if recursive "\
293 As long as you provide input you will insert another subskeleton.
295 If you enter the empty string, the loop inserting subskeletons is
296 left, and the current one is removed as far as it has been entered.
298 If you quit, the current subskeleton is removed as far as it has been
299 entered. No more of the skeleton will be inserted, except maybe for a
300 syntactically necessary termination."
302 You are inserting a skeleton. Standard text gets inserted into the buffer
303 automatically, and you are prompted to fill in the variable parts.")))
304 (eolp (eolp)))
305 ;; since Emacs doesn't show main window's cursor, do something noticeable
306 (or eolp
307 ;; We used open-line before, but that can do a lot more than we want,
308 ;; since it runs self-insert-command. E.g. it may remove spaces
309 ;; before point.
310 (save-excursion (insert "\n")))
311 (unwind-protect
312 (setq prompt (if (stringp prompt)
313 (read-string (format prompt skeleton-subprompt)
314 (setq initial-input
315 (or initial-input
316 (symbol-value 'input))))
317 (eval prompt)))
318 (or eolp
319 (delete-char 1))))
320 (if (and recursive
321 (or (null prompt)
322 (string= prompt "")
323 (equal prompt initial-input)
324 (equal prompt (car-safe initial-input))))
325 (signal 'quit t)
326 prompt))
328 (defun skeleton-internal-list (skeleton-il &optional str recursive)
329 (let* ((start (line-beginning-position))
330 (column (current-column))
331 (line (buffer-substring start (line-end-position)))
332 opoint)
333 (or str
334 (setq str `(setq str
335 (skeleton-read ',(car skeleton-il) nil ,recursive))))
336 (when (and (eq (cadr skeleton-il) '\n) (not recursive)
337 (save-excursion (skip-chars-backward " \t") (bolp)))
338 (setq skeleton-il (cons nil (cons '> (cddr skeleton-il)))))
339 (while (setq skeleton-modified (eq opoint (point))
340 opoint (point)
341 skeleton-il (cdr skeleton-il))
342 (condition-case quit
343 (skeleton-internal-1 (car skeleton-il) nil recursive)
344 (quit
345 (if (eq (cdr quit) 'recursive)
346 (setq recursive 'quit
347 skeleton-il (memq 'resume: skeleton-il))
348 ;; Remove the subskeleton as far as it has been shown
349 ;; the subskeleton shouldn't have deleted outside current line.
350 (end-of-line)
351 (delete-region start (point))
352 (insert line)
353 (move-to-column column)
354 (if (cdr quit)
355 (setq skeleton-il ()
356 recursive nil)
357 (signal 'quit 'recursive)))))))
358 ;; maybe continue loop or go on to next outer resume: section
359 (if (eq recursive 'quit)
360 (signal 'quit 'recursive)
361 recursive))
364 (defun skeleton-internal-1 (element &optional literal recursive)
365 (cond
366 ((or (integerp element) (stringp element))
367 (if (and (integerp element) ; -num
368 (< element 0))
369 (if skeleton-untabify
370 (backward-delete-char-untabify (- element))
371 (delete-char element))
372 (insert (if (not literal)
373 (funcall skeleton-transformation-function element)
374 element))))
375 ((or (eq element '\n) ; actually (eq '\n 'n)
376 ;; The sequence `> \n' is handled specially so as to indent the first
377 ;; line after inserting the newline (to get the proper indentation).
378 (and (eq element '>) (eq (nth 1 skeleton-il) '\n) (pop skeleton-il)))
379 (let ((pos (if (eq element '>) (point))))
380 (cond
381 ((and skeleton-regions (eq (nth 1 skeleton-il) '_))
382 (or (eolp) (insert "\n"))
383 (if pos (save-excursion (goto-char pos) (indent-according-to-mode)))
384 (indent-region (line-beginning-position)
385 (car skeleton-regions) nil))
386 ;; \n as last element only inserts \n if not at eol.
387 ((and (null (cdr skeleton-il)) (not recursive) (eolp))
388 (if pos (indent-according-to-mode)))
389 (skeleton-newline-indent-rigidly
390 (let ((pt (point)))
391 (insert "\n")
392 (indent-to (save-excursion
393 (goto-char pt)
394 (if pos (indent-according-to-mode))
395 (current-indentation)))))
396 (t (if pos (reindent-then-newline-and-indent)
397 (insert "\n")
398 (indent-according-to-mode))))))
399 ((eq element '>)
400 (if (and skeleton-regions (eq (nth 1 skeleton-il) '_))
401 (indent-region (line-beginning-position)
402 (car skeleton-regions) nil)
403 (indent-according-to-mode)))
404 ((eq element '_)
405 (if skeleton-regions
406 (progn
407 (goto-char (pop skeleton-regions))
408 (and (<= (current-column) (current-indentation))
409 (eq (nth 1 skeleton-il) '\n)
410 (end-of-line 0)))
411 (or skeleton-point
412 (setq skeleton-point (point)))))
413 ((eq element '-)
414 (setq skeleton-point (point)))
415 ((eq element '&)
416 (when skeleton-modified (pop skeleton-il)))
417 ((eq element '|)
418 (unless skeleton-modified (pop skeleton-il)))
419 ((eq element '@)
420 (push (point) skeleton-positions))
421 ((eq 'quote (car-safe element))
422 (eval (nth 1 element)))
423 ((and (consp element)
424 (or (stringp (car element)) (listp (car element))))
425 ;; Don't forget: `symbolp' is also true for nil.
426 (if (symbolp (car-safe (car element)))
427 (while (and (skeleton-internal-list element nil t)
428 ;; If the interactor is nil, don't infinite loop.
429 (car element)))
430 (setq literal (car element))
431 (while literal
432 (skeleton-internal-list element (car literal))
433 (setq literal (cdr literal)))))
434 ((null element))
435 (t (skeleton-internal-1 (eval element) t recursive))))
437 ;; Maybe belongs into simple.el or elsewhere
438 ;; ;;;###autoload
439 ;; (define-skeleton local-variables-section
440 ;; "Insert a local variables section. Use current comment syntax if any."
441 ;; (completing-read "Mode: " obarray
442 ;; (lambda (symbol)
443 ;; (if (commandp symbol)
444 ;; (string-match "-mode$" (symbol-name symbol))))
445 ;; t)
446 ;; '(save-excursion
447 ;; (if (re-search-forward page-delimiter nil t)
448 ;; (error "Not on last page")))
449 ;; comment-start "Local Variables:" comment-end \n
450 ;; comment-start "mode: " str
451 ;; & -5 | '(kill-line 0) & -1 | comment-end \n
452 ;; ( (completing-read (format "Variable, %s: " skeleton-subprompt)
453 ;; obarray
454 ;; (lambda (symbol)
455 ;; (or (eq symbol 'eval)
456 ;; (custom-variable-p symbol)))
457 ;; t)
458 ;; comment-start str ": "
459 ;; (read-from-minibuffer "Expression: " nil read-expression-map nil
460 ;; 'read-expression-history) | _
461 ;; comment-end \n)
462 ;; resume:
463 ;; comment-start "End:" comment-end \n)
465 ;; Variables and command for automatically inserting pairs like () or "".
467 (defvar skeleton-pair nil
468 "If this is nil pairing is turned off, no matter what else is set.
469 Otherwise modes with `skeleton-pair-insert-maybe' on some keys
470 will attempt to insert pairs of matching characters.")
473 (defvar skeleton-pair-on-word nil
474 "If this is nil, paired insertion is inhibited before or inside a word.")
477 (defvar skeleton-pair-filter-function (lambda () nil)
478 "Attempt paired insertion if this function returns nil, before inserting.
479 This allows for context-sensitive checking whether pairing is appropriate.")
482 (defvar skeleton-pair-alist ()
483 "An override alist of pairing partners matched against `last-command-event'.
484 Each alist element, which looks like (ELEMENT ...), is passed to
485 `skeleton-insert' with no interactor. Variable `str' does nothing.
487 Elements might be (?` ?` _ \"''\"), (?\\( ? _ \" )\") or (?{ \\n > _ \\n ?} >).")
489 (defvar skeleton-pair-default-alist '((?( _ ?)) (?\))
490 (?[ _ ?]) (?\])
491 (?{ _ ?}) (?\})
492 (?< _ ?>) (?\>)
493 (?« _ ?») (?\»)
494 (?` _ ?')))
496 ;;;###autoload
497 (defun skeleton-pair-insert-maybe (arg)
498 "Insert the character you type ARG times.
500 With no ARG, if `skeleton-pair' is non-nil, pairing can occur. If the region
501 is visible the pair is wrapped around it depending on `skeleton-autowrap'.
502 Else, if `skeleton-pair-on-word' is non-nil or we are not before or inside a
503 word, and if `skeleton-pair-filter-function' returns nil, pairing is performed.
504 Pairing is also prohibited if we are right after a quoting character
505 such as backslash.
507 If a match is found in `skeleton-pair-alist', that is inserted, else
508 the defaults are used. These are (), [], {}, <> and `' for the
509 symmetrical ones, and the same character twice for the others."
510 (interactive "*P")
511 (if (or arg (not skeleton-pair))
512 (self-insert-command (prefix-numeric-value arg))
513 (let* ((mark (and skeleton-autowrap
514 (or (eq last-command 'mouse-drag-region)
515 (and transient-mark-mode mark-active))))
516 (char last-command-event)
517 (skeleton (or (assq char skeleton-pair-alist)
518 (assq char skeleton-pair-default-alist)
519 `(,char _ ,char))))
520 (if (or (memq (char-syntax (preceding-char)) '(?\\ ?/))
521 (and (not mark)
522 (or overwrite-mode
523 (if (not skeleton-pair-on-word) (looking-at "\\w"))
524 (funcall skeleton-pair-filter-function))))
525 (self-insert-command (prefix-numeric-value arg))
526 ;; Newlines not desirable for inserting pairs. See bug#16138.
527 (let ((skeleton-end-newline nil))
528 (skeleton-insert (cons nil skeleton) (if mark -1)))))))
531 ;; A more serious example can be found in sh-script.el
532 ;; (defun mirror-mode ()
533 ;; "This major mode is an amusing little example of paired insertion.
534 ;;All printable characters do a paired self insert, while the other commands
535 ;;work normally."
536 ;; (interactive)
537 ;; (kill-all-local-variables)
538 ;; (make-local-variable 'skeleton-pair)
539 ;; (make-local-variable 'skeleton-pair-on-word)
540 ;; (make-local-variable 'skeleton-pair-filter-function)
541 ;; (make-local-variable 'skeleton-pair-alist)
542 ;; (setq major-mode 'mirror-mode
543 ;; mode-name "Mirror"
544 ;; skeleton-pair-on-word t
545 ;; ;; in the middle column insert one or none if odd window-width
546 ;; skeleton-pair-filter-function (lambda ()
547 ;; (if (>= (current-column)
548 ;; (/ (window-width) 2))
549 ;; ;; insert both on next line
550 ;; (next-line 1)
551 ;; ;; insert one or both?
552 ;; (= (* 2 (1+ (current-column)))
553 ;; (window-width))))
554 ;; ;; mirror these the other way round as well
555 ;; skeleton-pair-alist '((?) _ ?()
556 ;; (?] _ ?[)
557 ;; (?} _ ?{)
558 ;; (?> _ ?<)
559 ;; (?/ _ ?\\)
560 ;; (?\\ _ ?/)
561 ;; (?` ?` _ "''")
562 ;; (?' ?' _ "``"))
563 ;; ;; in this mode we exceptionally ignore the user, else it's no fun
564 ;; skeleton-pair t)
565 ;; (let ((map (make-vector 256 'skeleton-pair-insert-maybe))
566 ;; (i 0))
567 ;; (use-local-map `(keymap ,map))
568 ;; (while (< i ? )
569 ;; (aset map i nil)
570 ;; (aset map (+ i 128) nil)
571 ;; (setq i (1+ i))))
572 ;; (run-mode-hooks 'mirror-mode-hook))
574 (provide 'skeleton)
576 ;;; skeleton.el ends here