In Imenu, don't show defvars with no second argument.
[emacs.git] / lisp / emacs-lisp / lisp-mode.el
blob7e9dd9e6cfedc6d8cb7ad04fccc678606297c1fe
1 ;;; lisp-mode.el --- Lisp mode, and its idiosyncratic commands
3 ;; Copyright (C) 1985-1986, 1999-2012 Free Software Foundation, Inc.
5 ;; Maintainer: FSF
6 ;; Keywords: lisp, languages
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
24 ;;; Commentary:
26 ;; The base major mode for editing Lisp code (used also for Emacs Lisp).
27 ;; This mode is documented in the Emacs manual.
29 ;;; Code:
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)
36 (defvar lisp-mode-abbrev-table nil)
37 (define-abbrev-table 'lisp-mode-abbrev-table ()
38 "Abbrev table for Lisp mode.")
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))
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'.")
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'.")
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_\\)+\\)"))
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_\\)+\\)"))
124 ;; For `defvar', we ignore (defvar FOO) constructs.
125 (list (purecopy "Variables")
126 (purecopy (concat "^\\s-*(defvar\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"
127 "[[:space:]\n]+[^)]"))
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_\\)+\\)"))
139 "Imenu generic expression for Lisp mode. See `imenu-generic-expression'.")
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)
150 (defvar lisp-doc-string-elt-property 'doc-string-elt
151 "The symbol property that holds the docstring position info.")
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.
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))
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))))
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)))
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.")
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"))
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.")
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")))
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))
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)
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)
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)
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.
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))
434 (defvar lisp-mode-map
435 (let ((map (make-sparse-keymap))
436 (menu-map (make-sparse-keymap "Lisp")))
437 (set-keymap-parent map lisp-mode-shared-map)
438 (define-key map "\e\C-x" 'lisp-eval-defun)
439 (define-key map "\C-c\C-z" 'run-lisp)
440 (bindings--define-key map [menu-bar lisp] (cons "Lisp" menu-map))
441 (bindings--define-key menu-map [run-lisp]
442 '(menu-item "Run inferior Lisp" run-lisp
443 :help "Run an inferior Lisp process, input and output via buffer `*inferior-lisp*'"))
444 (bindings--define-key menu-map [ev-def]
445 '(menu-item "Eval defun" lisp-eval-defun
446 :help "Send the current defun to the Lisp process made by M-x run-lisp"))
447 (bindings--define-key menu-map [ind-sexp]
448 '(menu-item "Indent sexp" indent-sexp
449 :help "Indent each line of the list starting just after point"))
450 map)
451 "Keymap for ordinary Lisp mode.
452 All commands in `lisp-mode-shared-map' are inherited by this map.")
454 (define-derived-mode lisp-mode prog-mode "Lisp"
455 "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
456 Commands:
457 Delete converts tabs to spaces as it moves back.
458 Blank lines separate paragraphs. Semicolons start comments.
460 \\{lisp-mode-map}
461 Note that `run-lisp' may be used either to start an inferior Lisp job
462 or to switch back to an existing one.
464 Entry to this mode calls the value of `lisp-mode-hook'
465 if that value is non-nil."
466 (lisp-mode-variables nil t)
467 (set (make-local-variable 'find-tag-default-function) 'lisp-find-tag-default)
468 (make-local-variable 'comment-start-skip)
469 (setq comment-start-skip
470 "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
471 (setq imenu-case-fold-search t))
473 (defun lisp-find-tag-default ()
474 (let ((default (find-tag-default)))
475 (when (stringp default)
476 (if (string-match ":+" default)
477 (substring default (match-end 0))
478 default))))
480 ;; Used in old LispM code.
481 (defalias 'common-lisp-mode 'lisp-mode)
483 ;; This will do unless inf-lisp.el is loaded.
484 (defun lisp-eval-defun (&optional and-go)
485 "Send the current defun to the Lisp process made by \\[run-lisp]."
486 (interactive)
487 (error "Process lisp does not exist"))
489 (defvar lisp-interaction-mode-map
490 (let ((map (make-sparse-keymap))
491 (menu-map (make-sparse-keymap "Lisp-Interaction")))
492 (set-keymap-parent map lisp-mode-shared-map)
493 (define-key map "\e\C-x" 'eval-defun)
494 (define-key map "\e\C-q" 'indent-pp-sexp)
495 (define-key map "\e\t" 'completion-at-point)
496 (define-key map "\n" 'eval-print-last-sexp)
497 (bindings--define-key map [menu-bar lisp-interaction]
498 (cons "Lisp-Interaction" menu-map))
499 (bindings--define-key menu-map [eval-defun]
500 '(menu-item "Evaluate Defun" eval-defun
501 :help "Evaluate the top-level form containing point, or after point"))
502 (bindings--define-key menu-map [eval-print-last-sexp]
503 '(menu-item "Evaluate and Print" eval-print-last-sexp
504 :help "Evaluate sexp before point; print value into current buffer"))
505 (bindings--define-key menu-map [edebug-defun-lisp-interaction]
506 '(menu-item "Instrument Function for Debugging" edebug-defun
507 :help "Evaluate the top level form point is in, stepping through with Edebug"
508 :keys "C-u C-M-x"))
509 (bindings--define-key menu-map [indent-pp-sexp]
510 '(menu-item "Indent or Pretty-Print" indent-pp-sexp
511 :help "Indent each line of the list starting just after point, or prettyprint it"))
512 (bindings--define-key menu-map [complete-symbol]
513 '(menu-item "Complete Lisp Symbol" completion-at-point
514 :help "Perform completion on Lisp symbol preceding point"))
515 map)
516 "Keymap for Lisp Interaction mode.
517 All commands in `lisp-mode-shared-map' are inherited by this map.")
519 (define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
520 "Major mode for typing and evaluating Lisp forms.
521 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
522 before point, and prints its value into the buffer, advancing point.
523 Note that printing is controlled by `eval-expression-print-length'
524 and `eval-expression-print-level'.
526 Commands:
527 Delete converts tabs to spaces as it moves back.
528 Paragraphs are separated only by blank lines.
529 Semicolons start comments.
531 \\{lisp-interaction-mode-map}
532 Entry to this mode calls the value of `lisp-interaction-mode-hook'
533 if that value is non-nil."
534 :abbrev-table nil)
536 (defun eval-print-last-sexp ()
537 "Evaluate sexp before point; print value into current buffer.
539 If `eval-expression-debug-on-error' is non-nil, which is the default,
540 this command arranges for all errors to enter the debugger.
542 Note that printing the result is controlled by the variables
543 `eval-expression-print-length' and `eval-expression-print-level',
544 which see."
545 (interactive)
546 (let ((standard-output (current-buffer)))
547 (terpri)
548 (eval-last-sexp t)
549 (terpri)))
552 (defun last-sexp-setup-props (beg end value alt1 alt2)
553 "Set up text properties for the output of `eval-last-sexp-1'.
554 BEG and END are the start and end of the output in current-buffer.
555 VALUE is the Lisp value printed, ALT1 and ALT2 are strings for the
556 alternative printed representations that can be displayed."
557 (let ((map (make-sparse-keymap)))
558 (define-key map "\C-m" 'last-sexp-toggle-display)
559 (define-key map [down-mouse-2] 'mouse-set-point)
560 (define-key map [mouse-2] 'last-sexp-toggle-display)
561 (add-text-properties
562 beg end
563 `(printed-value (,value ,alt1 ,alt2)
564 mouse-face highlight
565 keymap ,map
566 help-echo "RET, mouse-2: toggle abbreviated display"
567 rear-nonsticky (mouse-face keymap help-echo
568 printed-value)))))
571 (defun last-sexp-toggle-display (&optional arg)
572 "Toggle between abbreviated and unabbreviated printed representations."
573 (interactive "P")
574 (save-restriction
575 (widen)
576 (let ((value (get-text-property (point) 'printed-value)))
577 (when value
578 (let ((beg (or (previous-single-property-change (min (point-max) (1+ (point)))
579 'printed-value)
580 (point)))
581 (end (or (next-single-char-property-change (point) 'printed-value) (point)))
582 (standard-output (current-buffer))
583 (point (point)))
584 (delete-region beg end)
585 (insert (nth 1 value))
586 (or (= beg point)
587 (setq point (1- (point))))
588 (last-sexp-setup-props beg (point)
589 (nth 0 value)
590 (nth 2 value)
591 (nth 1 value))
592 (goto-char (min (point-max) point)))))))
594 (defun prin1-char (char)
595 "Return a string representing CHAR as a character rather than as an integer.
596 If CHAR is not a character, return nil."
597 (and (integerp char)
598 (eventp char)
599 (let ((c (event-basic-type char))
600 (mods (event-modifiers char))
601 string)
602 ;; Prevent ?A from turning into ?\S-a.
603 (if (and (memq 'shift mods)
604 (zerop (logand char ?\S-\^@))
605 (not (let ((case-fold-search nil))
606 (char-equal c (upcase c)))))
607 (setq c (upcase c) mods nil))
608 ;; What string are we considering using?
609 (condition-case nil
610 (setq string
611 (concat
613 (mapconcat
614 (lambda (modif)
615 (cond ((eq modif 'super) "\\s-")
616 (t (string ?\\ (upcase (aref (symbol-name modif) 0)) ?-))))
617 mods "")
618 (cond
619 ((memq c '(?\; ?\( ?\) ?\{ ?\} ?\[ ?\] ?\" ?\' ?\\)) (string ?\\ c))
620 ((eq c 127) "\\C-?")
622 (string c)))))
623 (error nil))
624 ;; Verify the string reads a CHAR, not to some other character.
625 ;; If it doesn't, return nil instead.
626 (and string
627 (= (car (read-from-string string)) char)
628 string))))
631 (defun preceding-sexp ()
632 "Return sexp before the point."
633 (let ((opoint (point))
634 ignore-quotes
635 expr)
636 (save-excursion
637 (with-syntax-table emacs-lisp-mode-syntax-table
638 ;; If this sexp appears to be enclosed in `...'
639 ;; then ignore the surrounding quotes.
640 (setq ignore-quotes
641 (or (eq (following-char) ?\')
642 (eq (preceding-char) ?\')))
643 (forward-sexp -1)
644 ;; If we were after `?\e' (or similar case),
645 ;; use the whole thing, not just the `e'.
646 (when (eq (preceding-char) ?\\)
647 (forward-char -1)
648 (when (eq (preceding-char) ??)
649 (forward-char -1)))
651 ;; Skip over hash table read syntax.
652 (and (> (point) (1+ (point-min)))
653 (looking-back "#s" (- (point) 2))
654 (forward-char -2))
656 ;; Skip over `#N='s.
657 (when (eq (preceding-char) ?=)
658 (let (labeled-p)
659 (save-excursion
660 (skip-chars-backward "0-9#=")
661 (setq labeled-p (looking-at "\\(#[0-9]+=\\)+")))
662 (when labeled-p
663 (forward-sexp -1))))
665 (save-restriction
666 ;; vladimir@cs.ualberta.ca 30-Jul-1997: skip ` in
667 ;; `variable' so that the value is returned, not the
668 ;; name
669 (if (and ignore-quotes
670 (eq (following-char) ?`))
671 (forward-char))
672 (narrow-to-region (point-min) opoint)
673 (setq expr (read (current-buffer)))
674 ;; If it's an (interactive ...) form, it's more
675 ;; useful to show how an interactive call would
676 ;; use it.
677 (and (consp expr)
678 (eq (car expr) 'interactive)
679 (setq expr
680 (list 'call-interactively
681 (list 'quote
682 (list 'lambda
683 '(&rest args)
684 expr
685 'args)))))
686 expr)))))
689 (defun eval-last-sexp-1 (eval-last-sexp-arg-internal)
690 "Evaluate sexp before point; print value in minibuffer.
691 With argument, print output into current buffer."
692 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
693 ;; Setup the lexical environment if lexical-binding is enabled.
694 (eval-last-sexp-print-value
695 (eval (eval-sexp-add-defvars (preceding-sexp)) lexical-binding))))
698 (defun eval-last-sexp-print-value (value)
699 (let ((unabbreviated (let ((print-length nil) (print-level nil))
700 (prin1-to-string value)))
701 (print-length eval-expression-print-length)
702 (print-level eval-expression-print-level)
703 (beg (point))
704 end)
705 (prog1
706 (prin1 value)
707 (let ((str (eval-expression-print-format value)))
708 (if str (princ str)))
709 (setq end (point))
710 (when (and (bufferp standard-output)
711 (or (not (null print-length))
712 (not (null print-level)))
713 (not (string= unabbreviated
714 (buffer-substring-no-properties beg end))))
715 (last-sexp-setup-props beg end value
716 unabbreviated
717 (buffer-substring-no-properties beg end))
718 ))))
721 (defvar eval-last-sexp-fake-value (make-symbol "t"))
723 (defun eval-sexp-add-defvars (exp &optional pos)
724 "Prepend EXP with all the `defvar's that precede it in the buffer.
725 POS specifies the starting position where EXP was found and defaults to point."
726 (if (not lexical-binding)
728 (save-excursion
729 (unless pos (setq pos (point)))
730 (let ((vars ()))
731 (goto-char (point-min))
732 (while (re-search-forward
733 "^(def\\(?:var\\|const\\|custom\\)[ \t\n]+\\([^; '()\n\t]+\\)"
734 pos t)
735 (let ((var (intern (match-string 1))))
736 (unless (special-variable-p var)
737 (push var vars))))
738 `(progn ,@(mapcar (lambda (v) `(defvar ,v)) vars) ,exp)))))
740 (defun eval-last-sexp (eval-last-sexp-arg-internal)
741 "Evaluate sexp before point; print value in minibuffer.
742 Interactively, with prefix argument, print output into current buffer.
743 Truncates long output according to the value of the variables
744 `eval-expression-print-length' and `eval-expression-print-level'.
746 If `eval-expression-debug-on-error' is non-nil, which is the default,
747 this command arranges for all errors to enter the debugger."
748 (interactive "P")
749 (if (null eval-expression-debug-on-error)
750 (eval-last-sexp-1 eval-last-sexp-arg-internal)
751 (let ((value
752 (let ((debug-on-error eval-last-sexp-fake-value))
753 (cons (eval-last-sexp-1 eval-last-sexp-arg-internal)
754 debug-on-error))))
755 (unless (eq (cdr value) eval-last-sexp-fake-value)
756 (setq debug-on-error (cdr value)))
757 (car value))))
759 (defun eval-defun-1 (form)
760 "Treat some expressions specially.
761 Reset the `defvar' and `defcustom' variables to the initial value.
762 Reinitialize the face according to the `defface' specification."
763 ;; The code in edebug-defun should be consistent with this, but not
764 ;; the same, since this gets a macroexpanded form.
765 (cond ((not (listp form))
766 form)
767 ((and (eq (car form) 'defvar)
768 (cdr-safe (cdr-safe form))
769 (boundp (cadr form)))
770 ;; Force variable to be re-set.
771 `(progn (defvar ,(nth 1 form) nil ,@(nthcdr 3 form))
772 (setq-default ,(nth 1 form) ,(nth 2 form))))
773 ;; `defcustom' is now macroexpanded to
774 ;; `custom-declare-variable' with a quoted value arg.
775 ((and (eq (car form) 'custom-declare-variable)
776 (default-boundp (eval (nth 1 form) lexical-binding)))
777 ;; Force variable to be bound.
778 (set-default (eval (nth 1 form) lexical-binding)
779 (eval (nth 1 (nth 2 form)) lexical-binding))
780 form)
781 ;; `defface' is macroexpanded to `custom-declare-face'.
782 ((eq (car form) 'custom-declare-face)
783 ;; Reset the face.
784 (let ((face-symbol (eval (nth 1 form) lexical-binding)))
785 (setq face-new-frame-defaults
786 (assq-delete-all face-symbol face-new-frame-defaults))
787 (put face-symbol 'face-defface-spec nil)
788 (put face-symbol 'face-documentation (nth 3 form))
789 ;; Setting `customized-face' to the new spec after calling
790 ;; the form, but preserving the old saved spec in `saved-face',
791 ;; imitates the situation when the new face spec is set
792 ;; temporarily for the current session in the customize
793 ;; buffer, thus allowing `face-user-default-spec' to use the
794 ;; new customized spec instead of the saved spec.
795 ;; Resetting `saved-face' temporarily to nil is needed to let
796 ;; `defface' change the spec, regardless of a saved spec.
797 (prog1 `(prog1 ,form
798 (put ,(nth 1 form) 'saved-face
799 ',(get face-symbol 'saved-face))
800 (put ,(nth 1 form) 'customized-face
801 ,(nth 2 form)))
802 (put face-symbol 'saved-face nil))))
803 ((eq (car form) 'progn)
804 (cons 'progn (mapcar 'eval-defun-1 (cdr form))))
805 (t form)))
807 (defun eval-defun-2 ()
808 "Evaluate defun that point is in or before.
809 The value is displayed in the minibuffer.
810 If the current defun is actually a call to `defvar',
811 then reset the variable using the initial value expression
812 even if the variable already has some other value.
813 \(Normally `defvar' does not change the variable's value
814 if it already has a value.\)
816 With argument, insert value in current buffer after the defun.
817 Return the result of evaluation."
818 (interactive "P")
819 ;; FIXME: the print-length/level bindings should only be applied while
820 ;; printing, not while evaluating.
821 (let ((debug-on-error eval-expression-debug-on-error)
822 (print-length eval-expression-print-length)
823 (print-level eval-expression-print-level))
824 (save-excursion
825 ;; Arrange for eval-region to "read" the (possibly) altered form.
826 ;; eval-region handles recording which file defines a function or
827 ;; variable. Re-written using `apply' to avoid capturing
828 ;; variables like `end'.
829 (apply
830 #'eval-region
831 (let ((standard-output t)
832 beg end form)
833 ;; Read the form from the buffer, and record where it ends.
834 (save-excursion
835 (end-of-defun)
836 (beginning-of-defun)
837 (setq beg (point))
838 (setq form (read (current-buffer)))
839 (setq end (point)))
840 ;; Alter the form if necessary.
841 (setq form (eval-sexp-add-defvars (eval-defun-1 (macroexpand form))))
842 (list beg end standard-output
843 `(lambda (ignore)
844 ;; Skipping to the end of the specified region
845 ;; will make eval-region return.
846 (goto-char ,end)
847 ',form))))))
848 ;; The result of evaluation has been put onto VALUES. So return it.
849 (car values))
851 (defun eval-defun (edebug-it)
852 "Evaluate the top-level form containing point, or after point.
854 If the current defun is actually a call to `defvar' or `defcustom',
855 evaluating it this way resets the variable using its initial value
856 expression even if the variable already has some other value.
857 \(Normally `defvar' and `defcustom' do not alter the value if there
858 already is one.) In an analogous way, evaluating a `defface'
859 overrides any customizations of the face, so that it becomes
860 defined exactly as the `defface' expression says.
862 If `eval-expression-debug-on-error' is non-nil, which is the default,
863 this command arranges for all errors to enter the debugger.
865 With a prefix argument, instrument the code for Edebug.
867 If acting on a `defun' for FUNCTION, and the function was
868 instrumented, `Edebug: FUNCTION' is printed in the minibuffer. If not
869 instrumented, just FUNCTION is printed.
871 If not acting on a `defun', the result of evaluation is displayed in
872 the minibuffer. This display is controlled by the variables
873 `eval-expression-print-length' and `eval-expression-print-level',
874 which see."
875 (interactive "P")
876 (cond (edebug-it
877 (require 'edebug)
878 (eval-defun (not edebug-all-defs)))
880 (if (null eval-expression-debug-on-error)
881 (eval-defun-2)
882 (let ((old-value (make-symbol "t")) new-value value)
883 (let ((debug-on-error old-value))
884 (setq value (eval-defun-2))
885 (setq new-value debug-on-error))
886 (unless (eq old-value new-value)
887 (setq debug-on-error new-value))
888 value)))))
890 ;; May still be used by some external Lisp-mode variant.
891 (define-obsolete-function-alias 'lisp-comment-indent
892 'comment-indent-default "22.1")
893 (define-obsolete-function-alias 'lisp-mode-auto-fill 'do-auto-fill "23.1")
895 (defcustom lisp-indent-offset nil
896 "If non-nil, indent second line of expressions that many more columns."
897 :group 'lisp
898 :type '(choice (const nil) integer))
899 (put 'lisp-indent-offset 'safe-local-variable
900 (lambda (x) (or (null x) (integerp x))))
902 (defcustom lisp-indent-function 'lisp-indent-function
903 "A function to be called by `calculate-lisp-indent'.
904 It indents the arguments of a Lisp function call. This function
905 should accept two arguments: the indent-point, and the
906 `parse-partial-sexp' state at that position. One option for this
907 function is `common-lisp-indent-function'."
908 :type 'function
909 :group 'lisp)
911 (defun lisp-indent-line (&optional whole-exp)
912 "Indent current line as Lisp code.
913 With argument, indent any additional lines of the same expression
914 rigidly along with this one."
915 (interactive "P")
916 (let ((indent (calculate-lisp-indent)) shift-amt end
917 (pos (- (point-max) (point)))
918 (beg (progn (beginning-of-line) (point))))
919 (skip-chars-forward " \t")
920 (if (or (null indent) (looking-at "\\s<\\s<\\s<"))
921 ;; Don't alter indentation of a ;;; comment line
922 ;; or a line that starts in a string.
923 (goto-char (- (point-max) pos))
924 (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
925 ;; Single-semicolon comment lines should be indented
926 ;; as comment lines, not as code.
927 (progn (indent-for-comment) (forward-char -1))
928 (if (listp indent) (setq indent (car indent)))
929 (setq shift-amt (- indent (current-column)))
930 (if (zerop shift-amt)
932 (delete-region beg (point))
933 (indent-to indent)))
934 ;; If initial point was within line's indentation,
935 ;; position after the indentation. Else stay at same point in text.
936 (if (> (- (point-max) pos) (point))
937 (goto-char (- (point-max) pos)))
938 ;; If desired, shift remaining lines of expression the same amount.
939 (and whole-exp (not (zerop shift-amt))
940 (save-excursion
941 (goto-char beg)
942 (forward-sexp 1)
943 (setq end (point))
944 (goto-char beg)
945 (forward-line 1)
946 (setq beg (point))
947 (> end beg))
948 (indent-code-rigidly beg end shift-amt)))))
950 (defvar calculate-lisp-indent-last-sexp)
952 (defun calculate-lisp-indent (&optional parse-start)
953 "Return appropriate indentation for current line as Lisp code.
954 In usual case returns an integer: the column to indent to.
955 If the value is nil, that means don't change the indentation
956 because the line starts inside a string.
958 The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
959 This means that following lines at the same level of indentation
960 should not necessarily be indented the same as this line.
961 Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
962 is the buffer position of the start of the containing expression."
963 (save-excursion
964 (beginning-of-line)
965 (let ((indent-point (point))
966 state paren-depth
967 ;; setting this to a number inhibits calling hook
968 (desired-indent nil)
969 (retry t)
970 calculate-lisp-indent-last-sexp containing-sexp)
971 (if parse-start
972 (goto-char parse-start)
973 (beginning-of-defun))
974 ;; Find outermost containing sexp
975 (while (< (point) indent-point)
976 (setq state (parse-partial-sexp (point) indent-point 0)))
977 ;; Find innermost containing sexp
978 (while (and retry
979 state
980 (> (setq paren-depth (elt state 0)) 0))
981 (setq retry nil)
982 (setq calculate-lisp-indent-last-sexp (elt state 2))
983 (setq containing-sexp (elt state 1))
984 ;; Position following last unclosed open.
985 (goto-char (1+ containing-sexp))
986 ;; Is there a complete sexp since then?
987 (if (and calculate-lisp-indent-last-sexp
988 (> calculate-lisp-indent-last-sexp (point)))
989 ;; Yes, but is there a containing sexp after that?
990 (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
991 indent-point 0)))
992 (if (setq retry (car (cdr peek))) (setq state peek)))))
993 (if retry
995 ;; Innermost containing sexp found
996 (goto-char (1+ containing-sexp))
997 (if (not calculate-lisp-indent-last-sexp)
998 ;; indent-point immediately follows open paren.
999 ;; Don't call hook.
1000 (setq desired-indent (current-column))
1001 ;; Find the start of first element of containing sexp.
1002 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1003 (cond ((looking-at "\\s(")
1004 ;; First element of containing sexp is a list.
1005 ;; Indent under that list.
1007 ((> (save-excursion (forward-line 1) (point))
1008 calculate-lisp-indent-last-sexp)
1009 ;; This is the first line to start within the containing sexp.
1010 ;; It's almost certainly a function call.
1011 (if (= (point) calculate-lisp-indent-last-sexp)
1012 ;; Containing sexp has nothing before this line
1013 ;; except the first element. Indent under that element.
1015 ;; Skip the first element, find start of second (the first
1016 ;; argument of the function call) and indent under.
1017 (progn (forward-sexp 1)
1018 (parse-partial-sexp (point)
1019 calculate-lisp-indent-last-sexp
1020 0 t)))
1021 (backward-prefix-chars))
1023 ;; Indent beneath first sexp on same line as
1024 ;; `calculate-lisp-indent-last-sexp'. Again, it's
1025 ;; almost certainly a function call.
1026 (goto-char calculate-lisp-indent-last-sexp)
1027 (beginning-of-line)
1028 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
1029 0 t)
1030 (backward-prefix-chars)))))
1031 ;; Point is at the point to indent under unless we are inside a string.
1032 ;; Call indentation hook except when overridden by lisp-indent-offset
1033 ;; or if the desired indentation has already been computed.
1034 (let ((normal-indent (current-column)))
1035 (cond ((elt state 3)
1036 ;; Inside a string, don't change indentation.
1037 nil)
1038 ((and (integerp lisp-indent-offset) containing-sexp)
1039 ;; Indent by constant offset
1040 (goto-char containing-sexp)
1041 (+ (current-column) lisp-indent-offset))
1042 ;; in this case calculate-lisp-indent-last-sexp is not nil
1043 (calculate-lisp-indent-last-sexp
1045 ;; try to align the parameters of a known function
1046 (and lisp-indent-function
1047 (not retry)
1048 (funcall lisp-indent-function indent-point state))
1049 ;; If the function has no special alignment
1050 ;; or it does not apply to this argument,
1051 ;; try to align a constant-symbol under the last
1052 ;; preceding constant symbol, if there is such one of
1053 ;; the last 2 preceding symbols, in the previous
1054 ;; uncommented line.
1055 (and (save-excursion
1056 (goto-char indent-point)
1057 (skip-chars-forward " \t")
1058 (looking-at ":"))
1059 ;; The last sexp may not be at the indentation
1060 ;; where it begins, so find that one, instead.
1061 (save-excursion
1062 (goto-char calculate-lisp-indent-last-sexp)
1063 ;; Handle prefix characters and whitespace
1064 ;; following an open paren. (Bug#1012)
1065 (backward-prefix-chars)
1066 (while (and (not (looking-back "^[ \t]*\\|([ \t]+"))
1067 (or (not containing-sexp)
1068 (< (1+ containing-sexp) (point))))
1069 (forward-sexp -1)
1070 (backward-prefix-chars))
1071 (setq calculate-lisp-indent-last-sexp (point)))
1072 (> calculate-lisp-indent-last-sexp
1073 (save-excursion
1074 (goto-char (1+ containing-sexp))
1075 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1076 (point)))
1077 (let ((parse-sexp-ignore-comments t)
1078 indent)
1079 (goto-char calculate-lisp-indent-last-sexp)
1080 (or (and (looking-at ":")
1081 (setq indent (current-column)))
1082 (and (< (line-beginning-position)
1083 (prog2 (backward-sexp) (point)))
1084 (looking-at ":")
1085 (setq indent (current-column))))
1086 indent))
1087 ;; another symbols or constants not preceded by a constant
1088 ;; as defined above.
1089 normal-indent))
1090 ;; in this case calculate-lisp-indent-last-sexp is nil
1091 (desired-indent)
1093 normal-indent))))))
1095 (defun lisp-indent-function (indent-point state)
1096 "This function is the normal value of the variable `lisp-indent-function'.
1097 The function `calculate-lisp-indent' calls this to determine
1098 if the arguments of a Lisp function call should be indented specially.
1100 INDENT-POINT is the position where the user typed TAB, or equivalent.
1101 Point is located at the point to indent under (for default indentation);
1102 STATE is the `parse-partial-sexp' state for that position.
1104 If the current line is in a call to a Lisp function that has a non-nil
1105 property `lisp-indent-function' (or the deprecated `lisp-indent-hook'),
1106 it specifies how to indent. The property value can be:
1108 * `defun', meaning indent `defun'-style
1109 \(this is also the case if there is no property and the function
1110 has a name that begins with \"def\", and three or more arguments);
1112 * an integer N, meaning indent the first N arguments specially
1113 (like ordinary function arguments), and then indent any further
1114 arguments like a body;
1116 * a function to call that returns the indentation (or nil).
1117 `lisp-indent-function' calls this function with the same two arguments
1118 that it itself received.
1120 This function returns either the indentation to use, or nil if the
1121 Lisp function does not specify a special indentation."
1122 (let ((normal-indent (current-column)))
1123 (goto-char (1+ (elt state 1)))
1124 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1125 (if (and (elt state 2)
1126 (not (looking-at "\\sw\\|\\s_")))
1127 ;; car of form doesn't seem to be a symbol
1128 (progn
1129 (if (not (> (save-excursion (forward-line 1) (point))
1130 calculate-lisp-indent-last-sexp))
1131 (progn (goto-char calculate-lisp-indent-last-sexp)
1132 (beginning-of-line)
1133 (parse-partial-sexp (point)
1134 calculate-lisp-indent-last-sexp 0 t)))
1135 ;; Indent under the list or under the first sexp on the same
1136 ;; line as calculate-lisp-indent-last-sexp. Note that first
1137 ;; thing on that line has to be complete sexp since we are
1138 ;; inside the innermost containing sexp.
1139 (backward-prefix-chars)
1140 (current-column))
1141 (let ((function (buffer-substring (point)
1142 (progn (forward-sexp 1) (point))))
1143 method)
1144 (setq method (or (function-get (intern-soft function)
1145 'lisp-indent-function)
1146 (get (intern-soft function) 'lisp-indent-hook)))
1147 (cond ((or (eq method 'defun)
1148 (and (null method)
1149 (> (length function) 3)
1150 (string-match "\\`def" function)))
1151 (lisp-indent-defform state indent-point))
1152 ((integerp method)
1153 (lisp-indent-specform method state
1154 indent-point normal-indent))
1155 (method
1156 (funcall method indent-point state)))))))
1158 (defcustom lisp-body-indent 2
1159 "Number of columns to indent the second line of a `(def...)' form."
1160 :group 'lisp
1161 :type 'integer)
1162 (put 'lisp-body-indent 'safe-local-variable 'integerp)
1164 (defun lisp-indent-specform (count state indent-point normal-indent)
1165 (let ((containing-form-start (elt state 1))
1166 (i count)
1167 body-indent containing-form-column)
1168 ;; Move to the start of containing form, calculate indentation
1169 ;; to use for non-distinguished forms (> count), and move past the
1170 ;; function symbol. lisp-indent-function guarantees that there is at
1171 ;; least one word or symbol character following open paren of containing
1172 ;; form.
1173 (goto-char containing-form-start)
1174 (setq containing-form-column (current-column))
1175 (setq body-indent (+ lisp-body-indent containing-form-column))
1176 (forward-char 1)
1177 (forward-sexp 1)
1178 ;; Now find the start of the last form.
1179 (parse-partial-sexp (point) indent-point 1 t)
1180 (while (and (< (point) indent-point)
1181 (condition-case ()
1182 (progn
1183 (setq count (1- count))
1184 (forward-sexp 1)
1185 (parse-partial-sexp (point) indent-point 1 t))
1186 (error nil))))
1187 ;; Point is sitting on first character of last (or count) sexp.
1188 (if (> count 0)
1189 ;; A distinguished form. If it is the first or second form use double
1190 ;; lisp-body-indent, else normal indent. With lisp-body-indent bound
1191 ;; to 2 (the default), this just happens to work the same with if as
1192 ;; the older code, but it makes unwind-protect, condition-case,
1193 ;; with-output-to-temp-buffer, et. al. much more tasteful. The older,
1194 ;; less hacked, behavior can be obtained by replacing below with
1195 ;; (list normal-indent containing-form-start).
1196 (if (<= (- i count) 1)
1197 (list (+ containing-form-column (* 2 lisp-body-indent))
1198 containing-form-start)
1199 (list normal-indent containing-form-start))
1200 ;; A non-distinguished form. Use body-indent if there are no
1201 ;; distinguished forms and this is the first undistinguished form,
1202 ;; or if this is the first undistinguished form and the preceding
1203 ;; distinguished form has indentation at least as great as body-indent.
1204 (if (or (and (= i 0) (= count 0))
1205 (and (= count 0) (<= body-indent normal-indent)))
1206 body-indent
1207 normal-indent))))
1209 (defun lisp-indent-defform (state indent-point)
1210 (goto-char (car (cdr state)))
1211 (forward-line 1)
1212 (if (> (point) (car (cdr (cdr state))))
1213 (progn
1214 (goto-char (car (cdr state)))
1215 (+ lisp-body-indent (current-column)))))
1218 ;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
1219 ;; like defun if the first form is placed on the next line, otherwise
1220 ;; it is indented like any other form (i.e. forms line up under first).
1222 (put 'autoload 'lisp-indent-function 'defun)
1223 (put 'progn 'lisp-indent-function 0)
1224 (put 'prog1 'lisp-indent-function 1)
1225 (put 'prog2 'lisp-indent-function 2)
1226 (put 'save-excursion 'lisp-indent-function 0)
1227 (put 'save-restriction 'lisp-indent-function 0)
1228 (put 'save-match-data 'lisp-indent-function 0)
1229 (put 'save-current-buffer 'lisp-indent-function 0)
1230 (put 'let 'lisp-indent-function 1)
1231 (put 'let* 'lisp-indent-function 1)
1232 (put 'while 'lisp-indent-function 1)
1233 (put 'if 'lisp-indent-function 2)
1234 (put 'catch 'lisp-indent-function 1)
1235 (put 'condition-case 'lisp-indent-function 2)
1236 (put 'unwind-protect 'lisp-indent-function 1)
1237 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
1239 (defun indent-sexp (&optional endpos)
1240 "Indent each line of the list starting just after point.
1241 If optional arg ENDPOS is given, indent each line, stopping when
1242 ENDPOS is encountered."
1243 (interactive)
1244 (let ((indent-stack (list nil))
1245 (next-depth 0)
1246 ;; If ENDPOS is non-nil, use nil as STARTING-POINT
1247 ;; so that calculate-lisp-indent will find the beginning of
1248 ;; the defun we are in.
1249 ;; If ENDPOS is nil, it is safe not to scan before point
1250 ;; since every line we indent is more deeply nested than point is.
1251 (starting-point (if endpos nil (point)))
1252 (last-point (point))
1253 last-depth bol outer-loop-done inner-loop-done state this-indent)
1254 (or endpos
1255 ;; Get error now if we don't have a complete sexp after point.
1256 (save-excursion (forward-sexp 1)))
1257 (save-excursion
1258 (setq outer-loop-done nil)
1259 (while (if endpos (< (point) endpos)
1260 (not outer-loop-done))
1261 (setq last-depth next-depth
1262 inner-loop-done nil)
1263 ;; Parse this line so we can learn the state
1264 ;; to indent the next line.
1265 ;; This inner loop goes through only once
1266 ;; unless a line ends inside a string.
1267 (while (and (not inner-loop-done)
1268 (not (setq outer-loop-done (eobp))))
1269 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
1270 nil nil state))
1271 (setq next-depth (car state))
1272 ;; If the line contains a comment other than the sort
1273 ;; that is indented like code,
1274 ;; indent it now with indent-for-comment.
1275 ;; Comments indented like code are right already.
1276 ;; In any case clear the in-comment flag in the state
1277 ;; because parse-partial-sexp never sees the newlines.
1278 (if (car (nthcdr 4 state))
1279 (progn (indent-for-comment)
1280 (end-of-line)
1281 (setcar (nthcdr 4 state) nil)))
1282 ;; If this line ends inside a string,
1283 ;; go straight to next line, remaining within the inner loop,
1284 ;; and turn off the \-flag.
1285 (if (car (nthcdr 3 state))
1286 (progn
1287 (forward-line 1)
1288 (setcar (nthcdr 5 state) nil))
1289 (setq inner-loop-done t)))
1290 (and endpos
1291 (<= next-depth 0)
1292 (progn
1293 (setq indent-stack (nconc indent-stack
1294 (make-list (- next-depth) nil))
1295 last-depth (- last-depth next-depth)
1296 next-depth 0)))
1297 (forward-line 1)
1298 ;; Decide whether to exit.
1299 (if endpos
1300 ;; If we have already reached the specified end,
1301 ;; give up and do not reindent this line.
1302 (if (<= endpos (point))
1303 (setq outer-loop-done t))
1304 ;; If no specified end, we are done if we have finished one sexp.
1305 (if (<= next-depth 0)
1306 (setq outer-loop-done t)))
1307 (unless outer-loop-done
1308 (while (> last-depth next-depth)
1309 (setq indent-stack (cdr indent-stack)
1310 last-depth (1- last-depth)))
1311 (while (< last-depth next-depth)
1312 (setq indent-stack (cons nil indent-stack)
1313 last-depth (1+ last-depth)))
1314 ;; Now indent the next line according
1315 ;; to what we learned from parsing the previous one.
1316 (setq bol (point))
1317 (skip-chars-forward " \t")
1318 ;; But not if the line is blank, or just a comment
1319 ;; (except for double-semi comments; indent them as usual).
1320 (if (or (eobp) (looking-at "\\s<\\|\n"))
1322 (if (and (car indent-stack)
1323 (>= (car indent-stack) 0))
1324 (setq this-indent (car indent-stack))
1325 (let ((val (calculate-lisp-indent
1326 (if (car indent-stack) (- (car indent-stack))
1327 starting-point))))
1328 (if (null val)
1329 (setq this-indent val)
1330 (if (integerp val)
1331 (setcar indent-stack
1332 (setq this-indent val))
1333 (setcar indent-stack (- (car (cdr val))))
1334 (setq this-indent (car val))))))
1335 (if (and this-indent (/= (current-column) this-indent))
1336 (progn (delete-region bol (point))
1337 (indent-to this-indent)))))
1338 (or outer-loop-done
1339 (setq outer-loop-done (= (point) last-point))
1340 (setq last-point (point)))))))
1342 (defun indent-pp-sexp (&optional arg)
1343 "Indent each line of the list starting just after point, or prettyprint it.
1344 A prefix argument specifies pretty-printing."
1345 (interactive "P")
1346 (if arg
1347 (save-excursion
1348 (save-restriction
1349 (narrow-to-region (point) (progn (forward-sexp 1) (point)))
1350 (pp-buffer)
1351 (goto-char (point-max))
1352 (if (eq (char-before) ?\n)
1353 (delete-char -1)))))
1354 (indent-sexp))
1356 ;;;; Lisp paragraph filling commands.
1358 (defcustom emacs-lisp-docstring-fill-column 65
1359 "Value of `fill-column' to use when filling a docstring.
1360 Any non-integer value means do not use a different value of
1361 `fill-column' when filling docstrings."
1362 :type '(choice (integer)
1363 (const :tag "Use the current `fill-column'" t))
1364 :group 'lisp)
1366 (defun lisp-fill-paragraph (&optional justify)
1367 "Like \\[fill-paragraph], but handle Emacs Lisp comments and docstrings.
1368 If any of the current line is a comment, fill the comment or the
1369 paragraph of it that point is in, preserving the comment's indentation
1370 and initial semicolons."
1371 (interactive "P")
1372 (or (fill-comment-paragraph justify)
1373 ;; Since fill-comment-paragraph returned nil, that means we're not in
1374 ;; a comment: Point is on a program line; we are interested
1375 ;; particularly in docstring lines.
1377 ;; We bind `paragraph-start' and `paragraph-separate' temporarily. They
1378 ;; are buffer-local, but we avoid changing them so that they can be set
1379 ;; to make `forward-paragraph' and friends do something the user wants.
1381 ;; `paragraph-start': The `(' in the character alternative and the
1382 ;; left-singlequote plus `(' sequence after the \\| alternative prevent
1383 ;; sexps and backquoted sexps that follow a docstring from being filled
1384 ;; with the docstring. This setting has the consequence of inhibiting
1385 ;; filling many program lines that are not docstrings, which is sensible,
1386 ;; because the user probably asked to fill program lines by accident, or
1387 ;; expecting indentation (perhaps we should try to do indenting in that
1388 ;; case). The `;' and `:' stop the paragraph being filled at following
1389 ;; comment lines and at keywords (e.g., in `defcustom'). Left parens are
1390 ;; escaped to keep font-locking, filling, & paren matching in the source
1391 ;; file happy.
1393 ;; `paragraph-separate': A clever regexp distinguishes the first line of
1394 ;; a docstring and identifies it as a paragraph separator, so that it
1395 ;; won't be filled. (Since the first line of documentation stands alone
1396 ;; in some contexts, filling should not alter the contents the author has
1397 ;; chosen.) Only the first line of a docstring begins with whitespace
1398 ;; and a quotation mark and ends with a period or (rarely) a comma.
1400 ;; The `fill-column' is temporarily bound to
1401 ;; `emacs-lisp-docstring-fill-column' if that value is an integer.
1402 (let ((paragraph-start (concat paragraph-start
1403 "\\|\\s-*\\([(;:\"]\\|`(\\|#'(\\)"))
1404 (paragraph-separate
1405 (concat paragraph-separate "\\|\\s-*\".*[,\\.]$"))
1406 (fill-column (if (and (integerp emacs-lisp-docstring-fill-column)
1407 (derived-mode-p 'emacs-lisp-mode))
1408 emacs-lisp-docstring-fill-column
1409 fill-column)))
1410 (fill-paragraph justify))
1411 ;; Never return nil.
1414 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
1415 "Indent all lines of code, starting in the region, sideways by ARG columns.
1416 Does not affect lines starting inside comments or strings, assuming that
1417 the start of the region is not inside them.
1419 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1420 The last is a regexp which, if matched at the beginning of a line,
1421 means don't indent that line."
1422 (interactive "r\np")
1423 (let (state)
1424 (save-excursion
1425 (goto-char end)
1426 (setq end (point-marker))
1427 (goto-char start)
1428 (or (bolp)
1429 (setq state (parse-partial-sexp (point)
1430 (progn
1431 (forward-line 1) (point))
1432 nil nil state)))
1433 (while (< (point) end)
1434 (or (car (nthcdr 3 state))
1435 (and nochange-regexp
1436 (looking-at nochange-regexp))
1437 ;; If line does not start in string, indent it
1438 (let ((indent (current-indentation)))
1439 (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1440 (or (eolp)
1441 (indent-to (max 0 (+ indent arg)) 0))))
1442 (setq state (parse-partial-sexp (point)
1443 (progn
1444 (forward-line 1) (point))
1445 nil nil state))))))
1447 (provide 'lisp-mode)
1449 ;;; lisp-mode.el ends here