mostly fix move-beginning-of-line
[lice.git] / src / emacs-lisp / easy-mmode.lisp
blob42f1402371b7899989da0746c2d16bde6adf3f4f
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 ;; FIXME: when aliases really work maybe uncomment this
88 ;;(defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
89 ;;;###autoload
90 (defmacro define-minor-mode ((mode doc ;;&optional init-value lighter keymap
91 &key init-value lighter ((:global globalp)) extra-args set
92 initialize group type (require t) keymap
93 ;; FIXME: in the original any keys not
94 ;; above were added to extra-keywords,
95 ;; but i'm too lazy to do it that way
96 ;; atm. -sabetts
97 extra-keywords)
98 &body body)
99 "Define a new minor mode MODE.
100 This function defines the associated control variable MODE, keymap MODE-map,
101 and toggle command MODE.
103 DOC is the documentation for the mode toggle command.
104 Optional INIT-VALUE is the initial value of the mode's variable.
105 Optional LIGHTER is displayed in the modeline when the mode is on.
106 Optional KEYMAP is the default (defvar) keymap bound to the mode keymap.
107 If it is a list, it is passed to `easy-mmode-define-keymap'
108 in order to build a valid keymap. It's generally better to use
109 a separate MODE-map variable than to use this argument.
110 The above three arguments can be skipped if keyword arguments are
111 used (see below).
113 BODY contains code to execute each time the mode is activated or deactivated.
114 It is executed after toggling the mode,
115 and before running the hook variable `mode-HOOK'.
116 Before the actual body code, you can write keyword arguments (alternating
117 keywords and values). These following keyword arguments are supported (other
118 keywords will be passed to `defcustom' if the minor mode is global):
119 :group GROUP Custom group name to use in all generated `defcustom' forms.
120 Defaults to MODE without the possible trailing \"-mode\".
121 Don't use this default group name unless you have written a
122 `defgroup' to define that group properly.
123 :global GLOBAL If non-nil specifies that the minor mode is not meant to be
124 buffer-local, so don't make the variable MODE buffer-local.
125 By default, the mode is buffer-local.
126 :init-value VAL Same as the INIT-VALUE argument.
127 :lighter SPEC Same as the LIGHTER argument.
128 :keymap MAP Same as the KEYMAP argument.
129 :require SYM Same as in `defcustom'.
131 For example, you could write
132 (define-minor-mode foo-mode \"If enabled, foo on you!\"
133 :lighter \" Foo\" :require 'foo :global t :group 'hassle :version \"27.5\"
134 ...BODY CODE...)"
135 (let* ((last-message (current-message))
136 (mode-name (symbol-name mode))
137 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
138 (hook (intern (concat mode-name "-hook")))
139 (hook-on (intern (concat mode-name "-on-hook")))
140 (hook-off (intern (concat mode-name "-off-hook")))
141 keymap-sym)
143 ;; ;; Check keys.
144 ;; (while (keywordp (setq keyw (car body)))
145 ;; (setq body (cdr body))
146 ;; (case keyw
147 ;; (:init-value (setq init-value (pop body)))
148 ;; (:lighter (setq lighter (pop body)))
149 ;; (:global (setq globalp (pop body)))
150 ;; (:extra-args (setq extra-args (pop body)))
151 ;; (:set (setq set (list :set (pop body))))
152 ;; (:initialize (setq initialize (list :initialize (pop body))))
153 ;; (:group (setq group (nconc group (list :group (pop body)))))
154 ;; (:type (setq type (list :type (pop body))))
155 ;; (:require (setq require (pop body)))
156 ;; (:keymap (setq keymap (pop body)))
157 ;; (t (push keyw extra-keywords) (push (pop body) extra-keywords))))
159 ;; XXX: :group can occur many times in the original. here only once.
160 (setf keymap-sym (if (and keymap (symbolp keymap)) keymap
161 (intern (concat mode-name "-MAP")))
162 set `(:set ,(or set 'custom-set-minor-mode))
163 initialize `(:initialize ,(or initialize 'custom-initialize-default))
164 ;; We might as well provide a best-guess default group.
165 group `(:group (or ,group '(intern (replace-regexp-in-string
166 "-mode\\'" "" mode-name))))
167 type `(:type ,(or type 'boolean)))
169 `(progn
170 ;; Define the variable to enable or disable the mode.
171 ,(if (not globalp)
172 `(progn
173 (define-buffer-local ,mode ,init-value ,(format "Non-nil if %s is enabled.
174 Use the command `%s' to change this variable." pretty-name mode))
175 (make-variable-buffer-local ',mode))
177 (let ((base-doc-string
178 (concat "Non-nil if %s is enabled.
179 See the command `%s' for a description of this minor-mode."
180 (if body "
181 Setting this variable directly does not take effect;
182 use either \\[customize] or the function `%s'."))))
183 `(defcustom ,mode ,init-value
184 ,(format base-doc-string pretty-name mode mode)
185 ,@set
186 ,@initialize
187 ,@group
188 ,@type
189 ,@(unless (eq require t) `(:require ,require))
190 ,@(nreverse extra-keywords))))
192 ;; The actual function.
193 (defcommand ,mode ((&optional arg ,@extra-args)
194 :raw-prefix)
195 ,(or doc
196 (format nil (concat "Toggle ~a on or off.
197 Interactively, with no prefix argument, toggle the mode.
198 With universal prefix ARG turn mode on.
199 With zero or negative ARG turn mode off.
200 \\{~s}") pretty-name keymap-sym))
201 ;; Use `toggle' rather than (if ,mode 0 1) so that using
202 ;; repeat-command still does the toggling correctly.
203 ;;(interactive (list (or current-prefix-arg 'toggle)))
204 (unless arg (setf arg 'toggle))
205 (setq ,mode
206 (cond
207 ((eq arg 'toggle) (not ,mode))
208 (arg (> (prefix-numeric-value arg) 0))
210 (el:if (null ,mode) t
211 (message
212 "Toggling %s off; better pass an explicit argument."
213 ',mode)
214 nil))))
215 ,@body
216 ;; The on/off hooks are here for backward compatibility only.
217 (run-hooks ',hook (if ,mode ',hook-on ',hook-off))
218 (if (called-interactively-p)
219 (progn
220 ,(if globalp `(customize-mark-as-set ',mode))
221 ;; Avoid overwriting a message shown by the body,
222 ;; but do overwrite previous messages.
223 (unless ,(and (current-message)
224 (not (equal last-message (current-message))))
225 (message ,(format "~a ~~aabled" pretty-name)
226 (if ,mode "en" "dis")))))
227 (force-mode-line-update)
228 ;; Return the new setting.
229 ,mode)
231 ;; XXX: What do we do with this? -sabetts
232 ;; ;; Autoloading a define-minor-mode autoloads everything
233 ;; ;; up-to-here.
234 ;; :autoload-end
236 ;; Define the minor-mode keymap.
237 ,(unless (symbolp keymap) ;nil is also a symbol.
238 `(defvar ,keymap-sym
239 (let ((m ,keymap))
240 (cond ((keymapp m) m)
241 ((listp m) (easy-mmode-define-keymap m))
242 (t (error "Invalid keymap %S" ,keymap))))
243 ,(format nil "Keymap for `~s'." mode-name)))
245 (add-minor-mode ',mode ',lighter
246 ,(if keymap keymap-sym
247 `(if (boundp ',keymap-sym)
248 (symbol-value ',keymap-sym)))))))
251 ;;; make global minor mode
254 ;;;###autoload
255 (defalias 'easy-mmode-define-global-mode 'define-global-minor-mode)
256 ;;;###autoload
257 (defmacro define-global-minor-mode (global-mode mode turn-on &key group global extra-keywords)
258 "Make GLOBAL-MODE out of the buffer-local minor MODE.
259 TURN-ON is a function that will be called with no args in every buffer
260 and that should try to turn MODE on if applicable for that buffer.
261 KEYS is a list of CL-style keyword arguments. As the minor mode
262 defined by this function is always global, any :global keyword is
263 ignored. Other keywords have the same meaning as in `define-minor-mode',
264 which see. In particular, :group specifies the custom group.
265 The most useful keywords are those that are passed on to the
266 `defcustom'. It normally makes no sense to pass the :lighter
267 or :keymap keywords to `define-global-minor-mode', since these
268 are usually passed to the buffer-local version of the minor mode.
270 If MODE's set-up depends on the major mode in effect when it was
271 enabled, then disabling and reenabling MODE should make MODE work
272 correctly with the current major mode. This is important to
273 prevent problems with derived modes, that is, major modes that
274 call another major mode in their body."
276 (let* ((global-mode-name (symbol-name global-mode))
277 (pretty-name (easy-mmode-pretty-mode-name mode))
278 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
279 (MODE-buffers (intern (concat global-mode-name "-buffers")))
280 (MODE-enable-in-buffers
281 (intern (concat global-mode-name "-enable-in-buffers")))
282 (MODE-check-buffers
283 (intern (concat global-mode-name "-check-buffers")))
284 (MODE-cmhh (intern (concat global-mode-name "-cmhh")))
285 (MODE-major-mode (intern (concat (symbol-name mode) "-major-mode"))))
287 ;; FIXME: :group can occur multiple times in the emacs version but not in this one.
289 ;; We might as well provide a best-guess default group.
290 (setq group
291 `(:group ,(or group '(intern (replace-regexp-in-string
292 "-mode\\'" "" (symbol-name mode))))))
294 `(progn
295 (defvar ,MODE-major-mode nil)
296 (make-variable-buffer-local ',MODE-major-mode)
297 ;; The actual global minor-mode
298 (define-minor-mode ,global-mode
299 ,(format nil "Toggle ~a in every buffer.
300 With prefix ARG, turn ~a on if and only if ARG is positive.
301 ~a is actually not turned on in every buffer but only in those
302 in which `~s' turns it on."
303 pretty-name pretty-global-name pretty-name turn-on)
304 (:global t ,@group ,@(nreverse extra-keywords))
306 ;; Setup hook to handle future mode changes and new buffers.
307 (el:if ,global-mode
308 (progn
309 (add-hook 'after-change-major-mode-hook
310 ',MODE-enable-in-buffers)
311 (add-hook 'find-file-hook ',MODE-check-buffers)
312 (add-hook 'change-major-mode-hook ',MODE-cmhh))
313 (remove-hook 'after-change-major-mode-hook ',MODE-enable-in-buffers)
314 (remove-hook 'find-file-hook ',MODE-check-buffers)
315 (remove-hook 'change-major-mode-hook ',MODE-cmhh))
317 ;; Go through existing buffers.
318 (dolist (buf (buffer-list))
319 (with-current-buffer buf
320 (if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
322 ;; FIXME: when we figure out autoload stuff maybe uncomment this -sabetts
323 ;; ;; Autoloading define-global-minor-mode autoloads everything
324 ;; ;; up-to-here.
325 ;; :autoload-end
327 ;; List of buffers left to process.
328 (defvar ,MODE-buffers nil)
330 ;; The function that calls TURN-ON in each buffer.
331 (defun ,MODE-enable-in-buffers ()
332 (dolist (buf ,MODE-buffers)
333 (when (buffer-live-p buf)
334 (with-current-buffer buf
335 (el:if ,mode
336 (unless (eq ,MODE-major-mode major-mode)
337 (,mode -1)
338 (,turn-on)
339 (setq ,MODE-major-mode major-mode))
340 (,turn-on)
341 (setq ,MODE-major-mode major-mode))))))
342 (put ',MODE-enable-in-buffers 'definition-name ',global-mode)
344 (defun ,MODE-check-buffers ()
345 (,MODE-enable-in-buffers)
346 (setq ,MODE-buffers nil)
347 (remove-hook 'post-command-hook ',MODE-check-buffers))
348 (put ',MODE-check-buffers 'definition-name ',global-mode)
350 ;; The function that catches kill-all-local-variables.
351 (defun ,MODE-cmhh ()
352 (add-to-list ',MODE-buffers (current-buffer))
353 (add-hook 'post-command-hook ',MODE-check-buffers))
354 (put ',MODE-cmhh 'definition-name ',global-mode))))
357 ;;; easy-mmode-defmap
360 (if (fboundp 'set-keymap-parents)
361 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
362 (defun easy-mmode-set-keymap-parents (m parents)
363 (set-keymap-parent
365 (cond
366 ((not (consp parents)) parents)
367 ((not (cdr parents)) (car parents))
368 (t (let ((m (copy-keymap (pop parents))))
369 (easy-mmode-set-keymap-parents m parents)
370 m))))))
372 ;;;###autoload
373 (defun easy-mmode-define-keymap (bs &optional name m args)
374 "Return a keymap built from bindings BS.
375 BS must be a list of (KEY . BINDING) where
376 KEY and BINDINGS are suitable for `define-key'.
377 Optional NAME is passed to `make-sparse-keymap'.
378 Optional map M can be used to modify an existing map.
379 ARGS is a list of additional keyword arguments."
380 (let (inherit dense)
381 (while args
382 (let ((key (pop args))
383 (val (pop args)))
384 (case key
385 (:name (setq name val))
386 (:dense (setq dense val))
387 (:inherit (setq inherit val))
388 (:group)
389 (t (message "Unknown argument %s in defmap" key)))))
390 (unless (keymapp m)
391 (setq bs (append m bs))
392 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
393 (dolist (b bs)
394 (let ((keys (car b))
395 (binding (cdr b)))
396 (dolist (key (if (consp keys) keys (list keys)))
397 (cond
398 ((symbolp key)
399 (substitute-key-definition key binding m *global-map*))
400 ((null binding)
401 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
402 ((let ((o (lookup-key m key)))
403 (or (null o) (numberp o) (eq o 'undefined)))
404 (define-key m key binding))))))
405 (cond
406 ((keymapp inherit) (set-keymap-parent m inherit))
407 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
410 ;;;###autoload
411 (defmacro easy-mmode-defmap (m bs doc &rest args)
412 `(defconst ,m
413 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
414 ,doc))
418 ;;; easy-mmode-defsyntax
421 (defun easy-mmode-define-syntax (css args)
422 (let ((st (make-syntax-table (plist-get args :copy)))
423 (parent (plist-get args :inherit)))
424 (dolist (cs css)
425 (let ((char (car cs))
426 (syntax (cdr cs)))
427 (if (sequencep char)
428 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
429 (modify-syntax-entry char syntax st))))
430 (if parent (set-char-table-parent
431 st (if (symbolp parent) (symbol-value parent) parent)))
432 st))
434 ;;;###autoload
435 (defmacro easy-mmode-defsyntax (st css doc &rest args)
436 "Define variable ST as a syntax-table.
437 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
438 `(progn
439 (autoload 'easy-mmode-define-syntax "easy-mmode")
440 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
445 ;;; easy-mmode-define-navigation
448 (defmacro easy-mmode-define-navigation (base re &optional name endfun narrowfun)
449 "Define BASE-next and BASE-prev to navigate in the buffer.
450 RE determines the places the commands should move point to.
451 NAME should describe the entities matched by RE. It is used to build
452 the docstrings of the two functions.
453 BASE-next also tries to make sure that the whole entry is visible by
454 searching for its end (by calling ENDFUN if provided or by looking for
455 the next entry) and recentering if necessary.
456 ENDFUN should return the end position (with or without moving point).
457 NARROWFUN non-nil means to check for narrowing before moving, and if
458 found, do widen first and then call NARROWFUN with no args after moving."
459 (let* ((base-name (symbol-name base))
460 (prev-sym (intern (concat base-name "-prev")))
461 (next-sym (intern (concat base-name "-next")))
462 (check-narrow-maybe
463 (when narrowfun
464 '(setq was-narrowed
465 (prog1 (or (< (- (point-max) (point-min)) (buffer-size)))
466 (widen)))))
467 (re-narrow-maybe (when narrowfun
468 `(when was-narrowed (,narrowfun)))))
469 (unless name (setq name base-name))
470 `(progn
471 (add-to-list 'debug-ignored-errors
472 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
473 (defun ,next-sym (&optional count)
474 ,(format "Go to the next COUNT'th %s." name)
475 (interactive)
476 (unless count (setq count 1))
477 (el:if (< count 0) (,prev-sym (- count))
478 (if (looking-at ,re) (setq count (1+ count)))
479 (let (was-narrowed)
480 ,check-narrow-maybe
481 (if (not (re-search-forward ,re nil t count))
482 (if (looking-at ,re)
483 (goto-char (or ,(if endfun `(,endfun)) (point-max)))
484 (error "No next %s" ,name))
485 (goto-char (match-beginning 0))
486 (when (and (eq (current-buffer) (window-buffer (selected-window)))
487 (interactive-p))
488 (let ((endpt (or (save-excursion
489 ,(if endfun `(,endfun)
490 `(re-search-forward ,re nil t 2)))
491 (point-max))))
492 (unless (pos-visible-in-window-p endpt nil t)
493 (recenter '(0))))))
494 ,re-narrow-maybe)))
495 (put ',next-sym 'definition-name ',base)
496 (defun ,prev-sym (&optional count)
497 ,(format "Go to the previous COUNT'th %s" (or name base-name))
498 (interactive)
499 (unless count (setq count 1))
500 (if (< count 0) (,next-sym (- count))
501 (let (was-narrowed)
502 ,check-narrow-maybe
503 (unless (re-search-backward ,re nil t count)
504 (error "No previous %s" ,name))
505 ,re-narrow-maybe)))
506 (put ',prev-sym 'definition-name ',base))))
509 (provide 'easy-mmode)
511 ;;; arch-tag: d48a5250-6961-4528-9cb0-3c9ea042a66a
512 ;;; easy-mmode.el ends here