(define-minor-mode): Generate `turn-on-MODE' and `turn-off-MODE'
[emacs.git] / lisp / emacs-lisp / easy-mmode.el
blob1089d81cd4d068beb14d3faad7d97f50b3573e46
1 ;;; easy-mmode.el --- easy definition for major and minor modes.
3 ;; Copyright (C) 1997,2000 Free Software Foundation, Inc.
5 ;; Author: Georges Brun-Cottan <Georges.Brun-Cottan@inria.fr>
6 ;; Maintainer: Stefan Monnier <monnier@gnu.org>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
25 ;;; Commentary:
27 ;; Minor modes are useful and common. This package makes defining a
28 ;; minor mode easy, by focusing on the writing of the minor mode
29 ;; functionalities themselves. Moreover, this package enforces a
30 ;; conventional naming of user interface primitives, making things
31 ;; natural for the minor-mode end-users.
33 ;; For each mode, easy-mmode defines the following:
34 ;; <mode> : The minor mode predicate. A buffer-local variable.
35 ;; <mode>-map : The keymap possibly associated to <mode>.
36 ;; <mode>-hook : The hook run at the end of the toggle function.
37 ;; see `define-minor-mode' documentation
39 ;; eval
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
47 ;; orderings.
49 ;; Additionally to `define-minor-mode', the package provides convenient
50 ;; ways to define keymaps, and other helper functions for major and minor modes.
52 ;;; Code:
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."
59 (let* ((case-fold-search t)
60 (name (concat (replace-regexp-in-string
61 "-Minor" " minor"
62 (capitalize (replace-regexp-in-string
63 "-mode\\'" "" (symbol-name mode))))
64 " mode")))
65 (if (not (stringp lighter)) name
66 (setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\-s+\\'" "" lighter))
67 (replace-regexp-in-string lighter lighter name t t))))
69 ;;;###autoload
70 (defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
71 ;;;###autoload
72 (defmacro define-minor-mode (mode doc &optional init-value lighter keymap &rest body)
73 "Define a new minor mode MODE.
74 This function defines the associated control variable MODE, keymap MODE-map,
75 toggle command MODE, and hook MODE-hook.
77 DOC is the documentation for the mode toggle command.
78 Optional INIT-VALUE is the initial value of the mode's variable.
79 Optional LIGHTER is displayed in the modeline when the mode is on.
80 Optional KEYMAP is the default (defvar) keymap bound to the mode keymap.
81 If it is a list, it is passed to `easy-mmode-define-keymap'
82 in order to build a valid keymap.
83 BODY contains code that will be executed each time the mode is (dis)activated.
84 It will be executed after any toggling but before running the hooks.
85 BODY can start with a list of CL-style keys specifying additional arguments.
86 Currently three such keyword arguments are supported:
87 :group, followed by the group name to use for any generated `defcustom'.
88 :global, followed by a value, which --
89 If `t' specifies that the minor mode is not meant to be
90 buffer-local (by default, the variable is made buffer-local).
91 If non-nil, but not `t' (for instance, `:global optionally'), then
92 specifies that the minor mode should be buffer-local, but that a
93 corresponding `global-MODE' function should also be added, which can
94 be used to turn on MODE in every buffer.
95 :conditional-turn-on, followed by a function-name which turns on MODE
96 only when applicable to the current buffer. This is used in
97 conjunction with any `global-MODE' function (see :global above) when
98 turning on the buffer-local minor mode. By default, any generated
99 `global-MODE' function unconditionally turns on the minor mode in
100 every new buffer."
101 (let* ((mode-name (symbol-name mode))
102 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
103 (globalp nil)
104 (define-global-mode-p nil)
105 (conditional-turn-on nil)
106 ;; We might as well provide a best-guess default group.
107 (group
108 (list 'quote
109 (intern (replace-regexp-in-string "-mode\\'" "" mode-name))))
110 (keymap-sym (if (and keymap (symbolp keymap)) keymap
111 (intern (concat mode-name "-map"))))
112 (hook (intern (concat mode-name "-hook")))
113 (hook-on (intern (concat mode-name "-on-hook")))
114 (hook-off (intern (concat mode-name "-off-hook"))))
116 ;; FIXME: compatibility that should be removed.
117 (when (and (consp init-value) (eq (car init-value) 'global))
118 (setq init-value (cdr init-value) globalp t))
120 ;; Check keys.
121 (while (keywordp (car body))
122 (case (pop body)
123 (:global (setq globalp (pop body)))
124 (:group (setq group (pop body)))
125 (:conditional-turn-on (setq conditional-turn-on (pop body)))
126 (t (setq body (cdr body)))))
128 (when (and globalp (not (eq globalp t)))
129 (setq globalp nil)
130 (setq define-global-mode-p t))
132 ;; Add default properties to LIGHTER.
133 (unless (or (not (stringp lighter)) (get-text-property 0 'local-map lighter)
134 (get-text-property 0 'keymap lighter))
135 (setq lighter
136 (apply 'propertize lighter
137 'local-map (make-mode-line-mouse2-map mode)
138 (unless (get-text-property 0 'help-echo lighter)
139 (list 'help-echo
140 (format "mouse-2: turn off %s" pretty-name))))))
142 `(progn
143 ;; Define the variable to enable or disable the mode.
144 ,(if (not globalp)
145 `(progn
146 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
147 Use the function `%s' to change this variable." pretty-name mode))
148 (make-variable-buffer-local ',mode))
150 (let ((curfile (or (and (boundp 'byte-compile-current-file)
151 byte-compile-current-file)
152 load-file-name)))
153 `(defcustom ,mode ,init-value
154 ,(format "Toggle %s.
155 Setting this variable directly does not take effect;
156 use either \\[customize] or the function `%s'."
157 pretty-name mode)
158 :set (lambda (symbol value) (funcall symbol (or value 0)))
159 :initialize 'custom-initialize-default
160 :group ,group
161 :type 'boolean
162 ,@(when curfile
163 (list
164 :require
165 (list 'quote
166 (intern (file-name-nondirectory
167 (file-name-sans-extension curfile)))))))))
169 ;; The toggle's hook. Wrapped in `progn' to prevent autoloading.
170 (progn
171 (defcustom ,hook nil
172 ,(format "Hook run at the end of function `%s'." mode-name)
173 :group ,group
174 :type 'hook))
176 ;; The actual function.
177 (defun ,mode (&optional arg)
178 ,(or doc
179 (format "With no argument, toggle %s.
180 With universal prefix ARG turn mode on.
181 With zero or negative ARG turn mode off.
182 \\{%s}" pretty-name keymap-sym))
183 (interactive "P")
184 (setq ,mode
185 (if arg
186 (> (prefix-numeric-value arg) 0)
187 (not ,mode)))
188 ,@body
189 ;; The on/off hooks are here for backward compatibility only.
190 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
191 ;; Return the new setting.
192 (if (interactive-p)
193 (message ,(format "%s %%sabled" pretty-name)
194 (if ,mode "en" "dis")))
195 ,mode)
197 ,(unless globalp
198 (let ((turn-on (intern (concat "turn-on-" mode-name)))
199 (turn-off (intern (concat "turn-off-" mode-name))))
200 `(progn
201 (defun ,turn-on ()
202 ,(format "Turn on %s.
204 This function is designed to be added to hooks, for example:
205 (add-hook 'text-mode-hook '%s)"
206 pretty-name
207 turn-on)
208 (interactive)
209 (,mode t))
210 (defun ,turn-off ()
211 ,(format "Turn off %s." pretty-name)
212 (interactive)
213 (,mode -1))
214 ,(when define-global-mode-p
215 `(easy-mmode-define-global-mode
216 ,(intern (concat "global-" mode-name))
217 ,mode
218 ,(or conditional-turn-on turn-on)
219 :group ,group)))))
221 ;; Autoloading an easy-mmode-define-minor-mode autoloads
222 ;; everything up-to-here.
223 :autoload-end
225 ;; Define the minor-mode keymap.
226 ,(unless (symbolp keymap) ;nil is also a symbol.
227 `(defvar ,keymap-sym
228 (let ((m ,keymap))
229 (cond ((keymapp m) m)
230 ((listp m) (easy-mmode-define-keymap m))
231 (t (error "Invalid keymap %S" ,keymap))))
232 ,(format "Keymap for `%s'." mode-name)))
234 (add-minor-mode ',mode ',lighter
235 ,(if keymap keymap-sym
236 `(if (boundp ',keymap-sym)
237 (symbol-value ',keymap-sym))))
239 ;; If the mode is global, call the function according to the default.
240 ,(if globalp `(if ,mode (,mode 1))))))
243 ;;; make global minor mode
246 ;;;###autoload
247 (defmacro easy-mmode-define-global-mode (global-mode mode turn-on
248 &rest keys)
249 "Make GLOBAL-MODE out of the MODE buffer-local minor mode.
250 TURN-ON is a function that will be called with no args in every buffer
251 and that should try to turn MODE on if applicable for that buffer.
252 KEYS is a list of CL-style keyword arguments:
253 :group to specify the custom group."
254 (let* ((mode-name (symbol-name mode))
255 (global-mode-name (symbol-name global-mode))
256 (pretty-name (easy-mmode-pretty-mode-name mode))
257 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
258 ;; We might as well provide a best-guess default group.
259 (group
260 (list 'quote
261 (intern (replace-regexp-in-string "-mode\\'" "" mode-name))))
262 (buffers (intern (concat global-mode-name "-buffers")))
263 (cmmh (intern (concat global-mode-name "-cmmh"))))
265 ;; Check keys.
266 (while (keywordp (car keys))
267 (case (pop keys)
268 (:group (setq group (pop keys)))
269 (t (setq keys (cdr keys)))))
271 `(progn
272 ;; The actual global minor-mode
273 (define-minor-mode ,global-mode
274 ,(format "Toggle %s in every buffer.
275 With prefix ARG, turn %s on if and only if ARG is positive.
276 %s is actually not turned on in every buffer but only in those
277 in which `%s' turns it on."
278 pretty-name pretty-global-name pretty-name turn-on)
279 nil nil nil :global t :group ,group
281 ;; Setup hook to handle future mode changes and new buffers.
282 (if ,global-mode
283 (progn
284 (add-hook 'find-file-hooks ',buffers)
285 (add-hook 'change-major-mode-hook ',cmmh))
286 (remove-hook 'find-file-hooks ',buffers)
287 (remove-hook 'change-major-mode-hook ',cmmh))
289 ;; Go through existing buffers.
290 (dolist (buf (buffer-list))
291 (with-current-buffer buf
292 (if ,global-mode (,turn-on) (,mode -1)))))
294 ;; Autoloading easy-mmode-define-global-mode
295 ;; autoloads everything up-to-here.
296 :autoload-end
298 ;; List of buffers left to process.
299 (defvar ,buffers nil)
301 ;; The function that calls TURN-ON in each buffer.
302 (defun ,buffers ()
303 (remove-hook 'post-command-hook ',buffers)
304 (while ,buffers
305 (let ((buf (pop ,buffers)))
306 (when (buffer-live-p buf)
307 (with-current-buffer buf (,turn-on))))))
309 ;; The function that catches kill-all-local-variables.
310 (defun ,cmmh ()
311 (add-to-list ',buffers (current-buffer))
312 (add-hook 'post-command-hook ',buffers)))))
315 ;;; easy-mmode-defmap
318 (if (fboundp 'set-keymap-parents)
319 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
320 (defun easy-mmode-set-keymap-parents (m parents)
321 (set-keymap-parent
323 (cond
324 ((not (consp parents)) parents)
325 ((not (cdr parents)) (car parents))
326 (t (let ((m (copy-keymap (pop parents))))
327 (easy-mmode-set-keymap-parents m parents)
328 m))))))
330 ;;;###autoload
331 (defun easy-mmode-define-keymap (bs &optional name m args)
332 "Return a keymap built from bindings BS.
333 BS must be a list of (KEY . BINDING) where
334 KEY and BINDINGS are suitable for `define-key'.
335 Optional NAME is passed to `make-sparse-keymap'.
336 Optional map M can be used to modify an existing map.
337 ARGS is a list of additional arguments."
338 (let (inherit dense suppress)
339 (while args
340 (let ((key (pop args))
341 (val (pop args)))
342 (case key
343 (:dense (setq dense val))
344 (:inherit (setq inherit val))
345 (:group)
346 ;;((eq key :suppress) (setq suppress val))
347 (t (message "Unknown argument %s in defmap" key)))))
348 (unless (keymapp m)
349 (setq bs (append m bs))
350 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
351 (dolist (b bs)
352 (let ((keys (car b))
353 (binding (cdr b)))
354 (dolist (key (if (consp keys) keys (list keys)))
355 (cond
356 ((symbolp key)
357 (substitute-key-definition key binding m global-map))
358 ((null binding)
359 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
360 ((let ((o (lookup-key m key)))
361 (or (null o) (numberp o) (eq o 'undefined)))
362 (define-key m key binding))))))
363 (cond
364 ((keymapp inherit) (set-keymap-parent m inherit))
365 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
368 ;;;###autoload
369 (defmacro easy-mmode-defmap (m bs doc &rest args)
370 `(defconst ,m
371 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
372 ,doc))
376 ;;; easy-mmode-defsyntax
379 (defun easy-mmode-define-syntax (css args)
380 (let ((st (make-syntax-table (plist-get args :copy)))
381 (parent (plist-get args :inherit)))
382 (dolist (cs css)
383 (let ((char (car cs))
384 (syntax (cdr cs)))
385 (if (sequencep char)
386 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
387 (modify-syntax-entry char syntax st))))
388 (if parent (set-char-table-parent
389 st (if (symbolp parent) (symbol-value parent) parent)))
390 st))
392 ;;;###autoload
393 (defmacro easy-mmode-defsyntax (st css doc &rest args)
394 "Define variable ST as a syntax-table.
395 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX).
397 `(progn
398 (autoload 'easy-mmode-define-syntax "easy-mmode")
399 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) doc)))
404 ;;; A "macro-only" reimplementation of define-derived-mode.
407 ;;;###autoload
408 (defmacro define-derived-mode (child parent name &optional docstring &rest body)
409 "Create a new mode as a variant of an existing mode.
411 The arguments to this command are as follow:
413 CHILD: the name of the command for the derived mode.
414 PARENT: the name of the command for the parent mode (e.g. `text-mode').
415 NAME: a string which will appear in the status line (e.g. \"Hypertext\")
416 DOCSTRING: an optional documentation string--if you do not supply one,
417 the function will attempt to invent something useful.
418 BODY: forms to execute just before running the
419 hooks for the new mode.
421 Here is how you could define LaTeX-Thesis mode as a variant of LaTeX mode:
423 (define-derived-mode LaTeX-thesis-mode LaTeX-mode \"LaTeX-Thesis\")
425 You could then make new key bindings for `LaTeX-thesis-mode-map'
426 without changing regular LaTeX mode. In this example, BODY is empty,
427 and DOCSTRING is generated by default.
429 On a more complicated level, the following command uses `sgml-mode' as
430 the parent, and then sets the variable `case-fold-search' to nil:
432 (define-derived-mode article-mode sgml-mode \"Article\"
433 \"Major mode for editing technical articles.\"
434 (setq case-fold-search nil))
436 Note that if the documentation string had been left out, it would have
437 been generated automatically, with a reference to the keymap."
439 (let* ((child-name (symbol-name child))
440 (map (intern (concat child-name "-map")))
441 (syntax (intern (concat child-name "-syntax-table")))
442 (abbrev (intern (concat child-name "-abbrev-table")))
443 (hook (intern (concat child-name "-hook"))))
445 (unless parent (setq parent 'fundamental-mode))
447 (when (and docstring (not (stringp docstring)))
448 ;; DOCSTRING is really the first command and there's no docstring
449 (push docstring body)
450 (setq docstring nil))
452 (unless (stringp docstring)
453 ;; Use a default docstring.
454 (setq docstring
455 (format "Major mode derived from `%s' by `define-derived-mode'.
456 Inherits all of the parent's attributes, but has its own keymap,
457 abbrev table and syntax table:
459 `%s', `%s' and `%s'
461 which more-or-less shadow %s's corresponding tables."
462 parent map syntax abbrev parent)))
464 (unless (string-match (regexp-quote (symbol-name hook)) docstring)
465 ;; Make sure the docstring mentions the mode's hook
466 (setq docstring
467 (concat docstring
468 (if (eq parent 'fundamental-mode)
469 "\n\nThis mode "
470 (concat
471 "\n\nIn addition to any hooks its parent mode "
472 (if (string-match (regexp-quote (format "`%s'" parent))
473 docstring) nil
474 (format "`%s' " parent))
475 "might have run,\nthis mode "))
476 (format "runs the hook `%s'" hook)
477 ", as the final step\nduring initialization.")))
479 (unless (string-match "\\\\[{[]" docstring)
480 ;; And don't forget to put the mode's keymap
481 (setq docstring (concat docstring "\n\n\\{" (symbol-name map) "}")))
483 `(progn
484 (defvar ,map (make-sparse-keymap))
485 (defvar ,syntax (make-char-table 'syntax-table nil))
486 (defvar ,abbrev)
487 (define-abbrev-table ',abbrev nil)
488 (put ',child 'derived-mode-parent ',parent)
490 (defun ,child ()
491 ,docstring
492 (interactive)
493 ; Run the parent.
494 (combine-run-hooks
496 (,parent)
497 ; Identify special modes.
498 (put ',child 'special (get ',parent 'special))
499 ; Identify the child mode.
500 (setq major-mode ',child)
501 (setq mode-name ,name)
502 ; Set up maps and tables.
503 (unless (keymap-parent ,map)
504 (set-keymap-parent ,map (current-local-map)))
505 (let ((parent (char-table-parent ,syntax)))
506 (unless (and parent (not (eq parent (standard-syntax-table))))
507 (set-char-table-parent ,syntax (syntax-table))))
508 (when local-abbrev-table
509 (mapatoms
510 (lambda (symbol)
511 (or (intern-soft (symbol-name symbol) ,abbrev)
512 (define-abbrev ,abbrev (symbol-name symbol)
513 (symbol-value symbol) (symbol-function symbol))))
514 local-abbrev-table))
516 (use-local-map ,map)
517 (set-syntax-table ,syntax)
518 (setq local-abbrev-table ,abbrev)
519 ; Splice in the body (if any).
520 ,@body)
521 ; Run the hooks, if any.
522 (run-hooks ',hook)))))
524 ;; Inspired from derived-mode-class in derived.el
525 (defun easy-mmode-derived-mode-p (mode)
526 "Non-nil if the current major mode is derived from MODE.
527 Uses the `derived-mode-parent' property of the symbol to trace backwards."
528 (let ((parent major-mode))
529 (while (and (not (eq parent mode))
530 (setq parent (get parent 'derived-mode-parent))))
531 parent))
535 ;;; easy-mmode-define-navigation
538 (defmacro easy-mmode-define-navigation (base re &optional name endfun)
539 "Define BASE-next and BASE-prev to navigate in the buffer.
540 RE determines the places the commands should move point to.
541 NAME should describe the entities matched by RE and is used to build
542 the docstrings of the two functions.
543 BASE-next also tries to make sure that the whole entry is visible by
544 searching for its end (by calling ENDFUN if provided or by looking for
545 the next entry) and recentering if necessary.
546 ENDFUN should return the end position (with or without moving point)."
547 (let* ((base-name (symbol-name base))
548 (prev-sym (intern (concat base-name "-prev")))
549 (next-sym (intern (concat base-name "-next"))))
550 (unless name (setq name (symbol-name base-name)))
551 `(progn
552 (add-to-list 'debug-ignored-errors
553 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
554 (defun ,next-sym (&optional count)
555 ,(format "Go to the next COUNT'th %s." name)
556 (interactive)
557 (unless count (setq count 1))
558 (if (< count 0) (,prev-sym (- count))
559 (if (looking-at ,re) (incf count))
560 (unless (re-search-forward ,re nil t count)
561 (error ,(format "No next %s" name)))
562 (goto-char (match-beginning 0))
563 (when (eq (current-buffer) (window-buffer (selected-window)))
564 (let ((endpt (or (save-excursion
565 ,(if endfun `(,endfun)
566 `(re-search-forward ,re nil t 2)))
567 (point-max))))
568 (unless (<= endpt (window-end))
569 (recenter '(0)))))))
570 (defun ,prev-sym (&optional count)
571 ,(format "Go to the previous COUNT'th %s" (or name base-name))
572 (interactive)
573 (unless count (setq count 1))
574 (if (< count 0) (,next-sym (- count))
575 (unless (re-search-backward ,re nil t count)
576 (error ,(format "No previous %s" name))))))))
578 (provide 'easy-mmode)
580 ;;; easy-mmode.el ends here