8c8d37b21944f32c5f5469b4d732ec0bf0246a9a
[bpt/emacs.git] / lisp / emacs-lisp / derived.el
1 ;;; derived.el --- allow inheritance of major modes
2 ;; (formerly mode-clone.el)
3
4 ;; Copyright (C) 1993-1994, 1999, 2001-2012 Free Software Foundation, Inc.
5
6 ;; Author: David Megginson (dmeggins@aix1.uottawa.ca)
7 ;; Maintainer: FSF
8 ;; Keywords: extensions
9 ;; Package: emacs
10
11 ;; This file is part of GNU Emacs.
12
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 3 of the License, or
16 ;; (at your option) any later version.
17
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.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 \f
26 ;;; Commentary:
27
28 ;; GNU Emacs is already, in a sense, object oriented -- each object
29 ;; (buffer) belongs to a class (major mode), and that class defines
30 ;; the relationship between messages (input events) and methods
31 ;; (commands) by means of a keymap.
32 ;;
33 ;; The only thing missing is a good scheme of inheritance. It is
34 ;; possible to simulate a single level of inheritance with generous
35 ;; use of hooks and a bit of work -- sgml-mode, for example, also runs
36 ;; the hooks for text-mode, and keymaps can inherit from other keymaps
37 ;; -- but generally, each major mode ends up reinventing the wheel.
38 ;; Ideally, someone should redesign all of Emacs's major modes to
39 ;; follow a more conventional object-oriented system: when defining a
40 ;; new major mode, the user should need only to name the existing mode
41 ;; it is most similar to, then list the (few) differences.
42 ;;
43 ;; In the mean time, this package offers most of the advantages of
44 ;; full inheritance with the existing major modes. The macro
45 ;; `define-derived-mode' allows the user to make a variant of an existing
46 ;; major mode, with its own keymap. The new mode will inherit the key
47 ;; bindings of its parent, and will, in fact, run its parent first
48 ;; every time it is called. For example, the commands
49 ;;
50 ;; (define-derived-mode hypertext-mode text-mode "Hypertext"
51 ;; "Major mode for hypertext.\n\n\\{hypertext-mode-map}"
52 ;; (setq case-fold-search nil))
53 ;;
54 ;; (define-key hypertext-mode-map [down-mouse-3] 'do-hyper-link)
55 ;;
56 ;; will create a function `hypertext-mode' with its own (sparse)
57 ;; keymap `hypertext-mode-map.' The command M-x hypertext-mode will
58 ;; perform the following actions:
59 ;;
60 ;; - run the command (text-mode) to get its default setup
61 ;; - replace the current keymap with 'hypertext-mode-map,' which will
62 ;; inherit from 'text-mode-map'.
63 ;; - replace the current syntax table with
64 ;; 'hypertext-mode-syntax-table', which will borrow its defaults
65 ;; from the current text-mode-syntax-table.
66 ;; - replace the current abbrev table with
67 ;; 'hypertext-mode-abbrev-table', which will borrow its defaults
68 ;; from the current text-mode-abbrev table
69 ;; - change the mode line to read "Hypertext"
70 ;; - assign the value 'hypertext-mode' to the 'major-mode' variable
71 ;; - run the body of commands provided in the macro -- in this case,
72 ;; set the local variable `case-fold-search' to nil.
73 ;;
74 ;; The advantages of this system are threefold. First, text mode is
75 ;; untouched -- if you had added the new keystroke to `text-mode-map,'
76 ;; possibly using hooks, you would have added it to all text buffers
77 ;; -- here, it appears only in hypertext buffers, where it makes
78 ;; sense. Second, it is possible to build even further, and make
79 ;; a derived mode from a derived mode. The commands
80 ;;
81 ;; (define-derived-mode html-mode hypertext-mode "HTML")
82 ;; [various key definitions]
83 ;;
84 ;; will add a new major mode for HTML with very little fuss.
85 ;;
86 ;; Note also the function `derived-mode-p' which can tell if the current
87 ;; mode derives from another. In a hypertext-mode, buffer, for example,
88 ;; (derived-mode-p 'text-mode) would return non-nil. This should always
89 ;; be used in place of (eq major-mode 'text-mode).
90 \f
91 ;;; Code:
92
93 ;;; PRIVATE: defsubst must be defined before they are first used
94
95 (defsubst derived-mode-hook-name (mode)
96 "Construct a mode-hook name based on a MODE name."
97 (intern (concat (symbol-name mode) "-hook")))
98
99 (defsubst derived-mode-map-name (mode)
100 "Construct a map name based on a MODE name."
101 (intern (concat (symbol-name mode) "-map")))
102
103 (defsubst derived-mode-syntax-table-name (mode)
104 "Construct a syntax-table name based on a MODE name."
105 (intern (concat (symbol-name mode) "-syntax-table")))
106
107 (defsubst derived-mode-abbrev-table-name (mode)
108 "Construct an abbrev-table name based on a MODE name."
109 (intern (concat (symbol-name mode) "-abbrev-table")))
110
111 ;; PUBLIC: define a new major mode which inherits from an existing one.
112
113 ;;;###autoload
114 (defmacro define-derived-mode (child parent name &optional docstring &rest body)
115 "Create a new mode as a variant of an existing mode.
116
117 The arguments to this command are as follow:
118
119 CHILD: the name of the command for the derived mode.
120 PARENT: the name of the command for the parent mode (e.g. `text-mode')
121 or nil if there is no parent.
122 NAME: a string which will appear in the status line (e.g. \"Hypertext\")
123 DOCSTRING: an optional documentation string--if you do not supply one,
124 the function will attempt to invent something useful.
125 BODY: forms to execute just before running the
126 hooks for the new mode. Do not use `interactive' here.
127
128 BODY can start with a bunch of keyword arguments. The following keyword
129 arguments are currently understood:
130 :group GROUP
131 Declare the customization group that corresponds to this mode.
132 The command `customize-mode' uses this.
133 :syntax-table TABLE
134 Use TABLE instead of the default (CHILD-syntax-table).
135 A nil value means to simply use the same syntax-table as the parent.
136 :abbrev-table TABLE
137 Use TABLE instead of the default (CHILD-abbrev-table).
138 A nil value means to simply use the same abbrev-table as the parent.
139
140 Here is how you could define LaTeX-Thesis mode as a variant of LaTeX mode:
141
142 (define-derived-mode LaTeX-thesis-mode LaTeX-mode \"LaTeX-Thesis\")
143
144 You could then make new key bindings for `LaTeX-thesis-mode-map'
145 without changing regular LaTeX mode. In this example, BODY is empty,
146 and DOCSTRING is generated by default.
147
148 On a more complicated level, the following command uses `sgml-mode' as
149 the parent, and then sets the variable `case-fold-search' to nil:
150
151 (define-derived-mode article-mode sgml-mode \"Article\"
152 \"Major mode for editing technical articles.\"
153 (setq case-fold-search nil))
154
155 Note that if the documentation string had been left out, it would have
156 been generated automatically, with a reference to the keymap.
157
158 The new mode runs the hook constructed by the function
159 `derived-mode-hook-name'.
160
161 See Info node `(elisp)Derived Modes' for more details."
162 (declare (debug (&define name symbolp sexp [&optional stringp]
163 [&rest keywordp sexp] def-body))
164 (doc-string 4))
165
166 (when (and docstring (not (stringp docstring)))
167 ;; Some trickiness, since what appears to be the docstring may really be
168 ;; the first element of the body.
169 (push docstring body)
170 (setq docstring nil))
171
172 (when (eq parent 'fundamental-mode) (setq parent nil))
173
174 (let ((map (derived-mode-map-name child))
175 (syntax (derived-mode-syntax-table-name child))
176 (abbrev (derived-mode-abbrev-table-name child))
177 (declare-abbrev t)
178 (declare-syntax t)
179 (hook (derived-mode-hook-name child))
180 (group nil))
181
182 ;; Process the keyword args.
183 (while (keywordp (car body))
184 (pcase (pop body)
185 (`:group (setq group (pop body)))
186 (`:abbrev-table (setq abbrev (pop body)) (setq declare-abbrev nil))
187 (`:syntax-table (setq syntax (pop body)) (setq declare-syntax nil))
188 (_ (pop body))))
189
190 (setq docstring (derived-mode-make-docstring
191 parent child docstring syntax abbrev))
192
193 `(progn
194 (unless (get ',hook 'variable-documentation)
195 (put ',hook 'variable-documentation
196 (purecopy ,(format "Hook run when entering %s mode.
197 No problems result if this variable is not bound.
198 `add-hook' automatically binds it. (This is true for all hook variables.)"
199 name))))
200 (unless (boundp ',map)
201 (put ',map 'definition-name ',child))
202 (with-no-warnings (defvar ,map (make-sparse-keymap)))
203 (unless (get ',map 'variable-documentation)
204 (put ',map 'variable-documentation
205 (purecopy ,(format "Keymap for `%s'." child))))
206 ,(if declare-syntax
207 `(progn
208 (unless (boundp ',syntax)
209 (put ',syntax 'definition-name ',child))
210 (defvar ,syntax (make-syntax-table))
211 (unless (get ',syntax 'variable-documentation)
212 (put ',syntax 'variable-documentation
213 (purecopy ,(format "Syntax table for `%s'." child))))))
214 ,(if declare-abbrev
215 `(progn
216 (put ',abbrev 'definition-name ',child)
217 (defvar ,abbrev
218 (progn (define-abbrev-table ',abbrev nil) ,abbrev))
219 (unless (get ',abbrev 'variable-documentation)
220 (put ',abbrev 'variable-documentation
221 (purecopy ,(format "Abbrev table for `%s'." child))))))
222 (put ',child 'derived-mode-parent ',parent)
223 ,(if group `(put ',child 'custom-mode-group ,group))
224
225 (defun ,child ()
226 ,docstring
227 (interactive)
228 ; Run the parent.
229 (delay-mode-hooks
230
231 (,(or parent 'kill-all-local-variables))
232 ; Identify the child mode.
233 (setq major-mode (quote ,child))
234 (setq mode-name ,name)
235 ; Identify special modes.
236 ,(when parent
237 `(progn
238 (if (get (quote ,parent) 'mode-class)
239 (put (quote ,child) 'mode-class
240 (get (quote ,parent) 'mode-class)))
241 ; Set up maps and tables.
242 (unless (keymap-parent ,map)
243 ;; It would probably be better to set the keymap's parent
244 ;; at the toplevel rather than inside the mode function,
245 ;; but this is not easy for at least the following reasons:
246 ;; - the parent (and its keymap) may not yet be loaded.
247 ;; - the parent's keymap name may be called something else
248 ;; than <parent>-mode-map.
249 (set-keymap-parent ,map (current-local-map)))
250 ,(when declare-syntax
251 `(let ((parent (char-table-parent ,syntax)))
252 (unless (and parent
253 (not (eq parent (standard-syntax-table))))
254 (set-char-table-parent ,syntax (syntax-table)))))
255 ,(when declare-abbrev
256 `(unless (or (abbrev-table-get ,abbrev :parents)
257 ;; This can happen if the major mode defines
258 ;; the abbrev-table to be its parent's.
259 (eq ,abbrev local-abbrev-table))
260 (abbrev-table-put ,abbrev :parents
261 (list local-abbrev-table))))))
262 (use-local-map ,map)
263 ,(when syntax `(set-syntax-table ,syntax))
264 ,(when abbrev `(setq local-abbrev-table ,abbrev))
265 ; Splice in the body (if any).
266 ,@body
267 )
268 ;; Run the hooks, if any.
269 (run-mode-hooks ',hook)))))
270
271 ;; PUBLIC: find the ultimate class of a derived mode.
272
273 (defun derived-mode-class (mode)
274 "Find the class of a major MODE.
275 A mode's class is the first ancestor which is NOT a derived mode.
276 Use the `derived-mode-parent' property of the symbol to trace backwards.
277 Since major-modes might all derive from `fundamental-mode', this function
278 is not very useful."
279 (declare (obsolete derived-mode-p "22.1"))
280 (while (get mode 'derived-mode-parent)
281 (setq mode (get mode 'derived-mode-parent)))
282 mode)
283
284 \f
285 ;;; PRIVATE
286
287 (defun derived-mode-make-docstring (parent child &optional
288 docstring syntax abbrev)
289 "Construct a docstring for a new mode if none is provided."
290
291 (let ((map (derived-mode-map-name child))
292 (hook (derived-mode-hook-name child)))
293
294 (unless (stringp docstring)
295 ;; Use a default docstring.
296 (setq docstring
297 (if (null parent)
298 (format "Major-mode.
299 Uses keymap `%s', abbrev table `%s' and syntax-table `%s'." map abbrev syntax)
300 (format "Major mode derived from `%s' by `define-derived-mode'.
301 It inherits all of the parent's attributes, but has its own keymap,
302 abbrev table and syntax table:
303
304 `%s', `%s' and `%s'
305
306 which more-or-less shadow %s's corresponding tables."
307 parent map abbrev syntax parent))))
308
309 (unless (string-match (regexp-quote (symbol-name hook)) docstring)
310 ;; Make sure the docstring mentions the mode's hook.
311 (setq docstring
312 (concat docstring
313 (if (null parent)
314 "\n\nThis mode "
315 (concat
316 "\n\nIn addition to any hooks its parent mode "
317 (if (string-match (regexp-quote (format "`%s'" parent))
318 docstring) nil
319 (format "`%s' " parent))
320 "might have run,\nthis mode "))
321 (format "runs the hook `%s'" hook)
322 ", as the final step\nduring initialization.")))
323
324 (unless (string-match "\\\\[{[]" docstring)
325 ;; And don't forget to put the mode's keymap.
326 (setq docstring (concat docstring "\n\n\\{" (symbol-name map) "}")))
327
328 docstring))
329
330 \f
331 ;;; OBSOLETE
332 ;; The functions below are only provided for backward compatibility with
333 ;; code byte-compiled with versions of derived.el prior to Emacs-21.
334
335 (defsubst derived-mode-setup-function-name (mode)
336 "Construct a setup-function name based on a MODE name."
337 (intern (concat (symbol-name mode) "-setup")))
338
339 \f
340 ;; Utility functions for defining a derived mode.
341
342 ;;;###autoload
343 (defun derived-mode-init-mode-variables (mode)
344 "Initialize variables for a new MODE.
345 Right now, if they don't already exist, set up a blank keymap, an
346 empty syntax table, and an empty abbrev table -- these will be merged
347 the first time the mode is used."
348
349 (if (boundp (derived-mode-map-name mode))
350 t
351 (eval `(defvar ,(derived-mode-map-name mode)
352 (make-sparse-keymap)
353 ,(format "Keymap for %s." mode)))
354 (put (derived-mode-map-name mode) 'derived-mode-unmerged t))
355
356 (if (boundp (derived-mode-syntax-table-name mode))
357 t
358 (eval `(defvar ,(derived-mode-syntax-table-name mode)
359 ;; Make a syntax table which doesn't specify anything
360 ;; for any char. Valid data will be merged in by
361 ;; derived-mode-merge-syntax-tables.
362 (make-char-table 'syntax-table nil)
363 ,(format "Syntax table for %s." mode)))
364 (put (derived-mode-syntax-table-name mode) 'derived-mode-unmerged t))
365
366 (if (boundp (derived-mode-abbrev-table-name mode))
367 t
368 (eval `(defvar ,(derived-mode-abbrev-table-name mode)
369 (progn
370 (define-abbrev-table (derived-mode-abbrev-table-name mode) nil)
371 (make-abbrev-table))
372 ,(format "Abbrev table for %s." mode)))))
373 \f
374 ;; Utility functions for running a derived mode.
375
376 (defun derived-mode-set-keymap (mode)
377 "Set the keymap of the new MODE, maybe merging with the parent."
378 (let* ((map-name (derived-mode-map-name mode))
379 (new-map (eval map-name))
380 (old-map (current-local-map)))
381 (and old-map
382 (get map-name 'derived-mode-unmerged)
383 (derived-mode-merge-keymaps old-map new-map))
384 (put map-name 'derived-mode-unmerged nil)
385 (use-local-map new-map)))
386
387 (defun derived-mode-set-syntax-table (mode)
388 "Set the syntax table of the new MODE, maybe merging with the parent."
389 (let* ((table-name (derived-mode-syntax-table-name mode))
390 (old-table (syntax-table))
391 (new-table (eval table-name)))
392 (if (get table-name 'derived-mode-unmerged)
393 (derived-mode-merge-syntax-tables old-table new-table))
394 (put table-name 'derived-mode-unmerged nil)
395 (set-syntax-table new-table)))
396
397 (defun derived-mode-set-abbrev-table (mode)
398 "Set the abbrev table for MODE if it exists.
399 Always merge its parent into it, since the merge is non-destructive."
400 (let* ((table-name (derived-mode-abbrev-table-name mode))
401 (old-table local-abbrev-table)
402 (new-table (eval table-name)))
403 (derived-mode-merge-abbrev-tables old-table new-table)
404 (setq local-abbrev-table new-table)))
405
406 (defun derived-mode-run-hooks (mode)
407 "Run the mode hook for MODE."
408 (let ((hooks-name (derived-mode-hook-name mode)))
409 (if (boundp hooks-name)
410 (run-hooks hooks-name))))
411
412 ;; Functions to merge maps and tables.
413
414 (defun derived-mode-merge-keymaps (old new)
415 "Merge an OLD keymap into a NEW one.
416 The old keymap is set to be the last cdr of the new one, so that there will
417 be automatic inheritance."
418 ;; ?? Can this just use `set-keymap-parent'?
419 (let ((tail new))
420 ;; Scan the NEW map for prefix keys.
421 (while (consp tail)
422 (and (consp (car tail))
423 (let* ((key (vector (car (car tail))))
424 (subnew (lookup-key new key))
425 (subold (lookup-key old key)))
426 ;; If KEY is a prefix key in both OLD and NEW, merge them.
427 (and (keymapp subnew) (keymapp subold)
428 (derived-mode-merge-keymaps subold subnew))))
429 (and (vectorp (car tail))
430 ;; Search a vector of ASCII char bindings for prefix keys.
431 (let ((i (1- (length (car tail)))))
432 (while (>= i 0)
433 (let* ((key (vector i))
434 (subnew (lookup-key new key))
435 (subold (lookup-key old key)))
436 ;; If KEY is a prefix key in both OLD and NEW, merge them.
437 (and (keymapp subnew) (keymapp subold)
438 (derived-mode-merge-keymaps subold subnew)))
439 (setq i (1- i)))))
440 (setq tail (cdr tail))))
441 (setcdr (nthcdr (1- (length new)) new) old))
442
443 (defun derived-mode-merge-syntax-tables (old new)
444 "Merge an OLD syntax table into a NEW one.
445 Where the new table already has an entry, nothing is copied from the old one."
446 (set-char-table-parent new old))
447
448 ;; Merge an old abbrev table into a new one.
449 ;; This function requires internal knowledge of how abbrev tables work,
450 ;; presuming that they are obarrays with the abbrev as the symbol, the expansion
451 ;; as the value of the symbol, and the hook as the function definition.
452 (defun derived-mode-merge-abbrev-tables (old new)
453 (if old
454 (mapatoms
455 (lambda (symbol)
456 (or (intern-soft (symbol-name symbol) new)
457 (define-abbrev new (symbol-name symbol)
458 (symbol-value symbol) (symbol-function symbol))))
459 old)))
460
461 (provide 'derived)
462
463 ;;; derived.el ends here