[lice @ more rearranging. define-key modifications to accomodate bindings.lisp. this...
[lice.git] / src / emacs-lisp / easy-mmode.lisp
blob4891217a05e88ac2cb302d47daee534b49ad8a14
1 ;;; easy-mmode.el --- easy definition for major and minor modes
3 ;; Copyright (C) 1997, 2000, 2001, 2002, 2003, 2004, 2005,
4 ;; 2006 Free Software Foundation, Inc.
6 ;; Author: Georges Brun-Cottan <Georges.Brun-Cottan@inria.fr>
7 ;; Maintainer: Stefan Monnier <monnier@gnu.org>
9 ;; Keywords: extensions lisp
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
16 ;; any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
28 ;;; Commentary:
30 ;; Minor modes are useful and common. This package makes defining a
31 ;; minor mode easy, by focusing on the writing of the minor mode
32 ;; functionalities themselves. Moreover, this package enforces a
33 ;; conventional naming of user interface primitives, making things
34 ;; natural for the minor-mode end-users.
36 ;; For each mode, easy-mmode defines the following:
37 ;; <mode> : The minor mode predicate. A buffer-local variable.
38 ;; <mode>-map : The keymap possibly associated to <mode>.
39 ;; see `define-minor-mode' documentation
41 ;; eval
42 ;; (pp (macroexpand '(define-minor-mode <your-mode> <doc>)))
43 ;; to check the result before using it.
45 ;; The order in which minor modes are installed is important. Keymap
46 ;; lookup proceeds down minor-mode-map-alist, and the order there
47 ;; tends to be the reverse of the order in which the modes were
48 ;; installed. Perhaps there should be a feature to let you specify
49 ;; orderings.
51 ;; Additionally to `define-minor-mode', the package provides convenient
52 ;; ways to define keymaps, and other helper functions for major and minor modes.
54 ;;; Code:
56 (in-package "LICE")
58 (defun easy-mmode-pretty-mode-name (mode &optional lighter)
59 "Turn the symbol MODE into a string intended for the user.
60 If provided, LIGHTER will be used to help choose capitalization by,
61 replacing its case-insensitive matches with the literal string in LIGHTER."
62 (let* ((case-fold-search t)
63 ;; Produce "Foo-Bar minor mode" from foo-bar-minor-mode.
64 (name (concat (replace-regexp-in-string
65 ;; If the original mode name included "-minor" (some
66 ;; of them don't, e.g. auto-revert-mode), then
67 ;; replace it with " minor".
68 "-Minor" " minor"
69 ;; "foo-bar-minor" -> "Foo-Bar-Minor"
70 (capitalize (replace-regexp-in-string
71 ;; "foo-bar-minor-mode" -> "foo-bar-minor"
72 "-mode\\'" "" (symbol-name mode))))
73 " mode")))
74 (el:if (not (stringp lighter)) name
75 ;; Strip leading and trailing whitespace from LIGHTER.
76 (setq lighter (replace-regexp-in-string "\\`\\s-+\\|\\s-+\\'" ""
77 lighter))
78 ;; Replace any (case-insensitive) matches for LIGHTER in NAME
79 ;; with a literal LIGHTER. E.g., if NAME is "Iimage mode" and
80 ;; LIGHTER is " iImag", then this will produce "iImage mode".
81 ;; (LIGHTER normally comes from the mode-line string passed to
82 ;; define-minor-mode, and normally includes at least one leading
83 ;; space.)
84 (replace-regexp-in-string (regexp-quote lighter) lighter name t t))))
86 ;;;###autoload
87 (defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
88 ;;;###autoload
89 (defmacro define-minor-mode ((mode doc ;;&optional init-value lighter keymap
90 &key init-value lighter ((:global globalp)) extra-args set
91 initialize group type (require t) keymap)
92 ;; FIXME: in the original any keys not
93 ;; above were added to extra-keywords,
94 ;; but i'm too lazy to do it that way
95 ;; atm. -sabetts
96 extra-keywords
97 &body body)
98 "Define a new minor mode MODE.
99 This function defines the associated control variable MODE, keymap MODE-map,
100 and toggle command MODE.
102 DOC is the documentation for the mode toggle command.
103 Optional INIT-VALUE is the initial value of the mode's variable.
104 Optional LIGHTER is displayed in the modeline when the mode is on.
105 Optional KEYMAP is the default (defvar) keymap bound to the mode keymap.
106 If it is a list, it is passed to `easy-mmode-define-keymap'
107 in order to build a valid keymap. It's generally better to use
108 a separate MODE-map variable than to use this argument.
109 The above three arguments can be skipped if keyword arguments are
110 used (see below).
112 BODY contains code to execute each time the mode is activated or deactivated.
113 It is executed after toggling the mode,
114 and before running the hook variable `mode-HOOK'.
115 Before the actual body code, you can write keyword arguments (alternating
116 keywords and values). These following keyword arguments are supported (other
117 keywords will be passed to `defcustom' if the minor mode is global):
118 :group GROUP Custom group name to use in all generated `defcustom' forms.
119 Defaults to MODE without the possible trailing \"-mode\".
120 Don't use this default group name unless you have written a
121 `defgroup' to define that group properly.
122 :global GLOBAL If non-nil specifies that the minor mode is not meant to be
123 buffer-local, so don't make the variable MODE buffer-local.
124 By default, the mode is buffer-local.
125 :init-value VAL Same as the INIT-VALUE argument.
126 :lighter SPEC Same as the LIGHTER argument.
127 :keymap MAP Same as the KEYMAP argument.
128 :require SYM Same as in `defcustom'.
130 For example, you could write
131 (define-minor-mode foo-mode \"If enabled, foo on you!\"
132 :lighter \" Foo\" :require 'foo :global t :group 'hassle :version \"27.5\"
133 ...BODY CODE...)"
134 (let* ((last-message (current-message))
135 (mode-name (symbol-name mode))
136 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
137 (hook (intern (concat mode-name "-hook")))
138 (hook-on (intern (concat mode-name "-on-hook")))
139 (hook-off (intern (concat mode-name "-off-hook")))
140 keymap-sym)
142 ;; ;; Check keys.
143 ;; (while (keywordp (setq keyw (car body)))
144 ;; (setq body (cdr body))
145 ;; (case keyw
146 ;; (:init-value (setq init-value (pop body)))
147 ;; (:lighter (setq lighter (pop body)))
148 ;; (:global (setq globalp (pop body)))
149 ;; (:extra-args (setq extra-args (pop body)))
150 ;; (:set (setq set (list :set (pop body))))
151 ;; (:initialize (setq initialize (list :initialize (pop body))))
152 ;; (:group (setq group (nconc group (list :group (pop body)))))
153 ;; (:type (setq type (list :type (pop body))))
154 ;; (:require (setq require (pop body)))
155 ;; (:keymap (setq keymap (pop body)))
156 ;; (t (push keyw extra-keywords) (push (pop body) extra-keywords))))
158 ;; XXX: :group can occur many times in the original. here only once.
159 (setf keymap-sym (if (and keymap (symbolp keymap)) keymap
160 (intern (concat mode-name "-MAP")))
161 set `(:set ,(or set 'custom-set-minor-mode))
162 initialize `(:initialize ,(or initialize 'custom-initialize-default))
163 ;; We might as well provide a best-guess default group.
164 group `(:group (or ,group '(intern (replace-regexp-in-string
165 "-mode\\'" "" mode-name))))
166 type `(:type ,(or type 'boolean)))
168 `(progn
169 ;; Define the variable to enable or disable the mode.
170 ,(if (not globalp)
171 `(progn
172 (define-buffer-local ,mode ,init-value ,(format "Non-nil if %s is enabled.
173 Use the command `%s' to change this variable." pretty-name mode))
174 (make-variable-buffer-local ',mode))
176 (let ((base-doc-string
177 (concat "Non-nil if %s is enabled.
178 See the command `%s' for a description of this minor-mode."
179 (if body "
180 Setting this variable directly does not take effect;
181 use either \\[customize] or the function `%s'."))))
182 `(defcustom ,mode ,init-value
183 ,(format base-doc-string pretty-name mode mode)
184 ,@set
185 ,@initialize
186 ,@group
187 ,@type
188 ,@(unless (eq require t) `(:require ,require))
189 ,@(nreverse extra-keywords))))
191 ;; The actual function.
192 (defcommand ,mode ((&optional arg ,@extra-args)
193 :raw-prefix)
194 ,(or doc
195 (format nil (concat "Toggle ~a on or off.
196 Interactively, with no prefix argument, toggle the mode.
197 With universal prefix ARG turn mode on.
198 With zero or negative ARG turn mode off.
199 \\{~s}") pretty-name keymap-sym))
200 ;; Use `toggle' rather than (if ,mode 0 1) so that using
201 ;; repeat-command still does the toggling correctly.
202 ;;(interactive (list (or current-prefix-arg 'toggle)))
203 (unless arg (setf arg 'toggle))
204 (setq ,mode
205 (cond
206 ((eq arg 'toggle) (not ,mode))
207 (arg (> (prefix-numeric-value arg) 0))
209 (el:if (null ,mode) t
210 (message
211 "Toggling %s off; better pass an explicit argument."
212 ',mode)
213 nil))))
214 ,@body
215 ;; The on/off hooks are here for backward compatibility only.
216 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
217 (if (called-interactively-p)
218 (progn
219 ,(if globalp `(customize-mark-as-set ',mode))
220 ;; Avoid overwriting a message shown by the body,
221 ;; but do overwrite previous messages.
222 (unless ,(and (current-message)
223 (not (equal last-message (current-message))))
224 (message ,(format "~a ~~aabled" pretty-name)
225 (if ,mode "en" "dis")))))
226 (force-mode-line-update)
227 ;; Return the new setting.
228 ,mode)
230 ;; XXX: What do we do with this? -sabetts
231 ;; ;; Autoloading a define-minor-mode autoloads everything
232 ;; ;; up-to-here.
233 ;; :autoload-end
235 ;; Define the minor-mode keymap.
236 ,(unless (symbolp keymap) ;nil is also a symbol.
237 `(defvar ,keymap-sym
238 (let ((m ,keymap))
239 (cond ((keymapp m) m)
240 ((listp m) (easy-mmode-define-keymap m))
241 (t (error "Invalid keymap %S" ,keymap))))
242 ,(format nil "Keymap for `~s'." mode-name)))
244 (add-minor-mode ',mode ',lighter
245 ,(if keymap keymap-sym
246 `(if (boundp ',keymap-sym)
247 (symbol-value ',keymap-sym)))))))
250 ;;; make global minor mode
253 ;;;###autoload
254 (defalias 'easy-mmode-define-global-mode 'define-global-minor-mode)
255 ;;;###autoload
256 (defmacro define-global-minor-mode (global-mode mode turn-on &rest keys)
257 "Make GLOBAL-MODE out of the buffer-local minor MODE.
258 TURN-ON is a function that will be called with no args in every buffer
259 and that should try to turn MODE on if applicable for that buffer.
260 KEYS is a list of CL-style keyword arguments. As the minor mode
261 defined by this function is always global, any :global keyword is
262 ignored. Other keywords have the same meaning as in `define-minor-mode',
263 which see. In particular, :group specifies the custom group.
264 The most useful keywords are those that are passed on to the
265 `defcustom'. It normally makes no sense to pass the :lighter
266 or :keymap keywords to `define-global-minor-mode', since these
267 are usually passed to the buffer-local version of the minor mode.
269 If MODE's set-up depends on the major mode in effect when it was
270 enabled, then disabling and reenabling MODE should make MODE work
271 correctly with the current major mode. This is important to
272 prevent problems with derived modes, that is, major modes that
273 call another major mode in their body."
275 (let* ((global-mode-name (symbol-name global-mode))
276 (pretty-name (easy-mmode-pretty-mode-name mode))
277 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
278 (group nil)
279 (extra-keywords nil)
280 (MODE-buffers (intern (concat global-mode-name "-buffers")))
281 (MODE-enable-in-buffers
282 (intern (concat global-mode-name "-enable-in-buffers")))
283 (MODE-check-buffers
284 (intern (concat global-mode-name "-check-buffers")))
285 (MODE-cmhh (intern (concat global-mode-name "-cmhh")))
286 (MODE-major-mode (intern (concat (symbol-name mode) "-major-mode")))
287 keyw)
289 ;; Check keys.
290 (while (keywordp (setq keyw (car keys)))
291 (setq keys (cdr keys))
292 (case keyw
293 (:group (setq group (nconc group (list :group (pop keys)))))
294 (:global (setq keys (cdr keys)))
295 (t (push keyw extra-keywords) (push (pop keys) extra-keywords))))
297 (unless group
298 ;; We might as well provide a best-guess default group.
299 (setq group
300 `(:group ',(intern (replace-regexp-in-string
301 "-mode\\'" "" (symbol-name mode))))))
303 `(progn
304 (defvar ,MODE-major-mode nil)
305 (make-variable-buffer-local ',MODE-major-mode)
306 ;; The actual global minor-mode
307 (define-minor-mode ,global-mode
308 ,(format "Toggle %s in every buffer.
309 With prefix ARG, turn %s on if and only if ARG is positive.
310 %s is actually not turned on in every buffer but only in those
311 in which `%s' turns it on."
312 pretty-name pretty-global-name pretty-name turn-on)
313 :global t ,@group ,@(nreverse extra-keywords)
315 ;; Setup hook to handle future mode changes and new buffers.
316 (el:if ,global-mode
317 (progn
318 (add-hook 'after-change-major-mode-hook
319 ',MODE-enable-in-buffers)
320 (add-hook 'find-file-hook ',MODE-check-buffers)
321 (add-hook 'change-major-mode-hook ',MODE-cmhh))
322 (remove-hook 'after-change-major-mode-hook ',MODE-enable-in-buffers)
323 (remove-hook 'find-file-hook ',MODE-check-buffers)
324 (remove-hook 'change-major-mode-hook ',MODE-cmhh))
326 ;; Go through existing buffers.
327 (dolist (buf (buffer-list))
328 (with-current-buffer buf
329 (if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
331 ;; Autoloading define-global-minor-mode autoloads everything
332 ;; up-to-here.
333 :autoload-end
335 ;; List of buffers left to process.
336 (defvar ,MODE-buffers nil)
338 ;; The function that calls TURN-ON in each buffer.
339 (defun ,MODE-enable-in-buffers ()
340 (dolist (buf ,MODE-buffers)
341 (when (buffer-live-p buf)
342 (with-current-buffer buf
343 (el:if ,mode
344 (unless (eq ,MODE-major-mode major-mode)
345 (,mode -1)
346 (,turn-on)
347 (setq ,MODE-major-mode major-mode))
348 (,turn-on)
349 (setq ,MODE-major-mode major-mode))))))
350 (put ',MODE-enable-in-buffers 'definition-name ',global-mode)
352 (defun ,MODE-check-buffers ()
353 (,MODE-enable-in-buffers)
354 (setq ,MODE-buffers nil)
355 (remove-hook 'post-command-hook ',MODE-check-buffers))
356 (put ',MODE-check-buffers 'definition-name ',global-mode)
358 ;; The function that catches kill-all-local-variables.
359 (defun ,MODE-cmhh ()
360 (add-to-list ',MODE-buffers (current-buffer))
361 (add-hook 'post-command-hook ',MODE-check-buffers))
362 (put ',MODE-cmhh 'definition-name ',global-mode))))
365 ;;; easy-mmode-defmap
368 (if (fboundp 'set-keymap-parents)
369 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
370 (defun easy-mmode-set-keymap-parents (m parents)
371 (set-keymap-parent
373 (cond
374 ((not (consp parents)) parents)
375 ((not (cdr parents)) (car parents))
376 (t (let ((m (copy-keymap (pop parents))))
377 (easy-mmode-set-keymap-parents m parents)
378 m))))))
380 ;;;###autoload
381 (defun easy-mmode-define-keymap (bs &optional name m args)
382 "Return a keymap built from bindings BS.
383 BS must be a list of (KEY . BINDING) where
384 KEY and BINDINGS are suitable for `define-key'.
385 Optional NAME is passed to `make-sparse-keymap'.
386 Optional map M can be used to modify an existing map.
387 ARGS is a list of additional keyword arguments."
388 (let (inherit dense)
389 (while args
390 (let ((key (pop args))
391 (val (pop args)))
392 (case key
393 (:name (setq name val))
394 (:dense (setq dense val))
395 (:inherit (setq inherit val))
396 (:group)
397 (t (message "Unknown argument %s in defmap" key)))))
398 (unless (keymapp m)
399 (setq bs (append m bs))
400 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
401 (dolist (b bs)
402 (let ((keys (car b))
403 (binding (cdr b)))
404 (dolist (key (if (consp keys) keys (list keys)))
405 (cond
406 ((symbolp key)
407 (substitute-key-definition key binding m *global-map*))
408 ((null binding)
409 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
410 ((let ((o (lookup-key m key)))
411 (or (null o) (numberp o) (eq o 'undefined)))
412 (define-key m key binding))))))
413 (cond
414 ((keymapp inherit) (set-keymap-parent m inherit))
415 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
418 ;;;###autoload
419 (defmacro easy-mmode-defmap (m bs doc &rest args)
420 `(defconst ,m
421 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
422 ,doc))
426 ;;; easy-mmode-defsyntax
429 (defun easy-mmode-define-syntax (css args)
430 (let ((st (make-syntax-table (plist-get args :copy)))
431 (parent (plist-get args :inherit)))
432 (dolist (cs css)
433 (let ((char (car cs))
434 (syntax (cdr cs)))
435 (if (sequencep char)
436 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
437 (modify-syntax-entry char syntax st))))
438 (if parent (set-char-table-parent
439 st (if (symbolp parent) (symbol-value parent) parent)))
440 st))
442 ;;;###autoload
443 (defmacro easy-mmode-defsyntax (st css doc &rest args)
444 "Define variable ST as a syntax-table.
445 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
446 `(progn
447 (autoload 'easy-mmode-define-syntax "easy-mmode")
448 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
453 ;;; easy-mmode-define-navigation
456 (defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun)
457 "Define BASE-next and BASE-prev to navigate in the buffer.
458 RE determines the places the commands should move point to.
459 NAME should describe the entities matched by RE. It is used to build
460 the docstrings of the two functions.
461 BASE-next also tries to make sure that the whole entry is visible by
462 searching for its end (by calling ENDFUN if provided or by looking for
463 the next entry) and recentering if necessary.
464 ENDFUN should return the end position (with or without moving point).
465 NARROWFUN non-nil means to check for narrowing before moving, and if
466 found, do widen first and then call NARROWFUN with no args after moving."
467 (let* ((base-name (symbol-name base))
468 (prev-sym (intern (concat base-name "-prev")))
469 (next-sym (intern (concat base-name "-next")))
470 (check-narrow-maybe
471 (when narrowfun
472 '(setq was-narrowed
473 (prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
474 (widen)))))
475 (re-narrow-maybe (when narrowfun
476 `(when was-narrowed (,narrowfun)))))
477 (unless name (setq name base-name))
478 `(progn
479 (add-to-list 'debug-ignored-errors
480 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
481 (defun ,next-sym (&optional count)
482 ,(format "Go to the next COUNT'th %s." name)
483 (interactive)
484 (unless count (setq count 1))
485 (el:if (< count 0) (,prev-sym (- count))
486 (if (looking-at ,re) (setq count (1+ count)))
487 (let (was-narrowed)
488 ,check-narrow-maybe
489 (if (not (re-search-forward ,re nil t count))
490 (if (looking-at ,re)
491 (goto-char (or ,(if endfun `(,endfun)) (point-max)))
492 (error "No next %s" ,name))
493 (goto-char (match-beginning 0))
494 (when (and (eq (current-buffer) (window-buffer (selected-window)))
495 (interactive-p))
496 (let ((endpt (or (save-excursion
497 ,(if endfun `(,endfun)
498 `(re-search-forward ,re nil t 2)))
499 (point-max))))
500 (unless (pos-visible-in-window-p endpt nil t)
501 (recenter '(0))))))
502 ,re-narrow-maybe)))
503 (put ',next-sym 'definition-name ',base)
504 (defun ,prev-sym (&optional count)
505 ,(format "Go to the previous COUNT'th %s" (or name base-name))
506 (interactive)
507 (unless count (setq count 1))
508 (if (< count 0) (,next-sym (- count))
509 (let (was-narrowed)
510 ,check-narrow-maybe
511 (unless (re-search-backward ,re nil t count)
512 (error "No previous %s" ,name))
513 ,re-narrow-maybe)))
514 (put ',prev-sym 'definition-name ',base))))
517 (provide 'easy-mmode)
519 ;;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
520 ;;; easy-mmode.el ends here