]> code.delx.au - gnu-emacs/blob - lisp/emacs-lisp/lisp-mode.el
Update copyright notices for 2013.
[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 (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-documentation (nth 3 form))
851 ;; Setting `customized-face' to the new spec after calling
852 ;; the form, but preserving the old saved spec in `saved-face',
853 ;; imitates the situation when the new face spec is set
854 ;; temporarily for the current session in the customize
855 ;; buffer, thus allowing `face-user-default-spec' to use the
856 ;; new customized spec instead of the saved spec.
857 ;; Resetting `saved-face' temporarily to nil is needed to let
858 ;; `defface' change the spec, regardless of a saved spec.
859 (prog1 `(prog1 ,form
860 (put ,(nth 1 form) 'saved-face
861 ',(get face-symbol 'saved-face))
862 (put ,(nth 1 form) 'customized-face
863 ,(nth 2 form)))
864 (put face-symbol 'saved-face nil))))
865 ((eq (car form) 'progn)
866 (cons 'progn (mapcar 'eval-defun-1 (cdr form))))
867 (t form)))
868
869 (defun eval-defun-2 ()
870 "Evaluate defun that point is in or before.
871 The value is displayed in the minibuffer.
872 If the current defun is actually a call to `defvar',
873 then reset the variable using the initial value expression
874 even if the variable already has some other value.
875 \(Normally `defvar' does not change the variable's value
876 if it already has a value.\)
877
878 With argument, insert value in current buffer after the defun.
879 Return the result of evaluation."
880 ;; FIXME: the print-length/level bindings should only be applied while
881 ;; printing, not while evaluating.
882 (let ((debug-on-error eval-expression-debug-on-error)
883 (print-length eval-expression-print-length)
884 (print-level eval-expression-print-level))
885 (save-excursion
886 ;; Arrange for eval-region to "read" the (possibly) altered form.
887 ;; eval-region handles recording which file defines a function or
888 ;; variable. Re-written using `apply' to avoid capturing
889 ;; variables like `end'.
890 (apply
891 #'eval-region
892 (let ((standard-output t)
893 beg end form)
894 ;; Read the form from the buffer, and record where it ends.
895 (save-excursion
896 (end-of-defun)
897 (beginning-of-defun)
898 (setq beg (point))
899 (setq form (read (current-buffer)))
900 (setq end (point)))
901 ;; Alter the form if necessary.
902 (setq form (eval-sexp-add-defvars (eval-defun-1 (macroexpand form))))
903 (list beg end standard-output
904 `(lambda (ignore)
905 ;; Skipping to the end of the specified region
906 ;; will make eval-region return.
907 (goto-char ,end)
908 ',form))))))
909 ;; The result of evaluation has been put onto VALUES. So return it.
910 (car values))
911
912 (defun eval-defun (edebug-it)
913 "Evaluate the top-level form containing point, or after point.
914
915 If the current defun is actually a call to `defvar' or `defcustom',
916 evaluating it this way resets the variable using its initial value
917 expression even if the variable already has some other value.
918 \(Normally `defvar' and `defcustom' do not alter the value if there
919 already is one.) In an analogous way, evaluating a `defface'
920 overrides any customizations of the face, so that it becomes
921 defined exactly as the `defface' expression says.
922
923 If `eval-expression-debug-on-error' is non-nil, which is the default,
924 this command arranges for all errors to enter the debugger.
925
926 With a prefix argument, instrument the code for Edebug.
927
928 If acting on a `defun' for FUNCTION, and the function was
929 instrumented, `Edebug: FUNCTION' is printed in the minibuffer. If not
930 instrumented, just FUNCTION is printed.
931
932 If not acting on a `defun', the result of evaluation is displayed in
933 the minibuffer. This display is controlled by the variables
934 `eval-expression-print-length' and `eval-expression-print-level',
935 which see."
936 (interactive "P")
937 (cond (edebug-it
938 (require 'edebug)
939 (eval-defun (not edebug-all-defs)))
940 (t
941 (if (null eval-expression-debug-on-error)
942 (eval-defun-2)
943 (let ((old-value (make-symbol "t")) new-value value)
944 (let ((debug-on-error old-value))
945 (setq value (eval-defun-2))
946 (setq new-value debug-on-error))
947 (unless (eq old-value new-value)
948 (setq debug-on-error new-value))
949 value)))))
950
951 ;; May still be used by some external Lisp-mode variant.
952 (define-obsolete-function-alias 'lisp-comment-indent
953 'comment-indent-default "22.1")
954 (define-obsolete-function-alias 'lisp-mode-auto-fill 'do-auto-fill "23.1")
955
956 (defcustom lisp-indent-offset nil
957 "If non-nil, indent second line of expressions that many more columns."
958 :group 'lisp
959 :type '(choice (const nil) integer))
960 (put 'lisp-indent-offset 'safe-local-variable
961 (lambda (x) (or (null x) (integerp x))))
962
963 (defcustom lisp-indent-function 'lisp-indent-function
964 "A function to be called by `calculate-lisp-indent'.
965 It indents the arguments of a Lisp function call. This function
966 should accept two arguments: the indent-point, and the
967 `parse-partial-sexp' state at that position. One option for this
968 function is `common-lisp-indent-function'."
969 :type 'function
970 :group 'lisp)
971
972 (defun lisp-indent-line (&optional whole-exp)
973 "Indent current line as Lisp code.
974 With argument, indent any additional lines of the same expression
975 rigidly along with this one."
976 (interactive "P")
977 (let ((indent (calculate-lisp-indent)) shift-amt end
978 (pos (- (point-max) (point)))
979 (beg (progn (beginning-of-line) (point))))
980 (skip-chars-forward " \t")
981 (if (or (null indent) (looking-at "\\s<\\s<\\s<"))
982 ;; Don't alter indentation of a ;;; comment line
983 ;; or a line that starts in a string.
984 ;; FIXME: inconsistency: comment-indent moves ;;; to column 0.
985 (goto-char (- (point-max) pos))
986 (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
987 ;; Single-semicolon comment lines should be indented
988 ;; as comment lines, not as code.
989 (progn (indent-for-comment) (forward-char -1))
990 (if (listp indent) (setq indent (car indent)))
991 (setq shift-amt (- indent (current-column)))
992 (if (zerop shift-amt)
993 nil
994 (delete-region beg (point))
995 (indent-to indent)))
996 ;; If initial point was within line's indentation,
997 ;; position after the indentation. Else stay at same point in text.
998 (if (> (- (point-max) pos) (point))
999 (goto-char (- (point-max) pos))))))
1000
1001 (defvar calculate-lisp-indent-last-sexp)
1002
1003 (defun calculate-lisp-indent (&optional parse-start)
1004 "Return appropriate indentation for current line as Lisp code.
1005 In usual case returns an integer: the column to indent to.
1006 If the value is nil, that means don't change the indentation
1007 because the line starts inside a string.
1008
1009 The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
1010 This means that following lines at the same level of indentation
1011 should not necessarily be indented the same as this line.
1012 Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
1013 is the buffer position of the start of the containing expression."
1014 (save-excursion
1015 (beginning-of-line)
1016 (let ((indent-point (point))
1017 state paren-depth
1018 ;; setting this to a number inhibits calling hook
1019 (desired-indent nil)
1020 (retry t)
1021 calculate-lisp-indent-last-sexp containing-sexp)
1022 (if parse-start
1023 (goto-char parse-start)
1024 (beginning-of-defun))
1025 ;; Find outermost containing sexp
1026 (while (< (point) indent-point)
1027 (setq state (parse-partial-sexp (point) indent-point 0)))
1028 ;; Find innermost containing sexp
1029 (while (and retry
1030 state
1031 (> (setq paren-depth (elt state 0)) 0))
1032 (setq retry nil)
1033 (setq calculate-lisp-indent-last-sexp (elt state 2))
1034 (setq containing-sexp (elt state 1))
1035 ;; Position following last unclosed open.
1036 (goto-char (1+ containing-sexp))
1037 ;; Is there a complete sexp since then?
1038 (if (and calculate-lisp-indent-last-sexp
1039 (> calculate-lisp-indent-last-sexp (point)))
1040 ;; Yes, but is there a containing sexp after that?
1041 (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
1042 indent-point 0)))
1043 (if (setq retry (car (cdr peek))) (setq state peek)))))
1044 (if retry
1045 nil
1046 ;; Innermost containing sexp found
1047 (goto-char (1+ containing-sexp))
1048 (if (not calculate-lisp-indent-last-sexp)
1049 ;; indent-point immediately follows open paren.
1050 ;; Don't call hook.
1051 (setq desired-indent (current-column))
1052 ;; Find the start of first element of containing sexp.
1053 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1054 (cond ((looking-at "\\s(")
1055 ;; First element of containing sexp is a list.
1056 ;; Indent under that list.
1057 )
1058 ((> (save-excursion (forward-line 1) (point))
1059 calculate-lisp-indent-last-sexp)
1060 ;; This is the first line to start within the containing sexp.
1061 ;; It's almost certainly a function call.
1062 (if (= (point) calculate-lisp-indent-last-sexp)
1063 ;; Containing sexp has nothing before this line
1064 ;; except the first element. Indent under that element.
1065 nil
1066 ;; Skip the first element, find start of second (the first
1067 ;; argument of the function call) and indent under.
1068 (progn (forward-sexp 1)
1069 (parse-partial-sexp (point)
1070 calculate-lisp-indent-last-sexp
1071 0 t)))
1072 (backward-prefix-chars))
1073 (t
1074 ;; Indent beneath first sexp on same line as
1075 ;; `calculate-lisp-indent-last-sexp'. Again, it's
1076 ;; almost certainly a function call.
1077 (goto-char calculate-lisp-indent-last-sexp)
1078 (beginning-of-line)
1079 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
1080 0 t)
1081 (backward-prefix-chars)))))
1082 ;; Point is at the point to indent under unless we are inside a string.
1083 ;; Call indentation hook except when overridden by lisp-indent-offset
1084 ;; or if the desired indentation has already been computed.
1085 (let ((normal-indent (current-column)))
1086 (cond ((elt state 3)
1087 ;; Inside a string, don't change indentation.
1088 nil)
1089 ((and (integerp lisp-indent-offset) containing-sexp)
1090 ;; Indent by constant offset
1091 (goto-char containing-sexp)
1092 (+ (current-column) lisp-indent-offset))
1093 ;; in this case calculate-lisp-indent-last-sexp is not nil
1094 (calculate-lisp-indent-last-sexp
1095 (or
1096 ;; try to align the parameters of a known function
1097 (and lisp-indent-function
1098 (not retry)
1099 (funcall lisp-indent-function indent-point state))
1100 ;; If the function has no special alignment
1101 ;; or it does not apply to this argument,
1102 ;; try to align a constant-symbol under the last
1103 ;; preceding constant symbol, if there is such one of
1104 ;; the last 2 preceding symbols, in the previous
1105 ;; uncommented line.
1106 (and (save-excursion
1107 (goto-char indent-point)
1108 (skip-chars-forward " \t")
1109 (looking-at ":"))
1110 ;; The last sexp may not be at the indentation
1111 ;; where it begins, so find that one, instead.
1112 (save-excursion
1113 (goto-char calculate-lisp-indent-last-sexp)
1114 ;; Handle prefix characters and whitespace
1115 ;; following an open paren. (Bug#1012)
1116 (backward-prefix-chars)
1117 (while (and (not (looking-back "^[ \t]*\\|([ \t]+"))
1118 (or (not containing-sexp)
1119 (< (1+ containing-sexp) (point))))
1120 (forward-sexp -1)
1121 (backward-prefix-chars))
1122 (setq calculate-lisp-indent-last-sexp (point)))
1123 (> calculate-lisp-indent-last-sexp
1124 (save-excursion
1125 (goto-char (1+ containing-sexp))
1126 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1127 (point)))
1128 (let ((parse-sexp-ignore-comments t)
1129 indent)
1130 (goto-char calculate-lisp-indent-last-sexp)
1131 (or (and (looking-at ":")
1132 (setq indent (current-column)))
1133 (and (< (line-beginning-position)
1134 (prog2 (backward-sexp) (point)))
1135 (looking-at ":")
1136 (setq indent (current-column))))
1137 indent))
1138 ;; another symbols or constants not preceded by a constant
1139 ;; as defined above.
1140 normal-indent))
1141 ;; in this case calculate-lisp-indent-last-sexp is nil
1142 (desired-indent)
1143 (t
1144 normal-indent))))))
1145
1146 (defun lisp-indent-function (indent-point state)
1147 "This function is the normal value of the variable `lisp-indent-function'.
1148 The function `calculate-lisp-indent' calls this to determine
1149 if the arguments of a Lisp function call should be indented specially.
1150
1151 INDENT-POINT is the position where the user typed TAB, or equivalent.
1152 Point is located at the point to indent under (for default indentation);
1153 STATE is the `parse-partial-sexp' state for that position.
1154
1155 If the current line is in a call to a Lisp function that has a non-nil
1156 property `lisp-indent-function' (or the deprecated `lisp-indent-hook'),
1157 it specifies how to indent. The property value can be:
1158
1159 * `defun', meaning indent `defun'-style
1160 \(this is also the case if there is no property and the function
1161 has a name that begins with \"def\", and three or more arguments);
1162
1163 * an integer N, meaning indent the first N arguments specially
1164 (like ordinary function arguments), and then indent any further
1165 arguments like a body;
1166
1167 * a function to call that returns the indentation (or nil).
1168 `lisp-indent-function' calls this function with the same two arguments
1169 that it itself received.
1170
1171 This function returns either the indentation to use, or nil if the
1172 Lisp function does not specify a special indentation."
1173 (let ((normal-indent (current-column)))
1174 (goto-char (1+ (elt state 1)))
1175 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1176 (if (and (elt state 2)
1177 (not (looking-at "\\sw\\|\\s_")))
1178 ;; car of form doesn't seem to be a symbol
1179 (progn
1180 (if (not (> (save-excursion (forward-line 1) (point))
1181 calculate-lisp-indent-last-sexp))
1182 (progn (goto-char calculate-lisp-indent-last-sexp)
1183 (beginning-of-line)
1184 (parse-partial-sexp (point)
1185 calculate-lisp-indent-last-sexp 0 t)))
1186 ;; Indent under the list or under the first sexp on the same
1187 ;; line as calculate-lisp-indent-last-sexp. Note that first
1188 ;; thing on that line has to be complete sexp since we are
1189 ;; inside the innermost containing sexp.
1190 (backward-prefix-chars)
1191 (current-column))
1192 (let ((function (buffer-substring (point)
1193 (progn (forward-sexp 1) (point))))
1194 method)
1195 (setq method (or (function-get (intern-soft function)
1196 'lisp-indent-function)
1197 (get (intern-soft function) 'lisp-indent-hook)))
1198 (cond ((or (eq method 'defun)
1199 (and (null method)
1200 (> (length function) 3)
1201 (string-match "\\`def" function)))
1202 (lisp-indent-defform state indent-point))
1203 ((integerp method)
1204 (lisp-indent-specform method state
1205 indent-point normal-indent))
1206 (method
1207 (funcall method indent-point state)))))))
1208
1209 (defcustom lisp-body-indent 2
1210 "Number of columns to indent the second line of a `(def...)' form."
1211 :group 'lisp
1212 :type 'integer)
1213 (put 'lisp-body-indent 'safe-local-variable 'integerp)
1214
1215 (defun lisp-indent-specform (count state indent-point normal-indent)
1216 (let ((containing-form-start (elt state 1))
1217 (i count)
1218 body-indent containing-form-column)
1219 ;; Move to the start of containing form, calculate indentation
1220 ;; to use for non-distinguished forms (> count), and move past the
1221 ;; function symbol. lisp-indent-function guarantees that there is at
1222 ;; least one word or symbol character following open paren of containing
1223 ;; form.
1224 (goto-char containing-form-start)
1225 (setq containing-form-column (current-column))
1226 (setq body-indent (+ lisp-body-indent containing-form-column))
1227 (forward-char 1)
1228 (forward-sexp 1)
1229 ;; Now find the start of the last form.
1230 (parse-partial-sexp (point) indent-point 1 t)
1231 (while (and (< (point) indent-point)
1232 (condition-case ()
1233 (progn
1234 (setq count (1- count))
1235 (forward-sexp 1)
1236 (parse-partial-sexp (point) indent-point 1 t))
1237 (error nil))))
1238 ;; Point is sitting on first character of last (or count) sexp.
1239 (if (> count 0)
1240 ;; A distinguished form. If it is the first or second form use double
1241 ;; lisp-body-indent, else normal indent. With lisp-body-indent bound
1242 ;; to 2 (the default), this just happens to work the same with if as
1243 ;; the older code, but it makes unwind-protect, condition-case,
1244 ;; with-output-to-temp-buffer, et. al. much more tasteful. The older,
1245 ;; less hacked, behavior can be obtained by replacing below with
1246 ;; (list normal-indent containing-form-start).
1247 (if (<= (- i count) 1)
1248 (list (+ containing-form-column (* 2 lisp-body-indent))
1249 containing-form-start)
1250 (list normal-indent containing-form-start))
1251 ;; A non-distinguished form. Use body-indent if there are no
1252 ;; distinguished forms and this is the first undistinguished form,
1253 ;; or if this is the first undistinguished form and the preceding
1254 ;; distinguished form has indentation at least as great as body-indent.
1255 (if (or (and (= i 0) (= count 0))
1256 (and (= count 0) (<= body-indent normal-indent)))
1257 body-indent
1258 normal-indent))))
1259
1260 (defun lisp-indent-defform (state indent-point)
1261 (goto-char (car (cdr state)))
1262 (forward-line 1)
1263 (if (> (point) (car (cdr (cdr state))))
1264 (progn
1265 (goto-char (car (cdr state)))
1266 (+ lisp-body-indent (current-column)))))
1267
1268
1269 ;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
1270 ;; like defun if the first form is placed on the next line, otherwise
1271 ;; it is indented like any other form (i.e. forms line up under first).
1272
1273 (put 'autoload 'lisp-indent-function 'defun)
1274 (put 'progn 'lisp-indent-function 0)
1275 (put 'prog1 'lisp-indent-function 1)
1276 (put 'prog2 'lisp-indent-function 2)
1277 (put 'save-excursion 'lisp-indent-function 0)
1278 (put 'save-restriction 'lisp-indent-function 0)
1279 (put 'save-current-buffer 'lisp-indent-function 0)
1280 (put 'let 'lisp-indent-function 1)
1281 (put 'let* 'lisp-indent-function 1)
1282 (put 'while 'lisp-indent-function 1)
1283 (put 'if 'lisp-indent-function 2)
1284 (put 'catch 'lisp-indent-function 1)
1285 (put 'condition-case 'lisp-indent-function 2)
1286 (put 'unwind-protect 'lisp-indent-function 1)
1287 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
1288
1289 (defun indent-sexp (&optional endpos)
1290 "Indent each line of the list starting just after point.
1291 If optional arg ENDPOS is given, indent each line, stopping when
1292 ENDPOS is encountered."
1293 (interactive)
1294 (let ((indent-stack (list nil))
1295 (next-depth 0)
1296 ;; If ENDPOS is non-nil, use nil as STARTING-POINT
1297 ;; so that calculate-lisp-indent will find the beginning of
1298 ;; the defun we are in.
1299 ;; If ENDPOS is nil, it is safe not to scan before point
1300 ;; since every line we indent is more deeply nested than point is.
1301 (starting-point (if endpos nil (point)))
1302 (last-point (point))
1303 last-depth bol outer-loop-done inner-loop-done state this-indent)
1304 (or endpos
1305 ;; Get error now if we don't have a complete sexp after point.
1306 (save-excursion (forward-sexp 1)))
1307 (save-excursion
1308 (setq outer-loop-done nil)
1309 (while (if endpos (< (point) endpos)
1310 (not outer-loop-done))
1311 (setq last-depth next-depth
1312 inner-loop-done nil)
1313 ;; Parse this line so we can learn the state
1314 ;; to indent the next line.
1315 ;; This inner loop goes through only once
1316 ;; unless a line ends inside a string.
1317 (while (and (not inner-loop-done)
1318 (not (setq outer-loop-done (eobp))))
1319 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
1320 nil nil state))
1321 (setq next-depth (car state))
1322 ;; If the line contains a comment other than the sort
1323 ;; that is indented like code,
1324 ;; indent it now with indent-for-comment.
1325 ;; Comments indented like code are right already.
1326 ;; In any case clear the in-comment flag in the state
1327 ;; because parse-partial-sexp never sees the newlines.
1328 (if (car (nthcdr 4 state))
1329 (progn (indent-for-comment)
1330 (end-of-line)
1331 (setcar (nthcdr 4 state) nil)))
1332 ;; If this line ends inside a string,
1333 ;; go straight to next line, remaining within the inner loop,
1334 ;; and turn off the \-flag.
1335 (if (car (nthcdr 3 state))
1336 (progn
1337 (forward-line 1)
1338 (setcar (nthcdr 5 state) nil))
1339 (setq inner-loop-done t)))
1340 (and endpos
1341 (<= next-depth 0)
1342 (progn
1343 (setq indent-stack (nconc indent-stack
1344 (make-list (- next-depth) nil))
1345 last-depth (- last-depth next-depth)
1346 next-depth 0)))
1347 (forward-line 1)
1348 ;; Decide whether to exit.
1349 (if endpos
1350 ;; If we have already reached the specified end,
1351 ;; give up and do not reindent this line.
1352 (if (<= endpos (point))
1353 (setq outer-loop-done t))
1354 ;; If no specified end, we are done if we have finished one sexp.
1355 (if (<= next-depth 0)
1356 (setq outer-loop-done t)))
1357 (unless outer-loop-done
1358 (while (> last-depth next-depth)
1359 (setq indent-stack (cdr indent-stack)
1360 last-depth (1- last-depth)))
1361 (while (< last-depth next-depth)
1362 (setq indent-stack (cons nil indent-stack)
1363 last-depth (1+ last-depth)))
1364 ;; Now indent the next line according
1365 ;; to what we learned from parsing the previous one.
1366 (setq bol (point))
1367 (skip-chars-forward " \t")
1368 ;; But not if the line is blank, or just a comment
1369 ;; (except for double-semi comments; indent them as usual).
1370 (if (or (eobp) (looking-at "\\s<\\|\n"))
1371 nil
1372 (if (and (car indent-stack)
1373 (>= (car indent-stack) 0))
1374 (setq this-indent (car indent-stack))
1375 (let ((val (calculate-lisp-indent
1376 (if (car indent-stack) (- (car indent-stack))
1377 starting-point))))
1378 (if (null val)
1379 (setq this-indent val)
1380 (if (integerp val)
1381 (setcar indent-stack
1382 (setq this-indent val))
1383 (setcar indent-stack (- (car (cdr val))))
1384 (setq this-indent (car val))))))
1385 (if (and this-indent (/= (current-column) this-indent))
1386 (progn (delete-region bol (point))
1387 (indent-to this-indent)))))
1388 (or outer-loop-done
1389 (setq outer-loop-done (= (point) last-point))
1390 (setq last-point (point)))))))
1391
1392 (defun indent-pp-sexp (&optional arg)
1393 "Indent each line of the list starting just after point, or prettyprint it.
1394 A prefix argument specifies pretty-printing."
1395 (interactive "P")
1396 (if arg
1397 (save-excursion
1398 (save-restriction
1399 (narrow-to-region (point) (progn (forward-sexp 1) (point)))
1400 (pp-buffer)
1401 (goto-char (point-max))
1402 (if (eq (char-before) ?\n)
1403 (delete-char -1)))))
1404 (indent-sexp))
1405
1406 ;;;; Lisp paragraph filling commands.
1407
1408 (defcustom emacs-lisp-docstring-fill-column 65
1409 "Value of `fill-column' to use when filling a docstring.
1410 Any non-integer value means do not use a different value of
1411 `fill-column' when filling docstrings."
1412 :type '(choice (integer)
1413 (const :tag "Use the current `fill-column'" t))
1414 :group 'lisp)
1415
1416 (defun lisp-fill-paragraph (&optional justify)
1417 "Like \\[fill-paragraph], but handle Emacs Lisp comments and docstrings.
1418 If any of the current line is a comment, fill the comment or the
1419 paragraph of it that point is in, preserving the comment's indentation
1420 and initial semicolons."
1421 (interactive "P")
1422 (or (fill-comment-paragraph justify)
1423 ;; Since fill-comment-paragraph returned nil, that means we're not in
1424 ;; a comment: Point is on a program line; we are interested
1425 ;; particularly in docstring lines.
1426 ;;
1427 ;; We bind `paragraph-start' and `paragraph-separate' temporarily. They
1428 ;; are buffer-local, but we avoid changing them so that they can be set
1429 ;; to make `forward-paragraph' and friends do something the user wants.
1430 ;;
1431 ;; `paragraph-start': The `(' in the character alternative and the
1432 ;; left-singlequote plus `(' sequence after the \\| alternative prevent
1433 ;; sexps and backquoted sexps that follow a docstring from being filled
1434 ;; with the docstring. This setting has the consequence of inhibiting
1435 ;; filling many program lines that are not docstrings, which is sensible,
1436 ;; because the user probably asked to fill program lines by accident, or
1437 ;; expecting indentation (perhaps we should try to do indenting in that
1438 ;; case). The `;' and `:' stop the paragraph being filled at following
1439 ;; comment lines and at keywords (e.g., in `defcustom'). Left parens are
1440 ;; escaped to keep font-locking, filling, & paren matching in the source
1441 ;; file happy.
1442 ;;
1443 ;; `paragraph-separate': A clever regexp distinguishes the first line of
1444 ;; a docstring and identifies it as a paragraph separator, so that it
1445 ;; won't be filled. (Since the first line of documentation stands alone
1446 ;; in some contexts, filling should not alter the contents the author has
1447 ;; chosen.) Only the first line of a docstring begins with whitespace
1448 ;; and a quotation mark and ends with a period or (rarely) a comma.
1449 ;;
1450 ;; The `fill-column' is temporarily bound to
1451 ;; `emacs-lisp-docstring-fill-column' if that value is an integer.
1452 (let ((paragraph-start (concat paragraph-start
1453 "\\|\\s-*\\([(;:\"]\\|`(\\|#'(\\)"))
1454 (paragraph-separate
1455 (concat paragraph-separate "\\|\\s-*\".*[,\\.]$"))
1456 (fill-column (if (and (integerp emacs-lisp-docstring-fill-column)
1457 (derived-mode-p 'emacs-lisp-mode))
1458 emacs-lisp-docstring-fill-column
1459 fill-column)))
1460 (fill-paragraph justify))
1461 ;; Never return nil.
1462 t))
1463
1464 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
1465 "Indent all lines of code, starting in the region, sideways by ARG columns.
1466 Does not affect lines starting inside comments or strings, assuming that
1467 the start of the region is not inside them.
1468
1469 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1470 The last is a regexp which, if matched at the beginning of a line,
1471 means don't indent that line."
1472 (interactive "r\np")
1473 (let (state)
1474 (save-excursion
1475 (goto-char end)
1476 (setq end (point-marker))
1477 (goto-char start)
1478 (or (bolp)
1479 (setq state (parse-partial-sexp (point)
1480 (progn
1481 (forward-line 1) (point))
1482 nil nil state)))
1483 (while (< (point) end)
1484 (or (car (nthcdr 3 state))
1485 (and nochange-regexp
1486 (looking-at nochange-regexp))
1487 ;; If line does not start in string, indent it
1488 (let ((indent (current-indentation)))
1489 (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1490 (or (eolp)
1491 (indent-to (max 0 (+ indent arg)) 0))))
1492 (setq state (parse-partial-sexp (point)
1493 (progn
1494 (forward-line 1) (point))
1495 nil nil state))))))
1496
1497 (provide 'lisp-mode)
1498
1499 ;;; lisp-mode.el ends here