1 ;;; tempo.el --- Flexible template insertion
2 ;; Copyright (C) 1994, 1995 Free Software Foundation, Inc.
4 ;; Author: David K}gedal <davidk@lysator.liu.se >
5 ;; Created: 16 Feb 1994
7 ;; Keywords: 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 2, or (at your option)
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; see the file COPYING. If not, write to
24 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
28 ;; This file provides a simple way to define powerful templates, or
29 ;; macros, if you wish. It is mainly intended for, but not limited to,
30 ;; other programmers to be used for creating shortcuts for editing
31 ;; certain kind of documents. It was originally written to be used by
32 ;; a HTML editing mode written by Nelson Minar <nelson@santafe.edu>,
33 ;; and his html-helper-mode.el is probably the best example of how to
36 ;; A template is defined as a list of items to be inserted in the
37 ;; current buffer at point. Some of the items can be simple strings,
38 ;; while other can control formatting or define special points of
39 ;; interest in the inserted text.
41 ;; If a template defines a "point of interest" that point is inserted
42 ;; in a buffer-local list of "points of interest" that the user can
43 ;; jump between with the commands `tempo-backward-mark' and
44 ;; `tempo-forward-mark'. If the template definer provides a prompt for
45 ;; the point, and the variable `tempo-interactive' is non-nil, the
46 ;; user will be prompted for a string to be inserted in the buffer,
47 ;; using the minibuffer.
49 ;; The template can also define one point to be replaced with the
50 ;; current region if the template command is called with a prefix (or
51 ;; a non-nil argument).
53 ;; More flexible templates can be created by including lisp symbols,
54 ;; which will be evaluated as variables, or lists, which will will be
55 ;; evaluated as lisp expressions.
57 ;; See the documentation for tempo-define-template for the different
58 ;; items that can be used to define a tempo template.
60 ;; One of the more powerful features of tempo templates are automatic
61 ;; completion. With every template can be assigned a special tag that
62 ;; should be recognized by `tempo-complete-tag' and expanded to the
63 ;; complete template. By default the tags are added to a global list
64 ;; of template tags, and are matched against the last word before
65 ;; point. But if you assign your tags to a specific list, you can also
66 ;; specify another method for matching text in the buffer against the
67 ;; tags. In the HTML mode, for instance, the tags are matched against
68 ;; the text between the last `<' and point.
70 ;; When defining a template named `foo', a symbol named
71 ;; `tempo-template-foo' will be created whose value as a variable will
72 ;; be the template definition, and its function value will be an
73 ;; interactive function that inserts the template at the point.
75 ;; The latest tempo.el distribution can be fetched from
76 ;; ftp.lysator.liu.se in the directory /pub/emacs
80 ;; If the 'o is the first element in a template, strange things can
81 ;; happen when the template is inserted at the beginning of a
82 ;; line. This is due to strange behaviour in open-line. But it should
85 ;; The 'o tag is also a problem when including the region. This will
88 ;; Clicking mouse-2 in the completion buffer gives strange results.
90 ;; There is a bug in some emacs versions that prevents completion from
91 ;; working. If it doesn't work for you, send me a note indicating your
92 ;; emacs version and your problems.
96 ;; These people have given me importand feedback and new ideas for
99 ;; Nelson Minar <nelson@santafe.edu>
100 ;; Richard Stallman <rms@gnu.ai.mit.edu>
101 ;; Lars Lindberg <Lars.Lindberg@sypro.cap.se>
102 ;; Glen Whitney <Glen.Whitney@math.lsa.umich.edu>
110 (defvar tempo-interactive nil
111 "*Prompt user for strings in templates.
112 If this variable is non-nil, `tempo-insert' prompts the
113 user for text to insert in the templates")
115 (defvar tempo-insert-region nil
116 "*Automatically insert current region when there is a `r' in the template
117 If this variable is NIL, `r' elements will be treated just like `p'
118 elements, unless the template function is given a prefix (or a non-nil
119 argument). If this variable is non-NIL, the behaviour is reversed.
121 In Transient Mark mode, this option is unused.")
123 (defvar tempo-show-completion-buffer t
124 "*If non-NIL, show a buffer with possible completions, when only
125 a partial completion can be found")
127 (defvar tempo-leave-completion-buffer nil
128 "*If NIL, a completion buffer generated by \\[tempo-complete-tag]
129 disappears at the next keypress; otherwise, it remains forever.")
131 ;;; Internal variables
133 (defvar tempo-insert-string-functions nil
134 "List of functions to run when inserting a string.
135 Each function is called with a single arg, STRING." )
137 (defvar tempo-tags nil
138 "An association list with tags and corresponding templates")
140 (defvar tempo-local-tags '((tempo-tags . nil))
141 "A list of locally installed tag completion lists.
142 It is a association list where the car of every element is a symbol
143 whose varable value is a template list. The cdr part, if non-nil, is a
144 function or a regexp that defines the string to match. See the
145 documentation for the function `tempo-complete-tag' for more info.
147 `tempo-tags' is always in the last position in this list.")
149 (defvar tempo-collection nil
150 "A collection of all the tags defined for the current buffer.")
152 (defvar tempo-dirty-collection t
153 "Indicates if the tag collection needs to be rebuilt.")
155 (defvar tempo-marks nil
156 "A list of marks to jump to with `\\[tempo-forward-mark]' and `\\[tempo-backward-mark]'.")
158 (defvar tempo-match-finder "\\b\\([^\\b]+\\)\\="
159 "The regexp or function used to find the string to match against tags.
161 If `tempo-match-finder is a string, it should contain a regular
162 expression with at least one \\( \\) pair. When searching for tags,
163 `tempo-complete-tag' calls `re-search-backward' with this string, and
164 the string between the first \\( and \\) is used for matching against
165 each string in the tag list. If one is found, the whole text between
166 the first \\( and the point is replaced with the inserted template.
168 You will probably want to include \\ \= at the end of the regexp to
169 make sure that the string is matched only against text adjacent to the
172 If `tempo-match-finder' is a symbol, it should be a function that
173 returns a pair of the form (STRING . POS), where STRING is the string
174 used for matching and POS is the buffer position after which text
175 should be replaced with a template.")
177 (defvar tempo-user-elements nil
178 "Element handlers for user-defined elements.
179 A list of symbols which are bound to functions that take one argument.
180 This function should return somthing to be sent to `tempo-insert' if
181 it recognizes the argument, and NIL otherwise")
183 (defvar tempo-named-insertions nil
184 "Temporary storage for named insertions")
186 (defvar tempo-region-start (make-marker)
187 "Region start when inserting around the region")
189 (defvar tempo-region-stop (make-marker)
190 "Region stop when inserting around the region")
192 ;; Make some variables local to every buffer
194 (make-variable-buffer-local 'tempo-marks)
195 (make-variable-buffer-local 'tempo-local-tags)
196 (make-variable-buffer-local 'tempo-match-finder)
197 (make-variable-buffer-local 'tempo-collection)
198 (make-variable-buffer-local 'tempo-dirty-collection)
202 ;;; First some useful functions and macros
204 (defun tempo-mapc (fun lst)
206 (funcall fun (car lst))
207 (tempo-mapc fun (cdr lst))))
209 (defmacro tempo-dolist (il &rest forms)
213 (list 'function (append (list 'lambda
217 (put 'tempo-dolist 'lisp-indent-function 1)
220 ;; tempo-define-template
222 (defun tempo-define-template (name elements &optional tag documentation taglist)
224 This function creates a template variable `tempo-template-NAME' and an
225 interactive function `tempo-template-NAME' that inserts the template
226 at the point. The created function is returned.
228 NAME is a string that contains the name of the template, ELEMENTS is a
229 list of elements in the template, TAG is the tag used for completion,
230 DOCUMENTATION is the documentation string for the insertion command
231 created, and TAGLIST (a symbol) is the tag list that TAG (if provided)
232 should be added to). If TAGLIST is nil and TAG is non-nil, TAG is
233 added to `tempo-tags'
235 The elements in ELEMENTS can be of several types:
237 - A string. It is sent to the hooks in `tempo-insert-string-functions',
238 and the result is inserted.
239 - The symbol 'p. This position is saved in `tempo-marks'.
240 - The symbol 'r. If `tempo-insert' is called with ON-REGION non-nil
241 the current region is placed here. Otherwise it works like 'p.
242 - (p PROMPT <NAME>) If `tempo-interactive' is non-nil, the user is
243 prompted in the minbuffer with PROMPT for a string to be inserted.
244 If the optional parameter NAME is non-nil, the text is saved for
245 later insertion with the `s' tag.
246 If `tempo-interactive' is nil, it works like 'p.
247 - (r PROMPT) like the previous, but if `tempo-interactive' is nil
248 and `tempo-insert' is called with ON-REGION non-nil, the current
249 region is placed here. This usually happens when you call the
250 template function with a prefix argument.
251 - (s NAME) Inserts text previously read with the (p ..) construct.
252 Finds the insertion saved under NAME and inserts it. Acts like 'p
253 if tempo-interactive is nil.
254 - '& If there is only whitespace between the line start and point,
255 nothing happens. Otherwise a newline is inserted.
256 - '% If there is only whitespace between point and end-of-line
257 nothing happens. Otherwise a newline is inserted.
258 - 'n inserts a newline.
259 - '> The line is indented using `indent-according-to-mode'. Note that
260 you often should place this item after the text you want on the
262 - 'n> Inserts a newline and indents line.
263 - 'o Like '% but leaves the point before the newline.
264 - nil. It is ignored.
265 - Anything else. It is evaluated and the result is parsed again."
267 (let* ((template-name (intern (concat "tempo-template-"
269 (command-name template-name))
270 (set template-name elements)
271 (fset command-name (list 'lambda (list '&optional 'arg)
273 (concat "Insert a " name "."))
274 (list 'interactive "*P")
275 (list 'tempo-insert-template (list 'quote
277 (list 'if 'tempo-insert-region
278 (list 'not 'arg) 'arg))))
280 (tempo-add-tag tag template-name taglist))
284 ;;; tempo-insert-template
286 (defun tempo-insert-template (template on-region)
288 TEMPLATE is the template to be inserted. If ON-REGION is non-nil the
289 `r' elements are replaced with the current region. In Transient Mark
290 mode, ON-REGION is ignored and assumed true if the region is active."
291 (if (and (boundp 'transient-mark-mode)
296 (set-marker tempo-region-start (min (mark) (point)))
297 (set-marker tempo-region-stop (max (mark) (point))))
299 (goto-char tempo-region-start))
301 (tempo-insert-mark (point-marker))
302 (mapcar (function (lambda (elt)
303 (tempo-insert elt on-region)))
304 (symbol-value template))
305 (tempo-insert-mark (point-marker)))
307 (tempo-forget-insertions)
308 (and (boundp 'transient-mark-mode)
315 (defun tempo-insert (element on-region)
316 "Insert a template element.
317 Insert one element from a template. If ON-REGION is non-nil the `r'
318 elements are replaced with the current region.
320 See documentation for `tempo-define-template' for the kind of elements
322 (cond ((stringp element) (tempo-process-and-insert-string element))
323 ((and (consp element) (eq (car element) 'p))
324 (tempo-insert-prompt (cdr element)))
325 ((and (consp element) (eq (car element) 'P))
326 (let ((tempo-interactive t))
327 (tempo-insert-prompt (cdr element))))
328 ((and (consp element) (eq (car element) 'r))
330 (goto-char tempo-region-stop)
331 (tempo-insert-prompt (cdr element))))
332 ((and (consp element) (eq (car element) 's))
333 (tempo-insert-named (car (cdr element))))
334 ((and (consp element) (eq (car element) 'l))
335 (mapcar (function (lambda (elt) (tempo-insert elt on-region)))
337 ((eq element 'p) (tempo-insert-mark (point-marker)))
338 ((eq element 'r) (if on-region
339 (goto-char tempo-region-stop)
340 (tempo-insert-mark (point-marker))))
341 ((eq element 'r>) (if on-region
343 (goto-char tempo-region-stop)
344 (indent-region (mark) (point) nil))
345 (tempo-insert-mark (point-marker))))
346 ((eq element '>) (indent-according-to-mode))
347 ((eq element '&) (if (not (or (= (current-column) 0)
350 "^\\s-*\\=" nil t))))
352 ((eq element '%) (if (not (or (eolp)
355 "\\=\\s-*$" nil t))))
357 ((eq element 'n) (insert "\n"))
358 ((eq element 'n>) (insert "\n") (indent-according-to-mode))
359 ;; Bug: If the 'o is the first element in a template, strange
360 ;; things can happen when the template is inserted at the
361 ;; beginning of a line.
362 ((eq element 'o) (if (not (or on-region
366 "\\=\\s-*$" nil t))))
369 (t (tempo-insert (or (tempo-is-user-element element)
374 ;;; tempo-insert-prompt
376 (defun tempo-insert-prompt (prompt)
377 "Prompt for a text string and insert it in the current buffer.
378 If the variable `tempo-interactive' is non-nil the user is prompted
379 for a string in the minibuffer, which is then inserted in the current
380 buffer. If `tempo-interactive' is nil, the current point is placed on
383 PROMPT is the prompt string or a list containing the prompt string and
384 a name to save the inserted text under."
385 (if tempo-interactive
386 (let ((prompt-string (if (listp prompt)
389 (save-name (and (listp prompt) (nth 1 prompt)))
393 (setq inserted-text (read-string prompt-string))
394 (insert inserted-text)
396 (tempo-remember-insertion save-name inserted-text))))
397 (tempo-insert-mark (point-marker))))
400 ;;; tempo-is-user-element
402 (defun tempo-is-user-element (element)
403 "Tries all the user-defined element handlers in
404 `tempo-user-elements'"
405 ;; Sigh... I need (some list)
407 (mapcar (function (lambda (handler)
408 (let ((result (funcall handler element)))
409 (if result (throw 'found result)))))
414 ;;; tempo-remember-insertion
416 (defun tempo-remember-insertion (save-name string)
417 "Save the text in STRING under the name SAVE-NAME for later retrieval."
418 (setq tempo-named-insertions (cons (cons save-name string)
419 tempo-named-insertions)))
422 ;;; tempo-forget-insertions
424 (defun tempo-forget-insertions ()
425 "Forget all the saved named insertions."
426 (setq tempo-named-insertions nil))
429 ;;; tempo-insert-named
431 (defun tempo-insert-named (name)
432 "Insert the previous insertion saved under a named specified in NAME.
433 If there is no such name saved, a tempo mark is inserted."
434 (let* ((insertion (cdr (assq name tempo-named-insertions))))
437 (tempo-insert-mark (point-marker)))))
440 ;;; tempo-process-and-insert-string
442 (defun tempo-process-and-insert-string (string)
443 "Insert a string from a template.
444 Run a string through the preprocessors in `tempo-insert-string-functions'
445 and insert the results."
446 (cond ((null tempo-insert-string-functions)
448 ((symbolp tempo-insert-string-functions)
450 (funcall tempo-insert-string-functions string)))
451 ((listp tempo-insert-string-functions)
452 (tempo-dolist (fn tempo-insert-string-functions)
453 (setq string (funcall fn string))))
455 (error "Bogus value in tempo-insert-string-functions: %s"
456 tempo-insert-string-functions)))
460 ;;; tempo-insert-mark
462 (defun tempo-insert-mark (mark)
463 "Insert a mark `tempo-marks' while keeping it sorted"
464 (cond ((null tempo-marks) (setq tempo-marks (list mark)))
465 ((< mark (car tempo-marks)) (setq tempo-marks (cons mark tempo-marks)))
466 (t (let ((lp tempo-marks))
468 (<= (car (cdr lp)) mark))
470 (if (not (= mark (car lp)))
471 (setcdr lp (cons mark (cdr lp))))))))
474 ;;; tempo-forward-mark
476 (defun tempo-forward-mark ()
477 "Jump to the next mark in `tempo-forward-mark-list'."
479 (let ((next-mark (catch 'found
484 (throw 'found mark))))
486 ;; return nil if not found
489 (goto-char next-mark))))
492 ;;; tempo-backward-mark
494 (defun tempo-backward-mark ()
495 "Jump to the previous mark in `tempo-back-mark-list'."
497 (let ((prev-mark (catch 'found
502 (if (<= (point) mark)
508 (goto-char prev-mark))))
513 (defun tempo-add-tag (tag template &optional tag-list)
515 Add the TAG, that should complete to TEMPLATE to the list in TAG-LIST,
516 or to `tempo-tags' if TAG-LIST is nil."
518 (interactive "sTag: \nCTemplate: ")
520 (setq tag-list 'tempo-tags))
521 (if (not (assoc tag (symbol-value tag-list)))
522 (set tag-list (cons (cons tag template) (symbol-value tag-list))))
523 (tempo-invalidate-collection))
526 ;;; tempo-use-tag-list
528 (defun tempo-use-tag-list (tag-list &optional completion-function)
529 "Install TAG-LIST to be used for template completion in the current buffer.
530 TAG-LIST is a symbol whose variable value is a tag list created with
533 COMPLETION-FUNCTION is an obsolete option for specifyingis an optional
534 function or string that is used by `\\[tempo-complete-tag]' to find a
535 string to match the tag against. It has the same definition as the
536 variable `tempo-match-finder'. In this version, supplying a
537 COMPLETION-FUNCTION just sets `tempo-match-finder' locally."
538 (let ((old (assq tag-list tempo-local-tags)))
540 (setcdr old completion-function)
541 (setq tempo-local-tags (cons (cons tag-list completion-function)
543 (if completion-function
544 (setq tempo-match-finder completion-function))
545 (tempo-invalidate-collection))
548 ;;; tempo-invalidate-collection
550 (defun tempo-invalidate-collection ()
551 "Marks the tag collection as obsolete.
552 Whenever it is needed again it will be rebuilt."
553 (setq tempo-dirty-collection t))
556 ;;; tempo-build-collection
558 (defun tempo-build-collection ()
559 "Build a collection of all the tags and return it.
560 If `tempo-dirty-collection' is NIL, the old collection is reused."
562 (or (and (not tempo-dirty-collection)
564 (setq tempo-collection
565 (apply (function append)
566 (mapcar (function (lambda (tag-list)
568 ; tempo-local-tags changes,
570 (eval (car tag-list))))
572 (setq tempo-dirty-collection nil)))
575 ;;; tempo-find-match-string
577 (defun tempo-find-match-string (finder)
578 "Find a string to be matched against a tag list.
579 FINDER is a function or a string. Returns (STRING . POS), or nil
580 if no reasonable string is found."
581 (cond ((stringp finder)
584 (or (setq successful (re-search-backward finder nil t))
587 (cons (buffer-substring (match-beginning 1)
588 (match-end 1)) ; This seems to be a
596 ;;; tempo-complete-tag
598 (defun tempo-complete-tag (&optional silent)
599 "Look for a tag and expand it.
600 All the tags in the tag lists in `tempo-local-tags'
601 \(this includes `tempo-tags') are searched for a match for the text
602 before the point. The way the string to match for is determined can
603 be altered with the variable `tempo-match-finder'. If
604 `tempo-match-finder' returns nil, then the results are the same as
607 If a single match is found, the corresponding template is expanded in
608 place of the matching string.
610 If a partial completion or no match at all is found, and SILENT is
611 non-NIL, the function will give a signal.
613 If a partial completion is found and `tempo-show-completion-buffer' is
614 non-NIL, a buffer containing possible completions is displayed."
616 ;; This function may look like a hack, but this is how I want it to
619 (let* ((collection (tempo-build-collection))
620 (match-info (tempo-find-match-string tempo-match-finder))
621 (match-string (car match-info))
622 (match-start (cdr match-info))
623 (exact (assoc match-string collection))
624 (compl (or (car exact)
625 (and match-info (try-completion match-string collection)))))
626 (if compl (delete-region match-start (point)))
627 (cond ((null match-info) (or silent (ding)))
628 ((null compl) (or silent (ding)))
629 ((eq compl t) (tempo-insert-template
630 (cdr (assoc match-string
633 (t (if (setq exact (assoc compl collection))
634 (tempo-insert-template (cdr exact) nil)
637 (if tempo-show-completion-buffer
638 (tempo-display-completions match-string
643 ;;; tempo-display-completions
645 (defun tempo-display-completions (string tag-list)
646 "Show a buffer containing possible completions for STRING."
647 (if tempo-leave-completion-buffer
648 (with-output-to-temp-buffer "*Completions*"
649 (display-completion-list
650 (all-completions string tag-list)))
651 (save-window-excursion
652 (with-output-to-temp-buffer "*Completions*"
653 (display-completion-list
654 (all-completions string tag-list)))
658 ;;; tempo-expand-if-complete
660 (defun tempo-expand-if-complete ()
661 "Expand the tag before point if it is complete.
662 Returns non-nil if an expansion was made and nil otherwise.
664 This could as an example be used in a command that is bound to the
665 space bar, and looks something like this:
667 (defun tempo-space ()
669 (or (tempo-expand-if-complete)
673 (let* ((collection (tempo-build-collection))
674 (match-info (tempo-find-match-string tempo-match-finder))
675 (match-string (car match-info))
676 (match-start (cdr match-info))
677 (exact (assoc match-string collection)))
680 (delete-region match-start (point))
681 (tempo-insert-template (cdr exact) nil)
687 ;;; tempo.el ends here