*** empty log message ***
[bpt/emacs.git] / lisp / skeleton.el
CommitLineData
f3611c70 1;;; skeleton.el --- Lisp language extension for writing statement skeletons
b578f267 2
c90f2757 3;; Copyright (C) 1993, 1994, 1995, 1996, 2001, 2002, 2003,
d7a0267c 4;; 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
ac59aed8 5
3e910376 6;; Author: Daniel Pfeiffer <occitan@esperanto.org>
ac59aed8 7;; Maintainer: FSF
f3611c70 8;; Keywords: extensions, abbrev, languages, tools
ac59aed8
RS
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
b4aa6026 14;; the Free Software Foundation; either version 3, or (at your option)
ac59aed8
RS
15;; 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
b578f267 23;; along with GNU Emacs; see the file COPYING. If not, write to the
086add15
LK
24;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25;; Boston, MA 02110-1301, USA.
ac59aed8
RS
26
27;;; Commentary:
28
f3611c70 29;; A very concise language extension for writing structured statement
ac59aed8
RS
30;; skeleton insertion commands for programming language modes. This
31;; originated in shell-script mode and was applied to ada-mode's
32;; commands which shrunk to one third. And these commands are now
33;; user configurable.
34
35;;; Code:
36
f3611c70 37;; page 1: statement skeleton language definition & interpreter
ac59aed8
RS
38;; page 2: paired insertion
39;; page 3: mirror-mode, an example for setting up paired insertion
40
41
5c741ceb 42(defvar skeleton-transformation-function 'identity
f3611c70 43 "*If non-nil, function applied to literal strings before they are inserted.
ac59aed8
RS
44It should take strings and characters and return them transformed, or nil
45which means no transformation.
46Typical examples might be `upcase' or `capitalize'.")
5c741ceb 47(defvaralias 'skeleton-transformation 'skeleton-transformation-function)
ac59aed8
RS
48
49; this should be a fourth argument to defvar
5c741ceb 50(put 'skeleton-transformation-function 'variable-interactive
ac59aed8
RS
51 "aTransformation function: ")
52
53
017d787a 54(defvar skeleton-autowrap t
fb607ff1 55 "Controls wrapping behavior of functions created with `define-skeleton'.
017d787a 56When the region is visible (due to `transient-mark-mode' or marking a region
4ba4c353 57with the mouse) and this is non-nil and the function was called without an
017d787a
RS
58explicit ARG, then the ARG defaults to -1, i.e. wrapping around the visible
59region.
60
61We will probably delete this variable in a future Emacs version
62unless we get a substantial number of complaints about the auto-wrap
63feature.")
ac59aed8 64
d21584d6
SM
65(defvar skeleton-end-newline t
66 "If non-nil, make sure that the skeleton inserted ends with a newline.
67This just influences the way the default `skeleton-end-hook' behaves.")
68
da6a884f
KH
69(defvar skeleton-end-hook
70 (lambda ()
d21584d6 71 (or (eolp) (not skeleton-end-newline) (newline-and-indent)))
da6a884f 72 "Hook called at end of skeleton but before going to point of interest.
d21584d6
SM
73By default this moves out anything following to next line,
74 unless `skeleton-end-newline' is set to nil.
da6a884f
KH
75The variables `v1' and `v2' are still set when calling this.")
76
77
f3611c70 78;;;###autoload
5c741ceb 79(defvar skeleton-filter-function 'identity
017d787a 80 "Function for transforming a skeleton proxy's aliases' variable value.")
5c741ceb 81(defvaralias 'skeleton-filter 'skeleton-filter-function)
f3611c70 82
f3611c70 83(defvar skeleton-untabify t
4ba4c353 84 "When non-nil untabifies when deleting backwards with element -ARG.")
f3611c70 85
4bfd70e9 86(defvar skeleton-newline-indent-rigidly nil
4ba4c353 87 "When non-nil, indent rigidly under current line for element `\\n'.
4bfd70e9 88Else use mode's `indent-line-function'.")
f3611c70
KH
89
90(defvar skeleton-further-elements ()
91 "A buffer-local varlist (see `let') of mode specific skeleton elements.
92These variables are bound while interpreting a skeleton. Their value may
93in turn be any valid skeleton element if they are themselves to be used as
94skeleton elements.")
95(make-variable-buffer-local 'skeleton-further-elements)
96
97
ac59aed8
RS
98(defvar skeleton-subprompt
99 (substitute-command-keys
100 "RET, \\<minibuffer-local-map>\\[abort-recursive-edit] or \\[help-command]")
f3611c70
KH
101 "*Replacement for %s in prompts of recursive subskeletons.")
102
ac59aed8 103
ac59aed8
RS
104(defvar skeleton-debug nil
105 "*If non-nil `define-skeleton' will override previous definition.")
106
157b7809
RS
107(defvar skeleton-positions nil
108 "List of positions marked with @, after skeleton insertion.
109The list describes the most recent skeleton insertion, and its elements
110are integer buffer positions in the reverse order of the insertion order.")
a6dccb51 111
4bfd70e9
KH
112;; reduce the number of compiler warnings
113(defvar skeleton)
114(defvar skeleton-modified)
115(defvar skeleton-point)
116(defvar skeleton-regions)
ac59aed8 117
7076c5cd
SM
118(def-edebug-spec skeleton-edebug-spec
119 ([&or null stringp (stringp &rest stringp) [[&not atom] def-form]]
120 &rest &or "n" "_" "-" ">" "@" "&" "!" "resume:"
121 ("quote" def-form) skeleton-edebug-spec def-form))
ac59aed8 122;;;###autoload
f3611c70 123(defmacro define-skeleton (command documentation &rest skeleton)
ac59aed8 124 "Define a user-configurable COMMAND that enters a statement skeleton.
8fb7ff73
SM
125DOCUMENTATION is that of the command.
126SKELETON is as defined under `skeleton-insert'."
7076c5cd 127 (declare (debug (&define name stringp skeleton-edebug-spec)))
ac59aed8 128 (if skeleton-debug
f3611c70 129 (set command skeleton))
773500ab 130 `(progn
8fb7ff73
SM
131 ;; Tell self-insert-command that this function, if called by an
132 ;; abbrev, should cause the self-insert to be skipped.
133 (put ',command 'no-self-insert t)
28895aea
RS
134 (defun ,command (&optional str arg)
135 ,(concat documentation
8fb7ff73 136 (if (string-match "\n\\'" documentation)
28895aea
RS
137 "" "\n")
138 "\n"
139 "This is a skeleton command (see `skeleton-insert').
140Normally the skeleton text is inserted at point, with nothing \"inside\".
141If there is a highlighted region, the skeleton text is wrapped
142around the region text.
143
144A prefix argument ARG says to wrap the skeleton around the next ARG words.
53d393c9 145A prefix argument of -1 says to wrap around region, even if not highlighted.
28895aea 146A prefix argument of zero says to wrap around zero words---that is, nothing.
53d393c9 147This is a way of overriding the use of a highlighted region.")
28895aea
RS
148 (interactive "*P\nP")
149 (skeleton-proxy-new ',skeleton str arg))))
f3611c70 150
28895aea
RS
151;;;###autoload
152(defun skeleton-proxy-new (skeleton &optional str arg)
8fb7ff73 153 "Insert SKELETON.
28895aea
RS
154Prefix ARG allows wrapping around words or regions (see `skeleton-insert').
155If no ARG was given, but the region is visible, ARG defaults to -1 depending
156on `skeleton-autowrap'. An ARG of M-0 will prevent this just for once.
157This command can also be an abbrev expansion (3rd and 4th columns in
158\\[edit-abbrevs] buffer: \"\" command-name).
f3611c70 159
afdff50e 160Optional second argument STR may also be a string which will be the value
8fb7ff73 161of `str' whereas the skeleton's interactor is then ignored."
5c741ceb 162 (skeleton-insert (funcall skeleton-filter-function skeleton)
8fb7ff73
SM
163 ;; Pretend C-x a e passed its prefix arg to us
164 (if (or arg current-prefix-arg)
165 (prefix-numeric-value (or arg
166 current-prefix-arg))
167 (and skeleton-autowrap
168 (or (eq last-command 'mouse-drag-region)
169 (and transient-mark-mode mark-active))
b532266d
SM
170 ;; Deactivate the mark, in case one of the
171 ;; elements of the skeleton is sensitive
172 ;; to such situations (e.g. it is itself a
173 ;; skeleton).
174 (progn (deactivate-mark)
175 -1)))
8fb7ff73
SM
176 (if (stringp str)
177 str))
178 ;; Return non-nil to tell expand-abbrev that expansion has happened.
179 ;; Otherwise the no-self-insert is ignored.
180 t)
ac59aed8 181
ac59aed8 182;;;###autoload
93c36a6d 183(defun skeleton-insert (skeleton &optional regions str)
f3611c70 184 "Insert the complex statement skeleton SKELETON describes very concisely.
ac59aed8 185
93c36a6d
RS
186With optional second argument REGIONS, wrap first interesting point
187\(`_') in skeleton around next REGIONS words, if REGIONS is positive.
188If REGIONS is negative, wrap REGIONS preceding interregions into first
189REGIONS interesting positions \(successive `_'s) in skeleton.
f3611c70 190
93c36a6d
RS
191An interregion is the stretch of text between two contiguous marked
192points. If you marked A B C [] (where [] is the cursor) in
193alphabetical order, the 3 interregions are simply the last 3 regions.
194But if you marked B A [] C, the interregions are B-A, A-[], []-C.
195
196The optional third argument STR, if specified, is the value for the
197variable `str' within the skeleton. When this is non-nil, the
198interactor gets ignored, and this should be a valid skeleton element.
4bfd70e9 199
f3611c70
KH
200SKELETON is made up as (INTERACTOR ELEMENT ...). INTERACTOR may be nil if
201not needed, a prompt-string or an expression for complex read functions.
ac59aed8
RS
202
203If ELEMENT is a string or a character it gets inserted (see also
5c741ceb 204`skeleton-transformation-function'). Other possibilities are:
ac59aed8 205
4bfd70e9 206 \\n go to next line and indent according to mode
3bb34a02 207 _ interesting point, interregion here
b7d05949
JB
208 - interesting point, no interregion interaction, overrides
209 interesting point set by _
f3611c70 210 > indent line (or interregion if > _) according to major mode
157b7809 211 @ add position to `skeleton-positions'
4837b516
GM
212 & do next ELEMENT if previous moved point
213 | do next ELEMENT if previous didn't move point
f3611c70 214 -num delete num preceding characters (see `skeleton-untabify')
ac59aed8
RS
215 resume: skipped, continue here if quit is signaled
216 nil skipped
217
b7d05949
JB
218After termination, point will be positioned at the last occurrence of -
219or at the first occurrence of _ or at the end of the inserted text.
3bb34a02 220
f3611c70
KH
221Further elements can be defined via `skeleton-further-elements'. ELEMENT may
222itself be a SKELETON with an INTERACTOR. The user is prompted repeatedly for
223different inputs. The SKELETON is processed as often as the user enters a
224non-empty string. \\[keyboard-quit] terminates skeleton insertion, but
225continues after `resume:' and positions at `_' if any. If INTERACTOR in such
226a subskeleton is a prompt-string which contains a \".. %s ..\" it is
93c36a6d 227formatted with `skeleton-subprompt'. Such an INTERACTOR may also be a list of
4bfd70e9 228strings with the subskeleton being repeated once for each string.
ac59aed8 229
93c36a6d 230Quoted Lisp expressions are evaluated for their side-effects.
017d787a 231Other Lisp expressions are evaluated and the value treated as above.
4ba4c353 232Note that expressions may not return t since this implies an
f3611c70
KH
233endless loop. Modes can define other symbols by locally setting them
234to any valid skeleton element. The following local variables are
235available:
ac59aed8 236
f3611c70 237 str first time: read a string according to INTERACTOR
ac59aed8 238 then: insert previously read string once more
4ba4c353 239 help help-form during interaction with the user or nil
773500ab 240 input initial input (string or cons with index) while reading str
017d787a 241 v1, v2 local variables for memorizing anything you want
4bfd70e9
KH
242
243When done with skeleton, but before going back to `_'-point call
4ba4c353 244`skeleton-end-hook' if that is non-nil."
93c36a6d
RS
245 (let ((skeleton-regions regions))
246 (and skeleton-regions
247 (setq skeleton-regions
248 (if (> skeleton-regions 0)
25ab24bc 249 (list (copy-marker (point) t)
93c36a6d
RS
250 (save-excursion (forward-word skeleton-regions)
251 (point-marker)))
252 (setq skeleton-regions (- skeleton-regions))
253 ;; copy skeleton-regions - 1 elements from `mark-ring'
254 (let ((l1 (cons (mark-marker) mark-ring))
25ab24bc 255 (l2 (list (copy-marker (point) t))))
93c36a6d 256 (while (and l1 (> skeleton-regions 0))
25ab24bc
SM
257 (push (copy-marker (pop l1) t) l2)
258 (setq skeleton-regions (1- skeleton-regions)))
93c36a6d
RS
259 (sort l2 '<))))
260 (goto-char (car skeleton-regions))
261 (setq skeleton-regions (cdr skeleton-regions)))
262 (let ((beg (point))
263 skeleton-modified skeleton-point resume: help input v1 v2)
264 (setq skeleton-positions nil)
265 (unwind-protect
266 (eval `(let ,skeleton-further-elements
267 (skeleton-internal-list skeleton str)))
268 (run-hooks 'skeleton-end-hook)
269 (sit-for 0)
270 (or (pos-visible-in-window-p beg)
271 (progn
272 (goto-char beg)
273 (recenter 0)))
274 (if skeleton-point
275 (goto-char skeleton-point))))))
276
5b75ef8b 277(defun skeleton-read (prompt &optional initial-input recursive)
773500ab 278 "Function for reading a string from the minibuffer within skeletons.
f8a5751b
RS
279
280PROMPT must be a string or a form that evaluates to a string.
281It may contain a `%s' which will be replaced by `skeleton-subprompt'.
4ba4c353
JB
282If non-nil second arg INITIAL-INPUT or variable `input' is a string or
283cons with index to insert before reading. If third arg RECURSIVE is non-nil
773500ab
KH
284i.e. we are handling the iterator of a subskeleton, returns empty string if
285user didn't modify input.
286While reading, the value of `minibuffer-help-form' is variable `help' if that
93c36a6d 287is non-nil or a default string."
da6a884f
KH
288 (let ((minibuffer-help-form (or (if (boundp 'help) (symbol-value 'help))
289 (if recursive "\
ac59aed8
RS
290As long as you provide input you will insert another subskeleton.
291
292If you enter the empty string, the loop inserting subskeletons is
293left, and the current one is removed as far as it has been entered.
294
295If you quit, the current subskeleton is removed as far as it has been
296entered. No more of the skeleton will be inserted, except maybe for a
f3611c70 297syntactically necessary termination."
93c36a6d 298 "\
f3611c70 299You are inserting a skeleton. Standard text gets inserted into the buffer
da6a884f
KH
300automatically, and you are prompted to fill in the variable parts.")))
301 (eolp (eolp)))
302 ;; since Emacs doesn't show main window's cursor, do something noticeable
303 (or eolp
304 (open-line 1))
305 (unwind-protect
93c36a6d
RS
306 (setq prompt (if (stringp prompt)
307 (read-string (format prompt skeleton-subprompt)
308 (setq initial-input
309 (or initial-input
310 (symbol-value 'input))))
311 (eval prompt)))
da6a884f
KH
312 (or eolp
313 (delete-char 1))))
773500ab 314 (if (and recursive
93c36a6d
RS
315 (or (null prompt)
316 (string= prompt "")
317 (equal prompt initial-input)
318 (equal prompt (car-safe initial-input))))
ac59aed8 319 (signal 'quit t)
5b75ef8b 320 prompt))
ac59aed8 321
4bfd70e9 322(defun skeleton-internal-list (skeleton &optional str recursive)
f3611c70
KH
323 (let* ((start (save-excursion (beginning-of-line) (point)))
324 (column (current-column))
25ab24bc 325 (line (buffer-substring start (line-end-position)))
f3611c70 326 opoint)
4bfd70e9
KH
327 (or str
328 (setq str `(setq str (skeleton-read ',(car skeleton) nil ,recursive))))
da8249b4 329 (when (and (eq (cadr skeleton) '\n) (not recursive)
25ab24bc 330 (save-excursion (skip-chars-backward " \t") (bolp)))
5b83f9c0 331 (setq skeleton (cons nil (cons '> (cddr skeleton)))))
4bfd70e9 332 (while (setq skeleton-modified (eq opoint (point))
773500ab
KH
333 opoint (point)
334 skeleton (cdr skeleton))
335 (condition-case quit
8fb7ff73 336 (skeleton-internal-1 (car skeleton) nil recursive)
773500ab
KH
337 (quit
338 (if (eq (cdr quit) 'recursive)
4bfd70e9
KH
339 (setq recursive 'quit
340 skeleton (memq 'resume: skeleton))
25ab24bc
SM
341 ;; Remove the subskeleton as far as it has been shown
342 ;; the subskeleton shouldn't have deleted outside current line.
da6a884f 343 (end-of-line)
773500ab
KH
344 (delete-region start (point))
345 (insert line)
346 (move-to-column column)
347 (if (cdr quit)
348 (setq skeleton ()
349 recursive nil)
350 (signal 'quit 'recursive)))))))
351 ;; maybe continue loop or go on to next outer resume: section
352 (if (eq recursive 'quit)
353 (signal 'quit 'recursive)
354 recursive))
f3611c70 355
8fb7ff73 356(defun skeleton-internal-1 (element &optional literal recursive)
25ab24bc
SM
357 (cond
358 ((char-or-string-p element)
359 (if (and (integerp element) ; -num
360 (< element 0))
361 (if skeleton-untabify
362 (backward-delete-char-untabify (- element))
363 (delete-backward-char (- element)))
8fb7ff73 364 (insert (if (not literal)
5c741ceb 365 (funcall skeleton-transformation-function element)
25ab24bc
SM
366 element))))
367 ((or (eq element '\n) ; actually (eq '\n 'n)
368 ;; The sequence `> \n' is handled specially so as to indent the first
369 ;; line after inserting the newline (to get the proper indentation).
370 (and (eq element '>) (eq (nth 1 skeleton) '\n) (pop skeleton)))
371 (let ((pos (if (eq element '>) (point))))
372 (cond
373 ((and skeleton-regions (eq (nth 1 skeleton) '_))
374 (or (eolp) (newline))
375 (if pos (save-excursion (goto-char pos) (indent-according-to-mode)))
376 (indent-region (line-beginning-position)
377 (car skeleton-regions) nil))
378 ;; \n as last element only inserts \n if not at eol.
da8249b4 379 ((and (null (cdr skeleton)) (not recursive) (eolp))
25ab24bc
SM
380 (if pos (indent-according-to-mode)))
381 (skeleton-newline-indent-rigidly
382 (let ((pt (point)))
383 (newline)
384 (indent-to (save-excursion
385 (goto-char pt)
386 (if pos (indent-according-to-mode))
387 (current-indentation)))))
388 (t (if pos (reindent-then-newline-and-indent)
389 (newline)
390 (indent-according-to-mode))))))
391 ((eq element '>)
392 (if (and skeleton-regions (eq (nth 1 skeleton) '_))
393 (indent-region (line-beginning-position)
394 (car skeleton-regions) nil)
395 (indent-according-to-mode)))
396 ((eq element '_)
397 (if skeleton-regions
398 (progn
399 (goto-char (pop skeleton-regions))
400 (and (<= (current-column) (current-indentation))
401 (eq (nth 1 skeleton) '\n)
8fb7ff73
SM
402 (end-of-line 0)))
403 (or skeleton-point
404 (setq skeleton-point (point)))))
405 ((eq element '-)
406 (setq skeleton-point (point)))
407 ((eq element '&)
408 (when skeleton-modified (pop skeleton)))
409 ((eq element '|)
410 (unless skeleton-modified (pop skeleton)))
411 ((eq element '@)
412 (push (point) skeleton-positions))
413 ((eq 'quote (car-safe element))
414 (eval (nth 1 element)))
c93992b3
SM
415 ((and (consp element)
416 (or (stringp (car element)) (listp (car element))))
417 ;; Don't forget: `symbolp' is also true for nil.
25ab24bc 418 (if (symbolp (car-safe (car element)))
c93992b3
SM
419 (while (and (skeleton-internal-list element nil t)
420 ;; If the interactor is nil, don't infinite loop.
421 (car element)))
25ab24bc
SM
422 (setq literal (car element))
423 (while literal
424 (skeleton-internal-list element (car literal))
425 (setq literal (cdr literal)))))
426 ((null element))
8fb7ff73 427 (t (skeleton-internal-1 (eval element) t recursive))))
25ab24bc 428\f
f3611c70 429;; Maybe belongs into simple.el or elsewhere
25ab24bc
SM
430;; ;;;###autoload
431;; (define-skeleton local-variables-section
ff85d4f3
RS
432;; "Insert a local variables section. Use current comment syntax if any."
433;; (completing-read "Mode: " obarray
434;; (lambda (symbol)
435;; (if (commandp symbol)
436;; (string-match "-mode$" (symbol-name symbol))))
437;; t)
438;; '(save-excursion
439;; (if (re-search-forward page-delimiter nil t)
1cd7adc6 440;; (error "Not on last page")))
ff85d4f3
RS
441;; comment-start "Local Variables:" comment-end \n
442;; comment-start "mode: " str
443;; & -5 | '(kill-line 0) & -1 | comment-end \n
444;; ( (completing-read (format "Variable, %s: " skeleton-subprompt)
445;; obarray
446;; (lambda (symbol)
447;; (or (eq symbol 'eval)
448;; (user-variable-p symbol)))
449;; t)
450;; comment-start str ": "
451;; (read-from-minibuffer "Expression: " nil read-expression-map nil
452;; 'read-expression-history) | _
453;; comment-end \n)
454;; resume:
28895aea 455;; comment-start "End:" comment-end \n)
ac59aed8 456\f
bc35d5b3 457;; Variables and command for automatically inserting pairs like () or "".
ac59aed8 458
bc35d5b3 459(defvar skeleton-pair nil
ac59aed8 460 "*If this is nil pairing is turned off, no matter what else is set.
bc35d5b3
RS
461Otherwise modes with `skeleton-pair-insert-maybe' on some keys
462will attempt to insert pairs of matching characters.")
ac59aed8
RS
463
464
bc35d5b3
RS
465(defvar skeleton-pair-on-word nil
466 "*If this is nil, paired insertion is inhibited before or inside a word.")
ac59aed8
RS
467
468
5c741ceb 469(defvar skeleton-pair-filter-function (lambda () nil)
bc35d5b3 470 "Attempt paired insertion if this function returns nil, before inserting.
ac59aed8
RS
471This allows for context-sensitive checking whether pairing is appropriate.")
472
473
bc35d5b3
RS
474(defvar skeleton-pair-alist ()
475 "An override alist of pairing partners matched against `last-command-char'.
476Each alist element, which looks like (ELEMENT ...), is passed to
477`skeleton-insert' with no interactor. Variable `str' does nothing.
ac59aed8 478
f3611c70 479Elements might be (?` ?` _ \"''\"), (?\\( ? _ \" )\") or (?{ \\n > _ \\n ?} >).")
ac59aed8 480
c93992b3
SM
481(defvar skeleton-pair-default-alist '((?( _ ?)) (?\))
482 (?[ _ ?]) (?\])
483 (?{ _ ?}) (?\})
484 (?< _ ?>) (?\>)
485