Add 2011 to FSF/AIST copyright years.
[emacs.git] / lisp / emacs-lisp / easy-mmode.el
blobf22cc2c362d6f526b021c1e94b4a4419f8a20231
1 ;;; easy-mmode.el --- easy definition for major and minor modes
3 ;; Copyright (C) 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
4 ;; 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
6 ;; Author: Georges Brun-Cottan <Georges.Brun-Cottan@inria.fr>
7 ;; Maintainer: Stefan Monnier <monnier@gnu.org>
9 ;; Keywords: extensions lisp
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Minor modes are useful and common. This package makes defining a
29 ;; minor mode easy, by focusing on the writing of the minor mode
30 ;; functionalities themselves. Moreover, this package enforces a
31 ;; conventional naming of user interface primitives, making things
32 ;; natural for the minor-mode end-users.
34 ;; For each mode, easy-mmode defines the following:
35 ;; <mode> : The minor mode predicate. A buffer-local variable.
36 ;; <mode>-map : The keymap possibly associated to <mode>.
37 ;; see `define-minor-mode' documentation
39 ;; eval
40 ;; (pp (macroexpand '(define-minor-mode <your-mode> <doc>)))
41 ;; to check the result before using it.
43 ;; The order in which minor modes are installed is important. Keymap
44 ;; lookup proceeds down minor-mode-map-alist, and the order there
45 ;; tends to be the reverse of the order in which the modes were
46 ;; installed. Perhaps there should be a feature to let you specify
47 ;; orderings.
49 ;; Additionally to `define-minor-mode', the package provides convenient
50 ;; ways to define keymaps, and other helper functions for major and minor modes.
52 ;;; Code:
54 (eval-when-compile (require 'cl))
56 (defun easy-mmode-pretty-mode-name (mode &optional lighter)
57 "Turn the symbol MODE into a string intended for the user.
58 If provided, LIGHTER will be used to help choose capitalization by,
59 replacing its case-insensitive matches with the literal string in LIGHTER."
60 (let* ((case-fold-search t)
61 ;; Produce "Foo-Bar minor mode" from foo-bar-minor-mode.
62 (name (concat (replace-regexp-in-string
63 ;; If the original mode name included "-minor" (some
64 ;; of them don't, e.g. auto-revert-mode), then
65 ;; replace it with " minor".
66 "-Minor" " minor"
67 ;; "foo-bar-minor" -> "Foo-Bar-Minor"
68 (capitalize (replace-regexp-in-string
69 ;; "foo-bar-minor-mode" -> "foo-bar-minor"
70 "-mode\\'" "" (symbol-name mode))))
71 " mode")))
72 (if (not (stringp lighter)) name
73 ;; Strip leading and trailing whitespace from LIGHTER.
74 (setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\s-+\\'" ""
75 lighter))
76 ;; Replace any (case-insensitive) matches for LIGHTER in NAME
77 ;; with a literal LIGHTER. E.g., if NAME is "Iimage mode" and
78 ;; LIGHTER is " iImag", then this will produce "iImage mode".
79 ;; (LIGHTER normally comes from the mode-line string passed to
80 ;; define-minor-mode, and normally includes at least one leading
81 ;; space.)
82 (replace-regexp-in-string (regexp-quote lighter) lighter name t t))))
84 ;;;###autoload
85 (defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
86 ;;;###autoload
87 (defmacro define-minor-mode (mode doc &optional init-value lighter keymap &rest body)
88 "Define a new minor mode MODE.
89 This defines the control variable MODE and the toggle command MODE.
90 DOC is the documentation for the mode toggle command.
92 Optional INIT-VALUE is the initial value of the mode's variable.
93 Optional LIGHTER is displayed in the modeline when the mode is on.
94 Optional KEYMAP is the default keymap bound to the mode keymap.
95 If non-nil, it should be a variable name (whose value is a keymap),
96 a keymap, or a list of arguments for `easy-mmode-define-keymap'.
97 If KEYMAP is a keymap or list, this also defines the variable MODE-map.
99 BODY contains code to execute each time the mode is enabled or disabled.
100 It is executed after toggling the mode, and before running MODE-hook.
101 Before the actual body code, you can write keyword arguments, i.e.
102 alternating keywords and values. These following special keywords
103 are supported (other keywords are passed to `defcustom' if the minor
104 mode is global):
106 :group GROUP Custom group name to use in all generated `defcustom' forms.
107 Defaults to MODE without the possible trailing \"-mode\".
108 Don't use this default group name unless you have written a
109 `defgroup' to define that group properly.
110 :global GLOBAL If non-nil specifies that the minor mode is not meant to be
111 buffer-local, so don't make the variable MODE buffer-local.
112 By default, the mode is buffer-local.
113 :init-value VAL Same as the INIT-VALUE argument.
114 :lighter SPEC Same as the LIGHTER argument.
115 :keymap MAP Same as the KEYMAP argument.
116 :require SYM Same as in `defcustom'.
118 For example, you could write
119 (define-minor-mode foo-mode \"If enabled, foo on you!\"
120 :lighter \" Foo\" :require 'foo :global t :group 'hassle :version \"27.5\"
121 ...BODY CODE...)"
122 (declare (debug (&define name stringp
123 [&optional [&not keywordp] sexp
124 &optional [&not keywordp] sexp
125 &optional [&not keywordp] sexp]
126 [&rest [keywordp sexp]]
127 def-body)))
129 ;; Allow skipping the first three args.
130 (cond
131 ((keywordp init-value)
132 (setq body (list* init-value lighter keymap body)
133 init-value nil lighter nil keymap nil))
134 ((keywordp lighter)
135 (setq body (list* lighter keymap body) lighter nil keymap nil))
136 ((keywordp keymap) (push keymap body) (setq keymap nil)))
138 (let* ((last-message (make-symbol "last-message"))
139 (mode-name (symbol-name mode))
140 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
141 (globalp nil)
142 (set nil)
143 (initialize nil)
144 (group nil)
145 (type nil)
146 (extra-args nil)
147 (extra-keywords nil)
148 (require t)
149 (hook (intern (concat mode-name "-hook")))
150 (hook-on (intern (concat mode-name "-on-hook")))
151 (hook-off (intern (concat mode-name "-off-hook")))
152 keyw keymap-sym)
154 ;; Check keys.
155 (while (keywordp (setq keyw (car body)))
156 (setq body (cdr body))
157 (case keyw
158 (:init-value (setq init-value (pop body)))
159 (:lighter (setq lighter (purecopy (pop body))))
160 (:global (setq globalp (pop body)))
161 (:extra-args (setq extra-args (pop body)))
162 (:set (setq set (list :set (pop body))))
163 (:initialize (setq initialize (list :initialize (pop body))))
164 (:group (setq group (nconc group (list :group (pop body)))))
165 (:type (setq type (list :type (pop body))))
166 (:require (setq require (pop body)))
167 (:keymap (setq keymap (pop body)))
168 (t (push keyw extra-keywords) (push (pop body) extra-keywords))))
170 (setq keymap-sym (if (and keymap (symbolp keymap)) keymap
171 (intern (concat mode-name "-map"))))
173 (unless set (setq set '(:set 'custom-set-minor-mode)))
175 (unless initialize
176 (setq initialize '(:initialize 'custom-initialize-default)))
178 (unless group
179 ;; We might as well provide a best-guess default group.
180 (setq group
181 `(:group ',(intern (replace-regexp-in-string
182 "-mode\\'" "" mode-name)))))
184 (unless type (setq type '(:type 'boolean)))
186 `(progn
187 ;; Define the variable to enable or disable the mode.
188 ,(if (not globalp)
189 `(progn
190 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
191 Use the command `%s' to change this variable." pretty-name mode))
192 (make-variable-buffer-local ',mode))
194 (let ((base-doc-string
195 (concat "Non-nil if %s is enabled.
196 See the command `%s' for a description of this minor mode."
197 (if body "
198 Setting this variable directly does not take effect;
199 either customize it (see the info node `Easy Customization')
200 or call the function `%s'."))))
201 `(defcustom ,mode ,init-value
202 ,(format base-doc-string pretty-name mode mode)
203 ,@set
204 ,@initialize
205 ,@group
206 ,@type
207 ,@(unless (eq require t) `(:require ,require))
208 ,@(nreverse extra-keywords))))
210 ;; The actual function.
211 (defun ,mode (&optional arg ,@extra-args)
212 ,(or doc
213 (format (concat "Toggle %s on or off.
214 Interactively, with no prefix argument, toggle the mode.
215 With universal prefix ARG turn mode on.
216 With zero or negative ARG turn mode off.
217 \\{%s}") pretty-name keymap-sym))
218 ;; Use `toggle' rather than (if ,mode 0 1) so that using
219 ;; repeat-command still does the toggling correctly.
220 (interactive (list (or current-prefix-arg 'toggle)))
221 (let ((,last-message (current-message)))
222 (setq ,mode
223 (cond
224 ((eq arg 'toggle) (not ,mode))
225 (arg (> (prefix-numeric-value arg) 0))
227 (if (null ,mode) t
228 (message
229 "Toggling %s off; better pass an explicit argument."
230 ',mode)
231 nil))))
232 ,@body
233 ;; The on/off hooks are here for backward compatibility only.
234 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
235 (if (called-interactively-p 'any)
236 (progn
237 ,(if globalp `(customize-mark-as-set ',mode))
238 ;; Avoid overwriting a message shown by the body,
239 ;; but do overwrite previous messages.
240 (unless (and (current-message)
241 (not (equal ,last-message
242 (current-message))))
243 (message ,(format "%s %%sabled" pretty-name)
244 (if ,mode "en" "dis"))))))
245 (force-mode-line-update)
246 ;; Return the new setting.
247 ,mode)
249 ;; Autoloading a define-minor-mode autoloads everything
250 ;; up-to-here.
251 :autoload-end
253 ;; Define the minor-mode keymap.
254 ,(unless (symbolp keymap) ;nil is also a symbol.
255 `(defvar ,keymap-sym
256 (let ((m ,keymap))
257 (cond ((keymapp m) m)
258 ((listp m) (easy-mmode-define-keymap m))
259 (t (error "Invalid keymap %S" ,keymap))))
260 ,(format "Keymap for `%s'." mode-name)))
262 (add-minor-mode ',mode ',lighter
263 ,(if keymap keymap-sym
264 `(if (boundp ',keymap-sym) ,keymap-sym))))))
267 ;;; make global minor mode
270 ;;;###autoload
271 (defalias 'easy-mmode-define-global-mode 'define-globalized-minor-mode)
272 ;;;###autoload
273 (defalias 'define-global-minor-mode 'define-globalized-minor-mode)
274 ;;;###autoload
275 (defmacro define-globalized-minor-mode (global-mode mode turn-on &rest keys)
276 "Make a global mode GLOBAL-MODE corresponding to buffer-local minor MODE.
277 TURN-ON is a function that will be called with no args in every buffer
278 and that should try to turn MODE on if applicable for that buffer.
279 KEYS is a list of CL-style keyword arguments. As the minor mode
280 defined by this function is always global, any :global keyword is
281 ignored. Other keywords have the same meaning as in `define-minor-mode',
282 which see. In particular, :group specifies the custom group.
283 The most useful keywords are those that are passed on to the
284 `defcustom'. It normally makes no sense to pass the :lighter
285 or :keymap keywords to `define-globalized-minor-mode', since these
286 are usually passed to the buffer-local version of the minor mode.
288 If MODE's set-up depends on the major mode in effect when it was
289 enabled, then disabling and reenabling MODE should make MODE work
290 correctly with the current major mode. This is important to
291 prevent problems with derived modes, that is, major modes that
292 call another major mode in their body."
294 (let* ((global-mode-name (symbol-name global-mode))
295 (pretty-name (easy-mmode-pretty-mode-name mode))
296 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
297 (group nil)
298 (extra-keywords nil)
299 (MODE-buffers (intern (concat global-mode-name "-buffers")))
300 (MODE-enable-in-buffers
301 (intern (concat global-mode-name "-enable-in-buffers")))
302 (MODE-check-buffers
303 (intern (concat global-mode-name "-check-buffers")))
304 (MODE-cmhh (intern (concat global-mode-name "-cmhh")))
305 (MODE-major-mode (intern (concat (symbol-name mode) "-major-mode")))
306 keyw)
308 ;; Check keys.
309 (while (keywordp (setq keyw (car keys)))
310 (setq keys (cdr keys))
311 (case keyw
312 (:group (setq group (nconc group (list :group (pop keys)))))
313 (:global (setq keys (cdr keys)))
314 (t (push keyw extra-keywords) (push (pop keys) extra-keywords))))
316 (unless group
317 ;; We might as well provide a best-guess default group.
318 (setq group
319 `(:group ',(intern (replace-regexp-in-string
320 "-mode\\'" "" (symbol-name mode))))))
322 `(progn
323 (defvar ,MODE-major-mode nil)
324 (make-variable-buffer-local ',MODE-major-mode)
325 ;; The actual global minor-mode
326 (define-minor-mode ,global-mode
327 ;; Very short lines to avoid too long lines in the generated
328 ;; doc string.
329 ,(format "Toggle %s in every possible buffer.
330 With prefix ARG, turn %s on if and only if
331 ARG is positive.
332 %s is enabled in all buffers where
333 \`%s' would do it.
334 See `%s' for more information on %s."
335 pretty-name pretty-global-name pretty-name turn-on
336 mode pretty-name)
337 :global t ,@group ,@(nreverse extra-keywords)
339 ;; Setup hook to handle future mode changes and new buffers.
340 (if ,global-mode
341 (progn
342 (add-hook 'after-change-major-mode-hook
343 ',MODE-enable-in-buffers)
344 (add-hook 'find-file-hook ',MODE-check-buffers)
345 (add-hook 'change-major-mode-hook ',MODE-cmhh))
346 (remove-hook 'after-change-major-mode-hook ',MODE-enable-in-buffers)
347 (remove-hook 'find-file-hook ',MODE-check-buffers)
348 (remove-hook 'change-major-mode-hook ',MODE-cmhh))
350 ;; Go through existing buffers.
351 (dolist (buf (buffer-list))
352 (with-current-buffer buf
353 (if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
355 ;; Autoloading define-globalized-minor-mode autoloads everything
356 ;; up-to-here.
357 :autoload-end
359 ;; List of buffers left to process.
360 (defvar ,MODE-buffers nil)
362 ;; The function that calls TURN-ON in each buffer.
363 (defun ,MODE-enable-in-buffers ()
364 (dolist (buf ,MODE-buffers)
365 (when (buffer-live-p buf)
366 (with-current-buffer buf
367 (if ,mode
368 (unless (eq ,MODE-major-mode major-mode)
369 (,mode -1)
370 (,turn-on)
371 (setq ,MODE-major-mode major-mode))
372 (,turn-on)
373 (setq ,MODE-major-mode major-mode))))))
374 (put ',MODE-enable-in-buffers 'definition-name ',global-mode)
376 (defun ,MODE-check-buffers ()
377 (,MODE-enable-in-buffers)
378 (setq ,MODE-buffers nil)
379 (remove-hook 'post-command-hook ',MODE-check-buffers))
380 (put ',MODE-check-buffers 'definition-name ',global-mode)
382 ;; The function that catches kill-all-local-variables.
383 (defun ,MODE-cmhh ()
384 (add-to-list ',MODE-buffers (current-buffer))
385 (add-hook 'post-command-hook ',MODE-check-buffers))
386 (put ',MODE-cmhh 'definition-name ',global-mode))))
389 ;;; easy-mmode-defmap
392 (eval-and-compile
393 (if (fboundp 'set-keymap-parents)
394 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
395 (defun easy-mmode-set-keymap-parents (m parents)
396 (set-keymap-parent
398 (cond
399 ((not (consp parents)) parents)
400 ((not (cdr parents)) (car parents))
401 (t (let ((m (copy-keymap (pop parents))))
402 (easy-mmode-set-keymap-parents m parents)
403 m)))))))
405 ;;;###autoload
406 (defun easy-mmode-define-keymap (bs &optional name m args)
407 "Return a keymap built from bindings BS.
408 BS must be a list of (KEY . BINDING) where
409 KEY and BINDINGS are suitable for `define-key'.
410 Optional NAME is passed to `make-sparse-keymap'.
411 Optional map M can be used to modify an existing map.
412 ARGS is a list of additional keyword arguments.
414 Valid keywords and arguments are:
416 :name Name of the keymap; overrides NAME argument.
417 :dense Non-nil for a dense keymap.
418 :inherit Parent keymap.
419 :group Ignored.
420 :suppress Non-nil to call `suppress-keymap' on keymap,
421 'nodigits to suppress digits as prefix arguments."
422 (let (inherit dense suppress)
423 (while args
424 (let ((key (pop args))
425 (val (pop args)))
426 (case key
427 (:name (setq name val))
428 (:dense (setq dense val))
429 (:inherit (setq inherit val))
430 (:suppress (setq suppress val))
431 (:group)
432 (t (message "Unknown argument %s in defmap" key)))))
433 (unless (keymapp m)
434 (setq bs (append m bs))
435 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
436 (when suppress
437 (suppress-keymap m (eq suppress 'nodigits)))
438 (dolist (b bs)
439 (let ((keys (car b))
440 (binding (cdr b)))
441 (dolist (key (if (consp keys) keys (list keys)))
442 (cond
443 ((symbolp key)
444 (substitute-key-definition key binding m global-map))
445 ((null binding)
446 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
447 ((let ((o (lookup-key m key)))
448 (or (null o) (numberp o) (eq o 'undefined)))
449 (define-key m key binding))))))
450 (cond
451 ((keymapp inherit) (set-keymap-parent m inherit))
452 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
455 ;;;###autoload
456 (defmacro easy-mmode-defmap (m bs doc &rest args)
457 "Define a constant M whose value is the result of `easy-mmode-define-keymap'.
458 The M, BS, and ARGS arguments are as per that function. DOC is
459 the constant's documentation."
460 `(defconst ,m
461 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
462 ,doc))
466 ;;; easy-mmode-defsyntax
469 (defun easy-mmode-define-syntax (css args)
470 (let ((st (make-syntax-table (plist-get args :copy)))
471 (parent (plist-get args :inherit)))
472 (dolist (cs css)
473 (let ((char (car cs))
474 (syntax (cdr cs)))
475 (if (sequencep char)
476 (mapc (lambda (c) (modify-syntax-entry c syntax st)) char)
477 (modify-syntax-entry char syntax st))))
478 (if parent (set-char-table-parent
479 st (if (symbolp parent) (symbol-value parent) parent)))
480 st))
482 ;;;###autoload
483 (defmacro easy-mmode-defsyntax (st css doc &rest args)
484 "Define variable ST as a syntax-table.
485 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
486 `(progn
487 (autoload 'easy-mmode-define-syntax "easy-mmode")
488 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
493 ;;; easy-mmode-define-navigation
496 (defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun
497 &rest body)
498 "Define BASE-next and BASE-prev to navigate in the buffer.
499 RE determines the places the commands should move point to.
500 NAME should describe the entities matched by RE. It is used to build
501 the docstrings of the two functions.
502 BASE-next also tries to make sure that the whole entry is visible by
503 searching for its end (by calling ENDFUN if provided or by looking for
504 the next entry) and recentering if necessary.
505 ENDFUN should return the end position (with or without moving point).
506 NARROWFUN non-nil means to check for narrowing before moving, and if
507 found, do `widen' first and then call NARROWFUN with no args after moving.
508 BODY is executed after moving to the destination location."
509 (declare (indent 5) (debug (exp exp exp def-form def-form &rest def-body)))
510 (let* ((base-name (symbol-name base))
511 (prev-sym (intern (concat base-name "-prev")))
512 (next-sym (intern (concat base-name "-next")))
513 (when-narrowed
514 (lambda (body)
515 (if (null narrowfun) body
516 `(let ((was-narrowed
517 (prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
518 (widen))))
519 ,body
520 (when was-narrowed (,narrowfun)))))))
521 (unless name (setq name base-name))
522 `(progn
523 (add-to-list 'debug-ignored-errors
524 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
525 (defun ,next-sym (&optional count)
526 ,(format "Go to the next COUNT'th %s." name)
527 (interactive "p")
528 (unless count (setq count 1))
529 (if (< count 0) (,prev-sym (- count))
530 (if (looking-at ,re) (setq count (1+ count)))
531 ,(funcall when-narrowed
532 `(if (not (re-search-forward ,re nil t count))
533 (if (looking-at ,re)
534 (goto-char (or ,(if endfun `(,endfun)) (point-max)))
535 (error "No next %s" ,name))
536 (goto-char (match-beginning 0))
537 (when (and (eq (current-buffer) (window-buffer (selected-window)))
538 (called-interactively-p 'interactive))
539 (let ((endpt (or (save-excursion
540 ,(if endfun `(,endfun)
541 `(re-search-forward ,re nil t 2)))
542 (point-max))))
543 (unless (pos-visible-in-window-p endpt nil t)
544 (recenter '(0)))))))
545 ,@body))
546 (put ',next-sym 'definition-name ',base)
547 (defun ,prev-sym (&optional count)
548 ,(format "Go to the previous COUNT'th %s" (or name base-name))
549 (interactive "p")
550 (unless count (setq count 1))
551 (if (< count 0) (,next-sym (- count))
552 ,(funcall when-narrowed
553 `(unless (re-search-backward ,re nil t count)
554 (error "No previous %s" ,name)))
555 ,@body))
556 (put ',prev-sym 'definition-name ',base))))
559 (provide 'easy-mmode)
561 ;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
562 ;;; easy-mmode.el ends here