1 ;;; tempo.el --- Flexible template insertion -*- lexical-binding: t; -*-
3 ;; Copyright (C) 1994-1995, 2001-2019 Free Software Foundation, Inc.
5 ;; Author: David Kågedal <davidk@lysator.liu.se>
6 ;; Created: 16 Feb 1994
7 ;; Kågedal's last version number: 1.2.4
8 ;; Keywords: abbrev, extensions, languages, tools
10 ;; This file is part of GNU Emacs.
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.
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.
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/>.
27 ;; This file provides a simple way to define powerful templates, or
28 ;; macros, if you wish. It is mainly intended for, but not limited to,
29 ;; other programmers to be used for creating shortcuts for editing
30 ;; certain kind of documents. It was originally written to be used by
31 ;; a HTML editing mode written by Nelson Minar <nelson@santafe.edu>,
32 ;; and his html-helper-mode.el is probably the best example of how to
35 ;; A template is defined as a list of items to be inserted in the
36 ;; current buffer at point. Some of the items can be simple strings,
37 ;; while other can control formatting or define special points of
38 ;; interest in the inserted text.
40 ;; If a template defines a "point of interest" that point is inserted
41 ;; in a buffer-local list of "points of interest" that the user can
42 ;; jump between with the commands `tempo-backward-mark' and
43 ;; `tempo-forward-mark'. If the template definer provides a prompt for
44 ;; the point, and the variable `tempo-interactive' is non-nil, the
45 ;; user will be prompted for a string to be inserted in the buffer,
46 ;; using the minibuffer.
48 ;; The template can also define one point to be replaced with the
49 ;; current region if the template command is called with a prefix (or
50 ;; a non-nil argument).
52 ;; More flexible templates can be created by including lisp symbols,
53 ;; which will be evaluated as variables, or lists, which will be
54 ;; evaluated as lisp expressions.
56 ;; See the documentation for tempo-define-template for the different
57 ;; items that can be used to define a tempo template.
59 ;; One of the more powerful features of tempo templates are automatic
60 ;; completion. With every template can be assigned a special tag that
61 ;; should be recognized by `tempo-complete-tag' and expanded to the
62 ;; complete template. By default the tags are added to a global list
63 ;; of template tags, and are matched against the last word before
64 ;; point. But if you assign your tags to a specific list, you can also
65 ;; specify another method for matching text in the buffer against the
66 ;; tags. In the HTML mode, for instance, the tags are matched against
67 ;; the text between the last `<' and point.
69 ;; When defining a template named `foo', a symbol named
70 ;; `tempo-template-foo' will be created whose value as a variable will
71 ;; be the template definition, and its function value will be an
72 ;; interactive function that inserts the template at the point.
74 ;; The latest tempo.el distribution can be fetched from
75 ;; ftp.lysator.liu.se in the directory /pub/emacs
77 ;; There is also a WWW page at
78 ;; http://www.lysator.liu.se/~davidk/elisp/ which has some information
82 ;; If the 'o is the first element in a template, strange things can
83 ;; happen when the template is inserted at the beginning of a
84 ;; line. This is due to strange behavior in open-line. But it should
87 ;; The 'o tag is also a problem when including the region. This will
90 ;; Clicking mouse-2 in the completion buffer gives strange results.
92 ;; There is a bug in some emacs versions that prevents completion from
93 ;; working. If it doesn't work for you, send me a note indicating your
94 ;; emacs version and your problems.
98 ;; These people have given me important feedback and new ideas for
101 ;; Nelson Minar <nelson@santafe.edu>
102 ;; Richard Stallman <rms@gnu.org>
103 ;; Lars Lindberg <Lars.Lindberg@sypro.cap.se>
104 ;; Glen Whitney <Glen.Whitney@math.lsa.umich.edu>
111 "Flexible template insertion."
115 (defcustom tempo-interactive nil
116 "Prompt user for strings in templates.
117 If this variable is non-nil, `tempo-insert' prompts the
118 user for text to insert in the templates."
122 (defcustom tempo-insert-region nil
123 "Automatically insert current region when there is a `r' in the template
124 If this variable is nil, `r' elements will be treated just like `p'
125 elements, unless the template function is given a prefix (or a non-nil
126 argument). If this variable is non-nil, the behavior is reversed.
128 In Transient Mark mode, this option is unused."
132 (defcustom tempo-show-completion-buffer t
133 "If non-nil, show a buffer with possible completions, when only
134 a partial completion can be found."
138 (defcustom tempo-leave-completion-buffer nil
139 "If nil, a completion buffer generated by \\[tempo-complete-tag]
140 disappears at the next keypress; otherwise, it remains forever."
144 ;;; Internal variables
146 (defvar tempo-insert-string-functions nil
147 "List of functions to run when inserting a string.
148 Each function is called with a single arg, STRING and should return
149 another string. This could be used for making all strings upcase by
150 setting it to (upcase), for example.")
152 (defvar tempo-tags nil
153 "An association list with tags and corresponding templates.")
155 (defvar-local tempo-local-tags
'((tempo-tags . nil
))
156 "A list of locally installed tag completion lists.
157 It is an association list where the car of every element is a symbol
158 whose variable value is a template list. The cdr part, if non-nil,
159 is a function or a regexp that defines the string to match. See the
160 documentation for the function `tempo-complete-tag' for more info.
162 `tempo-tags' is always in the last position in this list.")
164 (defvar-local tempo-collection nil
165 "A collection of all the tags defined for the current buffer.")
167 (defvar-local tempo-dirty-collection t
168 "Indicates if the tag collection needs to be rebuilt.")
170 (defvar-local tempo-marks nil
171 "A list of marks to jump to with `\\[tempo-forward-mark]' and `\\[tempo-backward-mark]'.")
173 (defvar-local tempo-match-finder
"\\b\\([[:word:]]+\\)\\="
174 "The regexp or function used to find the string to match against tags.
176 If `tempo-match-finder' is a string, it should contain a regular
177 expression with at least one \\( \\) pair. When searching for tags,
178 `tempo-complete-tag' calls `re-search-backward' with this string, and
179 the string between the first \\( and \\) is used for matching against
180 each string in the tag list. If one is found, the whole text between
181 the first \\( and the point is replaced with the inserted template.
183 You will probably want to include \\=\\= at the end of the regexp to
184 make sure that the string is matched only against text adjacent to the
187 If `tempo-match-finder' is a symbol, it should be a function that
188 returns a pair of the form (STRING . POS), where STRING is the string
189 used for matching and POS is the buffer position after which text
190 should be replaced with a template.")
192 (defvar tempo-user-elements nil
193 "Element handlers for user-defined elements.
194 A list of symbols which are bound to functions that take one argument.
195 This function should return something to be sent to `tempo-insert' if
196 it recognizes the argument, and nil otherwise.")
198 (defvar-local tempo-named-insertions nil
199 "Temporary storage for named insertions.")
201 (defvar-local tempo-region-start
(make-marker)
202 "Region start when inserting around the region.")
204 (defvar-local tempo-region-stop
(make-marker)
205 "Region stop when inserting around the region.")
210 ;; tempo-define-template
212 (defun tempo-define-template (name elements
&optional tag documentation taglist
)
214 This function creates a template variable `tempo-template-NAME' and an
215 interactive function `tempo-template-NAME' that inserts the template
216 at the point. The created function is returned.
218 NAME is a string that contains the name of the template, ELEMENTS is a
219 list of elements in the template, TAG is the tag used for completion,
220 DOCUMENTATION is the documentation string for the insertion command
221 created, and TAGLIST (a symbol) is the tag list that TAG (if provided)
222 should be added to. If TAGLIST is nil and TAG is non-nil, TAG is
223 added to `tempo-tags'.
225 The elements in ELEMENTS can be of several types:
227 - A string: It is sent to the hooks in `tempo-insert-string-functions',
228 and the result is inserted.
229 - The symbol `p': This position is saved in `tempo-marks'.
230 - The symbol `r': If `tempo-insert' is called with ON-REGION non-nil
231 the current region is placed here. Otherwise it works like `p'.
232 - (p PROMPT <NAME> <NOINSERT>): If `tempo-interactive' is non-nil, the
233 user is prompted in the minibuffer with PROMPT for a string to be
234 inserted. If the optional parameter NAME is non-nil, the text is
235 saved for later insertion with the `s' tag. If there already is
236 something saved under NAME that value is used instead and no
237 prompting is made. If NOINSERT is provided and non-nil, nothing is
238 inserted, but text is still saved when a NAME is provided. For
239 clarity, the symbol `noinsert' should be used as argument.
240 - (P PROMPT <NAME> <NOINSERT>): Works just like the previous tag, but
241 forces `tempo-interactive' to be true.
242 - (r PROMPT <NAME> <NOINSERT>): Like the previous tag, but if
243 `tempo-interactive' is nil and `tempo-insert' is called with
244 ON-REGION non-nil, the current region is placed here. This usually
245 happens when you call the template function with a prefix argument.
246 - (s NAME): Inserts text previously read with the (p ..) construct.
247 Finds the insertion saved under NAME and inserts it. Acts like `p'
248 if tempo-interactive is nil.
249 - `&': If there is only whitespace between the line start and point,
250 nothing happens. Otherwise a newline is inserted.
251 - `%': If there is only whitespace between point and end of line,
252 nothing happens. Otherwise a newline is inserted.
253 - `n': Inserts a newline.
254 - `>': The line is indented using `indent-according-to-mode'. Note
255 that you often should place this item after the text you want on
257 - `r>': Like `r', but it also indents the region.
258 - (r> PROMPT <NAME> <NOINSERT>): Like (r ...), but is also indents
260 - `n>': Inserts a newline and indents line.
261 - `o': Like `%' but leaves the point before the newline.
262 - nil: It is ignored.
263 - Anything else: Each function in `tempo-user-elements' is called
264 with it as argument until one of them returns non-nil, and the
265 result is inserted. If all of them return nil, it is evaluated and
266 the result is treated as an element to be inserted. One additional
267 tag is useful for these cases. If an expression returns a list (l
268 foo bar), the elements after `l' will be inserted according to the
269 usual rules. This makes it possible to return several elements
270 from one expression."
271 (let* ((template-name (intern (concat "tempo-template-"
273 (command-name template-name
))
274 (set template-name elements
)
275 (fset command-name
(list 'lambda
(list '&optional
'arg
)
277 (concat "Insert a " name
"."))
278 (list 'interactive
"*P")
279 (list 'tempo-insert-template
(list 'quote
281 (list 'if
'tempo-insert-region
282 (list 'not
'arg
) 'arg
))))
284 (tempo-add-tag tag template-name taglist
))
288 ;;; tempo-insert-template
290 (defun tempo-insert-template (template on-region
)
292 TEMPLATE is the template to be inserted. If ON-REGION is non-nil the
293 `r' elements are replaced with the current region. In Transient Mark
294 mode, ON-REGION is ignored and assumed true if the region is active."
297 (if (or (and transient-mark-mode
301 (set-marker tempo-region-start
(min (mark) (point)))
302 (set-marker tempo-region-stop
(max (mark) (point))))
304 (goto-char tempo-region-start
))
306 (tempo-insert-mark (point-marker))
307 (mapc (function (lambda (elt)
308 (tempo-insert elt on-region
)))
309 (symbol-value template
))
310 (tempo-insert-mark (point-marker)))
311 (tempo-forward-mark))
312 (tempo-forget-insertions)
313 (and transient-mark-mode
319 (defun tempo-insert (element on-region
)
320 "Insert a template element.
321 Insert one element from a template. If ON-REGION is non-nil the `r'
322 elements are replaced with the current region.
324 See documentation for `tempo-define-template' for the kind of elements
326 (cond ((stringp element
) (tempo-process-and-insert-string element
))
327 ((and (consp element
)
328 (eq (car element
) 'p
)) (tempo-insert-prompt-compat
330 ((and (consp element
)
331 (eq (car element
) 'P
)) (let ((tempo-interactive t
))
332 (tempo-insert-prompt-compat
334 ;;; ((and (consp element)
335 ;;; (eq (car element) 'v)) (tempo-save-named
338 ;;; (nth 2 element)))
339 ((and (consp element
)
340 (eq (car element
) 'r
)) (if on-region
341 (goto-char tempo-region-stop
)
342 (tempo-insert-prompt-compat
344 ((and (consp element
)
345 (eq (car element
) 'r
>)) (if on-region
347 (goto-char tempo-region-stop
)
348 (indent-region (mark) (point) nil
))
349 (tempo-insert-prompt-compat
351 ((and (consp element
)
352 (eq (car element
) 's
)) (tempo-insert-named (car (cdr element
))))
353 ((and (consp element
)
354 (eq (car element
) 'l
)) (mapcar (function
356 (tempo-insert elt on-region
)))
358 ((eq element
'p
) (tempo-insert-mark (point-marker)))
359 ((eq element
'r
) (if on-region
360 (goto-char tempo-region-stop
)
361 (tempo-insert-mark (point-marker))))
362 ((eq element
'r
>) (if on-region
364 (goto-char tempo-region-stop
)
365 (indent-region (mark) (point) nil
))
366 (tempo-insert-mark (point-marker))))
367 ((eq element
'>) (indent-according-to-mode))
368 ((eq element
'&) (if (not (or (= (current-column) 0)
371 "^\\s-*\\=" nil t
))))
373 ((eq element
'%
) (if (not (or (eolp)
376 "\\=\\s-*$" nil t
))))
378 ((eq element
'n
) (insert "\n"))
379 ((eq element
'n
>) (insert "\n") (indent-according-to-mode))
380 ;; Bug: If the 'o is the first element in a template, strange
381 ;; things can happen when the template is inserted at the
382 ;; beginning of a line.
383 ((eq element
'o
) (if (not (or on-region
387 "\\=\\s-*$" nil t
))))
390 (t (tempo-insert (or (tempo-is-user-element element
)
395 ;;; tempo-insert-prompt
397 (defun tempo-insert-prompt-compat (prompt)
398 "Compatibility hack for `tempo-insert-prompt'.
399 PROMPT can be either a prompt string, or a list of arguments to
400 `tempo-insert-prompt', or nil."
401 (if (consp prompt
) ; not nil either
402 (apply 'tempo-insert-prompt prompt
)
403 (tempo-insert-prompt prompt
)))
405 (defun tempo-insert-prompt (prompt &optional save-name no-insert
)
406 "Prompt for a text string and insert it in the current buffer.
407 If the variable `tempo-interactive' is non-nil the user is prompted
408 for a string in the minibuffer, which is then inserted in the current
409 buffer. If `tempo-interactive' is nil, the current point is placed on
412 PROMPT is the prompt string, SAVE-NAME is a name to save the inserted
413 text under. If the optional argument NO-INSERT is non-nil, no text is
414 inserted. This can be useful when there is a SAVE-NAME.
416 If there already is a value for SAVE-NAME, it is used and the user is
419 (previous (and save-name
420 (tempo-lookup-named save-name
))))
422 ;; Insert previous value, unless no-insert is non-nil
425 (tempo-insert-named save-name
)) ; A double lookup here, but who
427 ;; If no-insert is non-nil, don't insert the previous value. Just
431 ;; No previous value. Prompt or insert mark
433 (if (not (stringp prompt
))
434 (error "tempo: The prompt (%s) is not a string" prompt
))
435 (setq insertion
(read-string prompt
))
439 (tempo-save-named save-name insertion
)))
441 (tempo-insert-mark (point-marker))))))
444 ;;; tempo-is-user-element
446 (defun tempo-is-user-element (element)
447 "Tries all the user-defined element handlers in `tempo-user-elements'."
448 ;; Sigh... I need (some list)
450 (mapc (function (lambda (handler)
451 (let ((result (funcall handler element
)))
452 (if result
(throw 'found result
)))))
457 ;;; tempo-forget-insertions
459 (defun tempo-forget-insertions ()
460 "Forget all the saved named insertions."
461 (setq tempo-named-insertions nil
))
466 (defun tempo-save-named (name data
) ; Had an optional prompt for 'v
467 "Save some data for later insertion
468 The contents of DATA is saved under the name NAME.
470 The data can later be retrieved with `tempo-lookup-named'.
472 This function returns nil, so it can be used in a template without
474 (setq tempo-named-insertions
475 (cons (cons name data
)
476 tempo-named-insertions
))
480 ;;; tempo-lookup-named
482 (defun tempo-lookup-named (name)
483 "Lookup some saved data under the name NAME.
484 Returns the data if NAME was found, and nil otherwise."
485 (cdr (assq name tempo-named-insertions
)))
488 ;;; tempo-insert-named
490 (defun tempo-insert-named (name)
491 "Insert the previous insertion saved under a named specified in NAME.
492 If there is no such name saved, a tempo mark is inserted.
494 Note that if the data is a string, it will not be run through the string
496 (let* ((insertion (tempo-lookup-named name
)))
497 (cond ((null insertion
)
498 (tempo-insert-mark (point-marker)))
502 (tempo-insert insertion nil
)))))
506 ;;; tempo-process-and-insert-string
508 (defun tempo-process-and-insert-string (string)
509 "Insert a string from a template.
510 Run a string through the preprocessors in `tempo-insert-string-functions'
511 and insert the results."
512 (cond ((null tempo-insert-string-functions
)
514 ((symbolp tempo-insert-string-functions
)
516 (funcall tempo-insert-string-functions string
)))
517 ((listp tempo-insert-string-functions
)
518 (dolist (fn tempo-insert-string-functions
)
519 (setq string
(funcall fn string
))))
521 (error "Bogus value in tempo-insert-string-functions: %s"
522 tempo-insert-string-functions
)))
526 ;;; tempo-insert-mark
528 (defun tempo-insert-mark (mark)
529 "Insert a mark `tempo-marks' while keeping it sorted."
530 (cond ((null tempo-marks
) (setq tempo-marks
(list mark
)))
531 ((< mark
(car tempo-marks
)) (setq tempo-marks
(cons mark tempo-marks
)))
532 (t (let ((lp tempo-marks
))
534 (<= (car (cdr lp
)) mark
))
536 (if (not (= mark
(car lp
)))
537 (setcdr lp
(cons mark
(cdr lp
))))))))
540 ;;; tempo-forward-mark
542 (defun tempo-forward-mark ()
543 "Jump to the next mark in `tempo-forward-mark-list'."
545 (let ((next-mark (catch 'found
550 (throw 'found mark
))))
552 ;; return nil if not found
555 (goto-char next-mark
))))
558 ;;; tempo-backward-mark
560 (defun tempo-backward-mark ()
561 "Jump to the previous mark in `tempo-back-mark-list'."
563 (let ((prev-mark (catch 'found
568 (if (<= (point) mark
)
574 (goto-char prev-mark
))))
579 (defun tempo-add-tag (tag template
&optional tag-list
)
581 Add the TAG, that should complete to TEMPLATE to the list in TAG-LIST,
582 or to `tempo-tags' if TAG-LIST is nil."
584 (interactive "sTag: \nCTemplate: ")
586 (setq tag-list
'tempo-tags
))
587 (if (not (assoc tag
(symbol-value tag-list
)))
588 (set tag-list
(cons (cons tag template
) (symbol-value tag-list
))))
589 (tempo-invalidate-collection))
592 ;;; tempo-use-tag-list
594 (defun tempo-use-tag-list (tag-list &optional completion-function
)
595 "Install TAG-LIST to be used for template completion in the current buffer.
596 TAG-LIST is a symbol whose variable value is a tag list created with
599 COMPLETION-FUNCTION is an obsolete option for specifying an optional
600 function or string that is used by `\\[tempo-complete-tag]' to find a
601 string to match the tag against. It has the same definition as the
602 variable `tempo-match-finder'. In this version, supplying a
603 COMPLETION-FUNCTION just sets `tempo-match-finder' locally."
604 (setf (alist-get tag-list tempo-local-tags
) completion-function
)
605 (if completion-function
606 (setq tempo-match-finder completion-function
))
607 (tempo-invalidate-collection))
610 ;;; tempo-invalidate-collection
612 (defun tempo-invalidate-collection ()
613 "Marks the tag collection as obsolete.
614 Whenever it is needed again it will be rebuilt."
615 (setq tempo-dirty-collection t
))
618 ;;; tempo-build-collection
620 (defun tempo-build-collection ()
621 "Build a collection of all the tags and return it.
622 If `tempo-dirty-collection' is nil, the old collection is reused."
624 (or (and (not tempo-dirty-collection
)
626 (setq tempo-collection
627 (apply (function append
)
628 (mapcar (function (lambda (tag-list)
630 ; tempo-local-tags changes,
632 (eval (car tag-list
))))
634 (setq tempo-dirty-collection nil
)))
637 ;;; tempo-find-match-string
639 (defun tempo-find-match-string (finder)
640 "Find a string to be matched against a tag list.
641 FINDER is a function or a string. Returns (STRING . POS), or nil
642 if no reasonable string is found."
643 (cond ((stringp finder
)
646 (or (setq successful
(re-search-backward finder nil t
))
649 (cons (buffer-substring (match-beginning 1)
650 (match-end 1)) ; This seems to be a
658 ;;; tempo-complete-tag
660 (defun tempo-complete-tag (&optional silent
)
661 "Look for a tag and expand it.
662 All the tags in the tag lists in `tempo-local-tags'
663 \(this includes `tempo-tags') are searched for a match for the text
664 before the point. The way the string to match for is determined can
665 be altered with the variable `tempo-match-finder'. If
666 `tempo-match-finder' returns nil, then the results are the same as
669 If a single match is found, the corresponding template is expanded in
670 place of the matching string.
672 If a partial completion or no match at all is found, and SILENT is
673 non-nil, the function will give a signal.
675 If a partial completion is found and `tempo-show-completion-buffer' is
676 non-nil, a buffer containing possible completions is displayed."
678 ;; This function may look like a hack, but this is how I want it to
681 (let* ((collection (tempo-build-collection))
682 (match-info (tempo-find-match-string tempo-match-finder
))
683 (match-string (car match-info
))
684 (match-start (cdr match-info
))
685 (exact (assoc match-string collection
))
686 (compl (or (car exact
)
687 (and match-info
(try-completion match-string collection
)))))
688 (if compl
(delete-region match-start
(point)))
689 (cond ((null match-info
) (or silent
(ding)))
690 ((null compl
) (or silent
(ding)))
691 ((eq compl t
) (tempo-insert-template
692 (cdr (assoc match-string
695 (t (if (setq exact
(assoc compl collection
))
696 (tempo-insert-template (cdr exact
) nil
)
699 (if tempo-show-completion-buffer
700 (tempo-display-completions match-string
705 ;;; tempo-display-completions
707 (defun tempo-display-completions (string tag-list
)
708 "Show a buffer containing possible completions for STRING."
709 (if tempo-leave-completion-buffer
710 (with-output-to-temp-buffer "*Completions*"
711 (display-completion-list
712 (completion-hilit-commonality (all-completions string tag-list
)
714 (save-window-excursion
715 (with-output-to-temp-buffer "*Completions*"
716 (display-completion-list
717 (completion-hilit-commonality (all-completions string tag-list
)
722 ;;; tempo-expand-if-complete
724 (defun tempo-expand-if-complete ()
725 "Expand the tag before point if it is complete.
726 Returns non-nil if an expansion was made and nil otherwise.
728 This could as an example be used in a command that is bound to the
729 space bar, and looks something like this:
731 \(defun tempo-space ()
733 (or (tempo-expand-if-complete)
737 (let* ((collection (tempo-build-collection))
738 (match-info (tempo-find-match-string tempo-match-finder
))
739 (match-string (car match-info
))
740 (match-start (cdr match-info
))
741 (exact (assoc match-string collection
)))
744 (delete-region match-start
(point))
745 (tempo-insert-template (cdr exact
) nil
)
751 ;;; tempo.el ends here