]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/easy-mmode.el
Add 2012 to FSF copyright years for Emacs files (do not merge to trunk)
[gnu-emacs] / lisp / emacs-lisp / easy-mmode.el
1 ;;; easy-mmode.el --- easy definition for major and minor modes
2
3 ;; Copyright (C) 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
4 ;; 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
5
6 ;; Author: Georges Brun-Cottan <Georges.Brun-Cottan@inria.fr>
7 ;; Maintainer: Stefan Monnier <monnier@gnu.org>
8
9 ;; Keywords: extensions lisp
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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/>.
25
26 ;;; Commentary:
27
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.
33
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
38 ;;
39 ;; eval
40 ;; (pp (macroexpand '(define-minor-mode <your-mode> <doc>)))
41 ;; to check the result before using it.
42
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.
48
49 ;; Additionally to `define-minor-mode', the package provides convenient
50 ;; ways to define keymaps, and other helper functions for major and minor modes.
51
52 ;;; Code:
53
54 (eval-when-compile (require 'cl))
55
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))))
83
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.
91
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 or an expression that returns either a keymap or a list of
97 arguments for `easy-mmode-define-keymap'. If KEYMAP is not a symbol,
98 this also defines the variable MODE-map.
99
100 BODY contains code to execute each time the mode is enabled or disabled.
101 It is executed after toggling the mode, and before running MODE-hook.
102 Before the actual body code, you can write keyword arguments, i.e.
103 alternating keywords and values. These following special keywords
104 are supported (other keywords are passed to `defcustom' if the minor
105 mode is global):
106
107 :group GROUP Custom group name to use in all generated `defcustom' forms.
108 Defaults to MODE without the possible trailing \"-mode\".
109 Don't use this default group name unless you have written a
110 `defgroup' to define that group properly.
111 :global GLOBAL If non-nil specifies that the minor mode is not meant to be
112 buffer-local, so don't make the variable MODE buffer-local.
113 By default, the mode is buffer-local.
114 :init-value VAL Same as the INIT-VALUE argument.
115 :lighter SPEC Same as the LIGHTER argument.
116 :keymap MAP Same as the KEYMAP argument.
117 :require SYM Same as in `defcustom'.
118
119 For example, you could write
120 (define-minor-mode foo-mode \"If enabled, foo on you!\"
121 :lighter \" Foo\" :require 'foo :global t :group 'hassle :version \"27.5\"
122 ...BODY CODE...)"
123 (declare (debug (&define name stringp
124 [&optional [&not keywordp] sexp
125 &optional [&not keywordp] sexp
126 &optional [&not keywordp] sexp]
127 [&rest [keywordp sexp]]
128 def-body)))
129
130 ;; Allow skipping the first three args.
131 (cond
132 ((keywordp init-value)
133 (setq body (list* init-value lighter keymap body)
134 init-value nil lighter nil keymap nil))
135 ((keywordp lighter)
136 (setq body (list* lighter keymap body) lighter nil keymap nil))
137 ((keywordp keymap) (push keymap body) (setq keymap nil)))
138
139 (let* ((last-message (make-symbol "last-message"))
140 (mode-name (symbol-name mode))
141 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
142 (globalp nil)
143 (set nil)
144 (initialize nil)
145 (group nil)
146 (type nil)
147 (extra-args nil)
148 (extra-keywords nil)
149 (require t)
150 (hook (intern (concat mode-name "-hook")))
151 (hook-on (intern (concat mode-name "-on-hook")))
152 (hook-off (intern (concat mode-name "-off-hook")))
153 keyw keymap-sym)
154
155 ;; Check keys.
156 (while (keywordp (setq keyw (car body)))
157 (setq body (cdr body))
158 (case keyw
159 (:init-value (setq init-value (pop body)))
160 (:lighter (setq lighter (purecopy (pop body))))
161 (:global (setq globalp (pop body)))
162 (:extra-args (setq extra-args (pop body)))
163 (:set (setq set (list :set (pop body))))
164 (:initialize (setq initialize (list :initialize (pop body))))
165 (:group (setq group (nconc group (list :group (pop body)))))
166 (:type (setq type (list :type (pop body))))
167 (:require (setq require (pop body)))
168 (:keymap (setq keymap (pop body)))
169 (t (push keyw extra-keywords) (push (pop body) extra-keywords))))
170
171 (setq keymap-sym (if (and keymap (symbolp keymap)) keymap
172 (intern (concat mode-name "-map"))))
173
174 (unless set (setq set '(:set 'custom-set-minor-mode)))
175
176 (unless initialize
177 (setq initialize '(:initialize 'custom-initialize-default)))
178
179 (unless group
180 ;; We might as well provide a best-guess default group.
181 (setq group
182 `(:group ',(intern (replace-regexp-in-string
183 "-mode\\'" "" mode-name)))))
184
185 (unless type (setq type '(:type 'boolean)))
186
187 `(progn
188 ;; Define the variable to enable or disable the mode.
189 ,(if (not globalp)
190 `(progn
191 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
192 Use the command `%s' to change this variable." pretty-name mode))
193 (make-variable-buffer-local ',mode))
194
195 (let ((base-doc-string
196 (concat "Non-nil if %s is enabled.
197 See the command `%s' for a description of this minor mode."
198 (if body "
199 Setting this variable directly does not take effect;
200 either customize it (see the info node `Easy Customization')
201 or call the function `%s'."))))
202 `(defcustom ,mode ,init-value
203 ,(format base-doc-string pretty-name mode mode)
204 ,@set
205 ,@initialize
206 ,@group
207 ,@type
208 ,@(unless (eq require t) `(:require ,require))
209 ,@(nreverse extra-keywords))))
210
211 ;; The actual function.
212 (defun ,mode (&optional arg ,@extra-args)
213 ,(or doc
214 (format (concat "Toggle %s on or off.
215 Interactively, with no prefix argument, toggle the mode.
216 With universal prefix ARG turn mode on.
217 With zero or negative ARG turn mode off.
218 \\{%s}") pretty-name keymap-sym))
219 ;; Use `toggle' rather than (if ,mode 0 1) so that using
220 ;; repeat-command still does the toggling correctly.
221 (interactive (list (or current-prefix-arg 'toggle)))
222 (let ((,last-message (current-message)))
223 (setq ,mode
224 (cond
225 ((eq arg 'toggle) (not ,mode))
226 (arg (> (prefix-numeric-value arg) 0))
227 (t
228 (if (null ,mode) t
229 (message
230 "Toggling %s off; better pass an explicit argument."
231 ',mode)
232 nil))))
233 ,@body
234 ;; The on/off hooks are here for backward compatibility only.
235 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
236 (if (called-interactively-p 'any)
237 (progn
238 ,(if globalp `(customize-mark-as-set ',mode))
239 ;; Avoid overwriting a message shown by the body,
240 ;; but do overwrite previous messages.
241 (unless (and (current-message)
242 (not (equal ,last-message
243 (current-message))))
244 (message ,(format "%s %%sabled" pretty-name)
245 (if ,mode "en" "dis"))))))
246 (force-mode-line-update)
247 ;; Return the new setting.
248 ,mode)
249
250 ;; Autoloading a define-minor-mode autoloads everything
251 ;; up-to-here.
252 :autoload-end
253
254 ;; Define the minor-mode keymap.
255 ,(unless (symbolp keymap) ;nil is also a symbol.
256 `(defvar ,keymap-sym
257 (let ((m ,keymap))
258 (cond ((keymapp m) m)
259 ((listp m) (easy-mmode-define-keymap m))
260 (t (error "Invalid keymap %S" m))))
261 ,(format "Keymap for `%s'." mode-name)))
262
263 (add-minor-mode ',mode ',lighter
264 ,(if keymap keymap-sym
265 `(if (boundp ',keymap-sym) ,keymap-sym))))))
266 \f
267 ;;;
268 ;;; make global minor mode
269 ;;;
270
271 ;;;###autoload
272 (defalias 'easy-mmode-define-global-mode 'define-globalized-minor-mode)
273 ;;;###autoload
274 (defalias 'define-global-minor-mode 'define-globalized-minor-mode)
275 ;;;###autoload
276 (defmacro define-globalized-minor-mode (global-mode mode turn-on &rest keys)
277 "Make a global mode GLOBAL-MODE corresponding to buffer-local minor MODE.
278 TURN-ON is a function that will be called with no args in every buffer
279 and that should try to turn MODE on if applicable for that buffer.
280 KEYS is a list of CL-style keyword arguments. As the minor mode
281 defined by this function is always global, any :global keyword is
282 ignored. Other keywords have the same meaning as in `define-minor-mode',
283 which see. In particular, :group specifies the custom group.
284 The most useful keywords are those that are passed on to the
285 `defcustom'. It normally makes no sense to pass the :lighter
286 or :keymap keywords to `define-globalized-minor-mode', since these
287 are usually passed to the buffer-local version of the minor mode.
288
289 If MODE's set-up depends on the major mode in effect when it was
290 enabled, then disabling and reenabling MODE should make MODE work
291 correctly with the current major mode. This is important to
292 prevent problems with derived modes, that is, major modes that
293 call another major mode in their body."
294
295 (let* ((global-mode-name (symbol-name global-mode))
296 (pretty-name (easy-mmode-pretty-mode-name mode))
297 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
298 (group nil)
299 (extra-keywords nil)
300 (MODE-buffers (intern (concat global-mode-name "-buffers")))
301 (MODE-enable-in-buffers
302 (intern (concat global-mode-name "-enable-in-buffers")))
303 (MODE-check-buffers
304 (intern (concat global-mode-name "-check-buffers")))
305 (MODE-cmhh (intern (concat global-mode-name "-cmhh")))
306 (MODE-major-mode (intern (concat (symbol-name mode) "-major-mode")))
307 keyw)
308
309 ;; Check keys.
310 (while (keywordp (setq keyw (car keys)))
311 (setq keys (cdr keys))
312 (case keyw
313 (:group (setq group (nconc group (list :group (pop keys)))))
314 (:global (setq keys (cdr keys)))
315 (t (push keyw extra-keywords) (push (pop keys) extra-keywords))))
316
317 (unless group
318 ;; We might as well provide a best-guess default group.
319 (setq group
320 `(:group ',(intern (replace-regexp-in-string
321 "-mode\\'" "" (symbol-name mode))))))
322
323 `(progn
324 (defvar ,MODE-major-mode nil)
325 (make-variable-buffer-local ',MODE-major-mode)
326 ;; The actual global minor-mode
327 (define-minor-mode ,global-mode
328 ;; Very short lines to avoid too long lines in the generated
329 ;; doc string.
330 ,(format "Toggle %s in every possible buffer.
331 With prefix ARG, turn %s on if and only if
332 ARG is positive.
333 %s is enabled in all buffers where
334 \`%s' would do it.
335 See `%s' for more information on %s."
336 pretty-name pretty-global-name pretty-name turn-on
337 mode pretty-name)
338 :global t ,@group ,@(nreverse extra-keywords)
339
340 ;; Setup hook to handle future mode changes and new buffers.
341 (if ,global-mode
342 (progn
343 (add-hook 'after-change-major-mode-hook
344 ',MODE-enable-in-buffers)
345 (add-hook 'find-file-hook ',MODE-check-buffers)
346 (add-hook 'change-major-mode-hook ',MODE-cmhh))
347 (remove-hook 'after-change-major-mode-hook ',MODE-enable-in-buffers)
348 (remove-hook 'find-file-hook ',MODE-check-buffers)
349 (remove-hook 'change-major-mode-hook ',MODE-cmhh))
350
351 ;; Go through existing buffers.
352 (dolist (buf (buffer-list))
353 (with-current-buffer buf
354 (if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
355
356 ;; Autoloading define-globalized-minor-mode autoloads everything
357 ;; up-to-here.
358 :autoload-end
359
360 ;; List of buffers left to process.
361 (defvar ,MODE-buffers nil)
362
363 ;; The function that calls TURN-ON in each buffer.
364 (defun ,MODE-enable-in-buffers ()
365 (dolist (buf ,MODE-buffers)
366 (when (buffer-live-p buf)
367 (with-current-buffer buf
368 (if ,mode
369 (unless (eq ,MODE-major-mode major-mode)
370 (,mode -1)
371 (,turn-on)
372 (setq ,MODE-major-mode major-mode))
373 (,turn-on)
374 (setq ,MODE-major-mode major-mode))))))
375 (put ',MODE-enable-in-buffers 'definition-name ',global-mode)
376
377 (defun ,MODE-check-buffers ()
378 (,MODE-enable-in-buffers)
379 (setq ,MODE-buffers nil)
380 (remove-hook 'post-command-hook ',MODE-check-buffers))
381 (put ',MODE-check-buffers 'definition-name ',global-mode)
382
383 ;; The function that catches kill-all-local-variables.
384 (defun ,MODE-cmhh ()
385 (add-to-list ',MODE-buffers (current-buffer))
386 (add-hook 'post-command-hook ',MODE-check-buffers))
387 (put ',MODE-cmhh 'definition-name ',global-mode))))
388
389 ;;;
390 ;;; easy-mmode-defmap
391 ;;;
392
393 (eval-and-compile
394 (if (fboundp 'set-keymap-parents)
395 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
396 (defun easy-mmode-set-keymap-parents (m parents)
397 (set-keymap-parent
398 m
399 (cond
400 ((not (consp parents)) parents)
401 ((not (cdr parents)) (car parents))
402 (t (let ((m (copy-keymap (pop parents))))
403 (easy-mmode-set-keymap-parents m parents)
404 m)))))))
405
406 ;;;###autoload
407 (defun easy-mmode-define-keymap (bs &optional name m args)
408 "Return a keymap built from bindings BS.
409 BS must be a list of (KEY . BINDING) where
410 KEY and BINDINGS are suitable for `define-key'.
411 Optional NAME is passed to `make-sparse-keymap'.
412 Optional map M can be used to modify an existing map.
413 ARGS is a list of additional keyword arguments.
414
415 Valid keywords and arguments are:
416
417 :name Name of the keymap; overrides NAME argument.
418 :dense Non-nil for a dense keymap.
419 :inherit Parent keymap.
420 :group Ignored.
421 :suppress Non-nil to call `suppress-keymap' on keymap,
422 'nodigits to suppress digits as prefix arguments."
423 (let (inherit dense suppress)
424 (while args
425 (let ((key (pop args))
426 (val (pop args)))
427 (case key
428 (:name (setq name val))
429 (:dense (setq dense val))
430 (:inherit (setq inherit val))
431 (:suppress (setq suppress val))
432 (:group)
433 (t (message "Unknown argument %s in defmap" key)))))
434 (unless (keymapp m)
435 (setq bs (append m bs))
436 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
437 (when suppress
438 (suppress-keymap m (eq suppress 'nodigits)))
439 (dolist (b bs)
440 (let ((keys (car b))
441 (binding (cdr b)))
442 (dolist (key (if (consp keys) keys (list keys)))
443 (cond
444 ((symbolp key)
445 (substitute-key-definition key binding m global-map))
446 ((null binding)
447 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
448 ((let ((o (lookup-key m key)))
449 (or (null o) (numberp o) (eq o 'undefined)))
450 (define-key m key binding))))))
451 (cond
452 ((keymapp inherit) (set-keymap-parent m inherit))
453 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
454 m))
455
456 ;;;###autoload
457 (defmacro easy-mmode-defmap (m bs doc &rest args)
458 "Define a constant M whose value is the result of `easy-mmode-define-keymap'.
459 The M, BS, and ARGS arguments are as per that function. DOC is
460 the constant's documentation."
461 `(defconst ,m
462 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
463 ,doc))
464
465 \f
466 ;;;
467 ;;; easy-mmode-defsyntax
468 ;;;
469
470 (defun easy-mmode-define-syntax (css args)
471 (let ((st (make-syntax-table (plist-get args :copy)))
472 (parent (plist-get args :inherit)))
473 (dolist (cs css)
474 (let ((char (car cs))
475 (syntax (cdr cs)))
476 (if (sequencep char)
477 (mapc (lambda (c) (modify-syntax-entry c syntax st)) char)
478 (modify-syntax-entry char syntax st))))
479 (if parent (set-char-table-parent
480 st (if (symbolp parent) (symbol-value parent) parent)))
481 st))
482
483 ;;;###autoload
484 (defmacro easy-mmode-defsyntax (st css doc &rest args)
485 "Define variable ST as a syntax-table.
486 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
487 `(progn
488 (autoload 'easy-mmode-define-syntax "easy-mmode")
489 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
490
491
492 \f
493 ;;;
494 ;;; easy-mmode-define-navigation
495 ;;;
496
497 (defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun
498 &rest body)
499 "Define BASE-next and BASE-prev to navigate in the buffer.
500 RE determines the places the commands should move point to.
501 NAME should describe the entities matched by RE. It is used to build
502 the docstrings of the two functions.
503 BASE-next also tries to make sure that the whole entry is visible by
504 searching for its end (by calling ENDFUN if provided or by looking for
505 the next entry) and recentering if necessary.
506 ENDFUN should return the end position (with or without moving point).
507 NARROWFUN non-nil means to check for narrowing before moving, and if
508 found, do `widen' first and then call NARROWFUN with no args after moving.
509 BODY is executed after moving to the destination location."
510 (declare (indent 5) (debug (exp exp exp def-form def-form &rest def-body)))
511 (let* ((base-name (symbol-name base))
512 (prev-sym (intern (concat base-name "-prev")))
513 (next-sym (intern (concat base-name "-next")))
514 (when-narrowed
515 (lambda (body)
516 (if (null narrowfun) body
517 `(let ((was-narrowed
518 (prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
519 (widen))))
520 ,body
521 (when was-narrowed (,narrowfun)))))))
522 (unless name (setq name base-name))
523 `(progn
524 (add-to-list 'debug-ignored-errors
525 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
526 (defun ,next-sym (&optional count)
527 ,(format "Go to the next COUNT'th %s." name)
528 (interactive "p")
529 (unless count (setq count 1))
530 (if (< count 0) (,prev-sym (- count))
531 (if (looking-at ,re) (setq count (1+ count)))
532 ,(funcall when-narrowed
533 `(if (not (re-search-forward ,re nil t count))
534 (if (looking-at ,re)
535 (goto-char (or ,(if endfun `(,endfun)) (point-max)))
536 (error "No next %s" ,name))
537 (goto-char (match-beginning 0))
538 (when (and (eq (current-buffer) (window-buffer (selected-window)))
539 (called-interactively-p 'interactive))
540 (let ((endpt (or (save-excursion
541 ,(if endfun `(,endfun)
542 `(re-search-forward ,re nil t 2)))
543 (point-max))))
544 (unless (pos-visible-in-window-p endpt nil t)
545 (recenter '(0)))))))
546 ,@body))
547 (put ',next-sym 'definition-name ',base)
548 (defun ,prev-sym (&optional count)
549 ,(format "Go to the previous COUNT'th %s" (or name base-name))
550 (interactive "p")
551 (unless count (setq count 1))
552 (if (< count 0) (,next-sym (- count))
553 ,(funcall when-narrowed
554 `(unless (re-search-backward ,re nil t count)
555 (error "No previous %s" ,name)))
556 ,@body))
557 (put ',prev-sym 'definition-name ',base))))
558
559
560 (provide 'easy-mmode)
561
562 ;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
563 ;;; easy-mmode.el ends here