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