Require CL during compilation.
[emacs.git] / lisp / emacs-lisp / easy-mmode.el
blob72b64a4a88107ccd809a283b1695cbd56f63e38e
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 (capitalize (replace-regexp-in-string
61 "-mode\\'" "" (symbol-name mode)))
62 " mode")))
63 (if (not (stringp lighter)) name
64 (setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\-s+\\'" "" lighter))
65 (replace-regexp-in-string lighter lighter name t t))))
67 ;;;###autoload
68 (defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
69 ;;;###autoload
70 (defmacro define-minor-mode (mode doc &optional init-value lighter keymap &rest body)
71 "Define a new minor mode MODE.
72 This function defines the associated control variable MODE, keymap MODE-map,
73 toggle command MODE, and hook MODE-hook.
75 DOC is the documentation for the mode toggle command.
76 Optional INIT-VALUE is the initial value of the mode's variable.
77 Optional LIGHTER is displayed in the modeline when the mode is on.
78 Optional KEYMAP is the default (defvar) keymap bound to the mode keymap.
79 If it is a list, it is passed to `easy-mmode-define-keymap'
80 in order to build a valid keymap.
81 BODY contains code that will be executed each time the mode is (dis)activated.
82 It will be executed after any toggling but before running the hooks.
83 BODY can start with a list of CL-style keys specifying additional arguments.
84 Currently two such keyword arguments are supported:
85 :group followed by the group name to use for any generated `defcustom'.
86 :global if non-nil specifies that the minor mode is not meant to be
87 buffer-local. By default, the variable is made buffer-local."
88 (let* ((mode-name (symbol-name mode))
89 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
90 (globalp nil)
91 ;; We might as well provide a best-guess default group.
92 (group
93 (list 'quote
94 (intern (replace-regexp-in-string "-mode\\'" "" mode-name))))
95 (keymap-sym (intern (concat mode-name "-map")))
96 (hook (intern (concat mode-name "-hook")))
97 (hook-on (intern (concat mode-name "-on-hook")))
98 (hook-off (intern (concat mode-name "-off-hook"))))
100 ;; FIXME: compatibility that should be removed.
101 (when (and (consp init-value) (eq (car init-value) 'global))
102 (setq init-value (cdr init-value) globalp t))
104 ;; Check keys.
105 (while (keywordp (car body))
106 (case (pop body)
107 (:global (setq globalp (pop body)))
108 (:group (setq group (pop body)))
109 (t (setq body (cdr body)))))
111 ;; Add default properties to LIGHTER.
112 (unless (or (not (stringp lighter)) (get-text-property 0 'local-map lighter)
113 (get-text-property 0 'keymap lighter))
114 (setq lighter
115 (apply 'propertize lighter
116 'local-map (make-mode-line-mouse2-map mode)
117 (unless (get-text-property 0 'help-echo lighter)
118 (list 'help-echo
119 (format "mouse-2: turn off %s" pretty-name))))))
121 `(progn
122 ;; Define the variable to enable or disable the mode.
123 ,(if globalp
124 ;; BEWARE! autoload.el depends on this `defcustom' coming
125 ;; as the first element after progn.
126 `(defcustom ,mode ,init-value
127 ,(format "Toggle %s.
128 Setting this variable directly does not take effect;
129 use either \\[customize] or the function `%s'."
130 pretty-name mode)
131 :set (lambda (symbol value) (funcall symbol (or value 0)))
132 :initialize 'custom-initialize-default
133 :group ,group
134 :type 'boolean)
135 `(progn
136 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
137 Use the function `%s' to change this variable." pretty-name mode))
138 (make-variable-buffer-local ',mode)))
140 ;; Define the minor-mode keymap.
141 ,(when keymap
142 `(defvar ,keymap-sym
143 (cond ((and ,keymap (keymapp ,keymap))
144 ,keymap)
145 ((listp ,keymap)
146 (easy-mmode-define-keymap ,keymap))
147 (t (error "Invalid keymap %S" ,keymap)))
148 ,(format "Keymap for `%s'." mode-name)))
150 ;; The toggle's hook.
151 (defcustom ,hook nil
152 ,(format "Hook run at the end of function `%s'." mode-name)
153 :group ,group
154 :type 'hook)
156 ;; The actual function.
157 (defun ,mode (&optional arg)
158 ,(or doc
159 (format "With no argument, toggle %s.
160 With universal prefix ARG turn mode on.
161 With zero or negative ARG turn mode off.
162 \\{%s}" pretty-name keymap-sym))
163 (interactive "P")
164 (setq ,mode
165 (if arg
166 (> (prefix-numeric-value arg) 0)
167 (not ,mode)))
168 ,@body
169 ;; The on/off hooks are here for backward compatibility only.
170 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
171 ;; Return the new setting.
172 (if (interactive-p)
173 (message ,(format "%s %%sabled" pretty-name)
174 (if ,mode "en" "dis")))
175 ,mode)
177 (add-minor-mode ',mode ',lighter
178 (if (boundp ',keymap-sym) (symbol-value ',keymap-sym)))
180 ;; If the mode is global, call the function according to the default.
181 ,(if globalp `(if ,mode (,mode 1))))))
184 ;;; make global minor mode
187 (defmacro easy-mmode-define-global-mode (global-mode mode turn-on
188 &rest keys)
189 "Make GLOBAL-MODE out of the MODE buffer-local minor mode.
190 TURN-ON is a function that will be called with no args in every buffer
191 and that should try to turn MODE on if applicable for that buffer.
192 KEYS is a list of CL-style keyword arguments:
193 :group to specify the custom group."
194 (let* ((mode-name (symbol-name mode))
195 (global-mode-name (symbol-name global-mode))
196 (pretty-name (easy-mmode-pretty-mode-name mode))
197 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
198 ;; We might as well provide a best-guess default group.
199 (group
200 (list 'quote
201 (intern (replace-regexp-in-string "-mode\\'" "" mode-name))))
202 (buffers (intern (concat global-mode-name "-buffers")))
203 (cmmh (intern (concat global-mode-name "-cmmh"))))
205 ;; Check keys.
206 (while (keywordp (car keys))
207 (case (pop keys)
208 (:group (setq group (pop keys)))
209 (t (setq keys (cdr keys)))))
211 `(progn
212 ;; BEWARE! autoload.el depends on `define-minor-mode' coming
213 ;; as the first element after progn.
215 ;; The actual global minor-mode
216 (define-minor-mode ,global-mode
217 ,(format "Toggle %s in every buffer.
218 With prefix ARG, turn %s on if and only if ARG is positive.
219 %s is actually not turned on in every buffer but only in those
220 in which `%s' turns it on."
221 pretty-name pretty-global-name pretty-name turn-on)
222 nil nil nil :global t :group ,group
224 ;; Setup hook to handle future mode changes and new buffers.
225 (if ,global-mode
226 (add-hook 'change-major-mode-hook ',cmmh)
227 (remove-hook 'change-major-mode-hook ',cmmh))
229 ;; Go through existing buffers.
230 (dolist (buf (buffer-list))
231 (with-current-buffer buf
232 (if ,global-mode (,turn-on) (,mode -1)))))
234 ;; List of buffers left to process.
235 (defvar ,buffers nil)
237 ;; The function that calls TURN-ON in each buffer.
238 (defun ,buffers ()
239 (while ,buffers
240 (when (buffer-name (car ,buffers))
241 (with-current-buffer (pop ,buffers)
242 (,turn-on))))
243 (remove-hook 'post-command-hook ',buffers)
244 (remove-hook 'after-find-file ',buffers))
246 ;; The function that catches kill-all-local-variables.
247 (defun ,cmmh ()
248 (add-to-list ',buffers (current-buffer))
249 (add-hook 'post-command-hook ',buffers)
250 (add-hook 'after-find-file ',buffers)))))
253 ;;; easy-mmode-defmap
256 (if (fboundp 'set-keymap-parents)
257 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
258 (defun easy-mmode-set-keymap-parents (m parents)
259 (set-keymap-parent
261 (cond
262 ((not (consp parents)) parents)
263 ((not (cdr parents)) (car parents))
264 (t (let ((m (copy-keymap (pop parents))))
265 (easy-mmode-set-keymap-parents m parents)
266 m))))))
268 (defun easy-mmode-define-keymap (bs &optional name m args)
269 "Return a keymap built from bindings BS.
270 BS must be a list of (KEY . BINDING) where
271 KEY and BINDINGS are suitable for `define-key'.
272 Optional NAME is passed to `make-sparse-keymap'.
273 Optional map M can be used to modify an existing map.
274 ARGS is a list of additional arguments."
275 (let (inherit dense suppress)
276 (while args
277 (let ((key (pop args))
278 (val (pop args)))
279 (case key
280 (:dense (setq dense val))
281 (:inherit (setq inherit val))
282 (:group)
283 ;;((eq key :suppress) (setq suppress val))
284 (t (message "Unknown argument %s in defmap" key)))))
285 (unless (keymapp m)
286 (setq bs (append m bs))
287 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
288 (dolist (b bs)
289 (let ((keys (car b))
290 (binding (cdr b)))
291 (dolist (key (if (consp keys) keys (list keys)))
292 (cond
293 ((symbolp key)
294 (substitute-key-definition key binding m global-map))
295 ((null binding)
296 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
297 ((let ((o (lookup-key m key)))
298 (or (null o) (numberp o) (eq o 'undefined)))
299 (define-key m key binding))))))
300 (cond
301 ((keymapp inherit) (set-keymap-parent m inherit))
302 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
305 ;;;###autoload
306 (defmacro easy-mmode-defmap (m bs doc &rest args)
307 `(progn
308 (autoload 'easy-mmode-define-keymap "easy-mmode")
309 (defconst ,m
310 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
311 ,doc)))
315 ;;; easy-mmode-defsyntax
318 (defun easy-mmode-define-syntax (css args)
319 (let ((st (make-syntax-table (cadr (memq :copy args)))))
320 (dolist (cs css)
321 (let ((char (car cs))
322 (syntax (cdr cs)))
323 (if (sequencep char)
324 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
325 (modify-syntax-entry char syntax st))))
326 st))
328 ;;;###autoload
329 (defmacro easy-mmode-defsyntax (st css doc &rest args)
330 `(progn
331 (autoload 'easy-mmode-define-syntax "easy-mmode")
332 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) doc)))
337 ;;; A "macro-only" reimplementation of define-derived-mode.
340 ;;;###autoload
341 (defmacro define-derived-mode (child parent name &optional docstring &rest body)
342 "Create a new mode as a variant of an existing mode.
344 The arguments to this command are as follow:
346 CHILD: the name of the command for the derived mode.
347 PARENT: the name of the command for the parent mode (e.g. `text-mode').
348 NAME: a string which will appear in the status line (e.g. \"Hypertext\")
349 DOCSTRING: an optional documentation string--if you do not supply one,
350 the function will attempt to invent something useful.
351 BODY: forms to execute just before running the
352 hooks for the new mode.
354 Here is how you could define LaTeX-Thesis mode as a variant of LaTeX mode:
356 (define-derived-mode LaTeX-thesis-mode LaTeX-mode \"LaTeX-Thesis\")
358 You could then make new key bindings for `LaTeX-thesis-mode-map'
359 without changing regular LaTeX mode. In this example, BODY is empty,
360 and DOCSTRING is generated by default.
362 On a more complicated level, the following command uses `sgml-mode' as
363 the parent, and then sets the variable `case-fold-search' to nil:
365 (define-derived-mode article-mode sgml-mode \"Article\"
366 \"Major mode for editing technical articles.\"
367 (setq case-fold-search nil))
369 Note that if the documentation string had been left out, it would have
370 been generated automatically, with a reference to the keymap."
372 (let* ((child-name (symbol-name child))
373 (map (intern (concat child-name "-map")))
374 (syntax (intern (concat child-name "-syntax-table")))
375 (abbrev (intern (concat child-name "-abbrev-table")))
376 (hook (intern (concat child-name "-hook"))))
378 (unless parent (setq parent 'fundamental-mode))
380 (when (and docstring (not (stringp docstring)))
381 ;; DOCSTRING is really the first command and there's no docstring
382 (push docstring body)
383 (setq docstring nil))
385 (unless (stringp docstring)
386 ;; Use a default docstring.
387 (setq docstring
388 (format "Major mode derived from `%s' by `define-derived-mode'.
389 Inherits all of the parent's attributes, but has its own keymap,
390 abbrev table and syntax table:
392 `%s', `%s' and `%s'
394 which more-or-less shadow %s's corresponding tables."
395 parent map syntax abbrev parent)))
397 (unless (string-match (regexp-quote (symbol-name hook)) docstring)
398 ;; Make sure the docstring mentions the mode's hook
399 (setq docstring
400 (concat docstring
401 (unless (eq parent 'fundamental-mode)
402 (concat
403 "\nAdditionally to any hooks its parent mode "
404 (if (string-match (regexp-quote (format "`%s'" parent))
405 docstring) nil
406 (format "`%s' " parent))
407 "might have run),"))
408 (format "\nThis mode runs `%s' just before exiting." hook))))
410 (unless (string-match "\\\\[{[]" docstring)
411 ;; And don't forget to put the mode's keymap
412 (setq docstring (concat docstring "\n\\{" (symbol-name map) "}")))
414 `(progn
415 (defvar ,map (make-sparse-keymap))
416 (defvar ,syntax (make-char-table 'syntax-table nil))
417 (defvar ,abbrev (progn (define-abbrev-table ',abbrev nil) ,abbrev))
418 (put ',child 'derived-mode-parent ',parent)
420 (defun ,child ()
421 ,docstring
422 (interactive)
423 ; Run the parent.
424 (combine-run-hooks
426 (,parent)
427 ; Identify special modes.
428 (put ',child 'special (get ',parent 'special))
429 ; Identify the child mode.
430 (setq major-mode ',child)
431 (setq mode-name ,name)
432 ; Set up maps and tables.
433 (unless (keymap-parent ,map)
434 (set-keymap-parent ,map (current-local-map)))
435 (let ((parent (char-table-parent ,syntax)))
436 (unless (and parent (not (eq parent (standard-syntax-table))))
437 (set-char-table-parent ,syntax (syntax-table))))
438 (when local-abbrev-table
439 (mapatoms
440 (lambda (symbol)
441 (or (intern-soft (symbol-name symbol) ,abbrev)
442 (define-abbrev ,abbrev (symbol-name symbol)
443 (symbol-value symbol) (symbol-function symbol))))
444 local-abbrev-table))
446 (use-local-map ,map)
447 (set-syntax-table ,syntax)
448 (setq local-abbrev-table ,abbrev)
449 ; Splice in the body (if any).
450 ,@body)
451 ; Run the hooks, if any.
452 (run-hooks ',hook)))))
454 ;; Inspired from derived-mode-class in derived.el
455 (defun easy-mmode-derived-mode-p (mode)
456 "Non-nil if the current major mode is derived from MODE.
457 Uses the `derived-mode-parent' property of the symbol to trace backwards."
458 (let ((parent major-mode))
459 (while (and (not (eq parent mode))
460 (setq parent (get parent 'derived-mode-parent))))
461 parent))
465 ;;; easy-mmode-define-navigation
468 (defmacro easy-mmode-define-navigation (base re &optional name endfun)
469 "Define BASE-next and BASE-prev to navigate in the buffer.
470 RE determines the places the commands should move point to.
471 NAME should describe the entities matched by RE and is used to build
472 the docstrings of the two functions.
473 BASE-next also tries to make sure that the whole entry is visible by
474 searching for its end (by calling ENDFUN if provided or by looking for
475 the next entry) and recentering if necessary.
476 ENDFUN should return the end position (with or without moving point)."
477 (let* ((base-name (symbol-name base))
478 (prev-sym (intern (concat base-name "-prev")))
479 (next-sym (intern (concat base-name "-next"))))
480 (unless name (setq name (symbol-name base-name)))
481 `(progn
482 (add-to-list 'debug-ignored-errors
483 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
484 (defun ,next-sym (&optional count)
485 ,(format "Go to the next COUNT'th %s." name)
486 (interactive)
487 (unless count (setq count 1))
488 (if (< count 0) (,prev-sym (- count))
489 (if (looking-at ,re) (incf count))
490 (unless (re-search-forward ,re nil t count)
491 (error ,(format "No next %s" name)))
492 (goto-char (match-beginning 0))
493 (when (eq (current-buffer) (window-buffer (selected-window)))
494 (let ((endpt (or (save-excursion
495 ,(if endfun `(,endfun)
496 `(re-search-forward ,re nil t 2)))
497 (point-max))))
498 (unless (<= endpt (window-end)) (recenter))))))
499 (defun ,prev-sym (&optional count)
500 ,(format "Go to the previous COUNT'th %s" (or name base-name))
501 (interactive)
502 (unless count (setq count 1))
503 (if (< count 0) (,next-sym (- count))
504 (unless (re-search-backward ,re nil t count)
505 (error ,(format "No previous %s" name))))))))
507 (provide 'easy-mmode)
509 ;;; easy-mmode.el ends here