]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/easy-mmode.el
(define-global-minor-mode): Use `after-change-major-mode-hook' instead
[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
4 ;; 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., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, 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 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'.
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* ((mode-name (symbol-name mode))
143 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
144 (globalp nil)
145 (group 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)
153
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 (pop body)))
160 (:global (setq globalp (pop body)))
161 (:extra-args (setq extra-args (pop body)))
162 (:group (setq group (nconc group (list :group (pop body)))))
163 (:require (setq require (pop body)))
164 (:keymap (setq keymap (pop body)))
165 (t (push keyw extra-keywords) (push (pop body) extra-keywords))))
166
167 (setq keymap-sym (if (and keymap (symbolp keymap)) keymap
168 (intern (concat mode-name "-map"))))
169
170 (unless group
171 ;; We might as well provide a best-guess default group.
172 (setq group
173 `(:group ',(intern (replace-regexp-in-string
174 "-mode\\'" "" mode-name)))))
175
176 `(progn
177 ;; Define the variable to enable or disable the mode.
178 ,(if (not globalp)
179 `(progn
180 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
181 Use the command `%s' to change this variable." pretty-name mode))
182 (make-variable-buffer-local ',mode))
183
184 (let ((curfile (or (and (boundp 'byte-compile-current-file)
185 byte-compile-current-file)
186 load-file-name)))
187 `(defcustom ,mode ,init-value
188 ,(format "Non-nil if %s is enabled.
189 See the command `%s' for a description of this minor-mode.
190 Setting this variable directly does not take effect;
191 use either \\[customize] or the function `%s'."
192 pretty-name mode mode)
193 :set 'custom-set-minor-mode
194 :initialize 'custom-initialize-default
195 ,@group
196 :type 'boolean
197 ,@(cond
198 ((not (and curfile require)) nil)
199 ((not (eq require t)) `(:require ,require))
200 (t `(:require
201 ',(intern (file-name-nondirectory
202 (file-name-sans-extension curfile))))))
203 ,@(nreverse extra-keywords))))
204
205 ;; The actual function.
206 (defun ,mode (&optional arg ,@extra-args)
207 ,(or doc
208 (format (concat "Toggle %s on or off.
209 Interactively, with no prefix argument, toggle the mode.
210 With universal prefix ARG turn mode on.
211 With zero or negative ARG turn mode off.
212 \\{%s}") pretty-name keymap-sym))
213 ;; Use `toggle' rather than (if ,mode 0 1) so that using
214 ;; repeat-command still does the toggling correctly.
215 (interactive (list (or current-prefix-arg 'toggle)))
216 (setq ,mode
217 (cond
218 ((eq arg 'toggle) (not ,mode))
219 (arg (> (prefix-numeric-value arg) 0))
220 (t
221 (if (null ,mode) t
222 (message
223 "Toggling %s off; better pass an explicit argument."
224 ',mode)
225 nil))))
226 ,@body
227 ;; The on/off hooks are here for backward compatibility only.
228 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
229 (if (called-interactively-p)
230 (progn
231 ,(if globalp `(customize-mark-as-set ',mode))
232 (unless (current-message)
233 (message ,(format "%s %%sabled" pretty-name)
234 (if ,mode "en" "dis")))))
235 (force-mode-line-update)
236 ;; Return the new setting.
237 ,mode)
238
239 ;; Autoloading a define-minor-mode autoloads everything
240 ;; up-to-here.
241 :autoload-end
242
243 ;; Define the minor-mode keymap.
244 ,(unless (symbolp keymap) ;nil is also a symbol.
245 `(defvar ,keymap-sym
246 (let ((m ,keymap))
247 (cond ((keymapp m) m)
248 ((listp m) (easy-mmode-define-keymap m))
249 (t (error "Invalid keymap %S" ,keymap))))
250 ,(format "Keymap for `%s'." mode-name)))
251
252 (add-minor-mode ',mode ',lighter
253 ,(if keymap keymap-sym
254 `(if (boundp ',keymap-sym)
255 (symbol-value ',keymap-sym))))
256
257 ;; If the mode is global, call the function according to the default.
258 ,(if globalp
259 `(if (and load-file-name (not (equal ,init-value ,mode)))
260 (eval-after-load load-file-name '(,mode (if ,mode 1 -1))))))))
261 \f
262 ;;;
263 ;;; make global minor mode
264 ;;;
265
266 ;;;###autoload
267 (defalias 'easy-mmode-define-global-mode 'define-global-minor-mode)
268 ;;;###autoload
269 (defmacro define-global-minor-mode (global-mode mode turn-on &rest keys)
270 "Make GLOBAL-MODE out of the buffer-local minor MODE.
271 TURN-ON is a function that will be called with no args in every buffer
272 and that should try to turn MODE on if applicable for that buffer.
273 KEYS is a list of CL-style keyword arguments:
274 :group to specify the custom group."
275 (let* ((global-mode-name (symbol-name global-mode))
276 (pretty-name (easy-mmode-pretty-mode-name mode))
277 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
278 (group nil)
279 (extra-args nil)
280 (buffers (intern (concat global-mode-name "-buffers")))
281 (cmmh (intern (concat global-mode-name "-cmmh"))))
282
283 ;; Check keys.
284 (while (keywordp (car keys))
285 (case (pop keys)
286 (:extra-args (setq extra-args (pop keys)))
287 (:group (setq group (nconc group (list :group (pop keys)))))
288 (t (setq keys (cdr keys)))))
289
290 (unless group
291 ;; We might as well provide a best-guess default group.
292 (setq group
293 `(:group ',(intern (replace-regexp-in-string
294 "-mode\\'" "" (symbol-name mode))))))
295
296 `(progn
297 ;; The actual global minor-mode
298 (define-minor-mode ,global-mode
299 ,(format "Toggle %s in every buffer.
300 With prefix ARG, turn %s on if and only if ARG is positive.
301 %s is actually not turned on in every buffer but only in those
302 in which `%s' turns it on."
303 pretty-name pretty-global-name pretty-name turn-on)
304 :global t :extra-args ,extra-args ,@group
305
306 ;; Setup hook to handle future mode changes and new buffers.
307 (if ,global-mode
308 (progn
309 (add-hook 'after-change-major-mode-hook ',buffers)
310 (add-hook 'change-major-mode-hook ',cmmh))
311 (remove-hook 'after-change-major-mode-hook ',buffers)
312 (remove-hook 'change-major-mode-hook ',cmmh))
313
314 ;; Go through existing buffers.
315 (dolist (buf (buffer-list))
316 (with-current-buffer buf
317 (if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
318
319 ;; Autoloading define-global-minor-mode autoloads everything
320 ;; up-to-here.
321 :autoload-end
322
323 ;; List of buffers left to process.
324 (defvar ,buffers nil)
325
326 ;; The function that calls TURN-ON in each buffer.
327 (defun ,buffers ()
328 (remove-hook 'post-command-hook ',buffers)
329 (while ,buffers
330 (let ((buf (pop ,buffers)))
331 (when (buffer-live-p buf)
332 (with-current-buffer buf (,turn-on))))))
333 (put ',buffers 'definition-name ',global-mode)
334
335 ;; The function that catches kill-all-local-variables.
336 (defun ,cmmh ()
337 (add-to-list ',buffers (current-buffer))
338 (add-hook 'post-command-hook ',buffers))
339 (put ',cmmh 'definition-name ',global-mode))))
340
341 ;;;
342 ;;; easy-mmode-defmap
343 ;;;
344
345 (if (fboundp 'set-keymap-parents)
346 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
347 (defun easy-mmode-set-keymap-parents (m parents)
348 (set-keymap-parent
349 m
350 (cond
351 ((not (consp parents)) parents)
352 ((not (cdr parents)) (car parents))
353 (t (let ((m (copy-keymap (pop parents))))
354 (easy-mmode-set-keymap-parents m parents)
355 m))))))
356
357 ;;;###autoload
358 (defun easy-mmode-define-keymap (bs &optional name m args)
359 "Return a keymap built from bindings BS.
360 BS must be a list of (KEY . BINDING) where
361 KEY and BINDINGS are suitable for `define-key'.
362 Optional NAME is passed to `make-sparse-keymap'.
363 Optional map M can be used to modify an existing map.
364 ARGS is a list of additional keyword arguments."
365 (let (inherit dense)
366 (while args
367 (let ((key (pop args))
368 (val (pop args)))
369 (case key
370 (:name (setq name val))
371 (:dense (setq dense val))
372 (:inherit (setq inherit val))
373 (:group)
374 (t (message "Unknown argument %s in defmap" key)))))
375 (unless (keymapp m)
376 (setq bs (append m bs))
377 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
378 (dolist (b bs)
379 (let ((keys (car b))
380 (binding (cdr b)))
381 (dolist (key (if (consp keys) keys (list keys)))
382 (cond
383 ((symbolp key)
384 (substitute-key-definition key binding m global-map))
385 ((null binding)
386 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
387 ((let ((o (lookup-key m key)))
388 (or (null o) (numberp o) (eq o 'undefined)))
389 (define-key m key binding))))))
390 (cond
391 ((keymapp inherit) (set-keymap-parent m inherit))
392 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
393 m))
394
395 ;;;###autoload
396 (defmacro easy-mmode-defmap (m bs doc &rest args)
397 `(defconst ,m
398 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
399 ,doc))
400
401 \f
402 ;;;
403 ;;; easy-mmode-defsyntax
404 ;;;
405
406 (defun easy-mmode-define-syntax (css args)
407 (let ((st (make-syntax-table (plist-get args :copy)))
408 (parent (plist-get args :inherit)))
409 (dolist (cs css)
410 (let ((char (car cs))
411 (syntax (cdr cs)))
412 (if (sequencep char)
413 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
414 (modify-syntax-entry char syntax st))))
415 (if parent (set-char-table-parent
416 st (if (symbolp parent) (symbol-value parent) parent)))
417 st))
418
419 ;;;###autoload
420 (defmacro easy-mmode-defsyntax (st css doc &rest args)
421 "Define variable ST as a syntax-table.
422 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
423 `(progn
424 (autoload 'easy-mmode-define-syntax "easy-mmode")
425 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
426
427
428 \f
429 ;;;
430 ;;; easy-mmode-define-navigation
431 ;;;
432
433 (defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun)
434 "Define BASE-next and BASE-prev to navigate in the buffer.
435 RE determines the places the commands should move point to.
436 NAME should describe the entities matched by RE. It is used to build
437 the docstrings of the two functions.
438 BASE-next also tries to make sure that the whole entry is visible by
439 searching for its end (by calling ENDFUN if provided or by looking for
440 the next entry) and recentering if necessary.
441 ENDFUN should return the end position (with or without moving point).
442 NARROWFUN non-nil means to check for narrowing before moving, and if
443 found, do widen first and then call NARROWFUN with no args after moving."
444 (let* ((base-name (symbol-name base))
445 (prev-sym (intern (concat base-name "-prev")))
446 (next-sym (intern (concat base-name "-next")))
447 (check-narrow-maybe
448 (when narrowfun
449 '(setq was-narrowed
450 (prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
451 (widen)))))
452 (re-narrow-maybe (when narrowfun
453 `(when was-narrowed (,narrowfun)))))
454 (unless name (setq name base-name))
455 `(progn
456 (add-to-list 'debug-ignored-errors
457 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
458 (defun ,next-sym (&optional count)
459 ,(format "Go to the next COUNT'th %s." name)
460 (interactive)
461 (unless count (setq count 1))
462 (if (< count 0) (,prev-sym (- count))
463 (if (looking-at ,re) (setq count (1+ count)))
464 (let (was-narrowed)
465 ,check-narrow-maybe
466 (if (not (re-search-forward ,re nil t count))
467 (if (looking-at ,re)
468 (goto-char (or ,(if endfun `(,endfun)) (point-max)))
469 (error "No next %s" ,name))
470 (goto-char (match-beginning 0))
471 (when (and (eq (current-buffer) (window-buffer (selected-window)))
472 (interactive-p))
473 (let ((endpt (or (save-excursion
474 ,(if endfun `(,endfun)
475 `(re-search-forward ,re nil t 2)))
476 (point-max))))
477 (unless (pos-visible-in-window-p endpt nil t)
478 (recenter '(0))))))
479 ,re-narrow-maybe)))
480 (defun ,prev-sym (&optional count)
481 ,(format "Go to the previous COUNT'th %s" (or name base-name))
482 (interactive)
483 (unless count (setq count 1))
484 (if (< count 0) (,next-sym (- count))
485 (let (was-narrowed)
486 ,check-narrow-maybe
487 (unless (re-search-backward ,re nil t count)
488 (error "No previous %s" ,name))
489 ,re-narrow-maybe))))))
490
491
492 (provide 'easy-mmode)
493
494 ;;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
495 ;;; easy-mmode.el ends here