Merge from emacs--devo--0
[bpt/emacs.git] / 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,
4 ;; 2006, 2007 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 2, or (at your option)
16 ;; 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; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Commentary:
29
30 ;; Minor modes are useful and common. This package makes defining a
31 ;; minor mode easy, by focusing on the writing of the minor mode
32 ;; functionalities themselves. Moreover, this package enforces a
33 ;; conventional naming of user interface primitives, making things
34 ;; natural for the minor-mode end-users.
35
36 ;; For each mode, easy-mmode defines the following:
37 ;; <mode> : The minor mode predicate. A buffer-local variable.
38 ;; <mode>-map : The keymap possibly associated to <mode>.
39 ;; see `define-minor-mode' documentation
40 ;;
41 ;; eval
42 ;; (pp (macroexpand '(define-minor-mode <your-mode> <doc>)))
43 ;; to check the result before using it.
44
45 ;; The order in which minor modes are installed is important. Keymap
46 ;; lookup proceeds down minor-mode-map-alist, and the order there
47 ;; tends to be the reverse of the order in which the modes were
48 ;; installed. Perhaps there should be a feature to let you specify
49 ;; orderings.
50
51 ;; Additionally to `define-minor-mode', the package provides convenient
52 ;; ways to define keymaps, and other helper functions for major and minor modes.
53
54 ;;; Code:
55
56 (eval-when-compile (require 'cl))
57
58 (defun easy-mmode-pretty-mode-name (mode &optional lighter)
59 "Turn the symbol MODE into a string intended for the user.
60 If provided, LIGHTER will be used to help choose capitalization by,
61 replacing its case-insensitive matches with the literal string in LIGHTER."
62 (let* ((case-fold-search t)
63 ;; Produce "Foo-Bar minor mode" from foo-bar-minor-mode.
64 (name (concat (replace-regexp-in-string
65 ;; If the original mode name included "-minor" (some
66 ;; of them don't, e.g. auto-revert-mode), then
67 ;; replace it with " minor".
68 "-Minor" " minor"
69 ;; "foo-bar-minor" -> "Foo-Bar-Minor"
70 (capitalize (replace-regexp-in-string
71 ;; "foo-bar-minor-mode" -> "foo-bar-minor"
72 "-mode\\'" "" (symbol-name mode))))
73 " mode")))
74 (if (not (stringp lighter)) name
75 ;; Strip leading and trailing whitespace from LIGHTER.
76 (setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\s-+\\'" ""
77 lighter))
78 ;; Replace any (case-insensitive) matches for LIGHTER in NAME
79 ;; with a literal LIGHTER. E.g., if NAME is "Iimage mode" and
80 ;; LIGHTER is " iImag", then this will produce "iImage mode".
81 ;; (LIGHTER normally comes from the mode-line string passed to
82 ;; define-minor-mode, and normally includes at least one leading
83 ;; space.)
84 (replace-regexp-in-string (regexp-quote lighter) lighter name t t))))
85
86 ;;;###autoload
87 (defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
88 ;;;###autoload
89 (defmacro define-minor-mode (mode doc &optional init-value lighter keymap &rest body)
90 "Define a new minor mode MODE.
91 This function defines the associated control variable MODE, keymap MODE-map,
92 and toggle command MODE.
93
94 DOC is the documentation for the mode toggle command.
95 Optional INIT-VALUE is the initial value of the mode's variable.
96 Optional LIGHTER is displayed in the modeline when the mode is on.
97 Optional KEYMAP is the default (defvar) keymap bound to the mode keymap.
98 If it is a list, it is passed to `easy-mmode-define-keymap'
99 in order to build a valid keymap. It's generally better to use
100 a separate MODE-map variable than to use this argument.
101 The above three arguments can be skipped if keyword arguments are
102 used (see below).
103
104 BODY contains code to execute each time the mode is activated or deactivated.
105 It is executed after toggling the mode,
106 and before running the hook variable `mode-HOOK'.
107 Before the actual body code, you can write keyword arguments (alternating
108 keywords and values). These following keyword arguments are supported (other
109 keywords will be passed to `defcustom' if the minor mode is global):
110 :group GROUP Custom group name to use in all generated `defcustom' forms.
111 Defaults to MODE without the possible trailing \"-mode\".
112 Don't use this default group name unless you have written a
113 `defgroup' to define that group properly.
114 :global GLOBAL If non-nil specifies that the minor mode is not meant to be
115 buffer-local, so don't make the variable MODE buffer-local.
116 By default, the mode is buffer-local.
117 :init-value VAL Same as the INIT-VALUE argument.
118 :lighter SPEC Same as the LIGHTER argument.
119 :keymap MAP Same as the KEYMAP argument.
120 :require SYM Same as in `defcustom'.
121
122 For example, you could write
123 (define-minor-mode foo-mode \"If enabled, foo on you!\"
124 :lighter \" Foo\" :require 'foo :global t :group 'hassle :version \"27.5\"
125 ...BODY CODE...)"
126 (declare (debug (&define name stringp
127 [&optional [&not keywordp] sexp
128 &optional [&not keywordp] sexp
129 &optional [&not keywordp] sexp]
130 [&rest [keywordp sexp]]
131 def-body)))
132
133 ;; Allow skipping the first three args.
134 (cond
135 ((keywordp init-value)
136 (setq body (list* init-value lighter keymap body)
137 init-value nil lighter nil keymap nil))
138 ((keywordp lighter)
139 (setq body (list* lighter keymap body) lighter nil keymap nil))
140 ((keywordp keymap) (push keymap body) (setq keymap nil)))
141
142 (let* ((last-message (current-message))
143 (mode-name (symbol-name mode))
144 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
145 (globalp nil)
146 (set nil)
147 (initialize nil)
148 (group nil)
149 (type nil)
150 (extra-args nil)
151 (extra-keywords nil)
152 (require t)
153 (hook (intern (concat mode-name "-hook")))
154 (hook-on (intern (concat mode-name "-on-hook")))
155 (hook-off (intern (concat mode-name "-off-hook")))
156 keyw keymap-sym)
157
158 ;; Check keys.
159 (while (keywordp (setq keyw (car body)))
160 (setq body (cdr body))
161 (case keyw
162 (:init-value (setq init-value (pop body)))
163 (:lighter (setq lighter (pop body)))
164 (:global (setq globalp (pop body)))
165 (:extra-args (setq extra-args (pop body)))
166 (:set (setq set (list :set (pop body))))
167 (:initialize (setq initialize (list :initialize (pop body))))
168 (:group (setq group (nconc group (list :group (pop body)))))
169 (:type (setq type (list :type (pop body))))
170 (:require (setq require (pop body)))
171 (:keymap (setq keymap (pop body)))
172 (t (push keyw extra-keywords) (push (pop body) extra-keywords))))
173
174 (setq keymap-sym (if (and keymap (symbolp keymap)) keymap
175 (intern (concat mode-name "-map"))))
176
177 (unless set (setq set '(:set 'custom-set-minor-mode)))
178
179 (unless initialize
180 (setq initialize '(:initialize 'custom-initialize-default)))
181
182 (unless group
183 ;; We might as well provide a best-guess default group.
184 (setq group
185 `(:group ',(intern (replace-regexp-in-string
186 "-mode\\'" "" mode-name)))))
187
188 (unless type (setq type '(:type 'boolean)))
189
190 `(progn
191 ;; Define the variable to enable or disable the mode.
192 ,(if (not globalp)
193 `(progn
194 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
195 Use the command `%s' to change this variable." pretty-name mode))
196 (make-variable-buffer-local ',mode))
197
198 (let ((base-doc-string
199 (concat "Non-nil if %s is enabled.
200 See the command `%s' for a description of this minor-mode."
201 (if body "
202 Setting this variable directly does not take effect;
203 either customize it (see the info node `Easy Customization')
204 or call the function `%s'."))))
205 `(defcustom ,mode ,init-value
206 ,(format base-doc-string pretty-name mode mode)
207 ,@set
208 ,@initialize
209 ,@group
210 ,@type
211 ,@(unless (eq require t) `(:require ,require))
212 ,@(nreverse extra-keywords))))
213
214 ;; The actual function.
215 (defun ,mode (&optional arg ,@extra-args)
216 ,(or doc
217 (format (concat "Toggle %s on or off.
218 Interactively, with no prefix argument, toggle the mode.
219 With universal prefix ARG turn mode on.
220 With zero or negative ARG turn mode off.
221 \\{%s}") pretty-name keymap-sym))
222 ;; Use `toggle' rather than (if ,mode 0 1) so that using
223 ;; repeat-command still does the toggling correctly.
224 (interactive (list (or current-prefix-arg 'toggle)))
225 (setq ,mode
226 (cond
227 ((eq arg 'toggle) (not ,mode))
228 (arg (> (prefix-numeric-value arg) 0))
229 (t
230 (if (null ,mode) t
231 (message
232 "Toggling %s off; better pass an explicit argument."
233 ',mode)
234 nil))))
235 ,@body
236 ;; The on/off hooks are here for backward compatibility only.
237 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
238 (if (called-interactively-p)
239 (progn
240 ,(if globalp `(customize-mark-as-set ',mode))
241 ;; Avoid overwriting a message shown by the body,
242 ;; but do overwrite previous messages.
243 (unless ,(and (current-message)
244 (not (equal last-message (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)
267 (symbol-value ',keymap-sym)))))))
268 \f
269 ;;;
270 ;;; make global minor mode
271 ;;;
272
273 ;;;###autoload
274 (defalias 'easy-mmode-define-global-mode 'define-global-minor-mode)
275 ;;;###autoload
276 (defmacro define-global-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-global-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 ,(format "Toggle %s in every buffer.
329 With prefix ARG, turn %s on if and only if ARG is positive.
330 %s is actually not turned on in every buffer but only in those
331 in which `%s' turns it on."
332 pretty-name pretty-global-name pretty-name turn-on)
333 :global t ,@group ,@(nreverse extra-keywords)
334
335 ;; Setup hook to handle future mode changes and new buffers.
336 (if ,global-mode
337 (progn
338 (add-hook 'after-change-major-mode-hook
339 ',MODE-enable-in-buffers)
340 (add-hook 'find-file-hook ',MODE-check-buffers)
341 (add-hook 'change-major-mode-hook ',MODE-cmhh))
342 (remove-hook 'after-change-major-mode-hook ',MODE-enable-in-buffers)
343 (remove-hook 'find-file-hook ',MODE-check-buffers)
344 (remove-hook 'change-major-mode-hook ',MODE-cmhh))
345
346 ;; Go through existing buffers.
347 (dolist (buf (buffer-list))
348 (with-current-buffer buf
349 (if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
350
351 ;; Autoloading define-global-minor-mode autoloads everything
352 ;; up-to-here.
353 :autoload-end
354
355 ;; List of buffers left to process.
356 (defvar ,MODE-buffers nil)
357
358 ;; The function that calls TURN-ON in each buffer.
359 (defun ,MODE-enable-in-buffers ()
360 (dolist (buf ,MODE-buffers)
361 (when (buffer-live-p buf)
362 (with-current-buffer buf
363 (if ,mode
364 (unless (eq ,MODE-major-mode major-mode)
365 (,mode -1)
366 (,turn-on)
367 (setq ,MODE-major-mode major-mode))
368 (,turn-on)
369 (setq ,MODE-major-mode major-mode))))))
370 (put ',MODE-enable-in-buffers 'definition-name ',global-mode)
371
372 (defun ,MODE-check-buffers ()
373 (,MODE-enable-in-buffers)
374 (setq ,MODE-buffers nil)
375 (remove-hook 'post-command-hook ',MODE-check-buffers))
376 (put ',MODE-check-buffers 'definition-name ',global-mode)
377
378 ;; The function that catches kill-all-local-variables.
379 (defun ,MODE-cmhh ()
380 (add-to-list ',MODE-buffers (current-buffer))
381 (add-hook 'post-command-hook ',MODE-check-buffers))
382 (put ',MODE-cmhh 'definition-name ',global-mode))))
383
384 ;;;
385 ;;; easy-mmode-defmap
386 ;;;
387
388 (if (fboundp 'set-keymap-parents)
389 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
390 (defun easy-mmode-set-keymap-parents (m parents)
391 (set-keymap-parent
392 m
393 (cond
394 ((not (consp parents)) parents)
395 ((not (cdr parents)) (car parents))
396 (t (let ((m (copy-keymap (pop parents))))
397 (easy-mmode-set-keymap-parents m parents)
398 m))))))
399
400 ;;;###autoload
401 (defun easy-mmode-define-keymap (bs &optional name m args)
402 "Return a keymap built from bindings BS.
403 BS must be a list of (KEY . BINDING) where
404 KEY and BINDINGS are suitable for `define-key'.
405 Optional NAME is passed to `make-sparse-keymap'.
406 Optional map M can be used to modify an existing map.
407 ARGS is a list of additional keyword arguments."
408 (let (inherit dense)
409 (while args
410 (let ((key (pop args))
411 (val (pop args)))
412 (case key
413 (:name (setq name val))
414 (:dense (setq dense val))
415 (:inherit (setq inherit val))
416 (:group)
417 (t (message "Unknown argument %s in defmap" key)))))
418 (unless (keymapp m)
419 (setq bs (append m bs))
420 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
421 (dolist (b bs)
422 (let ((keys (car b))
423 (binding (cdr b)))
424 (dolist (key (if (consp keys) keys (list keys)))
425 (cond
426 ((symbolp key)
427 (substitute-key-definition key binding m global-map))
428 ((null binding)
429 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
430 ((let ((o (lookup-key m key)))
431 (or (null o) (numberp o) (eq o 'undefined)))
432 (define-key m key binding))))))
433 (cond
434 ((keymapp inherit) (set-keymap-parent m inherit))
435 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
436 m))
437
438 ;;;###autoload
439 (defmacro easy-mmode-defmap (m bs doc &rest args)
440 `(defconst ,m
441 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
442 ,doc))
443
444 \f
445 ;;;
446 ;;; easy-mmode-defsyntax
447 ;;;
448
449 (defun easy-mmode-define-syntax (css args)
450 (let ((st (make-syntax-table (plist-get args :copy)))
451 (parent (plist-get args :inherit)))
452 (dolist (cs css)
453 (let ((char (car cs))
454 (syntax (cdr cs)))
455 (if (sequencep char)
456 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
457 (modify-syntax-entry char syntax st))))
458 (if parent (set-char-table-parent
459 st (if (symbolp parent) (symbol-value parent) parent)))
460 st))
461
462 ;;;###autoload
463 (defmacro easy-mmode-defsyntax (st css doc &rest args)
464 "Define variable ST as a syntax-table.
465 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
466 `(progn
467 (autoload 'easy-mmode-define-syntax "easy-mmode")
468 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
469
470
471 \f
472 ;;;
473 ;;; easy-mmode-define-navigation
474 ;;;
475
476 (defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun)
477 "Define BASE-next and BASE-prev to navigate in the buffer.
478 RE determines the places the commands should move point to.
479 NAME should describe the entities matched by RE. It is used to build
480 the docstrings of the two functions.
481 BASE-next also tries to make sure that the whole entry is visible by
482 searching for its end (by calling ENDFUN if provided or by looking for
483 the next entry) and recentering if necessary.
484 ENDFUN should return the end position (with or without moving point).
485 NARROWFUN non-nil means to check for narrowing before moving, and if
486 found, do widen first and then call NARROWFUN with no args after moving."
487 (let* ((base-name (symbol-name base))
488 (prev-sym (intern (concat base-name "-prev")))
489 (next-sym (intern (concat base-name "-next")))
490 (check-narrow-maybe
491 (when narrowfun
492 '(setq was-narrowed
493 (prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
494 (widen)))))
495 (re-narrow-maybe (when narrowfun
496 `(when was-narrowed (,narrowfun)))))
497 (unless name (setq name base-name))
498 `(progn
499 (add-to-list 'debug-ignored-errors
500 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
501 (defun ,next-sym (&optional count)
502 ,(format "Go to the next COUNT'th %s." name)
503 (interactive "p")
504 (unless count (setq count 1))
505 (if (< count 0) (,prev-sym (- count))
506 (if (looking-at ,re) (setq count (1+ count)))
507 (let (was-narrowed)
508 ,check-narrow-maybe
509 (if (not (re-search-forward ,re nil t count))
510 (if (looking-at ,re)
511 (goto-char (or ,(if endfun `(,endfun)) (point-max)))
512 (error "No next %s" ,name))
513 (goto-char (match-beginning 0))
514 (when (and (eq (current-buffer) (window-buffer (selected-window)))
515 (interactive-p))
516 (let ((endpt (or (save-excursion
517 ,(if endfun `(,endfun)
518 `(re-search-forward ,re nil t 2)))
519 (point-max))))
520 (unless (pos-visible-in-window-p endpt nil t)
521 (recenter '(0))))))
522 ,re-narrow-maybe)))
523 (put ',next-sym 'definition-name ',base)
524 (defun ,prev-sym (&optional count)
525 ,(format "Go to the previous COUNT'th %s" (or name base-name))
526 (interactive "p")
527 (unless count (setq count 1))
528 (if (< count 0) (,next-sym (- count))
529 (let (was-narrowed)
530 ,check-narrow-maybe
531 (unless (re-search-backward ,re nil t count)
532 (error "No previous %s" ,name))
533 ,re-narrow-maybe)))
534 (put ',prev-sym 'definition-name ',base))))
535
536
537 (provide 'easy-mmode)
538
539 ;;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
540 ;;; easy-mmode.el ends here