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