(easy-mmode-define-navigation): Put `definition-name' properties on the
[emacs.git] / lisp / emacs-lisp / easy-mmode.el
blob9d118cd53515b310fd2a19ff2b15a4eb614d007e
1 ;;; easy-mmode.el --- easy definition for major and minor modes
3 ;; Copyright (C) 1997, 2000, 2001, 2002, 2003, 2004, 2005
4 ;; 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 2, or (at your option)
16 ;; 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; 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.
28 ;;; Commentary:
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.
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
41 ;; eval
42 ;; (pp (macroexpand '(define-minor-mode <your-mode> <doc>)))
43 ;; to check the result before using it.
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.
51 ;; Additionally to `define-minor-mode', the package provides convenient
52 ;; ways to define keymaps, and other helper functions for major and minor modes.
54 ;;; Code:
56 (eval-when-compile (require 'cl))
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))))
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.
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).
104 BODY contains code that will be executed each time the mode is (dis)activated.
105 It will be executed after any toggling but before running the hook variable
106 `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'.
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)))
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)))
142 (let* ((mode-name (symbol-name mode))
143 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
144 (globalp nil)
145 (set nil)
146 (initialize nil)
147 (group nil)
148 (type nil)
149 (extra-args nil)
150 (extra-keywords nil)
151 (require t)
152 (hook (intern (concat mode-name "-hook")))
153 (hook-on (intern (concat mode-name "-on-hook")))
154 (hook-off (intern (concat mode-name "-off-hook")))
155 keyw keymap-sym)
157 ;; Check keys.
158 (while (keywordp (setq keyw (car body)))
159 (setq body (cdr body))
160 (case keyw
161 (:init-value (setq init-value (pop body)))
162 (:lighter (setq lighter (pop body)))
163 (:global (setq globalp (pop body)))
164 (:extra-args (setq extra-args (pop body)))
165 (:set (setq set (list :set (pop body))))
166 (:initialize (setq initialize (list :initialize (pop body))))
167 (:group (setq group (nconc group (list :group (pop body)))))
168 (:type (setq type (list :type (pop body))))
169 (:require (setq require (pop body)))
170 (:keymap (setq keymap (pop body)))
171 (t (push keyw extra-keywords) (push (pop body) extra-keywords))))
173 (setq keymap-sym (if (and keymap (symbolp keymap)) keymap
174 (intern (concat mode-name "-map"))))
176 (unless set (setq set '(:set 'custom-set-minor-mode)))
178 (unless initialize
179 (setq initialize '(:initialize 'custom-initialize-default)))
181 (unless group
182 ;; We might as well provide a best-guess default group.
183 (setq group
184 `(:group ',(intern (replace-regexp-in-string
185 "-mode\\'" "" mode-name)))))
187 (unless type (setq type '(:type 'boolean)))
189 `(progn
190 ;; Define the variable to enable or disable the mode.
191 ,(if (not globalp)
192 `(progn
193 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
194 Use the command `%s' to change this variable." pretty-name mode))
195 (make-variable-buffer-local ',mode))
197 (let ((base-doc-string
198 (concat "Non-nil if %s is enabled.
199 See the command `%s' for a description of this minor-mode."
200 (if body "
201 Setting this variable directly does not take effect;
202 use either \\[customize] or 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))))
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 (setq ,mode
224 (cond
225 ((eq arg 'toggle) (not ,mode))
226 (arg (> (prefix-numeric-value arg) 0))
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)
237 (progn
238 ,(if globalp `(customize-mark-as-set ',mode))
239 (unless (current-message)
240 (message ,(format "%s %%sabled" pretty-name)
241 (if ,mode "en" "dis")))))
242 (force-mode-line-update)
243 ;; Return the new setting.
244 ,mode)
246 ;; Autoloading a define-minor-mode autoloads everything
247 ;; up-to-here.
248 :autoload-end
250 ;; Define the minor-mode keymap.
251 ,(unless (symbolp keymap) ;nil is also a symbol.
252 `(defvar ,keymap-sym
253 (let ((m ,keymap))
254 (cond ((keymapp m) m)
255 ((listp m) (easy-mmode-define-keymap m))
256 (t (error "Invalid keymap %S" ,keymap))))
257 ,(format "Keymap for `%s'." mode-name)))
259 (add-minor-mode ',mode ',lighter
260 ,(if keymap keymap-sym
261 `(if (boundp ',keymap-sym)
262 (symbol-value ',keymap-sym)))))))
265 ;;; make global minor mode
268 ;;;###autoload
269 (defalias 'easy-mmode-define-global-mode 'define-global-minor-mode)
270 ;;;###autoload
271 (defmacro define-global-minor-mode (global-mode mode turn-on &rest keys)
272 "Make GLOBAL-MODE out of the buffer-local minor MODE.
273 TURN-ON is a function that will be called with no args in every buffer
274 and that should try to turn MODE on if applicable for that buffer.
275 KEYS is a list of CL-style keyword arguments. As the minor mode
276 defined by this function is always global, any :global keyword is
277 ignored. Other keywords have the same meaning as in `define-minor-mode',
278 which see. In particular, :group specifies the custom group.
279 The most useful keywords are those that are passed on to the
280 `defcustom'. It normally makes no sense to pass the :lighter
281 or :keymap keywords to `define-global-minor-mode', since these
282 are usually passed to the buffer-local version of the minor mode.
284 If MODE's set-up depends on the major mode in effect when it was
285 enabled, then disabling and reenabling MODE should make MODE work
286 correctly with the current major mode. This is important to
287 prevent problems with derived modes, that is, major modes that
288 call another major mode in their body."
290 (let* ((global-mode-name (symbol-name global-mode))
291 (pretty-name (easy-mmode-pretty-mode-name mode))
292 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
293 (group nil)
294 (extra-keywords nil)
295 (MODE-buffers (intern (concat global-mode-name "-buffers")))
296 (MODE-enable-in-buffers
297 (intern (concat global-mode-name "-enable-in-buffers")))
298 (MODE-check-buffers
299 (intern (concat global-mode-name "-check-buffers")))
300 (MODE-cmhh (intern (concat global-mode-name "-cmhh")))
301 (MODE-major-mode (intern (concat (symbol-name mode) "-major-mode")))
302 keyw)
304 ;; Check keys.
305 (while (keywordp (setq keyw (car keys)))
306 (setq keys (cdr keys))
307 (case keyw
308 (:group (setq group (nconc group (list :group (pop keys)))))
309 (:global (setq keys (cdr keys)))
310 (t (push keyw extra-keywords) (push (pop keys) extra-keywords))))
312 (unless group
313 ;; We might as well provide a best-guess default group.
314 (setq group
315 `(:group ',(intern (replace-regexp-in-string
316 "-mode\\'" "" (symbol-name mode))))))
318 `(progn
319 (defvar ,MODE-major-mode nil)
320 (make-variable-buffer-local ',MODE-major-mode)
321 ;; The actual global minor-mode
322 (define-minor-mode ,global-mode
323 ,(format "Toggle %s in every buffer.
324 With prefix ARG, turn %s on if and only if ARG is positive.
325 %s is actually not turned on in every buffer but only in those
326 in which `%s' turns it on."
327 pretty-name pretty-global-name pretty-name turn-on)
328 :global t ,@group ,@(nreverse extra-keywords)
330 ;; Setup hook to handle future mode changes and new buffers.
331 (if ,global-mode
332 (progn
333 (add-hook 'after-change-major-mode-hook
334 ',MODE-enable-in-buffers)
335 (add-hook 'find-file-hook ',MODE-check-buffers)
336 (add-hook 'change-major-mode-hook ',MODE-cmhh))
337 (remove-hook 'after-change-major-mode-hook ',MODE-enable-in-buffers)
338 (remove-hook 'find-file-hook ',MODE-check-buffers)
339 (remove-hook 'change-major-mode-hook ',MODE-cmhh))
341 ;; Go through existing buffers.
342 (dolist (buf (buffer-list))
343 (with-current-buffer buf
344 (if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
346 ;; Autoloading define-global-minor-mode autoloads everything
347 ;; up-to-here.
348 :autoload-end
350 ;; List of buffers left to process.
351 (defvar ,MODE-buffers nil)
353 ;; The function that calls TURN-ON in each buffer.
354 (defun ,MODE-enable-in-buffers ()
355 (dolist (buf ,MODE-buffers)
356 (when (buffer-live-p buf)
357 (with-current-buffer buf
358 (if ,mode
359 (unless (eq ,MODE-major-mode major-mode)
360 (,mode -1)
361 (,turn-on)
362 (setq ,MODE-major-mode major-mode))
363 (,turn-on)
364 (setq ,MODE-major-mode major-mode))))))
365 (put ',MODE-enable-in-buffers 'definition-name ',global-mode)
367 (defun ,MODE-check-buffers ()
368 (,MODE-enable-in-buffers)
369 (setq ,MODE-buffers nil)
370 (remove-hook 'post-command-hook ',MODE-check-buffers))
371 (put ',MODE-check-buffers 'definition-name ',global-mode)
373 ;; The function that catches kill-all-local-variables.
374 (defun ,MODE-cmhh ()
375 (add-to-list ',MODE-buffers (current-buffer))
376 (add-hook 'post-command-hook ',MODE-check-buffers))
377 (put ',MODE-cmhh 'definition-name ',global-mode))))
380 ;;; easy-mmode-defmap
383 (if (fboundp 'set-keymap-parents)
384 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
385 (defun easy-mmode-set-keymap-parents (m parents)
386 (set-keymap-parent
388 (cond
389 ((not (consp parents)) parents)
390 ((not (cdr parents)) (car parents))
391 (t (let ((m (copy-keymap (pop parents))))
392 (easy-mmode-set-keymap-parents m parents)
393 m))))))
395 ;;;###autoload
396 (defun easy-mmode-define-keymap (bs &optional name m args)
397 "Return a keymap built from bindings BS.
398 BS must be a list of (KEY . BINDING) where
399 KEY and BINDINGS are suitable for `define-key'.
400 Optional NAME is passed to `make-sparse-keymap'.
401 Optional map M can be used to modify an existing map.
402 ARGS is a list of additional keyword arguments."
403 (let (inherit dense)
404 (while args
405 (let ((key (pop args))
406 (val (pop args)))
407 (case key
408 (:name (setq name val))
409 (:dense (setq dense val))
410 (:inherit (setq inherit val))
411 (:group)
412 (t (message "Unknown argument %s in defmap" key)))))
413 (unless (keymapp m)
414 (setq bs (append m bs))
415 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
416 (dolist (b bs)
417 (let ((keys (car b))
418 (binding (cdr b)))
419 (dolist (key (if (consp keys) keys (list keys)))
420 (cond
421 ((symbolp key)
422 (substitute-key-definition key binding m global-map))
423 ((null binding)
424 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
425 ((let ((o (lookup-key m key)))
426 (or (null o) (numberp o) (eq o 'undefined)))
427 (define-key m key binding))))))
428 (cond
429 ((keymapp inherit) (set-keymap-parent m inherit))
430 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
433 ;;;###autoload
434 (defmacro easy-mmode-defmap (m bs doc &rest args)
435 `(defconst ,m
436 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
437 ,doc))
441 ;;; easy-mmode-defsyntax
444 (defun easy-mmode-define-syntax (css args)
445 (let ((st (make-syntax-table (plist-get args :copy)))
446 (parent (plist-get args :inherit)))
447 (dolist (cs css)
448 (let ((char (car cs))
449 (syntax (cdr cs)))
450 (if (sequencep char)
451 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
452 (modify-syntax-entry char syntax st))))
453 (if parent (set-char-table-parent
454 st (if (symbolp parent) (symbol-value parent) parent)))
455 st))
457 ;;;###autoload
458 (defmacro easy-mmode-defsyntax (st css doc &rest args)
459 "Define variable ST as a syntax-table.
460 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
461 `(progn
462 (autoload 'easy-mmode-define-syntax "easy-mmode")
463 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
468 ;;; easy-mmode-define-navigation
471 (defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun)
472 "Define BASE-next and BASE-prev to navigate in the buffer.
473 RE determines the places the commands should move point to.
474 NAME should describe the entities matched by RE. It is used to build
475 the docstrings of the two functions.
476 BASE-next also tries to make sure that the whole entry is visible by
477 searching for its end (by calling ENDFUN if provided or by looking for
478 the next entry) and recentering if necessary.
479 ENDFUN should return the end position (with or without moving point).
480 NARROWFUN non-nil means to check for narrowing before moving, and if
481 found, do widen first and then call NARROWFUN with no args after moving."
482 (let* ((base-name (symbol-name base))
483 (prev-sym (intern (concat base-name "-prev")))
484 (next-sym (intern (concat base-name "-next")))
485 (check-narrow-maybe
486 (when narrowfun
487 '(setq was-narrowed
488 (prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
489 (widen)))))
490 (re-narrow-maybe (when narrowfun
491 `(when was-narrowed (,narrowfun)))))
492 (unless name (setq name base-name))
493 `(progn
494 (add-to-list 'debug-ignored-errors
495 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
496 (defun ,next-sym (&optional count)
497 ,(format "Go to the next COUNT'th %s." name)
498 (interactive)
499 (unless count (setq count 1))
500 (if (< count 0) (,prev-sym (- count))
501 (if (looking-at ,re) (setq count (1+ count)))
502 (let (was-narrowed)
503 ,check-narrow-maybe
504 (if (not (re-search-forward ,re nil t count))
505 (if (looking-at ,re)
506 (goto-char (or ,(if endfun `(,endfun)) (point-max)))
507 (error "No next %s" ,name))
508 (goto-char (match-beginning 0))
509 (when (and (eq (current-buffer) (window-buffer (selected-window)))
510 (interactive-p))
511 (let ((endpt (or (save-excursion
512 ,(if endfun `(,endfun)
513 `(re-search-forward ,re nil t 2)))
514 (point-max))))
515 (unless (pos-visible-in-window-p endpt nil t)
516 (recenter '(0))))))
517 ,re-narrow-maybe)))
518 (put ',next-sym 'definition-name ',base)
519 (defun ,prev-sym (&optional count)
520 ,(format "Go to the previous COUNT'th %s" (or name base-name))
521 (interactive)
522 (unless count (setq count 1))
523 (if (< count 0) (,next-sym (- count))
524 (let (was-narrowed)
525 ,check-narrow-maybe
526 (unless (re-search-backward ,re nil t count)
527 (error "No previous %s" ,name))
528 ,re-narrow-maybe)))
529 (put ',prev-sym 'definition-name ',base))))
532 (provide 'easy-mmode)
534 ;;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
535 ;;; easy-mmode.el ends here