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