]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/lisp-mode.el
* mh-e.texi (VERSION, EDITION, UPDATED, UPDATE-MONTH): Update for
[gnu-emacs] / lisp / emacs-lisp / lisp-mode.el
1 ;;; lisp-mode.el --- Lisp mode, and its idiosyncratic commands
2
3 ;; Copyright (C) 1985-1986, 1999-2013 Free Software Foundation, Inc.
4
5 ;; Maintainer: FSF
6 ;; Keywords: lisp, languages
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; The base major mode for editing Lisp code (used also for Emacs Lisp).
27 ;; This mode is documented in the Emacs manual.
28
29 ;;; Code:
30
31 (defvar font-lock-comment-face)
32 (defvar font-lock-doc-face)
33 (defvar font-lock-keywords-case-fold-search)
34 (defvar font-lock-string-face)
35
36 (defvar lisp-mode-abbrev-table nil)
37 (define-abbrev-table 'lisp-mode-abbrev-table ()
38 "Abbrev table for Lisp mode.")
39
40 (defvar emacs-lisp-mode-abbrev-table nil)
41 (define-abbrev-table 'emacs-lisp-mode-abbrev-table ()
42 "Abbrev table for Emacs Lisp mode.
43 It has `lisp-mode-abbrev-table' as its parent."
44 :parents (list lisp-mode-abbrev-table))
45
46 (defvar emacs-lisp-mode-syntax-table
47 (let ((table (make-syntax-table))
48 (i 0))
49 (while (< i ?0)
50 (modify-syntax-entry i "_ " table)
51 (setq i (1+ i)))
52 (setq i (1+ ?9))
53 (while (< i ?A)
54 (modify-syntax-entry i "_ " table)
55 (setq i (1+ i)))
56 (setq i (1+ ?Z))
57 (while (< i ?a)
58 (modify-syntax-entry i "_ " table)
59 (setq i (1+ i)))
60 (setq i (1+ ?z))
61 (while (< i 128)
62 (modify-syntax-entry i "_ " table)
63 (setq i (1+ i)))
64 (modify-syntax-entry ?\s " " table)
65 ;; Non-break space acts as whitespace.
66 (modify-syntax-entry ?\x8a0 " " table)
67 (modify-syntax-entry ?\t " " table)
68 (modify-syntax-entry ?\f " " table)
69 (modify-syntax-entry ?\n "> " table)
70 ;; This is probably obsolete since nowadays such features use overlays.
71 ;; ;; Give CR the same syntax as newline, for selective-display.
72 ;; (modify-syntax-entry ?\^m "> " table)
73 (modify-syntax-entry ?\; "< " table)
74 (modify-syntax-entry ?` "' " table)
75 (modify-syntax-entry ?' "' " table)
76 (modify-syntax-entry ?, "' " table)
77 (modify-syntax-entry ?@ "' " table)
78 ;; Used to be singlequote; changed for flonums.
79 (modify-syntax-entry ?. "_ " table)
80 (modify-syntax-entry ?# "' " table)
81 (modify-syntax-entry ?\" "\" " table)
82 (modify-syntax-entry ?\\ "\\ " table)
83 (modify-syntax-entry ?\( "() " table)
84 (modify-syntax-entry ?\) ")( " table)
85 (modify-syntax-entry ?\[ "(] " table)
86 (modify-syntax-entry ?\] ")[ " table)
87 table)
88 "Syntax table used in `emacs-lisp-mode'.")
89
90 (defvar lisp-mode-syntax-table
91 (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
92 (modify-syntax-entry ?\[ "_ " table)
93 (modify-syntax-entry ?\] "_ " table)
94 (modify-syntax-entry ?# "' 14" table)
95 (modify-syntax-entry ?| "\" 23bn" table)
96 table)
97 "Syntax table used in `lisp-mode'.")
98
99 (defvar lisp-imenu-generic-expression
100 (list
101 (list nil
102 (purecopy (concat "^\\s-*("
103 (eval-when-compile
104 (regexp-opt
105 '("defun" "defun*" "defsubst" "defmacro"
106 "defadvice" "define-skeleton"
107 "define-minor-mode" "define-global-minor-mode"
108 "define-globalized-minor-mode"
109 "define-derived-mode" "define-generic-mode"
110 "define-compiler-macro" "define-modify-macro"
111 "defsetf" "define-setf-expander"
112 "define-method-combination"
113 "defgeneric" "defmethod") t))
114 "\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"))
115 2)
116 (list (purecopy "Variables")
117 (purecopy (concat "^\\s-*("
118 (eval-when-compile
119 (regexp-opt
120 '("defconst" "defconstant" "defcustom"
121 "defparameter" "define-symbol-macro") t))
122 "\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"))
123 2)
124 ;; For `defvar', we ignore (defvar FOO) constructs.
125 (list (purecopy "Variables")
126 (purecopy (concat "^\\s-*(defvar\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"
127 "[[:space:]\n]+[^)]"))
128 1)
129 (list (purecopy "Types")
130 (purecopy (concat "^\\s-*("
131 (eval-when-compile
132 (regexp-opt
133 '("defgroup" "deftheme" "deftype" "defstruct"
134 "defclass" "define-condition" "define-widget"
135 "defface" "defpackage") t))
136 "\\s-+'?\\(\\(\\sw\\|\\s_\\)+\\)"))
137 2))
138
139 "Imenu generic expression for Lisp mode. See `imenu-generic-expression'.")
140
141 ;; This was originally in autoload.el and is still used there.
142 (put 'autoload 'doc-string-elt 3)
143 (put 'defmethod 'doc-string-elt 3)
144 (put 'defvar 'doc-string-elt 3)
145 (put 'defconst 'doc-string-elt 3)
146 (put 'defalias 'doc-string-elt 3)
147 (put 'defvaralias 'doc-string-elt 3)
148 (put 'define-category 'doc-string-elt 2)
149
150 (defvar lisp-doc-string-elt-property 'doc-string-elt
151 "The symbol property that holds the docstring position info.")
152
153 (defun lisp-font-lock-syntactic-face-function (state)
154 (if (nth 3 state)
155 ;; This might be a (doc)string or a |...| symbol.
156 (let ((startpos (nth 8 state)))
157 (if (eq (char-after startpos) ?|)
158 ;; This is not a string, but a |...| symbol.
159 nil
160 (let* ((listbeg (nth 1 state))
161 (firstsym (and listbeg
162 (save-excursion
163 (goto-char listbeg)
164 (and (looking-at "([ \t\n]*\\(\\(\\sw\\|\\s_\\)+\\)")
165 (match-string 1)))))
166 (docelt (and firstsym
167 (function-get (intern-soft firstsym)
168 lisp-doc-string-elt-property))))
169 (if (and docelt
170 ;; It's a string in a form that can have a docstring.
171 ;; Check whether it's in docstring position.
172 (save-excursion
173 (when (functionp docelt)
174 (goto-char (match-end 1))
175 (setq docelt (funcall docelt)))
176 (goto-char listbeg)
177 (forward-char 1)
178 (condition-case nil
179 (while (and (> docelt 0) (< (point) startpos)
180 (progn (forward-sexp 1) t))
181 (setq docelt (1- docelt)))
182 (error nil))
183 (and (zerop docelt) (<= (point) startpos)
184 (progn (forward-comment (point-max)) t)
185 (= (point) (nth 8 state)))))
186 font-lock-doc-face
187 font-lock-string-face))))
188 font-lock-comment-face))
189
190 (defun lisp-mode-variables (&optional lisp-syntax keywords-case-insensitive)
191 "Common initialization routine for lisp modes.
192 The LISP-SYNTAX argument is used by code in inf-lisp.el and is
193 \(uselessly) passed from pp.el, chistory.el, gnus-kill.el and
194 score-mode.el. KEYWORDS-CASE-INSENSITIVE non-nil means that for
195 font-lock keywords will not be case sensitive."
196 (when lisp-syntax
197 (set-syntax-table lisp-mode-syntax-table))
198 (setq-local paragraph-ignore-fill-prefix t)
199 (setq-local fill-paragraph-function 'lisp-fill-paragraph)
200 ;; Adaptive fill mode gets the fill wrong for a one-line paragraph made of
201 ;; a single docstring. Let's fix it here.
202 (setq-local adaptive-fill-function
203 (lambda () (if (looking-at "\\s-+\"[^\n\"]+\"\\s-*$") "")))
204 ;; Adaptive fill mode gets in the way of auto-fill,
205 ;; and should make no difference for explicit fill
206 ;; because lisp-fill-paragraph should do the job.
207 ;; I believe that newcomment's auto-fill code properly deals with it -stef
208 ;;(set (make-local-variable 'adaptive-fill-mode) nil)
209 (setq-local indent-line-function 'lisp-indent-line)
210 (setq-local outline-regexp ";;;\\(;* [^ \t\n]\\|###autoload\\)\\|(")
211 (setq-local outline-level 'lisp-outline-level)
212 (setq-local add-log-current-defun-function #'lisp-current-defun-name)
213 (setq-local comment-start ";")
214 ;; Look within the line for a ; following an even number of backslashes
215 ;; after either a non-backslash or the line beginning.
216 (setq-local comment-start-skip "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\);+ *")
217 ;; Font lock mode uses this only when it KNOWS a comment is starting.
218 (setq-local font-lock-comment-start-skip ";+ *")
219 (setq-local comment-add 1) ;default to `;;' in comment-region
220 (setq-local comment-column 40)
221 ;; Don't get confused by `;' in doc strings when paragraph-filling.
222 (setq-local comment-use-global-state t)
223 (setq-local imenu-generic-expression lisp-imenu-generic-expression)
224 (setq-local multibyte-syntax-as-symbol t)
225 (setq-local syntax-begin-function 'beginning-of-defun)
226 (setq font-lock-defaults
227 `((lisp-font-lock-keywords
228 lisp-font-lock-keywords-1 lisp-font-lock-keywords-2)
229 nil ,keywords-case-insensitive nil nil
230 (font-lock-mark-block-function . mark-defun)
231 (font-lock-syntactic-face-function
232 . lisp-font-lock-syntactic-face-function))))
233
234 (defun lisp-outline-level ()
235 "Lisp mode `outline-level' function."
236 (let ((len (- (match-end 0) (match-beginning 0))))
237 (if (looking-at "(\\|;;;###autoload")
238 1000
239 len)))
240
241 (defun lisp-current-defun-name ()
242 "Return the name of the defun at point, or nil."
243 (save-excursion
244 (let ((location (point)))
245 ;; If we are now precisely at the beginning of a defun, make sure
246 ;; beginning-of-defun finds that one rather than the previous one.
247 (or (eobp) (forward-char 1))
248 (beginning-of-defun)
249 ;; Make sure we are really inside the defun found, not after it.
250 (when (and (looking-at "\\s(")
251 (progn (end-of-defun)
252 (< location (point)))
253 (progn (forward-sexp -1)
254 (>= location (point))))
255 (if (looking-at "\\s(")
256 (forward-char 1))
257 ;; Skip the defining construct name, typically "defun" or
258 ;; "defvar".
259 (forward-sexp 1)
260 ;; The second element is usually a symbol being defined. If it
261 ;; is not, use the first symbol in it.
262 (skip-chars-forward " \t\n'(")
263 (buffer-substring-no-properties (point)
264 (progn (forward-sexp 1)
265 (point)))))))
266
267 (defvar lisp-mode-shared-map
268 (let ((map (make-sparse-keymap)))
269 (define-key map "\e\C-q" 'indent-sexp)
270 (define-key map "\177" 'backward-delete-char-untabify)
271 ;; This gets in the way when viewing a Lisp file in view-mode. As
272 ;; long as [backspace] is mapped into DEL via the
273 ;; function-key-map, this should remain disabled!!
274 ;;;(define-key map [backspace] 'backward-delete-char-untabify)
275 map)
276 "Keymap for commands shared by all sorts of Lisp modes.")
277
278 (defvar emacs-lisp-mode-map
279 (let ((map (make-sparse-keymap "Emacs-Lisp"))
280 (menu-map (make-sparse-keymap "Emacs-Lisp"))
281 (lint-map (make-sparse-keymap))
282 (prof-map (make-sparse-keymap))
283 (tracing-map (make-sparse-keymap)))
284 (set-keymap-parent map lisp-mode-shared-map)
285 (define-key map "\e\t" 'completion-at-point)
286 (define-key map "\e\C-x" 'eval-defun)
287 (define-key map "\e\C-q" 'indent-pp-sexp)
288 (bindings--define-key map [menu-bar emacs-lisp]
289 (cons "Emacs-Lisp" menu-map))
290 (bindings--define-key menu-map [eldoc]
291 '(menu-item "Auto-Display Documentation Strings" eldoc-mode
292 :button (:toggle . (bound-and-true-p eldoc-mode))
293 :help "Display the documentation string for the item under cursor"))
294 (bindings--define-key menu-map [checkdoc]
295 '(menu-item "Check Documentation Strings" checkdoc
296 :help "Check documentation strings for style requirements"))
297 (bindings--define-key menu-map [re-builder]
298 '(menu-item "Construct Regexp" re-builder
299 :help "Construct a regexp interactively"))
300 (bindings--define-key menu-map [tracing] (cons "Tracing" tracing-map))
301 (bindings--define-key tracing-map [tr-a]
302 '(menu-item "Untrace All" untrace-all
303 :help "Untrace all currently traced functions"))
304 (bindings--define-key tracing-map [tr-uf]
305 '(menu-item "Untrace Function..." untrace-function
306 :help "Untrace function, and possibly activate all remaining advice"))
307 (bindings--define-key tracing-map [tr-sep] menu-bar-separator)
308 (bindings--define-key tracing-map [tr-q]
309 '(menu-item "Trace Function Quietly..." trace-function-background
310 :help "Trace the function with trace output going quietly to a buffer"))
311 (bindings--define-key tracing-map [tr-f]
312 '(menu-item "Trace Function..." trace-function
313 :help "Trace the function given as an argument"))
314 (bindings--define-key menu-map [profiling] (cons "Profiling" prof-map))
315 (bindings--define-key prof-map [prof-restall]
316 '(menu-item "Remove Instrumentation for All Functions" elp-restore-all
317 :help "Restore the original definitions of all functions being profiled"))
318 (bindings--define-key prof-map [prof-restfunc]
319 '(menu-item "Remove Instrumentation for Function..." elp-restore-function
320 :help "Restore an instrumented function to its original definition"))
321
322 (bindings--define-key prof-map [sep-rem] menu-bar-separator)
323 (bindings--define-key prof-map [prof-resall]
324 '(menu-item "Reset Counters for All Functions" elp-reset-all
325 :help "Reset the profiling information for all functions being profiled"))
326 (bindings--define-key prof-map [prof-resfunc]
327 '(menu-item "Reset Counters for Function..." elp-reset-function
328 :help "Reset the profiling information for a function"))
329 (bindings--define-key prof-map [prof-res]
330 '(menu-item "Show Profiling Results" elp-results
331 :help "Display current profiling results"))
332 (bindings--define-key prof-map [prof-pack]
333 '(menu-item "Instrument Package..." elp-instrument-package
334 :help "Instrument for profiling all function that start with a prefix"))
335 (bindings--define-key prof-map [prof-func]
336 '(menu-item "Instrument Function..." elp-instrument-function
337 :help "Instrument a function for profiling"))
338 ;; Maybe this should be in a separate submenu from the ELP stuff?
339 (bindings--define-key prof-map [sep-natprof] menu-bar-separator)
340 (bindings--define-key prof-map [prof-natprof-stop]
341 '(menu-item "Stop Native Profiler" profiler-stop
342 :help "Stop recording profiling information"
343 :enable (and (featurep 'profiler)
344 (profiler-running-p))))
345 (bindings--define-key prof-map [prof-natprof-report]
346 '(menu-item "Show Profiler Report" profiler-report
347 :help "Show the current profiler report"
348 :enable (and (featurep 'profiler)
349 (profiler-running-p))))
350 (bindings--define-key prof-map [prof-natprof-start]
351 '(menu-item "Start Native Profiler..." profiler-start
352 :help "Start recording profiling information"))
353
354 (bindings--define-key menu-map [lint] (cons "Linting" lint-map))
355 (bindings--define-key lint-map [lint-di]
356 '(menu-item "Lint Directory..." elint-directory
357 :help "Lint a directory"))
358 (bindings--define-key lint-map [lint-f]
359 '(menu-item "Lint File..." elint-file
360 :help "Lint a file"))
361 (bindings--define-key lint-map [lint-b]
362 '(menu-item "Lint Buffer" elint-current-buffer
363 :help "Lint the current buffer"))
364 (bindings--define-key lint-map [lint-d]
365 '(menu-item "Lint Defun" elint-defun
366 :help "Lint the function at point"))
367 (bindings--define-key menu-map [edebug-defun]
368 '(menu-item "Instrument Function for Debugging" edebug-defun
369 :help "Evaluate the top level form point is in, stepping through with Edebug"
370 :keys "C-u C-M-x"))
371 (bindings--define-key menu-map [separator-byte] menu-bar-separator)
372 (bindings--define-key menu-map [disas]
373 '(menu-item "Disassemble Byte Compiled Object..." disassemble
374 :help "Print disassembled code for OBJECT in a buffer"))
375 (bindings--define-key menu-map [byte-recompile]
376 '(menu-item "Byte-recompile Directory..." byte-recompile-directory
377 :help "Recompile every `.el' file in DIRECTORY that needs recompilation"))
378 (bindings--define-key menu-map [emacs-byte-compile-and-load]
379 '(menu-item "Byte-compile and Load" emacs-lisp-byte-compile-and-load
380 :help "Byte-compile the current file (if it has changed), then load compiled code"))
381 (bindings--define-key menu-map [byte-compile]
382 '(menu-item "Byte-compile This File" emacs-lisp-byte-compile
383 :help "Byte compile the file containing the current buffer"))
384 (bindings--define-key menu-map [separator-eval] menu-bar-separator)
385 (bindings--define-key menu-map [ielm]
386 '(menu-item "Interactive Expression Evaluation" ielm
387 :help "Interactively evaluate Emacs Lisp expressions"))
388 (bindings--define-key menu-map [eval-buffer]
389 '(menu-item "Evaluate Buffer" eval-buffer
390 :help "Execute the current buffer as Lisp code"))
391 (bindings--define-key menu-map [eval-region]
392 '(menu-item "Evaluate Region" eval-region
393 :help "Execute the region as Lisp code"
394 :enable mark-active))
395 (bindings--define-key menu-map [eval-sexp]
396 '(menu-item "Evaluate Last S-expression" eval-last-sexp
397 :help "Evaluate sexp before point; print value in minibuffer"))
398 (bindings--define-key menu-map [separator-format] menu-bar-separator)
399 (bindings--define-key menu-map [comment-region]
400 '(menu-item "Comment Out Region" comment-region
401 :help "Comment or uncomment each line in the region"
402 :enable mark-active))
403 (bindings--define-key menu-map [indent-region]
404 '(menu-item "Indent Region" indent-region
405 :help "Indent each nonblank line in the region"
406 :enable mark-active))
407 (bindings--define-key menu-map [indent-line]
408 '(menu-item "Indent Line" lisp-indent-line))
409 map)
410 "Keymap for Emacs Lisp mode.
411 All commands in `lisp-mode-shared-map' are inherited by this map.")
412
413 (defun emacs-lisp-byte-compile ()
414 "Byte compile the file containing the current buffer."
415 (interactive)
416 (if buffer-file-name
417 (byte-compile-file buffer-file-name)
418 (error "The buffer must be saved in a file first")))
419
420 (defun emacs-lisp-byte-compile-and-load ()
421 "Byte-compile the current file (if it has changed), then load compiled code."
422 (interactive)
423 (or buffer-file-name
424 (error "The buffer must be saved in a file first"))
425 (require 'bytecomp)
426 ;; Recompile if file or buffer has changed since last compilation.
427 (if (and (buffer-modified-p)
428 (y-or-n-p (format "Save buffer %s first? " (buffer-name))))
429 (save-buffer))
430 (byte-recompile-file buffer-file-name nil 0 t))
431
432 (defcustom emacs-lisp-mode-hook nil
433 "Hook run when entering Emacs Lisp mode."
434 :options '(turn-on-eldoc-mode imenu-add-menubar-index checkdoc-minor-mode)
435 :type 'hook
436 :group 'lisp)
437
438 (defcustom lisp-mode-hook nil
439 "Hook run when entering Lisp mode."
440 :options '(imenu-add-menubar-index)
441 :type 'hook
442 :group 'lisp)
443
444 (defcustom lisp-interaction-mode-hook nil
445 "Hook run when entering Lisp Interaction mode."
446 :options '(turn-on-eldoc-mode)
447 :type 'hook
448 :group 'lisp)
449
450 (define-derived-mode emacs-lisp-mode prog-mode "Emacs-Lisp"
451 "Major mode for editing Lisp code to run in Emacs.
452 Commands:
453 Delete converts tabs to spaces as it moves back.
454 Blank lines separate paragraphs. Semicolons start comments.
455
456 \\{emacs-lisp-mode-map}
457 Entry to this mode calls the value of `emacs-lisp-mode-hook'
458 if that value is non-nil."
459 :group 'lisp
460 (lisp-mode-variables)
461 (setq imenu-case-fold-search nil)
462 (add-hook 'completion-at-point-functions
463 'lisp-completion-at-point nil 'local))
464
465 ;;; Emacs Lisp Byte-Code mode
466
467 (eval-and-compile
468 (defconst emacs-list-byte-code-comment-re
469 (concat "\\(#\\)@\\([0-9]+\\) "
470 ;; Make sure it's a docstring and not a lazy-loaded byte-code.
471 "\\(?:[^(]\\|([^\"]\\)")))
472
473 (defun emacs-lisp-byte-code-comment (end &optional _point)
474 "Try to syntactically mark the #@NNN ....^_ docstrings in byte-code files."
475 (let ((ppss (syntax-ppss)))
476 (when (and (nth 4 ppss)
477 (eq (char-after (nth 8 ppss)) ?#))
478 (let* ((n (save-excursion
479 (goto-char (nth 8 ppss))
480 (when (looking-at emacs-list-byte-code-comment-re)
481 (string-to-number (match-string 2)))))
482 ;; `maxdiff' tries to make sure the loop below terminates.
483 (maxdiff n))
484 (when n
485 (let* ((bchar (match-end 2))
486 (b (position-bytes bchar)))
487 (goto-char (+ b n))
488 (while (let ((diff (- (position-bytes (point)) b n)))
489 (unless (zerop diff)
490 (when (> diff maxdiff) (setq diff maxdiff))
491 (forward-char (- diff))
492 (setq maxdiff (if (> diff 0) diff
493 (max (1- maxdiff) 1)))
494 t))))
495 (if (<= (point) end)
496 (put-text-property (1- (point)) (point)
497 'syntax-table
498 (string-to-syntax "> b"))
499 (goto-char end)))))))
500
501 (defun emacs-lisp-byte-code-syntax-propertize (start end)
502 (emacs-lisp-byte-code-comment end (point))
503 (funcall
504 (syntax-propertize-rules
505 (emacs-list-byte-code-comment-re
506 (1 (prog1 "< b" (emacs-lisp-byte-code-comment end (point))))))
507 start end))
508
509 (add-to-list 'auto-mode-alist '("\\.elc\\'" . emacs-lisp-byte-code-mode))
510 (define-derived-mode emacs-lisp-byte-code-mode emacs-lisp-mode
511 "Elisp-Byte-Code"
512 "Major mode for *.elc files."
513 ;; TODO: Add way to disassemble byte-code under point.
514 (setq-local open-paren-in-column-0-is-defun-start nil)
515 (setq-local syntax-propertize-function
516 #'emacs-lisp-byte-code-syntax-propertize))
517
518 ;;; Generic Lisp mode.
519
520 (defvar lisp-mode-map
521 (let ((map (make-sparse-keymap))
522 (menu-map (make-sparse-keymap "Lisp")))
523 (set-keymap-parent map lisp-mode-shared-map)
524 (define-key map "\e\C-x" 'lisp-eval-defun)
525 (define-key map "\C-c\C-z" 'run-lisp)
526 (bindings--define-key map [menu-bar lisp] (cons "Lisp" menu-map))
527 (bindings--define-key menu-map [run-lisp]
528 '(menu-item "Run inferior Lisp" run-lisp
529 :help "Run an inferior Lisp process, input and output via buffer `*inferior-lisp*'"))
530 (bindings--define-key menu-map [ev-def]
531 '(menu-item "Eval defun" lisp-eval-defun
532 :help "Send the current defun to the Lisp process made by M-x run-lisp"))
533 (bindings--define-key menu-map [ind-sexp]
534 '(menu-item "Indent sexp" indent-sexp
535 :help "Indent each line of the list starting just after point"))
536 map)
537 "Keymap for ordinary Lisp mode.
538 All commands in `lisp-mode-shared-map' are inherited by this map.")
539
540 (define-derived-mode lisp-mode prog-mode "Lisp"
541 "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
542 Commands:
543 Delete converts tabs to spaces as it moves back.
544 Blank lines separate paragraphs. Semicolons start comments.
545
546 \\{lisp-mode-map}
547 Note that `run-lisp' may be used either to start an inferior Lisp job
548 or to switch back to an existing one.
549
550 Entry to this mode calls the value of `lisp-mode-hook'
551 if that value is non-nil."
552 (lisp-mode-variables nil t)
553 (setq-local find-tag-default-function 'lisp-find-tag-default)
554 (setq-local comment-start-skip
555 "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
556 (setq imenu-case-fold-search t))
557
558 (defun lisp-find-tag-default ()
559 (let ((default (find-tag-default)))
560 (when (stringp default)
561 (if (string-match ":+" default)
562 (substring default (match-end 0))
563 default))))
564
565 ;; Used in old LispM code.
566 (defalias 'common-lisp-mode 'lisp-mode)
567
568 ;; This will do unless inf-lisp.el is loaded.
569 (defun lisp-eval-defun (&optional and-go)
570 "Send the current defun to the Lisp process made by \\[run-lisp]."
571 (interactive)
572 (error "Process lisp does not exist"))
573
574 (defvar lisp-interaction-mode-map
575 (let ((map (make-sparse-keymap))
576 (menu-map (make-sparse-keymap "Lisp-Interaction")))
577 (set-keymap-parent map lisp-mode-shared-map)
578 (define-key map "\e\C-x" 'eval-defun)
579 (define-key map "\e\C-q" 'indent-pp-sexp)
580 (define-key map "\e\t" 'completion-at-point)
581 (define-key map "\n" 'eval-print-last-sexp)
582 (bindings--define-key map [menu-bar lisp-interaction]
583 (cons "Lisp-Interaction" menu-map))
584 (bindings--define-key menu-map [eval-defun]
585 '(menu-item "Evaluate Defun" eval-defun
586 :help "Evaluate the top-level form containing point, or after point"))
587 (bindings--define-key menu-map [eval-print-last-sexp]
588 '(menu-item "Evaluate and Print" eval-print-last-sexp
589 :help "Evaluate sexp before point; print value into current buffer"))
590 (bindings--define-key menu-map [edebug-defun-lisp-interaction]
591 '(menu-item "Instrument Function for Debugging" edebug-defun
592 :help "Evaluate the top level form point is in, stepping through with Edebug"
593 :keys "C-u C-M-x"))
594 (bindings--define-key menu-map [indent-pp-sexp]
595 '(menu-item "Indent or Pretty-Print" indent-pp-sexp
596 :help "Indent each line of the list starting just after point, or prettyprint it"))
597 (bindings--define-key menu-map [complete-symbol]
598 '(menu-item "Complete Lisp Symbol" completion-at-point
599 :help "Perform completion on Lisp symbol preceding point"))
600 map)
601 "Keymap for Lisp Interaction mode.
602 All commands in `lisp-mode-shared-map' are inherited by this map.")
603
604 (define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
605 "Major mode for typing and evaluating Lisp forms.
606 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
607 before point, and prints its value into the buffer, advancing point.
608 Note that printing is controlled by `eval-expression-print-length'
609 and `eval-expression-print-level'.
610
611 Commands:
612 Delete converts tabs to spaces as it moves back.
613 Paragraphs are separated only by blank lines.
614 Semicolons start comments.
615
616 \\{lisp-interaction-mode-map}
617 Entry to this mode calls the value of `lisp-interaction-mode-hook'
618 if that value is non-nil."
619 :abbrev-table nil)
620
621 (defun eval-print-last-sexp ()
622 "Evaluate sexp before point; print value into current buffer.
623
624 If `eval-expression-debug-on-error' is non-nil, which is the default,
625 this command arranges for all errors to enter the debugger.
626
627 Note that printing the result is controlled by the variables
628 `eval-expression-print-length' and `eval-expression-print-level',
629 which see."
630 (interactive)
631 (let ((standard-output (current-buffer)))
632 (terpri)
633 (eval-last-sexp t)
634 (terpri)))
635
636
637 (defun last-sexp-setup-props (beg end value alt1 alt2)
638 "Set up text properties for the output of `eval-last-sexp-1'.
639 BEG and END are the start and end of the output in current-buffer.
640 VALUE is the Lisp value printed, ALT1 and ALT2 are strings for the
641 alternative printed representations that can be displayed."
642 (let ((map (make-sparse-keymap)))
643 (define-key map "\C-m" 'last-sexp-toggle-display)
644 (define-key map [down-mouse-2] 'mouse-set-point)
645 (define-key map [mouse-2] 'last-sexp-toggle-display)
646 (add-text-properties
647 beg end
648 `(printed-value (,value ,alt1 ,alt2)
649 mouse-face highlight
650 keymap ,map
651 help-echo "RET, mouse-2: toggle abbreviated display"
652 rear-nonsticky (mouse-face keymap help-echo
653 printed-value)))))
654
655
656 (defun last-sexp-toggle-display (&optional arg)
657 "Toggle between abbreviated and unabbreviated printed representations."
658 (interactive "P")
659 (save-restriction
660 (widen)
661 (let ((value (get-text-property (point) 'printed-value)))
662 (when value
663 (let ((beg (or (previous-single-property-change (min (point-max) (1+ (point)))
664 'printed-value)
665 (point)))
666 (end (or (next-single-char-property-change (point) 'printed-value) (point)))
667 (standard-output (current-buffer))
668 (point (point)))
669 (delete-region beg end)
670 (insert (nth 1 value))
671 (or (= beg point)
672 (setq point (1- (point))))
673 (last-sexp-setup-props beg (point)
674 (nth 0 value)
675 (nth 2 value)
676 (nth 1 value))
677 (goto-char (min (point-max) point)))))))
678
679 (defun prin1-char (char)
680 "Return a string representing CHAR as a character rather than as an integer.
681 If CHAR is not a character, return nil."
682 (and (integerp char)
683 (eventp char)
684 (let ((c (event-basic-type char))
685 (mods (event-modifiers char))
686 string)
687 ;; Prevent ?A from turning into ?\S-a.
688 (if (and (memq 'shift mods)
689 (zerop (logand char ?\S-\^@))
690 (not (let ((case-fold-search nil))
691 (char-equal c (upcase c)))))
692 (setq c (upcase c) mods nil))
693 ;; What string are we considering using?
694 (condition-case nil
695 (setq string
696 (concat
697 "?"
698 (mapconcat
699 (lambda (modif)
700 (cond ((eq modif 'super) "\\s-")
701 (t (string ?\\ (upcase (aref (symbol-name modif) 0)) ?-))))
702 mods "")
703 (cond
704 ((memq c '(?\; ?\( ?\) ?\{ ?\} ?\[ ?\] ?\" ?\' ?\\)) (string ?\\ c))
705 ((eq c 127) "\\C-?")
706 (t
707 (string c)))))
708 (error nil))
709 ;; Verify the string reads a CHAR, not to some other character.
710 ;; If it doesn't, return nil instead.
711 (and string
712 (= (car (read-from-string string)) char)
713 string))))
714
715
716 (defun preceding-sexp ()
717 "Return sexp before the point."
718 (let ((opoint (point))
719 ignore-quotes
720 expr)
721 (save-excursion
722 (with-syntax-table emacs-lisp-mode-syntax-table
723 ;; If this sexp appears to be enclosed in `...'
724 ;; then ignore the surrounding quotes.
725 (setq ignore-quotes
726 (or (eq (following-char) ?\')
727 (eq (preceding-char) ?\')))
728 (forward-sexp -1)
729 ;; If we were after `?\e' (or similar case),
730 ;; use the whole thing, not just the `e'.
731 (when (eq (preceding-char) ?\\)
732 (forward-char -1)
733 (when (eq (preceding-char) ??)
734 (forward-char -1)))
735
736 ;; Skip over hash table read syntax.
737 (and (> (point) (1+ (point-min)))
738 (looking-back "#s" (- (point) 2))
739 (forward-char -2))
740
741 ;; Skip over `#N='s.
742 (when (eq (preceding-char) ?=)
743 (let (labeled-p)
744 (save-excursion
745 (skip-chars-backward "0-9#=")
746 (setq labeled-p (looking-at "\\(#[0-9]+=\\)+")))
747 (when labeled-p
748 (forward-sexp -1))))
749
750 (save-restriction
751 ;; vladimir@cs.ualberta.ca 30-Jul-1997: skip ` in
752 ;; `variable' so that the value is returned, not the
753 ;; name
754 (if (and ignore-quotes
755 (eq (following-char) ?`))
756 (forward-char))
757 (narrow-to-region (point-min) opoint)
758 (setq expr (read (current-buffer)))
759 ;; If it's an (interactive ...) form, it's more
760 ;; useful to show how an interactive call would
761 ;; use it.
762 (and (consp expr)
763 (eq (car expr) 'interactive)
764 (setq expr
765 (list 'call-interactively
766 (list 'quote
767 (list 'lambda
768 '(&rest args)
769 expr
770 'args)))))
771 expr)))))
772
773
774 (defun eval-last-sexp-1 (eval-last-sexp-arg-internal)
775 "Evaluate sexp before point; print value in minibuffer.
776 With argument, print output into current buffer."
777 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
778 ;; Setup the lexical environment if lexical-binding is enabled.
779 (eval-last-sexp-print-value
780 (eval (eval-sexp-add-defvars (preceding-sexp)) lexical-binding))))
781
782
783 (defun eval-last-sexp-print-value (value)
784 (let ((unabbreviated (let ((print-length nil) (print-level nil))
785 (prin1-to-string value)))
786 (print-length eval-expression-print-length)
787 (print-level eval-expression-print-level)
788 (beg (point))
789 end)
790 (prog1
791 (prin1 value)
792 (let ((str (eval-expression-print-format value)))
793 (if str (princ str)))
794 (setq end (point))
795 (when (and (bufferp standard-output)
796 (or (not (null print-length))
797 (not (null print-level)))
798 (not (string= unabbreviated
799 (buffer-substring-no-properties beg end))))
800 (last-sexp-setup-props beg end value
801 unabbreviated
802 (buffer-substring-no-properties beg end))
803 ))))
804
805
806 (defvar eval-last-sexp-fake-value (make-symbol "t"))
807
808 (defun eval-sexp-add-defvars (exp &optional pos)
809 "Prepend EXP with all the `defvar's that precede it in the buffer.
810 POS specifies the starting position where EXP was found and defaults to point."
811 (if (not lexical-binding)
812 exp
813 (save-excursion
814 (unless pos (setq pos (point)))
815 (let ((vars ()))
816 (goto-char (point-min))
817 (while (re-search-forward
818 "(def\\(?:var\\|const\\|custom\\)[ \t\n]+\\([^; '()\n\t]+\\)"
819 pos t)
820 (let ((var (intern (match-string 1))))
821 (and (not (special-variable-p var))
822 (save-excursion
823 (zerop (car (syntax-ppss (match-beginning 0)))))
824 (push var vars))))
825 `(progn ,@(mapcar (lambda (v) `(defvar ,v)) vars) ,exp)))))
826
827 (defun eval-last-sexp (eval-last-sexp-arg-internal)
828 "Evaluate sexp before point; print value in minibuffer.
829 Interactively, with prefix argument, print output into current buffer.
830 Truncates long output according to the value of the variables
831 `eval-expression-print-length' and `eval-expression-print-level'.
832
833 If `eval-expression-debug-on-error' is non-nil, which is the default,
834 this command arranges for all errors to enter the debugger."
835 (interactive "P")
836 (if (null eval-expression-debug-on-error)
837 (eval-last-sexp-1 eval-last-sexp-arg-internal)
838 (let ((value
839 (let ((debug-on-error eval-last-sexp-fake-value))
840 (cons (eval-last-sexp-1 eval-last-sexp-arg-internal)
841 debug-on-error))))
842 (unless (eq (cdr value) eval-last-sexp-fake-value)
843 (setq debug-on-error (cdr value)))
844 (car value))))
845
846 (defun eval-defun-1 (form)
847 "Treat some expressions specially.
848 Reset the `defvar' and `defcustom' variables to the initial value.
849 \(For `defcustom', use the :set function if there is one.)
850 Reinitialize the face according to the `defface' specification."
851 ;; The code in edebug-defun should be consistent with this, but not
852 ;; the same, since this gets a macroexpanded form.
853 (cond ((not (listp form))
854 form)
855 ((and (eq (car form) 'defvar)
856 (cdr-safe (cdr-safe form))
857 (boundp (cadr form)))
858 ;; Force variable to be re-set.
859 `(progn (defvar ,(nth 1 form) nil ,@(nthcdr 3 form))
860 (setq-default ,(nth 1 form) ,(nth 2 form))))
861 ;; `defcustom' is now macroexpanded to
862 ;; `custom-declare-variable' with a quoted value arg.
863 ((and (eq (car form) 'custom-declare-variable)
864 (default-boundp (eval (nth 1 form) lexical-binding)))
865 ;; Force variable to be bound, using :set function if specified.
866 (let ((setfunc (memq :set form)))
867 (when setfunc
868 (setq setfunc (car-safe (cdr-safe setfunc)))
869 (or (functionp setfunc) (setq setfunc nil)))
870 (funcall (or setfunc 'set-default)
871 (eval (nth 1 form) lexical-binding)
872 ;; The second arg is an expression that evaluates to
873 ;; an expression. The second evaluation is the one
874 ;; normally performed not by normal execution but by
875 ;; custom-initialize-set (for example), which does not
876 ;; use lexical-binding.
877 (eval (eval (nth 2 form) lexical-binding))))
878 form)
879 ;; `defface' is macroexpanded to `custom-declare-face'.
880 ((eq (car form) 'custom-declare-face)
881 ;; Reset the face.
882 (let ((face-symbol (eval (nth 1 form) lexical-binding)))
883 (setq face-new-frame-defaults
884 (assq-delete-all face-symbol face-new-frame-defaults))
885 (put face-symbol 'face-defface-spec nil)
886 (put face-symbol 'face-override-spec nil))
887 form)
888 ((eq (car form) 'progn)
889 (cons 'progn (mapcar 'eval-defun-1 (cdr form))))
890 (t form)))
891
892 (defun eval-defun-2 ()
893 "Evaluate defun that point is in or before.
894 The value is displayed in the minibuffer.
895 If the current defun is actually a call to `defvar',
896 then reset the variable using the initial value expression
897 even if the variable already has some other value.
898 \(Normally `defvar' does not change the variable's value
899 if it already has a value.\)
900
901 With argument, insert value in current buffer after the defun.
902 Return the result of evaluation."
903 ;; FIXME: the print-length/level bindings should only be applied while
904 ;; printing, not while evaluating.
905 (let ((debug-on-error eval-expression-debug-on-error)
906 (print-length eval-expression-print-length)
907 (print-level eval-expression-print-level))
908 (save-excursion
909 ;; Arrange for eval-region to "read" the (possibly) altered form.
910 ;; eval-region handles recording which file defines a function or
911 ;; variable. Re-written using `apply' to avoid capturing
912 ;; variables like `end'.
913 (apply
914 #'eval-region
915 (let ((standard-output t)
916 beg end form)
917 ;; Read the form from the buffer, and record where it ends.
918 (save-excursion
919 (end-of-defun)
920 (beginning-of-defun)
921 (setq beg (point))
922 (setq form (read (current-buffer)))
923 (setq end (point)))
924 ;; Alter the form if necessary.
925 (setq form (eval-sexp-add-defvars (eval-defun-1 (macroexpand form))))
926 (list beg end standard-output
927 `(lambda (ignore)
928 ;; Skipping to the end of the specified region
929 ;; will make eval-region return.
930 (goto-char ,end)
931 ',form))))))
932 ;; The result of evaluation has been put onto VALUES. So return it.
933 (car values))
934
935 (defun eval-defun (edebug-it)
936 "Evaluate the top-level form containing point, or after point.
937
938 If the current defun is actually a call to `defvar' or `defcustom',
939 evaluating it this way resets the variable using its initial value
940 expression (using the defcustom's :set function if there is one), even
941 if the variable already has some other value. \(Normally `defvar' and
942 `defcustom' do not alter the value if there already is one.) In an
943 analogous way, evaluating a `defface' overrides any customizations of
944 the face, so that it becomes defined exactly as the `defface' expression
945 says.
946
947 If `eval-expression-debug-on-error' is non-nil, which is the default,
948 this command arranges for all errors to enter the debugger.
949
950 With a prefix argument, instrument the code for Edebug.
951
952 If acting on a `defun' for FUNCTION, and the function was
953 instrumented, `Edebug: FUNCTION' is printed in the minibuffer. If not
954 instrumented, just FUNCTION is printed.
955
956 If not acting on a `defun', the result of evaluation is displayed in
957 the minibuffer. This display is controlled by the variables
958 `eval-expression-print-length' and `eval-expression-print-level',
959 which see."
960 (interactive "P")
961 (cond (edebug-it
962 (require 'edebug)
963 (eval-defun (not edebug-all-defs)))
964 (t
965 (if (null eval-expression-debug-on-error)
966 (eval-defun-2)
967 (let ((old-value (make-symbol "t")) new-value value)
968 (let ((debug-on-error old-value))
969 (setq value (eval-defun-2))
970 (setq new-value debug-on-error))
971 (unless (eq old-value new-value)
972 (setq debug-on-error new-value))
973 value)))))
974
975 ;; May still be used by some external Lisp-mode variant.
976 (define-obsolete-function-alias 'lisp-comment-indent
977 'comment-indent-default "22.1")
978 (define-obsolete-function-alias 'lisp-mode-auto-fill 'do-auto-fill "23.1")
979
980 (defcustom lisp-indent-offset nil
981 "If non-nil, indent second line of expressions that many more columns."
982 :group 'lisp
983 :type '(choice (const nil) integer))
984 (put 'lisp-indent-offset 'safe-local-variable
985 (lambda (x) (or (null x) (integerp x))))
986
987 (defcustom lisp-indent-function 'lisp-indent-function
988 "A function to be called by `calculate-lisp-indent'.
989 It indents the arguments of a Lisp function call. This function
990 should accept two arguments: the indent-point, and the
991 `parse-partial-sexp' state at that position. One option for this
992 function is `common-lisp-indent-function'."
993 :type 'function
994 :group 'lisp)
995
996 (defun lisp-indent-line (&optional whole-exp)
997 "Indent current line as Lisp code.
998 With argument, indent any additional lines of the same expression
999 rigidly along with this one."
1000 (interactive "P")
1001 (let ((indent (calculate-lisp-indent)) shift-amt end
1002 (pos (- (point-max) (point)))
1003 (beg (progn (beginning-of-line) (point))))
1004 (skip-chars-forward " \t")
1005 (if (or (null indent) (looking-at "\\s<\\s<\\s<"))
1006 ;; Don't alter indentation of a ;;; comment line
1007 ;; or a line that starts in a string.
1008 ;; FIXME: inconsistency: comment-indent moves ;;; to column 0.
1009 (goto-char (- (point-max) pos))
1010 (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
1011 ;; Single-semicolon comment lines should be indented
1012 ;; as comment lines, not as code.
1013 (progn (indent-for-comment) (forward-char -1))
1014 (if (listp indent) (setq indent (car indent)))
1015 (setq shift-amt (- indent (current-column)))
1016 (if (zerop shift-amt)
1017 nil
1018 (delete-region beg (point))
1019 (indent-to indent)))
1020 ;; If initial point was within line's indentation,
1021 ;; position after the indentation. Else stay at same point in text.
1022 (if (> (- (point-max) pos) (point))
1023 (goto-char (- (point-max) pos))))))
1024
1025 (defvar calculate-lisp-indent-last-sexp)
1026
1027 (defun calculate-lisp-indent (&optional parse-start)
1028 "Return appropriate indentation for current line as Lisp code.
1029 In usual case returns an integer: the column to indent to.
1030 If the value is nil, that means don't change the indentation
1031 because the line starts inside a string.
1032
1033 The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
1034 This means that following lines at the same level of indentation
1035 should not necessarily be indented the same as this line.
1036 Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
1037 is the buffer position of the start of the containing expression."
1038 (save-excursion
1039 (beginning-of-line)
1040 (let ((indent-point (point))
1041 state paren-depth
1042 ;; setting this to a number inhibits calling hook
1043 (desired-indent nil)
1044 (retry t)
1045 calculate-lisp-indent-last-sexp containing-sexp)
1046 (if parse-start
1047 (goto-char parse-start)
1048 (beginning-of-defun))
1049 ;; Find outermost containing sexp
1050 (while (< (point) indent-point)
1051 (setq state (parse-partial-sexp (point) indent-point 0)))
1052 ;; Find innermost containing sexp
1053 (while (and retry
1054 state
1055 (> (setq paren-depth (elt state 0)) 0))
1056 (setq retry nil)
1057 (setq calculate-lisp-indent-last-sexp (elt state 2))
1058 (setq containing-sexp (elt state 1))
1059 ;; Position following last unclosed open.
1060 (goto-char (1+ containing-sexp))
1061 ;; Is there a complete sexp since then?
1062 (if (and calculate-lisp-indent-last-sexp
1063 (> calculate-lisp-indent-last-sexp (point)))
1064 ;; Yes, but is there a containing sexp after that?
1065 (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
1066 indent-point 0)))
1067 (if (setq retry (car (cdr peek))) (setq state peek)))))
1068 (if retry
1069 nil
1070 ;; Innermost containing sexp found
1071 (goto-char (1+ containing-sexp))
1072 (if (not calculate-lisp-indent-last-sexp)
1073 ;; indent-point immediately follows open paren.
1074 ;; Don't call hook.
1075 (setq desired-indent (current-column))
1076 ;; Find the start of first element of containing sexp.
1077 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1078 (cond ((looking-at "\\s(")
1079 ;; First element of containing sexp is a list.
1080 ;; Indent under that list.
1081 )
1082 ((> (save-excursion (forward-line 1) (point))
1083 calculate-lisp-indent-last-sexp)
1084 ;; This is the first line to start within the containing sexp.
1085 ;; It's almost certainly a function call.
1086 (if (= (point) calculate-lisp-indent-last-sexp)
1087 ;; Containing sexp has nothing before this line
1088 ;; except the first element. Indent under that element.
1089 nil
1090 ;; Skip the first element, find start of second (the first
1091 ;; argument of the function call) and indent under.
1092 (progn (forward-sexp 1)
1093 (parse-partial-sexp (point)
1094 calculate-lisp-indent-last-sexp
1095 0 t)))
1096 (backward-prefix-chars))
1097 (t
1098 ;; Indent beneath first sexp on same line as
1099 ;; `calculate-lisp-indent-last-sexp'. Again, it's
1100 ;; almost certainly a function call.
1101 (goto-char calculate-lisp-indent-last-sexp)
1102 (beginning-of-line)
1103 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
1104 0 t)
1105 (backward-prefix-chars)))))
1106 ;; Point is at the point to indent under unless we are inside a string.
1107 ;; Call indentation hook except when overridden by lisp-indent-offset
1108 ;; or if the desired indentation has already been computed.
1109 (let ((normal-indent (current-column)))
1110 (cond ((elt state 3)
1111 ;; Inside a string, don't change indentation.
1112 nil)
1113 ((and (integerp lisp-indent-offset) containing-sexp)
1114 ;; Indent by constant offset
1115 (goto-char containing-sexp)
1116 (+ (current-column) lisp-indent-offset))
1117 ;; in this case calculate-lisp-indent-last-sexp is not nil
1118 (calculate-lisp-indent-last-sexp
1119 (or
1120 ;; try to align the parameters of a known function
1121 (and lisp-indent-function
1122 (not retry)
1123 (funcall lisp-indent-function indent-point state))
1124 ;; If the function has no special alignment
1125 ;; or it does not apply to this argument,
1126 ;; try to align a constant-symbol under the last
1127 ;; preceding constant symbol, if there is such one of
1128 ;; the last 2 preceding symbols, in the previous
1129 ;; uncommented line.
1130 (and (save-excursion
1131 (goto-char indent-point)
1132 (skip-chars-forward " \t")
1133 (looking-at ":"))
1134 ;; The last sexp may not be at the indentation
1135 ;; where it begins, so find that one, instead.
1136 (save-excursion
1137 (goto-char calculate-lisp-indent-last-sexp)
1138 ;; Handle prefix characters and whitespace
1139 ;; following an open paren. (Bug#1012)
1140 (backward-prefix-chars)
1141 (while (and (not (looking-back "^[ \t]*\\|([ \t]+"))
1142 (or (not containing-sexp)
1143 (< (1+ containing-sexp) (point))))
1144 (forward-sexp -1)
1145 (backward-prefix-chars))
1146 (setq calculate-lisp-indent-last-sexp (point)))
1147 (> calculate-lisp-indent-last-sexp
1148 (save-excursion
1149 (goto-char (1+ containing-sexp))
1150 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1151 (point)))
1152 (let ((parse-sexp-ignore-comments t)
1153 indent)
1154 (goto-char calculate-lisp-indent-last-sexp)
1155 (or (and (looking-at ":")
1156 (setq indent (current-column)))
1157 (and (< (line-beginning-position)
1158 (prog2 (backward-sexp) (point)))
1159 (looking-at ":")
1160 (setq indent (current-column))))
1161 indent))
1162 ;; another symbols or constants not preceded by a constant
1163 ;; as defined above.
1164 normal-indent))
1165 ;; in this case calculate-lisp-indent-last-sexp is nil
1166 (desired-indent)
1167 (t
1168 normal-indent))))))
1169
1170 (defun lisp-indent-function (indent-point state)
1171 "This function is the normal value of the variable `lisp-indent-function'.
1172 The function `calculate-lisp-indent' calls this to determine
1173 if the arguments of a Lisp function call should be indented specially.
1174
1175 INDENT-POINT is the position at which the line being indented begins.
1176 Point is located at the point to indent under (for default indentation);
1177 STATE is the `parse-partial-sexp' state for that position.
1178
1179 If the current line is in a call to a Lisp function that has a non-nil
1180 property `lisp-indent-function' (or the deprecated `lisp-indent-hook'),
1181 it specifies how to indent. The property value can be:
1182
1183 * `defun', meaning indent `defun'-style
1184 \(this is also the case if there is no property and the function
1185 has a name that begins with \"def\", and three or more arguments);
1186
1187 * an integer N, meaning indent the first N arguments specially
1188 (like ordinary function arguments), and then indent any further
1189 arguments like a body;
1190
1191 * a function to call that returns the indentation (or nil).
1192 `lisp-indent-function' calls this function with the same two arguments
1193 that it itself received.
1194
1195 This function returns either the indentation to use, or nil if the
1196 Lisp function does not specify a special indentation."
1197 (let ((normal-indent (current-column)))
1198 (goto-char (1+ (elt state 1)))
1199 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1200 (if (and (elt state 2)
1201 (not (looking-at "\\sw\\|\\s_")))
1202 ;; car of form doesn't seem to be a symbol
1203 (progn
1204 (if (not (> (save-excursion (forward-line 1) (point))
1205 calculate-lisp-indent-last-sexp))
1206 (progn (goto-char calculate-lisp-indent-last-sexp)
1207 (beginning-of-line)
1208 (parse-partial-sexp (point)
1209 calculate-lisp-indent-last-sexp 0 t)))
1210 ;; Indent under the list or under the first sexp on the same
1211 ;; line as calculate-lisp-indent-last-sexp. Note that first
1212 ;; thing on that line has to be complete sexp since we are
1213 ;; inside the innermost containing sexp.
1214 (backward-prefix-chars)
1215 (current-column))
1216 (let ((function (buffer-substring (point)
1217 (progn (forward-sexp 1) (point))))
1218 method)
1219 (setq method (or (function-get (intern-soft function)
1220 'lisp-indent-function)
1221 (get (intern-soft function) 'lisp-indent-hook)))
1222 (cond ((or (eq method 'defun)
1223 (and (null method)
1224 (> (length function) 3)
1225 (string-match "\\`def" function)))
1226 (lisp-indent-defform state indent-point))
1227 ((integerp method)
1228 (lisp-indent-specform method state
1229 indent-point normal-indent))
1230 (method
1231 (funcall method indent-point state)))))))
1232
1233 (defcustom lisp-body-indent 2
1234 "Number of columns to indent the second line of a `(def...)' form."
1235 :group 'lisp
1236 :type 'integer)
1237 (put 'lisp-body-indent 'safe-local-variable 'integerp)
1238
1239 (defun lisp-indent-specform (count state indent-point normal-indent)
1240 (let ((containing-form-start (elt state 1))
1241 (i count)
1242 body-indent containing-form-column)
1243 ;; Move to the start of containing form, calculate indentation
1244 ;; to use for non-distinguished forms (> count), and move past the
1245 ;; function symbol. lisp-indent-function guarantees that there is at
1246 ;; least one word or symbol character following open paren of containing
1247 ;; form.
1248 (goto-char containing-form-start)
1249 (setq containing-form-column (current-column))
1250 (setq body-indent (+ lisp-body-indent containing-form-column))
1251 (forward-char 1)
1252 (forward-sexp 1)
1253 ;; Now find the start of the last form.
1254 (parse-partial-sexp (point) indent-point 1 t)
1255 (while (and (< (point) indent-point)
1256 (condition-case ()
1257 (progn
1258 (setq count (1- count))
1259 (forward-sexp 1)
1260 (parse-partial-sexp (point) indent-point 1 t))
1261 (error nil))))
1262 ;; Point is sitting on first character of last (or count) sexp.
1263 (if (> count 0)
1264 ;; A distinguished form. If it is the first or second form use double
1265 ;; lisp-body-indent, else normal indent. With lisp-body-indent bound
1266 ;; to 2 (the default), this just happens to work the same with if as
1267 ;; the older code, but it makes unwind-protect, condition-case,
1268 ;; with-output-to-temp-buffer, et. al. much more tasteful. The older,
1269 ;; less hacked, behavior can be obtained by replacing below with
1270 ;; (list normal-indent containing-form-start).
1271 (if (<= (- i count) 1)
1272 (list (+ containing-form-column (* 2 lisp-body-indent))
1273 containing-form-start)
1274 (list normal-indent containing-form-start))
1275 ;; A non-distinguished form. Use body-indent if there are no
1276 ;; distinguished forms and this is the first undistinguished form,
1277 ;; or if this is the first undistinguished form and the preceding
1278 ;; distinguished form has indentation at least as great as body-indent.
1279 (if (or (and (= i 0) (= count 0))
1280 (and (= count 0) (<= body-indent normal-indent)))
1281 body-indent
1282 normal-indent))))
1283
1284 (defun lisp-indent-defform (state indent-point)
1285 (goto-char (car (cdr state)))
1286 (forward-line 1)
1287 (if (> (point) (car (cdr (cdr state))))
1288 (progn
1289 (goto-char (car (cdr state)))
1290 (+ lisp-body-indent (current-column)))))
1291
1292
1293 ;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
1294 ;; like defun if the first form is placed on the next line, otherwise
1295 ;; it is indented like any other form (i.e. forms line up under first).
1296
1297 (put 'autoload 'lisp-indent-function 'defun)
1298 (put 'progn 'lisp-indent-function 0)
1299 (put 'prog1 'lisp-indent-function 1)
1300 (put 'prog2 'lisp-indent-function 2)
1301 (put 'save-excursion 'lisp-indent-function 0)
1302 (put 'save-restriction 'lisp-indent-function 0)
1303 (put 'save-current-buffer 'lisp-indent-function 0)
1304 (put 'let 'lisp-indent-function 1)
1305 (put 'let* 'lisp-indent-function 1)
1306 (put 'while 'lisp-indent-function 1)
1307 (put 'if 'lisp-indent-function 2)
1308 (put 'catch 'lisp-indent-function 1)
1309 (put 'condition-case 'lisp-indent-function 2)
1310 (put 'unwind-protect 'lisp-indent-function 1)
1311 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
1312
1313 (defun indent-sexp (&optional endpos)
1314 "Indent each line of the list starting just after point.
1315 If optional arg ENDPOS is given, indent each line, stopping when
1316 ENDPOS is encountered."
1317 (interactive)
1318 (let ((indent-stack (list nil))
1319 (next-depth 0)
1320 ;; If ENDPOS is non-nil, use nil as STARTING-POINT
1321 ;; so that calculate-lisp-indent will find the beginning of
1322 ;; the defun we are in.
1323 ;; If ENDPOS is nil, it is safe not to scan before point
1324 ;; since every line we indent is more deeply nested than point is.
1325 (starting-point (if endpos nil (point)))
1326 (last-point (point))
1327 last-depth bol outer-loop-done inner-loop-done state this-indent)
1328 (or endpos
1329 ;; Get error now if we don't have a complete sexp after point.
1330 (save-excursion (forward-sexp 1)))
1331 (save-excursion
1332 (setq outer-loop-done nil)
1333 (while (if endpos (< (point) endpos)
1334 (not outer-loop-done))
1335 (setq last-depth next-depth
1336 inner-loop-done nil)
1337 ;; Parse this line so we can learn the state
1338 ;; to indent the next line.
1339 ;; This inner loop goes through only once
1340 ;; unless a line ends inside a string.
1341 (while (and (not inner-loop-done)
1342 (not (setq outer-loop-done (eobp))))
1343 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
1344 nil nil state))
1345 (setq next-depth (car state))
1346 ;; If the line contains a comment other than the sort
1347 ;; that is indented like code,
1348 ;; indent it now with indent-for-comment.
1349 ;; Comments indented like code are right already.
1350 ;; In any case clear the in-comment flag in the state
1351 ;; because parse-partial-sexp never sees the newlines.
1352 (if (car (nthcdr 4 state))
1353 (progn (indent-for-comment)
1354 (end-of-line)
1355 (setcar (nthcdr 4 state) nil)))
1356 ;; If this line ends inside a string,
1357 ;; go straight to next line, remaining within the inner loop,
1358 ;; and turn off the \-flag.
1359 (if (car (nthcdr 3 state))
1360 (progn
1361 (forward-line 1)
1362 (setcar (nthcdr 5 state) nil))
1363 (setq inner-loop-done t)))
1364 (and endpos
1365 (<= next-depth 0)
1366 (progn
1367 (setq indent-stack (nconc indent-stack
1368 (make-list (- next-depth) nil))
1369 last-depth (- last-depth next-depth)
1370 next-depth 0)))
1371 (forward-line 1)
1372 ;; Decide whether to exit.
1373 (if endpos
1374 ;; If we have already reached the specified end,
1375 ;; give up and do not reindent this line.
1376 (if (<= endpos (point))
1377 (setq outer-loop-done t))
1378 ;; If no specified end, we are done if we have finished one sexp.
1379 (if (<= next-depth 0)
1380 (setq outer-loop-done t)))
1381 (unless outer-loop-done
1382 (while (> last-depth next-depth)
1383 (setq indent-stack (cdr indent-stack)
1384 last-depth (1- last-depth)))
1385 (while (< last-depth next-depth)
1386 (setq indent-stack (cons nil indent-stack)
1387 last-depth (1+ last-depth)))
1388 ;; Now indent the next line according
1389 ;; to what we learned from parsing the previous one.
1390 (setq bol (point))
1391 (skip-chars-forward " \t")
1392 ;; But not if the line is blank, or just a comment
1393 ;; (except for double-semi comments; indent them as usual).
1394 (if (or (eobp) (looking-at "\\s<\\|\n"))
1395 nil
1396 (if (and (car indent-stack)
1397 (>= (car indent-stack) 0))
1398 (setq this-indent (car indent-stack))
1399 (let ((val (calculate-lisp-indent
1400 (if (car indent-stack) (- (car indent-stack))
1401 starting-point))))
1402 (if (null val)
1403 (setq this-indent val)
1404 (if (integerp val)
1405 (setcar indent-stack
1406 (setq this-indent val))
1407 (setcar indent-stack (- (car (cdr val))))
1408 (setq this-indent (car val))))))
1409 (if (and this-indent (/= (current-column) this-indent))
1410 (progn (delete-region bol (point))
1411 (indent-to this-indent)))))
1412 (or outer-loop-done
1413 (setq outer-loop-done (= (point) last-point))
1414 (setq last-point (point)))))))
1415
1416 (defun indent-pp-sexp (&optional arg)
1417 "Indent each line of the list starting just after point, or prettyprint it.
1418 A prefix argument specifies pretty-printing."
1419 (interactive "P")
1420 (if arg
1421 (save-excursion
1422 (save-restriction
1423 (narrow-to-region (point) (progn (forward-sexp 1) (point)))
1424 (pp-buffer)
1425 (goto-char (point-max))
1426 (if (eq (char-before) ?\n)
1427 (delete-char -1)))))
1428 (indent-sexp))
1429
1430 ;;;; Lisp paragraph filling commands.
1431
1432 (defcustom emacs-lisp-docstring-fill-column 65
1433 "Value of `fill-column' to use when filling a docstring.
1434 Any non-integer value means do not use a different value of
1435 `fill-column' when filling docstrings."
1436 :type '(choice (integer)
1437 (const :tag "Use the current `fill-column'" t))
1438 :group 'lisp)
1439
1440 (defun lisp-fill-paragraph (&optional justify)
1441 "Like \\[fill-paragraph], but handle Emacs Lisp comments and docstrings.
1442 If any of the current line is a comment, fill the comment or the
1443 paragraph of it that point is in, preserving the comment's indentation
1444 and initial semicolons."
1445 (interactive "P")
1446 (or (fill-comment-paragraph justify)
1447 ;; Since fill-comment-paragraph returned nil, that means we're not in
1448 ;; a comment: Point is on a program line; we are interested
1449 ;; particularly in docstring lines.
1450 ;;
1451 ;; We bind `paragraph-start' and `paragraph-separate' temporarily. They
1452 ;; are buffer-local, but we avoid changing them so that they can be set
1453 ;; to make `forward-paragraph' and friends do something the user wants.
1454 ;;
1455 ;; `paragraph-start': The `(' in the character alternative and the
1456 ;; left-singlequote plus `(' sequence after the \\| alternative prevent
1457 ;; sexps and backquoted sexps that follow a docstring from being filled
1458 ;; with the docstring. This setting has the consequence of inhibiting
1459 ;; filling many program lines that are not docstrings, which is sensible,
1460 ;; because the user probably asked to fill program lines by accident, or
1461 ;; expecting indentation (perhaps we should try to do indenting in that
1462 ;; case). The `;' and `:' stop the paragraph being filled at following
1463 ;; comment lines and at keywords (e.g., in `defcustom'). Left parens are
1464 ;; escaped to keep font-locking, filling, & paren matching in the source
1465 ;; file happy.
1466 ;;
1467 ;; `paragraph-separate': A clever regexp distinguishes the first line of
1468 ;; a docstring and identifies it as a paragraph separator, so that it
1469 ;; won't be filled. (Since the first line of documentation stands alone
1470 ;; in some contexts, filling should not alter the contents the author has
1471 ;; chosen.) Only the first line of a docstring begins with whitespace
1472 ;; and a quotation mark and ends with a period or (rarely) a comma.
1473 ;;
1474 ;; The `fill-column' is temporarily bound to
1475 ;; `emacs-lisp-docstring-fill-column' if that value is an integer.
1476 (let ((paragraph-start (concat paragraph-start
1477 "\\|\\s-*\\([(;:\"]\\|`(\\|#'(\\)"))
1478 (paragraph-separate
1479 (concat paragraph-separate "\\|\\s-*\".*[,\\.]$"))
1480 (fill-column (if (and (integerp emacs-lisp-docstring-fill-column)
1481 (derived-mode-p 'emacs-lisp-mode))
1482 emacs-lisp-docstring-fill-column
1483 fill-column)))
1484 (fill-paragraph justify))
1485 ;; Never return nil.
1486 t))
1487
1488 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
1489 "Indent all lines of code, starting in the region, sideways by ARG columns.
1490 Does not affect lines starting inside comments or strings, assuming that
1491 the start of the region is not inside them.
1492
1493 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1494 The last is a regexp which, if matched at the beginning of a line,
1495 means don't indent that line."
1496 (interactive "r\np")
1497 (let (state)
1498 (save-excursion
1499 (goto-char end)
1500 (setq end (point-marker))
1501 (goto-char start)
1502 (or (bolp)
1503 (setq state (parse-partial-sexp (point)
1504 (progn
1505 (forward-line 1) (point))
1506 nil nil state)))
1507 (while (< (point) end)
1508 (or (car (nthcdr 3 state))
1509 (and nochange-regexp
1510 (looking-at nochange-regexp))
1511 ;; If line does not start in string, indent it
1512 (let ((indent (current-indentation)))
1513 (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1514 (or (eolp)
1515 (indent-to (max 0 (+ indent arg)) 0))))
1516 (setq state (parse-partial-sexp (point)
1517 (progn
1518 (forward-line 1) (point))
1519 nil nil state))))))
1520
1521 (provide 'lisp-mode)
1522
1523 ;;; lisp-mode.el ends here