1 ;;; easy-mmode.el --- easy definition for major and minor modes
3 ;; Copyright (C) 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
4 ;; 2008, 2009, 2010, 2011, 2012 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 3 of the License, or
16 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
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.
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
40 ;; (pp (macroexpand '(define-minor-mode <your-mode> <doc>)))
41 ;; to check the result before using it.
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
49 ;; Additionally to `define-minor-mode', the package provides convenient
50 ;; ways to define keymaps, and other helper functions for major and minor modes.
54 (eval-when-compile (require 'cl))
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".
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))))
72 (if (not (stringp lighter)) name
73 ;; Strip leading and trailing whitespace from LIGHTER.
74 (setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\s-+\\'" ""
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
82 (replace-regexp-in-string (regexp-quote lighter) lighter name t t))))
85 (defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
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.
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.
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
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'.
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\"
123 (declare (debug (&define name stringp
124 [&optional [¬ keywordp] sexp
125 &optional [¬ keywordp] sexp
126 &optional [¬ keywordp] sexp]
127 [&rest [keywordp sexp]]
130 ;; Allow skipping the first three args.
132 ((keywordp init-value)
133 (setq body (list* init-value lighter keymap body)
134 init-value nil lighter nil keymap nil))
136 (setq body (list* lighter keymap body) lighter nil keymap nil))
137 ((keywordp keymap) (push keymap body) (setq keymap nil)))
139 (let* ((last-message (make-symbol "last-message"))
140 (mode-name (symbol-name mode))
141 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
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")))
156 (while (keywordp (setq keyw (car body)))
157 (setq body (cdr body))
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))))
171 (setq keymap-sym (if (and keymap (symbolp keymap)) keymap
172 (intern (concat mode-name "-map"))))
174 (unless set (setq set '(:set 'custom-set-minor-mode)))
177 (setq initialize '(:initialize 'custom-initialize-default)))
180 ;; We might as well provide a best-guess default group.
182 `(:group ',(intern (replace-regexp-in-string
183 "-mode\\'" "" mode-name)))))
185 (unless type (setq type '(:type 'boolean)))
188 ;; Define the variable to enable or disable the mode.
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))
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."
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)
208 ,@(unless (eq require t) `(:require ,require))
209 ,@(nreverse extra-keywords))))
211 ;; The actual function.
212 (defun ,mode (&optional arg ,@extra-args)
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)))
225 ((eq arg 'toggle) (not ,mode))
226 (arg (> (prefix-numeric-value arg) 0))
230 "Toggling %s off; better pass an explicit argument."
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)
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
244 (message ,(format "%s %%sabled" pretty-name)
245 (if ,mode "en" "dis"))))))
246 (force-mode-line-update)
247 ;; Return the new setting.
250 ;; Autoloading a define-minor-mode autoloads everything
254 ;; Define the minor-mode keymap.
255 ,(unless (symbolp keymap) ;nil is also a symbol.
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)))
263 (add-minor-mode ',mode ',lighter
264 ,(if keymap keymap-sym
265 `(if (boundp ',keymap-sym) ,keymap-sym))))))
268 ;;; make global minor mode
272 (defalias 'easy-mmode-define-global-mode 'define-globalized-minor-mode)
274 (defalias 'define-global-minor-mode 'define-globalized-minor-mode)
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.
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."
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))
300 (MODE-buffers (intern (concat global-mode-name "-buffers")))
301 (MODE-enable-in-buffers
302 (intern (concat global-mode-name "-enable-in-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")))
310 (while (keywordp (setq keyw (car keys)))
311 (setq keys (cdr keys))
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))))
318 ;; We might as well provide a best-guess default group.
320 `(:group ',(intern (replace-regexp-in-string
321 "-mode\\'" "" (symbol-name mode))))))
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
330 ,(format "Toggle %s in every possible buffer.
331 With prefix ARG, turn %s on if and only if
333 %s is enabled in all buffers where
335 See `%s' for more information on %s."
336 pretty-name pretty-global-name pretty-name turn-on
338 :global t ,@group ,@(nreverse extra-keywords)
340 ;; Setup hook to handle future mode changes and new buffers.
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))
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))))))
356 ;; Autoloading define-globalized-minor-mode autoloads everything
360 ;; List of buffers left to process.
361 (defvar ,MODE-buffers nil)
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
369 (unless (eq ,MODE-major-mode major-mode)
372 (setq ,MODE-major-mode major-mode))
374 (setq ,MODE-major-mode major-mode))))))
375 (put ',MODE-enable-in-buffers 'definition-name ',global-mode)
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)
383 ;; The function that catches kill-all-local-variables.
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))))
390 ;;; easy-mmode-defmap
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)
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)
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.
415 Valid keywords and arguments are:
417 :name Name of the keymap; overrides NAME argument.
418 :dense Non-nil for a dense keymap.
419 :inherit Parent keymap.
421 :suppress Non-nil to call `suppress-keymap' on keymap,
422 'nodigits to suppress digits as prefix arguments."
423 (let (inherit dense suppress)
425 (let ((key (pop args))
428 (:name (setq name val))
429 (:dense (setq dense val))
430 (:inherit (setq inherit val))
431 (:suppress (setq suppress val))
433 (t (message "Unknown argument %s in defmap" key)))))
435 (setq bs (append m bs))
436 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
438 (suppress-keymap m (eq suppress 'nodigits)))
442 (dolist (key (if (consp keys) keys (list keys)))
445 (substitute-key-definition key binding m global-map))
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))))))
452 ((keymapp inherit) (set-keymap-parent m inherit))
453 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
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."
462 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
467 ;;; easy-mmode-defsyntax
470 (defun easy-mmode-define-syntax (css args)
471 (let ((st (make-syntax-table (plist-get args :copy)))
472 (parent (plist-get args :inherit)))
474 (let ((char (car cs))
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)))
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)."
488 (autoload 'easy-mmode-define-syntax "easy-mmode")
489 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
494 ;;; easy-mmode-define-navigation
497 (defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun
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")))
516 (if (null narrowfun) body
518 (prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
521 (when was-narrowed (,narrowfun)))))))
522 (unless name (setq name base-name))
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)
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))
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)))
544 (unless (pos-visible-in-window-p endpt nil t)
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))
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)))
557 (put ',prev-sym 'definition-name ',base))))
560 (provide 'easy-mmode)
562 ;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
563 ;;; easy-mmode.el ends here