(define-minor-mode): Remove :toggle arg.
[emacs.git] / lisp / emacs-lisp / easy-mmode.el
blob4d6897fc1d51f1ff5499c4b66f1586efe9d820b1
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. It's generally better to use
83 a separate MODE-map variable than to use this argument.
84 The above three arguments can be skipped if keyword arguments are
85 used (see below).
87 BODY contains code that will be executed each time the mode is (dis)activated.
88 It will be executed after any toggling but before running the hooks.
89 BODY can start with a list of CL-style keys specifying additional arguments.
90 The following keyword arguments are supported:
91 :group Followed by the group name to use for any generated `defcustom'.
92 :global If non-nil specifies that the minor mode is not meant to be
93 buffer-local. By default, the variable is made buffer-local.
94 :init-value Same as the INIT-VALUE argument.
95 :lighter Same as the LIGHTER argument."
96 ;; Allow skipping the first three args.
97 (cond
98 ((keywordp init-value)
99 (setq body (list* init-value lighter keymap body)
100 init-value nil lighter nil keymap nil))
101 ((keywordp lighter)
102 (setq body (list* lighter keymap body) lighter nil keymap nil))
103 ((keywordp keymap) (push keymap body) (setq keymap nil)))
105 (let* ((mode-name (symbol-name mode))
106 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
107 (globalp nil)
108 (togglep t) ;why would you ever want to toggle?
109 (group nil)
110 (extra-args nil)
111 (keymap-sym (if (and keymap (symbolp keymap)) keymap
112 (intern (concat mode-name "-map"))))
113 (hook (intern (concat mode-name "-hook")))
114 (hook-on (intern (concat mode-name "-on-hook")))
115 (hook-off (intern (concat mode-name "-off-hook"))))
117 ;; Check keys.
118 (while (keywordp (car body))
119 (case (pop body)
120 (:init-value (setq init-value (pop body)))
121 (:lighter (setq lighter (pop body)))
122 (:global (setq globalp (pop body)))
123 (:extra-args (setq extra-args (pop body)))
124 (:group (setq group (nconc group (list :group (pop body)))))
125 (t (pop body))))
127 (unless group
128 ;; We might as well provide a best-guess default group.
129 (setq group
130 `(:group ',(intern (replace-regexp-in-string "-mode\\'" ""
131 mode-name)))))
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 on or off.
155 See the command `%s' for a description of this minor-mode.
156 Setting this variable directly does not take effect;
157 use either \\[customize] or the function `%s'."
158 pretty-name mode mode)
159 :set (lambda (symbol value) (funcall symbol (or value 0)))
160 :initialize 'custom-initialize-default
161 ,@group
162 :type 'boolean
163 ,@(when curfile
164 (list
165 :require
166 (list 'quote
167 (intern (file-name-nondirectory
168 (file-name-sans-extension curfile)))))))))
170 ;; The actual function.
171 (defun ,mode (&optional arg ,@extra-args)
172 ,(or doc
173 (format (concat "Toggle %s on or off.
174 Interactively, with no prefix argument, toggle the mode.
175 With universal prefix ARG " (unless togglep "(or if ARG is nil) ") "turn mode on.
176 With zero or negative ARG turn mode off.
177 \\{%s}") pretty-name keymap-sym))
178 (interactive (list (or current-prefix-arg (if ,mode 0 1))))
179 (setq ,mode
180 (if arg
181 (> (prefix-numeric-value arg) 0)
182 ,(if togglep `(not ,mode) t)))
183 ,@body
184 ;; The on/off hooks are here for backward compatibility only.
185 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
186 ;; Return the new setting.
187 (if (interactive-p)
188 (message ,(format "%s %%sabled" pretty-name)
189 (if ,mode "en" "dis")))
190 (force-mode-line-update)
191 ,mode)
193 ;; Autoloading an easy-mmode-define-minor-mode autoloads
194 ;; everything up-to-here.
195 :autoload-end
197 ;; The toggle's hook.
198 (defcustom ,hook nil
199 ,(format "Hook run at the end of function `%s'." mode-name)
200 :group ,(cadr group)
201 :type 'hook)
203 ;; Define the minor-mode keymap.
204 ,(unless (symbolp keymap) ;nil is also a symbol.
205 `(defvar ,keymap-sym
206 (let ((m ,keymap))
207 (cond ((keymapp m) m)
208 ((listp m) (easy-mmode-define-keymap m))
209 (t (error "Invalid keymap %S" ,keymap))))
210 ,(format "Keymap for `%s'." mode-name)))
212 (add-minor-mode ',mode ',lighter
213 ,(if keymap keymap-sym
214 `(if (boundp ',keymap-sym)
215 (symbol-value ',keymap-sym))))
217 ;; If the mode is global, call the function according to the default.
218 ,(if globalp `(if ,mode (,mode 1))))))
221 ;;; make global minor mode
224 ;;;###autoload
225 (defmacro easy-mmode-define-global-mode (global-mode mode turn-on
226 &rest keys)
227 "Make GLOBAL-MODE out of the buffer-local minor MODE.
228 TURN-ON is a function that will be called with no args in every buffer
229 and that should try to turn MODE on if applicable for that buffer.
230 KEYS is a list of CL-style keyword arguments:
231 :group to specify the custom group."
232 (let* ((global-mode-name (symbol-name global-mode))
233 (pretty-name (easy-mmode-pretty-mode-name mode))
234 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
235 (group nil)
236 (extra-args nil)
237 (buffers (intern (concat global-mode-name "-buffers")))
238 (cmmh (intern (concat global-mode-name "-cmmh"))))
240 ;; Check keys.
241 (while (keywordp (car keys))
242 (case (pop keys)
243 (:extra-args (setq extra-args (pop keys)))
244 (:group (setq group (nconc group (list :group (pop keys)))))
245 (t (setq keys (cdr keys)))))
247 (unless group
248 ;; We might as well provide a best-guess default group.
249 (setq group
250 `(:group ',(intern (replace-regexp-in-string "-mode\\'" ""
251 (symbol-name mode))))))
252 `(progn
253 ;; The actual global minor-mode
254 (define-minor-mode ,global-mode
255 ,(format "Toggle %s in every buffer.
256 With prefix ARG, turn %s on if and only if ARG is positive.
257 %s is actually not turned on in every buffer but only in those
258 in which `%s' turns it on."
259 pretty-name pretty-global-name pretty-name turn-on)
260 :global t :extra-args ,extra-args ,@group
262 ;; Setup hook to handle future mode changes and new buffers.
263 (if ,global-mode
264 (progn
265 (add-hook 'find-file-hooks ',buffers)
266 (add-hook 'change-major-mode-hook ',cmmh))
267 (remove-hook 'find-file-hooks ',buffers)
268 (remove-hook 'change-major-mode-hook ',cmmh))
270 ;; Go through existing buffers.
271 (dolist (buf (buffer-list))
272 (with-current-buffer buf
273 (if ,global-mode (,turn-on) (,mode -1)))))
275 ;; Autoloading easy-mmode-define-global-mode
276 ;; autoloads everything up-to-here.
277 :autoload-end
279 ;; List of buffers left to process.
280 (defvar ,buffers nil)
282 ;; The function that calls TURN-ON in each buffer.
283 (defun ,buffers ()
284 (remove-hook 'post-command-hook ',buffers)
285 (while ,buffers
286 (let ((buf (pop ,buffers)))
287 (when (buffer-live-p buf)
288 (with-current-buffer buf (,turn-on))))))
290 ;; The function that catches kill-all-local-variables.
291 (defun ,cmmh ()
292 (add-to-list ',buffers (current-buffer))
293 (add-hook 'post-command-hook ',buffers)))))
296 ;;; easy-mmode-defmap
299 (if (fboundp 'set-keymap-parents)
300 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
301 (defun easy-mmode-set-keymap-parents (m parents)
302 (set-keymap-parent
304 (cond
305 ((not (consp parents)) parents)
306 ((not (cdr parents)) (car parents))
307 (t (let ((m (copy-keymap (pop parents))))
308 (easy-mmode-set-keymap-parents m parents)
309 m))))))
311 ;;;###autoload
312 (defun easy-mmode-define-keymap (bs &optional name m args)
313 "Return a keymap built from bindings BS.
314 BS must be a list of (KEY . BINDING) where
315 KEY and BINDINGS are suitable for `define-key'.
316 Optional NAME is passed to `make-sparse-keymap'.
317 Optional map M can be used to modify an existing map.
318 ARGS is a list of additional arguments."
319 (let (inherit dense suppress)
320 (while args
321 (let ((key (pop args))
322 (val (pop args)))
323 (case key
324 (:dense (setq dense val))
325 (:inherit (setq inherit val))
326 (:group)
327 ;;((eq key :suppress) (setq suppress val))
328 (t (message "Unknown argument %s in defmap" key)))))
329 (unless (keymapp m)
330 (setq bs (append m bs))
331 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
332 (dolist (b bs)
333 (let ((keys (car b))
334 (binding (cdr b)))
335 (dolist (key (if (consp keys) keys (list keys)))
336 (cond
337 ((symbolp key)
338 (substitute-key-definition key binding m global-map))
339 ((null binding)
340 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
341 ((let ((o (lookup-key m key)))
342 (or (null o) (numberp o) (eq o 'undefined)))
343 (define-key m key binding))))))
344 (cond
345 ((keymapp inherit) (set-keymap-parent m inherit))
346 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
349 ;;;###autoload
350 (defmacro easy-mmode-defmap (m bs doc &rest args)
351 `(defconst ,m
352 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
353 ,doc))
357 ;;; easy-mmode-defsyntax
360 (defun easy-mmode-define-syntax (css args)
361 (let ((st (make-syntax-table (plist-get args :copy)))
362 (parent (plist-get args :inherit)))
363 (dolist (cs css)
364 (let ((char (car cs))
365 (syntax (cdr cs)))
366 (if (sequencep char)
367 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
368 (modify-syntax-entry char syntax st))))
369 (if parent (set-char-table-parent
370 st (if (symbolp parent) (symbol-value parent) parent)))
371 st))
373 ;;;###autoload
374 (defmacro easy-mmode-defsyntax (st css doc &rest args)
375 "Define variable ST as a syntax-table.
376 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX).
378 `(progn
379 (autoload 'easy-mmode-define-syntax "easy-mmode")
380 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) doc)))
385 ;;; A "macro-only" reimplementation of define-derived-mode.
388 ;;;###autoload
389 (defmacro define-derived-mode (child parent name &optional docstring &rest body)
390 "Create a new mode as a variant of an existing mode.
392 The arguments to this command are as follow:
394 CHILD: the name of the command for the derived mode.
395 PARENT: the name of the command for the parent mode (e.g. `text-mode').
396 NAME: a string which will appear in the status line (e.g. \"Hypertext\")
397 DOCSTRING: an optional documentation string--if you do not supply one,
398 the function will attempt to invent something useful.
399 BODY: forms to execute just before running the
400 hooks for the new mode.
402 Here is how you could define LaTeX-Thesis mode as a variant of LaTeX mode:
404 (define-derived-mode LaTeX-thesis-mode LaTeX-mode \"LaTeX-Thesis\")
406 You could then make new key bindings for `LaTeX-thesis-mode-map'
407 without changing regular LaTeX mode. In this example, BODY is empty,
408 and DOCSTRING is generated by default.
410 On a more complicated level, the following command uses `sgml-mode' as
411 the parent, and then sets the variable `case-fold-search' to nil:
413 (define-derived-mode article-mode sgml-mode \"Article\"
414 \"Major mode for editing technical articles.\"
415 (setq case-fold-search nil))
417 Note that if the documentation string had been left out, it would have
418 been generated automatically, with a reference to the keymap."
420 (let* ((child-name (symbol-name child))
421 (map (intern (concat child-name "-map")))
422 (syntax (intern (concat child-name "-syntax-table")))
423 (abbrev (intern (concat child-name "-abbrev-table")))
424 (hook (intern (concat child-name "-hook"))))
426 (unless parent (setq parent 'fundamental-mode))
428 (when (and docstring (not (stringp docstring)))
429 ;; DOCSTRING is really the first command and there's no docstring
430 (push docstring body)
431 (setq docstring nil))
433 (unless (stringp docstring)
434 ;; Use a default docstring.
435 (setq docstring
436 (format "Major mode derived from `%s' by `define-derived-mode'.
437 Inherits all of the parent's attributes, but has its own keymap,
438 abbrev table and syntax table:
440 `%s', `%s' and `%s'
442 which more-or-less shadow %s's corresponding tables."
443 parent map syntax abbrev parent)))
445 (unless (string-match (regexp-quote (symbol-name hook)) docstring)
446 ;; Make sure the docstring mentions the mode's hook
447 (setq docstring
448 (concat docstring
449 (if (eq parent 'fundamental-mode)
450 "\n\nThis mode "
451 (concat
452 "\n\nIn addition to any hooks its parent mode "
453 (if (string-match (regexp-quote (format "`%s'" parent))
454 docstring) nil
455 (format "`%s' " parent))
456 "might have run,\nthis mode "))
457 (format "runs the hook `%s'" hook)
458 ", as the final step\nduring initialization.")))
460 (unless (string-match "\\\\[{[]" docstring)
461 ;; And don't forget to put the mode's keymap
462 (setq docstring (concat docstring "\n\n\\{" (symbol-name map) "}")))
464 `(progn
465 (defvar ,map (make-sparse-keymap))
466 (defvar ,syntax (make-char-table 'syntax-table nil))
467 (defvar ,abbrev)
468 (define-abbrev-table ',abbrev nil)
469 (put ',child 'derived-mode-parent ',parent)
471 (defun ,child ()
472 ,docstring
473 (interactive)
474 ; Run the parent.
475 (combine-run-hooks
477 (,parent)
478 ; Identify special modes.
479 (put ',child 'special (get ',parent 'special))
480 ; Identify the child mode.
481 (setq major-mode ',child)
482 (setq mode-name ,name)
483 ; Set up maps and tables.
484 (unless (keymap-parent ,map)
485 (set-keymap-parent ,map (current-local-map)))
486 (let ((parent (char-table-parent ,syntax)))
487 (unless (and parent (not (eq parent (standard-syntax-table))))
488 (set-char-table-parent ,syntax (syntax-table))))
489 (when local-abbrev-table
490 (mapatoms
491 (lambda (symbol)
492 (or (intern-soft (symbol-name symbol) ,abbrev)
493 (define-abbrev ,abbrev (symbol-name symbol)
494 (symbol-value symbol) (symbol-function symbol))))
495 local-abbrev-table))
497 (use-local-map ,map)
498 (set-syntax-table ,syntax)
499 (setq local-abbrev-table ,abbrev)
500 ; Splice in the body (if any).
501 ,@body)
502 ; Run the hooks, if any.
503 (run-hooks ',hook)))))
505 ;; Inspired from derived-mode-class in derived.el
506 (defun easy-mmode-derived-mode-p (mode)
507 "Non-nil if the current major mode is derived from MODE.
508 Uses the `derived-mode-parent' property of the symbol to trace backwards."
509 (let ((parent major-mode))
510 (while (and (not (eq parent mode))
511 (setq parent (get parent 'derived-mode-parent))))
512 parent))
516 ;;; easy-mmode-define-navigation
519 (defmacro easy-mmode-define-navigation (base re &optional name endfun)
520 "Define BASE-next and BASE-prev to navigate in the buffer.
521 RE determines the places the commands should move point to.
522 NAME should describe the entities matched by RE and is used to build
523 the docstrings of the two functions.
524 BASE-next also tries to make sure that the whole entry is visible by
525 searching for its end (by calling ENDFUN if provided or by looking for
526 the next entry) and recentering if necessary.
527 ENDFUN should return the end position (with or without moving point)."
528 (let* ((base-name (symbol-name base))
529 (prev-sym (intern (concat base-name "-prev")))
530 (next-sym (intern (concat base-name "-next"))))
531 (unless name (setq name (symbol-name base-name)))
532 `(progn
533 (add-to-list 'debug-ignored-errors
534 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
535 (defun ,next-sym (&optional count)
536 ,(format "Go to the next COUNT'th %s." name)
537 (interactive)
538 (unless count (setq count 1))
539 (if (< count 0) (,prev-sym (- count))
540 (if (looking-at ,re) (incf count))
541 (unless (re-search-forward ,re nil t count)
542 (error ,(format "No next %s" name)))
543 (goto-char (match-beginning 0))
544 (when (eq (current-buffer) (window-buffer (selected-window)))
545 (let ((endpt (or (save-excursion
546 ,(if endfun `(,endfun)
547 `(re-search-forward ,re nil t 2)))
548 (point-max))))
549 (unless (<= endpt (window-end))
550 (recenter '(0)))))))
551 (defun ,prev-sym (&optional count)
552 ,(format "Go to the previous COUNT'th %s" (or name base-name))
553 (interactive)
554 (unless count (setq count 1))
555 (if (< count 0) (,next-sym (- count))
556 (unless (re-search-backward ,re nil t count)
557 (error ,(format "No previous %s" name))))))))
559 (provide 'easy-mmode)
561 ;;; easy-mmode.el ends here