1 ;;; easy-mmode.el --- easy definition for major and minor modes
3 ;; Copyright (C) 1997, 2000, 2001 Free Software Foundation, Inc.
5 ;; Author: Georges Brun-Cottan <Georges.Brun-Cottan@inria.fr>
6 ;; Maintainer: Stefan Monnier <monnier@gnu.org>
8 ;; Keywords: extensions lisp
10 ;; This file is part of SXEmacs.
12 ;; SXEmacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; SXEmacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Synched up with: GNU Emacs 21.3.
29 ;; Minor modes are useful and common. This package makes defining a
30 ;; minor mode easy, by focusing on the writing of the minor mode
31 ;; functionalities themselves. Moreover, this package enforces a
32 ;; conventional naming of user interface primitives, making things
33 ;; natural for the minor-mode end-users.
35 ;; For each mode, easy-mmode defines the following:
36 ;; <mode> : The minor mode predicate. A buffer-local variable.
37 ;; <mode>-map : The keymap possibly associated to <mode>.
38 ;; <mode>-hook,<mode>-on-hook,<mode>-off-hook and <mode>-mode:
39 ;; see `define-minor-mode' documentation
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
51 ;; Additionally to `define-minor-mode', the package provides convenient
52 ;; ways to define keymaps, and other helper functions for major and minor
57 (eval-when-compile (require 'cl))
59 ;;; This file uses two functions that did not exist in some versions of
60 ;;; XEmacs: propertize and replace-regexp-in-string. We provide these
61 ;;; functions here for such XEmacsen.
63 ;;; FIXME: These function definitions should go into the future or
64 ;;; forward-compat package, once that package exists.
66 ;; XEmacs <= 21.4 does not have propertize, but XEmacs >= 21.5 dumps it (it is
67 ;; defined in subr.el). Therefore, it is either defined regardless of what
68 ;; has been loaded already, or it won't be defined regardless of what is
70 (if (not (fboundp 'propertize))
71 (defun propertize (string &rest properties)
72 "Return a copy of STRING with text properties added.
73 First argument is the string to copy.
74 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
75 properties to add to the result."
76 (let ((str (copy-sequence string)))
77 (add-text-properties 0 (length str)
82 ;; XEmacs <= 21.4 does not have replace-regexp-in-string, but XEmacs >= 21.5
83 ;; dumps it (it is defined in subr.el). Therefore, it is either defined
84 ;; regardless of what has been loaded already, or it won't be defined
85 ;; regardless of what is loaded.
86 (if (not (fboundp 'replace-regexp-in-string))
87 (defun replace-regexp-in-string (regexp rep string &optional
88 fixedcase literal subexp start)
89 "Replace all matches for REGEXP with REP in STRING.
91 Return a new string containing the replacements.
93 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
94 arguments with the same names of function `replace-match'. If START
95 is non-nil, start replacements at that index in STRING.
97 REP is either a string used as the NEWTEXT arg of `replace-match' or a
98 function. If it is a function it is applied to each match to generate
99 the replacement passed to `replace-match'; the match-data at this
100 point are such that match 0 is the function's argument.
102 To replace only the first match (if any), make REGEXP match up to \\'
103 and replace a sub-expression, e.g.
104 (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1)
107 (let ((l (length string))
111 (while (and (< start l) (string-match regexp string start))
112 (setq mb (match-beginning 0)
114 ;; If we matched the empty string, make sure we advance by one char
115 (when (= me mb) (setq me (min l (1+ mb))))
116 ;; Generate a replacement for the matched substring.
117 ;; Operate only on the substring to minimize string consing.
118 ;; Set up match data for the substring for replacement;
119 ;; presumably this is likely to be faster than munging the
120 ;; match data directly in Lisp.
121 (string-match regexp (setq str (substring string mb me)))
123 (cons (replace-match (if (stringp rep)
125 (funcall rep (match-string 0 str)))
126 fixedcase literal str subexp)
127 (cons (substring string start mb) ; unmatched prefix
130 ;; Reconstruct a string from the pieces.
131 (setq matches (cons (substring string start l) matches)) ; leftover
132 (apply #'concat (nreverse matches))))))
135 (defun easy-mmode-pretty-mode-name (mode &optional lighter)
136 "Turn the symbol MODE into a string intended for the user.
137 If provided LIGHTER will be used to help choose capitalization."
138 (let* ((case-fold-search t)
139 (name (concat (replace-regexp-in-string
141 (capitalize (replace-regexp-in-string
142 "-mode\\'" "" (symbol-name mode))))
144 (if (not (stringp lighter)) name
146 (replace-regexp-in-string "\\`\\s-+\\|\\-s+\\'" "" lighter))
147 (replace-regexp-in-string lighter lighter name t t))))
149 ;; XEmacs change: add -on-hook, -off-hook, and macro parameter documentation.
151 (defalias 'easy-mmode-define-minor-mode 'define-minor-mode)
153 (defmacro define-minor-mode (mode doc &optional init-value lighter keymap &rest body)
154 "Define a new minor mode MODE.
155 This function defines the associated control variable MODE, keymap MODE-map,
156 toggle command MODE, and hook MODE-hook.
158 DOC is the documentation for the mode toggle command.
159 Optional INIT-VALUE is the initial value of the mode's variable.
160 Optional LIGHTER is displayed in the modeline when the mode is on.
161 Optional KEYMAP is the default (defvar) keymap bound to the mode keymap.
162 If it is a list, it is passed to `easy-mmode-define-keymap'
163 in order to build a valid keymap. It's generally better to use
164 a separate MODE-map variable than to use this argument.
165 The above three arguments can be skipped if keyword arguments are
168 BODY contains code that will be executed each time the mode is (de)activated.
169 It will be executed after any toggling but before running the hooks.
170 Before the actual body code, you can write
171 keyword arguments (alternating keywords and values).
172 These following keyword arguments are supported:
173 :group GROUP Custom group name to use in all generated `defcustom' forms.
174 :global GLOBAL If non-nil specifies that the minor mode is not meant to be
175 buffer-local, so don't make the variable MODE buffer-local.
176 By default, the mode is buffer-local.
177 :init-value VAL Same as the INIT-VALUE argument.
178 :lighter SPEC Same as the LIGHTER argument.
179 :require SYM Same as in `defcustom'.
181 For backwards compatibility, these hooks are run each time the mode is
182 \(de)activated. When the mode is toggled, MODE-hook is always run before the
184 MODE-hook: run if the mode is toggled.
185 MODE-on-hook: run if the mode is activated.
186 MODE-off-hook: run if the mode is deactivated.
188 \(defmacro easy-mmode-define-minor-mode
189 (MODE DOC &optional INIT-VALUE LIGHTER KEYMAP &rest BODY)...\)
191 For example, you could write
192 (define-minor-mode foo-mode \"If enabled, foo on you!\"
193 nil \"Foo \" foo-keymap
194 :require 'foo :global t :group 'inconvenience
197 ;; Allow skipping the first three args.
199 ((keywordp init-value)
200 (setq body (list* init-value lighter keymap body)
201 init-value nil lighter nil keymap nil))
203 (setq body (list* lighter keymap body) lighter nil keymap nil))
204 ((keywordp keymap) (push keymap body) (setq keymap nil)))
206 (let* ((mode-name (symbol-name mode))
207 (pretty-name (easy-mmode-pretty-mode-name mode lighter))
212 (keymap-sym (if (and keymap (symbolp keymap)) keymap
213 (intern (concat mode-name "-map"))))
214 (hook (intern (concat mode-name "-hook")))
215 (hook-on (intern (concat mode-name "-on-hook")))
216 (hook-off (intern (concat mode-name "-off-hook"))))
219 (while (keywordp (car body))
221 (:init-value (setq init-value (pop body)))
222 (:lighter (setq lighter (pop body)))
223 (:global (setq globalp (pop body)))
224 (:extra-args (setq extra-args (pop body)))
225 (:group (setq group (nconc group (list :group (pop body)))))
226 (:require (setq require (pop body)))
230 ;; We might as well provide a best-guess default group.
232 ;; XEmacs: the commented-out functions are going to be in
233 ;; 21.5. easy-mmode will be moved to the core in any case,
234 ;; so don't worry for now.
235 `(:group ',(or ;(custom-current-group)
236 (intern (replace-regexp-in-string
237 "-mode\\'" "" mode-name))))))
238 ;; Add default properties to LIGHTER.
239 ;; #### FSF comments this out in 21.3.
240 ; (unless (or (not (stringp lighter))
241 ; (get-text-property 0 'local-map lighter)
242 ; (get-text-property 0 'keymap lighter))
244 ; (propertize lighter
245 ; 'local-map modeline-minor-mode-map ; XEmacs change
246 ; 'help-echo "mouse-3: minor mode menu")))
249 ;; Define the variable to enable or disable the mode.
252 (defvar ,mode ,init-value ,(format "Non-nil if %s is enabled.
253 Use the command `%s' to change this variable." pretty-name mode))
254 (make-variable-buffer-local ',mode))
256 (let ((curfile (or (and (boundp 'byte-compile-current-file)
257 byte-compile-current-file)
259 `(defcustom ,mode ,init-value
260 ,(format "Non-nil if %s is enabled.
261 See the command `%s' for a description of this minor-mode.
262 Setting this variable directly does not take effect;
263 use either \\[customize] or the function `%s'."
264 pretty-name mode mode)
265 :set (lambda (symbol value) (funcall symbol (or value 0)))
266 :initialize 'custom-initialize-default
270 ((not (and curfile require)) nil)
271 ((not (eq require t)) `(:require ,require))
273 ',(intern (file-name-nondirectory
274 (file-name-sans-extension curfile)))))))))
276 ;; The actual function.
277 (defun ,mode (&optional arg ,@extra-args)
279 (format (concat "Toggle %s on or off.
280 Interactively, with no prefix argument, toggle the mode.
281 With universal prefix ARG turn mode on.
282 With zero or negative ARG turn mode off.
283 \\{%s}") pretty-name keymap-sym))
284 ;; Use `toggle' rather than (if ,mode 0 1) so that using
285 ;; repeat-command still does the toggling correctly.
286 (interactive (list (or current-prefix-arg 'toggle)))
287 ;; XEmacs addition: save the old mode
288 (let ((old-mode ,mode))
291 ((eq arg 'toggle) (not ,mode))
292 (arg (or (listp arg);; XEmacs addition: C-u alone
293 (> (prefix-numeric-value arg) 0)))
297 "Toggling %s off; better pass an explicit argument."
301 ;; The on/off hooks are here for backward compatibility only.
302 ;; The on/off hooks are here for backward compatibility only.
303 ;; XEmacs change: check mode before running hooks
305 (not (equal old-mode ,mode))
309 (run-hooks ',hook-on))
312 (run-hooks ',hook-off)))
315 ;; see comment up at custom-current-group.
316 ;; ,(if globalp `(customize-mark-as-set ',mode))
317 (message ,(format "%s %%sabled" pretty-name)
318 (if ,mode "en" "dis"))))
319 (force-mode-line-update)
320 ;; Return the new setting.
323 ;; Autoloading an easy-mmode-define-minor-mode autoloads
324 ;; everything up-to-here.
326 ;; XEmacs change: XEmacs does not support :autoload-end. On the other
327 ;; hand, I don't see why we need to support it. An autoload cookie
328 ;; just before a (define-minor-mode foo) form will generate an autoload
329 ;; form for the file with name foo. But that's exactly right, since
330 ;; the defun created just above here has the name foo. There are no
331 ;; other top-level forms created above here by the macro, so we're done.
335 ;; The toggle's hook.
337 ,(format "Hook run at the end of function `%s'." mode-name)
341 ;; XEmacs addition: declare the on and off hooks also
342 (defcustom ,hook-on nil
343 ,(format "Hook to run when entering %s." mode-name)
347 (defcustom ,hook-off nil
348 ,(format "Hook to run when exiting %s." mode-name)
352 ;; Define the minor-mode keymap.
353 ,(unless (symbolp keymap) ;nil is also a symbol.
356 (cond ((keymapp m) m)
357 ((listp m) (easy-mmode-define-keymap m))
358 (t (error "Invalid keymap %S" ,keymap))))
359 ,(format "Keymap for `%s'." mode-name)))
361 (add-minor-mode ',mode ',lighter
362 ,(if keymap keymap-sym
363 `(if (boundp ',keymap-sym)
364 (symbol-value ',keymap-sym)))
365 ;; XEmacs change: supply the AFTER and TOGGLE-FUN args
368 ;; If the mode is global, call the function according to the default.
370 `(if (and load-file-name (not (equal ,init-value ,mode))
373 (eval-after-load load-file-name '(,mode (if ,mode 1 -1))))))))
376 ;;; make global minor mode
380 (defmacro easy-mmode-define-global-mode (global-mode mode turn-on
382 "Make GLOBAL-MODE out of the buffer-local minor MODE.
383 TURN-ON is a function that will be called with no args in every buffer
384 and that should try to turn MODE on if applicable for that buffer.
385 KEYS is a list of CL-style keyword arguments:
386 :group to specify the custom group."
387 (let* ((global-mode-name (symbol-name global-mode))
388 (pretty-name (easy-mmode-pretty-mode-name mode))
389 (pretty-global-name (easy-mmode-pretty-mode-name global-mode))
392 (buffers (intern (concat global-mode-name "-buffers")))
393 (cmmh (intern (concat global-mode-name "-cmmh"))))
396 (while (keywordp (car keys))
398 (:extra-args (setq extra-args (pop keys)))
399 (:group (setq group (nconc group (list :group (pop keys)))))
400 (t (setq keys (cdr keys)))))
403 ;; We might as well provide a best-guess default group.
405 `(:group ',(or ;(custom-current-group)
406 (intern (replace-regexp-in-string
407 "-mode\\'" "" (symbol-name mode)))))))
410 ;; The actual global minor-mode
411 (define-minor-mode ,global-mode
412 ,(format "Toggle %s in every buffer.
413 With prefix ARG, turn %s on if and only if ARG is positive.
414 %s is actually not turned on in every buffer but only in those
415 in which `%s' turns it on."
416 pretty-name pretty-global-name pretty-name turn-on)
417 :global t :extra-args ,extra-args ,@group
419 ;; Setup hook to handle future mode changes and new buffers.
421 ;; XEmacs: find-file-hooks not find-file-hook
423 (add-hook 'find-file-hooks ',buffers)
424 (add-hook 'change-major-mode-hook ',cmmh))
425 (remove-hook 'find-file-hooks ',buffers)
426 (remove-hook 'change-major-mode-hook ',cmmh))
428 ;; Go through existing buffers.
429 (dolist (buf (buffer-list))
430 (with-current-buffer buf
431 (if ,global-mode (,turn-on) (when ,mode (,mode -1))))))
433 ;; TODO: XEmacs does not support :autoload-end
434 ;; Autoloading easy-mmode-define-global-mode
435 ;; autoloads everything up-to-here.
438 ;; List of buffers left to process.
439 (defvar ,buffers nil)
441 ;; The function that calls TURN-ON in each buffer.
443 (remove-hook 'post-command-hook ',buffers)
445 (let ((buf (pop ,buffers)))
446 (when (buffer-live-p buf)
447 (with-current-buffer buf (,turn-on))))))
448 (put ',buffers 'definition-name ',global-mode)
450 ;; The function that catches kill-all-local-variables.
452 (add-to-list ',buffers (current-buffer))
453 (add-hook 'post-command-hook ',buffers))
454 (put ',cmmh 'definition-name ',global-mode))))
457 ;;; easy-mmode-defmap
460 (if (fboundp 'set-keymap-parents)
461 (defalias 'easy-mmode-set-keymap-parents 'set-keymap-parents)
462 (defun easy-mmode-set-keymap-parents (m parents)
466 ((not (consp parents)) parents)
467 ((not (cdr parents)) (car parents))
468 (t (let ((m (copy-keymap (pop parents))))
469 (easy-mmode-set-keymap-parents m parents)
473 (defun easy-mmode-define-keymap (bs &optional name m args)
474 "Return a keymap built from bindings BS.
475 BS must be a list of (KEY . BINDING) where
476 KEY and BINDINGS are suitable for `define-key'.
477 Optional NAME is passed to `make-sparse-keymap'.
478 Optional map M can be used to modify an existing map.
479 ARGS is a list of additional keyword arguments."
480 (let (inherit dense ;suppress
483 (let ((key (pop args))
486 (:name (setq name val))
487 (:dense (setq dense val))
488 (:inherit (setq inherit val))
490 ;;((eq key :suppress) (setq suppress val))
491 (t (message "Unknown argument %s in defmap" key)))))
493 (setq bs (append m bs))
494 (setq m (if dense (make-keymap name) (make-sparse-keymap name))))
498 (dolist (key (if (consp keys) keys (list keys)))
501 (substitute-key-definition key binding m global-map))
503 (unless (keymapp (lookup-key m key)) (define-key m key binding)))
504 ((let ((o (lookup-key m key)))
505 (or (null o) (numberp o) (eq o 'undefined)))
506 (define-key m key binding))))))
508 ((keymapp inherit) (set-keymap-parent m inherit))
509 ((consp inherit) (easy-mmode-set-keymap-parents m inherit)))
513 (defmacro easy-mmode-defmap (m bs doc &rest args)
515 (easy-mmode-define-keymap ,bs nil (if (boundp ',m) ,m) ,(cons 'list args))
520 ;;; easy-mmode-defsyntax
523 (defun easy-mmode-define-syntax (css args)
524 (let ((st (make-syntax-table (plist-get args :copy)))
525 (parent (plist-get args :inherit)))
527 (let ((char (car cs))
530 (mapcar (lambda (c) (modify-syntax-entry c syntax st)) char)
531 (modify-syntax-entry char syntax st))))
532 ;; XEmacs change: we do not have set-char-table-parent
533 (if parent (derived-mode-merge-syntax-tables
534 (if (symbolp parent) (symbol-value parent) parent) st))
538 (defmacro easy-mmode-defsyntax (st css doc &rest args)
539 "Define variable ST as a syntax-table.
540 CSS contains a list of syntax specifications of the form (CHAR . SYNTAX)."
542 (autoload 'easy-mmode-define-syntax "easy-mmode")
543 (defconst ,st (easy-mmode-define-syntax ,css ,(cons 'list args)) ,doc)))
548 ;;; easy-mmode-define-navigation
551 ;; XEmacs change: autoload
553 (defmacro easy-mmode-define-navigation (base re &optional name endfun)
554 "Define BASE-next and BASE-prev to navigate in the buffer.
555 RE determines the places the commands should move point to.
556 NAME should describe the entities matched by RE. It is used to build
557 the docstrings of the two functions.
558 BASE-next also tries to make sure that the whole entry is visible by
559 searching for its end (by calling ENDFUN if provided or by looking for
560 the next entry) and recentering if necessary.
561 ENDFUN should return the end position (with or without moving point)."
562 (let* ((base-name (symbol-name base))
563 (prev-sym (intern (concat base-name "-prev")))
564 (next-sym (intern (concat base-name "-next"))))
565 (unless name (setq name (symbol-name base-name)))
567 (add-to-list 'debug-ignored-errors
568 ,(concat "^No \\(previous\\|next\\) " (regexp-quote name)))
569 (defun ,next-sym (&optional count)
570 ,(format "Go to the next COUNT'th %s." name)
572 (unless count (setq count 1))
573 (if (< count 0) (,prev-sym (- count))
574 (if (looking-at ,re) (incf count))
575 (if (not (re-search-forward ,re nil t count))
577 (goto-char (or ,(if endfun `(,endfun)) (point-max)))
578 (error ,(format "No next %s" name)))
579 (goto-char (match-beginning 0))
580 (when (and (eq (current-buffer) (window-buffer (selected-window)))
582 (let ((endpt (or (save-excursion
583 ,(if endfun `(,endfun)
584 `(re-search-forward ,re nil t 2)))
586 ;; XEmacs change: versions < 21.5.16 have a
587 ;; pos-visible-in-window-p that takes only 2 parameters
589 (if (eq (function-max-args #'pos-visible-in-window-p) 2)
590 (pos-visible-in-window-p endpt nil)
591 (pos-visible-in-window-p endpt nil t))
592 (recenter '(0))))))))
593 (defun ,prev-sym (&optional count)
594 ,(format "Go to the previous COUNT'th %s" (or name base-name))
596 (unless count (setq count 1))
597 (if (< count 0) (,next-sym (- count))
598 (unless (re-search-backward ,re nil t count)
599 (error ,(format "No previous %s" name))))))))
601 (provide 'easy-mmode)
603 ;;; easy-mmode.el ends here