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