(easy-mmode-pretty-mode-name): Prettier.
[emacs.git] / lisp / emacs-lisp / easy-mmode.el
blob6b8ab0503f074028e0c558346e24e56d07b651b8
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 two such keyword arguments are supported:
87 :group followed by the group name to use for any generated `defcustom'.
88 :global if non-nil specifies that the minor mode is not meant to be
89 buffer-local. By default, the variable is made buffer-local."
90 (let* ((mode-name (symbol-name mode))
91 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
92 (globalp nil)
93 ;; We might as well provide a best-guess default group.
94 (group
95 (list 'quote
96 (intern (replace-regexp-in-string "-mode\\'" "" mode-name))))
97 (keymap-sym (if (and keymap (symbolp keymap)) keymap
98 (intern (concat mode-name "-map"))))
99 (hook (intern (concat mode-name "-hook")))
100 (hook-on (intern (concat mode-name "-on-hook")))
101 (hook-off (intern (concat mode-name "-off-hook"))))
103 ;; FIXME: compatibility that should be removed.
104 (when (and (consp init-value) (eq (car init-value) 'global))
105 (setq init-value (cdr init-value) globalp t))
107 ;; Check keys.
108 (while (keywordp (car body))
109 (case (pop body)
110 (:global (setq globalp (pop body)))
111 (:group (setq group (pop body)))
112 (t (setq body (cdr body)))))
114 ;; Add default properties to LIGHTER.
115 (unless (or (not (stringp lighter)) (get-text-property 0 'local-map lighter)
116 (get-text-property 0 'keymap lighter))
117 (setq lighter
118 (apply 'propertize lighter
119 'local-map (make-mode-line-mouse2-map mode)
120 (unless (get-text-property 0 'help-echo lighter)
121 (list 'help-echo
122 (format "mouse-2: turn off %s" pretty-name))))))
124 `(progn
125 ;; Define the variable to enable or disable the mode.
126 ,(if (not globalp)
127 `(progn
128 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
129 Use the function `%s' to change this variable." pretty-name mode))
130 (make-variable-buffer-local ',mode))
132 (let ((curfile (or (and (boundp 'byte-compile-current-file)
133 byte-compile-current-file)
134 load-file-name)))
135 `(defcustom ,mode ,init-value
136 ,(format "Toggle %s.
137 Setting this variable directly does not take effect;
138 use either \\[customize] or the function `%s'."
139 pretty-name mode)
140 :set (lambda (symbol value) (funcall symbol (or value 0)))
141 :initialize 'custom-initialize-default
142 :group ,group
143 :type 'boolean
144 ,@(when curfile
145 (list
146 :require
147 (list 'quote
148 (intern (file-name-nondirectory
149 (file-name-sans-extension curfile)))))))))
151 ;; The toggle's hook. Wrapped in `progn' to prevent autoloading.
152 (progn
153 (defcustom ,hook nil
154 ,(format "Hook run at the end of function `%s'." mode-name)
155 :group ,group
156 :type 'hook))
158 ;; The actual function.
159 (defun ,mode (&optional arg)
160 ,(or doc
161 (format "With no argument, toggle %s.
162 With universal prefix ARG turn mode on.
163 With zero or negative ARG turn mode off.
164 \\{%s}" pretty-name keymap-sym))
165 (interactive "P")
166 (setq ,mode
167 (if arg
168 (> (prefix-numeric-value arg) 0)
169 (not ,mode)))
170 ,@body
171 ;; The on/off hooks are here for backward compatibility only.
172 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
173 ;; Return the new setting.
174 (if (interactive-p)
175 (message ,(format "%s %%sabled" pretty-name)
176 (if ,mode "en" "dis")))
177 ,mode)
179 ;; Autoloading an easy-mmode-define-minor-mode autoloads
180 ;; everything up-to-here.
181 :autoload-end
183 ;; Define the minor-mode keymap.
184 ,(unless (symbolp keymap) ;nil is also a symbol.
185 `(defvar ,keymap-sym
186 (let ((m ,keymap))
187 (cond ((keymapp m) m)
188 ((listp m) (easy-mmode-define-keymap m))
189 (t (error "Invalid keymap %S" ,keymap))))
190 ,(format "Keymap for `%s'." mode-name)))
192 (add-minor-mode ',mode ',lighter
193 ,(if keymap keymap-sym
194 `(if (boundp ',keymap-sym)
195 (symbol-value ',keymap-sym))))
197 ;; If the mode is global, call the function according to the default.
198 ,(if globalp `(if ,mode (,mode 1))))))
201 ;;; make global minor mode
204 ;;;###autoload
205 (defmacro easy-mmode-define-global-mode (global-mode mode turn-on
206 &rest keys)
207 "Make GLOBAL-MODE out of the MODE buffer-local minor mode.
208 TURN-ON is a function that will be called with no args in every buffer
209 and that should try to turn MODE on if applicable for that buffer.
210 KEYS is a list of CL-style keyword arguments:
211 :group to specify the custom group."
212 (let* ((mode-name (symbol-name mode))
213 (global-mode-name (symbol-name global-mode))
214 (pretty-name (easy-mmode-pretty-mode-name mode))
215 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
216 ;; We might as well provide a best-guess default group.
217 (group
218 (list 'quote
219 (intern (replace-regexp-in-string "-mode\\'" "" mode-name))))
220 (buffers (intern (concat global-mode-name "-buffers")))
221 (cmmh (intern (concat global-mode-name "-cmmh"))))
223 ;; Check keys.
224 (while (keywordp (car keys))
225 (case (pop keys)
226 (:group (setq group (pop keys)))
227 (t (setq keys (cdr keys)))))
229 `(progn
230 ;; The actual global minor-mode
231 (define-minor-mode ,global-mode
232 ,(format "Toggle %s in every buffer.
233 With prefix ARG, turn %s on if and only if ARG is positive.
234 %s is actually not turned on in every buffer but only in those
235 in which `%s' turns it on."
236 pretty-name pretty-global-name pretty-name turn-on)
237 nil nil nil :global t :group ,group
239 ;; Setup hook to handle future mode changes and new buffers.
240 (if ,global-mode
241 (progn
242 (add-hook 'find-file-hooks ',buffers)
243 (add-hook 'change-major-mode-hook ',cmmh))
244 (remove-hook 'find-file-hooks ',buffers)
245 (remove-hook 'change-major-mode-hook ',cmmh))
247 ;; Go through existing buffers.
248 (dolist (buf (buffer-list))
249 (with-current-buffer buf
250 (if ,global-mode (,turn-on) (,mode -1)))))
252 ;; Autoloading easy-mmode-define-global-mode
253 ;; autoloads everything up-to-here.
254 :autoload-end
256 ;; List of buffers left to process.
257 (defvar ,buffers nil)
259 ;; The function that calls TURN-ON in each buffer.
260 (defun ,buffers ()
261 (remove-hook 'post-command-hook ',buffers)
262 (while ,buffers
263 (let ((buf (pop ,buffers)))
264 (when (buffer-live-p buf)
265 (with-current-buffer buf (,turn-on))))))
267 ;; The function that catches kill-all-local-variables.
268 (defun ,cmmh ()
269 (add-to-list ',buffers (current-buffer))
270 (add-hook 'post-command-hook ',buffers)))))
273 ;;; easy-mmode-defmap
276 (if (fboundp 'set-keymap-parents)
277 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
278 (defun easy-mmode-set-keymap-parents (m parents)
279 (set-keymap-parent
281 (cond
282 ((not (consp parents)) parents)
283 ((not (cdr parents)) (car parents))
284 (t (let ((m (copy-keymap (pop parents))))
285 (easy-mmode-set-keymap-parents m parents)
286 m))))))
288 ;;;###autoload
289 (defun easy-mmode-define-keymap (bs &optional name m args)
290 "Return a keymap built from bindings BS.
291 BS must be a list of (KEY . BINDING) where
292 KEY and BINDINGS are suitable for `define-key'.
293 Optional NAME is passed to `make-sparse-keymap'.
294 Optional map M can be used to modify an existing map.
295 ARGS is a list of additional arguments."
296 (let (inherit dense suppress)
297 (while args
298 (let ((key (pop args))
299 (val (pop args)))
300 (case key
301 (:dense (setq dense val))
302 (:inherit (setq inherit val))
303 (:group)
304 ;;((eq key :suppress) (setq suppress val))
305 (t (message "Unknown argument %s in defmap" key)))))
306 (unless (keymapp m)
307 (setq bs (append m bs))
308 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
309 (dolist (b bs)
310 (let ((keys (car b))
311 (binding (cdr b)))
312 (dolist (key (if (consp keys) keys (list keys)))
313 (cond
314 ((symbolp key)
315 (substitute-key-definition key binding m global-map))
316 ((null binding)
317 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
318 ((let ((o (lookup-key m key)))
319 (or (null o) (numberp o) (eq o 'undefined)))
320 (define-key m key binding))))))
321 (cond
322 ((keymapp inherit) (set-keymap-parent m inherit))
323 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
326 ;;;###autoload
327 (defmacro easy-mmode-defmap (m bs doc &rest args)
328 `(defconst ,m
329 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
330 ,doc))
334 ;;; easy-mmode-defsyntax
337 (defun easy-mmode-define-syntax (css args)
338 (let ((st (make-syntax-table (cadr (memq :copy args)))))
339 (dolist (cs css)
340 (let ((char (car cs))
341 (syntax (cdr cs)))
342 (if (sequencep char)
343 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
344 (modify-syntax-entry char syntax st))))
345 st))
347 ;;;###autoload
348 (defmacro easy-mmode-defsyntax (st css doc &rest args)
349 `(progn
350 (autoload 'easy-mmode-define-syntax "easy-mmode")
351 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) doc)))
356 ;;; A "macro-only" reimplementation of define-derived-mode.
359 ;;;###autoload
360 (defmacro define-derived-mode (child parent name &optional docstring &rest body)
361 "Create a new mode as a variant of an existing mode.
363 The arguments to this command are as follow:
365 CHILD: the name of the command for the derived mode.
366 PARENT: the name of the command for the parent mode (e.g. `text-mode').
367 NAME: a string which will appear in the status line (e.g. \"Hypertext\")
368 DOCSTRING: an optional documentation string--if you do not supply one,
369 the function will attempt to invent something useful.
370 BODY: forms to execute just before running the
371 hooks for the new mode.
373 Here is how you could define LaTeX-Thesis mode as a variant of LaTeX mode:
375 (define-derived-mode LaTeX-thesis-mode LaTeX-mode \"LaTeX-Thesis\")
377 You could then make new key bindings for `LaTeX-thesis-mode-map'
378 without changing regular LaTeX mode. In this example, BODY is empty,
379 and DOCSTRING is generated by default.
381 On a more complicated level, the following command uses `sgml-mode' as
382 the parent, and then sets the variable `case-fold-search' to nil:
384 (define-derived-mode article-mode sgml-mode \"Article\"
385 \"Major mode for editing technical articles.\"
386 (setq case-fold-search nil))
388 Note that if the documentation string had been left out, it would have
389 been generated automatically, with a reference to the keymap."
391 (let* ((child-name (symbol-name child))
392 (map (intern (concat child-name "-map")))
393 (syntax (intern (concat child-name "-syntax-table")))
394 (abbrev (intern (concat child-name "-abbrev-table")))
395 (hook (intern (concat child-name "-hook"))))
397 (unless parent (setq parent 'fundamental-mode))
399 (when (and docstring (not (stringp docstring)))
400 ;; DOCSTRING is really the first command and there's no docstring
401 (push docstring body)
402 (setq docstring nil))
404 (unless (stringp docstring)
405 ;; Use a default docstring.
406 (setq docstring
407 (format "Major mode derived from `%s' by `define-derived-mode'.
408 Inherits all of the parent's attributes, but has its own keymap,
409 abbrev table and syntax table:
411 `%s', `%s' and `%s'
413 which more-or-less shadow %s's corresponding tables."
414 parent map syntax abbrev parent)))
416 (unless (string-match (regexp-quote (symbol-name hook)) docstring)
417 ;; Make sure the docstring mentions the mode's hook
418 (setq docstring
419 (concat docstring
420 (unless (eq parent 'fundamental-mode)
421 (concat
422 "\nAdditionally to any hooks its parent mode "
423 (if (string-match (regexp-quote (format "`%s'" parent))
424 docstring) nil
425 (format "`%s' " parent))
426 "might have run),"))
427 (format "\nThis mode runs `%s' just before exiting." hook))))
429 (unless (string-match "\\\\[{[]" docstring)
430 ;; And don't forget to put the mode's keymap
431 (setq docstring (concat docstring "\n\\{" (symbol-name map) "}")))
433 `(progn
434 (defvar ,map (make-sparse-keymap))
435 (defvar ,syntax (make-char-table 'syntax-table nil))
436 (defvar ,abbrev)
437 (define-abbrev-table ',abbrev nil)
438 (put ',child 'derived-mode-parent ',parent)
440 (defun ,child ()
441 ,docstring
442 (interactive)
443 ; Run the parent.
444 (combine-run-hooks
446 (,parent)
447 ; Identify special modes.
448 (put ',child 'special (get ',parent 'special))
449 ; Identify the child mode.
450 (setq major-mode ',child)
451 (setq mode-name ,name)
452 ; Set up maps and tables.
453 (unless (keymap-parent ,map)
454 (set-keymap-parent ,map (current-local-map)))
455 (let ((parent (char-table-parent ,syntax)))
456 (unless (and parent (not (eq parent (standard-syntax-table))))
457 (set-char-table-parent ,syntax (syntax-table))))
458 (when local-abbrev-table
459 (mapatoms
460 (lambda (symbol)
461 (or (intern-soft (symbol-name symbol) ,abbrev)
462 (define-abbrev ,abbrev (symbol-name symbol)
463 (symbol-value symbol) (symbol-function symbol))))
464 local-abbrev-table))
466 (use-local-map ,map)
467 (set-syntax-table ,syntax)
468 (setq local-abbrev-table ,abbrev)
469 ; Splice in the body (if any).
470 ,@body)
471 ; Run the hooks, if any.
472 (run-hooks ',hook)))))
474 ;; Inspired from derived-mode-class in derived.el
475 (defun easy-mmode-derived-mode-p (mode)
476 "Non-nil if the current major mode is derived from MODE.
477 Uses the `derived-mode-parent' property of the symbol to trace backwards."
478 (let ((parent major-mode))
479 (while (and (not (eq parent mode))
480 (setq parent (get parent 'derived-mode-parent))))
481 parent))
485 ;;; easy-mmode-define-navigation
488 (defmacro easy-mmode-define-navigation (base re &optional name endfun)
489 "Define BASE-next and BASE-prev to navigate in the buffer.
490 RE determines the places the commands should move point to.
491 NAME should describe the entities matched by RE and is used to build
492 the docstrings of the two functions.
493 BASE-next also tries to make sure that the whole entry is visible by
494 searching for its end (by calling ENDFUN if provided or by looking for
495 the next entry) and recentering if necessary.
496 ENDFUN should return the end position (with or without moving point)."
497 (let* ((base-name (symbol-name base))
498 (prev-sym (intern (concat base-name "-prev")))
499 (next-sym (intern (concat base-name "-next"))))
500 (unless name (setq name (symbol-name base-name)))
501 `(progn
502 (add-to-list 'debug-ignored-errors
503 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
504 (defun ,next-sym (&optional count)
505 ,(format "Go to the next COUNT'th %s." name)
506 (interactive)
507 (unless count (setq count 1))
508 (if (< count 0) (,prev-sym (- count))
509 (if (looking-at ,re) (incf count))
510 (unless (re-search-forward ,re nil t count)
511 (error ,(format "No next %s" name)))
512 (goto-char (match-beginning 0))
513 (when (eq (current-buffer) (window-buffer (selected-window)))
514 (let ((endpt (or (save-excursion
515 ,(if endfun `(,endfun)
516 `(re-search-forward ,re nil t 2)))
517 (point-max))))
518 (unless (<= endpt (window-end)) (recenter))))))
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 (unless (re-search-backward ,re nil t count)
525 (error ,(format "No previous %s" name))))))))
527 (provide 'easy-mmode)
529 ;;; easy-mmode.el ends here