Fix and document recently introduced configuration options.
[bpt/emacs.git] / lisp / emacs-lisp / lisp-mode.el
CommitLineData
d6a3febd
MR
1;;; lisp-mode.el --- Lisp mode, and its idiosyncratic commands
2
acaf905b 3;; Copyright (C) 1985-1986, 1999-2012 Free Software Foundation, Inc.
d6a3febd
MR
4
5;; Maintainer: FSF
6;; Keywords: lisp, languages
bd78fa1d 7;; Package: emacs
d6a3febd
MR
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)
db174434
CY
37(define-abbrev-table 'lisp-mode-abbrev-table ()
38 "Abbrev table for Lisp mode.")
d6a3febd 39
db174434
CY
40(defvar emacs-lisp-mode-abbrev-table nil)
41(define-abbrev-table 'emacs-lisp-mode-abbrev-table ()
42 "Abbrev table for Emacs Lisp mode.
43It has `lisp-mode-abbrev-table' as its parent."
44 :parents (list lisp-mode-abbrev-table))
d6a3febd
MR
45
46(defvar emacs-lisp-mode-syntax-table
da68c4c8
DD
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)
e4a09a11
GM
87 table)
88 "Syntax table used in `emacs-lisp-mode'.")
d6a3febd
MR
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)
c5683ceb 94 (modify-syntax-entry ?# "' 14" table)
d6a3febd 95 (modify-syntax-entry ?| "\" 23bn" table)
a8106aec
GM
96 table)
97 "Syntax table used in `lisp-mode'.")
d6a3febd
MR
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
b7ccbdc2 120 '("defconst" "defconstant" "defcustom"
d6a3febd
MR
121 "defparameter" "define-symbol-macro") t))
122 "\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"))
123 2)
b7ccbdc2
CY
124 ;; For `defvar', we ignore (defvar FOO) constructs.
125 (list (purecopy "Variables")
126 (purecopy (concat "^\\s-*(defvar\\s-+\\(\\(\\sw\\|\\s_\\)+\\)"
127 "[[:space:]\n]+[^)]"))
128 1)
d6a3febd
MR
129 (list (purecopy "Types")
130 (purecopy (concat "^\\s-*("
131 (eval-when-compile
132 (regexp-opt
133 '("defgroup" "deftheme" "deftype" "defstruct"
134 "defclass" "define-condition" "define-widget"
135 "defface" "defpackage") t))
136 "\\s-+'?\\(\\(\\sw\\|\\s_\\)+\\)"))
137 2))
138
139 "Imenu generic expression for Lisp mode. See `imenu-generic-expression'.")
140
141;; This was originally in autoload.el and is still used there.
142(put 'autoload 'doc-string-elt 3)
98449af8 143(put 'defmethod 'doc-string-elt 3)
d6a3febd 144(put 'defvar 'doc-string-elt 3)
d6a3febd 145(put 'defconst 'doc-string-elt 3)
d6a3febd
MR
146(put 'defalias 'doc-string-elt 3)
147(put 'defvaralias 'doc-string-elt 3)
148(put 'define-category 'doc-string-elt 2)
149
150(defvar lisp-doc-string-elt-property 'doc-string-elt
151 "The symbol property that holds the docstring position info.")
152
153(defun lisp-font-lock-syntactic-face-function (state)
154 (if (nth 3 state)
155 ;; This might be a (doc)string or a |...| symbol.
156 (let ((startpos (nth 8 state)))
157 (if (eq (char-after startpos) ?|)
158 ;; This is not a string, but a |...| symbol.
159 nil
160 (let* ((listbeg (nth 1 state))
161 (firstsym (and listbeg
162 (save-excursion
163 (goto-char listbeg)
164 (and (looking-at "([ \t\n]*\\(\\(\\sw\\|\\s_\\)+\\)")
165 (match-string 1)))))
7abaf5cc
SM
166 (docelt (and firstsym
167 (function-get (intern-soft firstsym)
d6a3febd
MR
168 lisp-doc-string-elt-property))))
169 (if (and docelt
170 ;; It's a string in a form that can have a docstring.
171 ;; Check whether it's in docstring position.
172 (save-excursion
173 (when (functionp docelt)
174 (goto-char (match-end 1))
175 (setq docelt (funcall docelt)))
176 (goto-char listbeg)
177 (forward-char 1)
178 (condition-case nil
179 (while (and (> docelt 0) (< (point) startpos)
180 (progn (forward-sexp 1) t))
181 (setq docelt (1- docelt)))
182 (error nil))
183 (and (zerop docelt) (<= (point) startpos)
184 (progn (forward-comment (point-max)) t)
185 (= (point) (nth 8 state)))))
186 font-lock-doc-face
187 font-lock-string-face))))
188 font-lock-comment-face))
189
94686171
DN
190(defun lisp-mode-variables (&optional lisp-syntax keywords-case-insensitive)
191 "Common initialization routine for lisp modes.
192The LISP-SYNTAX argument is used by code in inf-lisp.el and is
5249a62d
MR
193\(uselessly) passed from pp.el, chistory.el, gnus-kill.el and
194score-mode.el. KEYWORDS-CASE-INSENSITIVE non-nil means that for
195font-lock keywords will not be case sensitive."
d6a3febd
MR
196 (when lisp-syntax
197 (set-syntax-table lisp-mode-syntax-table))
d6a3febd
MR
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)
d6a3febd
MR
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
94686171 238 `((lisp-font-lock-keywords
d6a3febd 239 lisp-font-lock-keywords-1 lisp-font-lock-keywords-2)
94686171 240 nil ,keywords-case-insensitive (("+-*/.<>=!?$%_&~^:@" . "w")) nil
d6a3febd
MR
241 (font-lock-mark-block-function . mark-defun)
242 (font-lock-syntactic-face-function
243 . lisp-font-lock-syntactic-face-function))))
244
245(defun lisp-outline-level ()
246 "Lisp mode `outline-level' function."
247 (let ((len (- (match-end 0) (match-beginning 0))))
248 (if (looking-at "(\\|;;;###autoload")
249 1000
250 len)))
251
252(defvar lisp-mode-shared-map
253 (let ((map (make-sparse-keymap)))
254 (define-key map "\e\C-q" 'indent-sexp)
255 (define-key map "\177" 'backward-delete-char-untabify)
256 ;; This gets in the way when viewing a Lisp file in view-mode. As
257 ;; long as [backspace] is mapped into DEL via the
258 ;; function-key-map, this should remain disabled!!
259 ;;;(define-key map [backspace] 'backward-delete-char-untabify)
260 map)
261 "Keymap for commands shared by all sorts of Lisp modes.")
262
263(defvar emacs-lisp-mode-map
264 (let ((map (make-sparse-keymap "Emacs-Lisp"))
265 (menu-map (make-sparse-keymap "Emacs-Lisp"))
a707eb05 266 (lint-map (make-sparse-keymap))
d6a3febd
MR
267 (prof-map (make-sparse-keymap))
268 (tracing-map (make-sparse-keymap)))
269 (set-keymap-parent map lisp-mode-shared-map)
51ef56c4 270 (define-key map "\e\t" 'completion-at-point)
d6a3febd
MR
271 (define-key map "\e\C-x" 'eval-defun)
272 (define-key map "\e\C-q" 'indent-pp-sexp)
1ec4b7b2
SM
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
d6a3febd 277 :button (:toggle . (bound-and-true-p eldoc-mode))
1ec4b7b2
SM
278 :help "Display the documentation string for the item under cursor"))
279 (bindings--define-key menu-map [checkdoc]
280 '(menu-item "Check Documentation Strings" checkdoc
281 :help "Check documentation strings for style requirements"))
282 (bindings--define-key menu-map [re-builder]
283 '(menu-item "Construct Regexp" re-builder
284 :help "Construct a regexp interactively"))
285 (bindings--define-key menu-map [tracing] (cons "Tracing" tracing-map))
286 (bindings--define-key tracing-map [tr-a]
287 '(menu-item "Untrace All" untrace-all
288 :help "Untrace all currently traced functions"))
289 (bindings--define-key tracing-map [tr-uf]
290 '(menu-item "Untrace Function..." untrace-function
291 :help "Untrace function, and possibly activate all remaining advice"))
292 (bindings--define-key tracing-map [tr-sep] menu-bar-separator)
293 (bindings--define-key tracing-map [tr-q]
294 '(menu-item "Trace Function Quietly..." trace-function-background
295 :help "Trace the function with trace output going quietly to a buffer"))
296 (bindings--define-key tracing-map [tr-f]
297 '(menu-item "Trace Function..." trace-function
298 :help "Trace the function given as an argument"))
299 (bindings--define-key menu-map [profiling] (cons "Profiling" prof-map))
300 (bindings--define-key prof-map [prof-restall]
301 '(menu-item "Remove Instrumentation for All Functions" elp-restore-all
302 :help "Restore the original definitions of all functions being profiled"))
303 (bindings--define-key prof-map [prof-restfunc]
304 '(menu-item "Remove Instrumentation for Function..." elp-restore-function
305 :help "Restore an instrumented function to its original definition"))
306
307 (bindings--define-key prof-map [sep-rem] menu-bar-separator)
308 (bindings--define-key prof-map [prof-resall]
309 '(menu-item "Reset Counters for All Functions" elp-reset-all
310 :help "Reset the profiling information for all functions being profiled"))
311 (bindings--define-key prof-map [prof-resfunc]
312 '(menu-item "Reset Counters for Function..." elp-reset-function
313 :help "Reset the profiling information for a function"))
314 (bindings--define-key prof-map [prof-res]
315 '(menu-item "Show Profiling Results" elp-results
316 :help "Display current profiling results"))
317 (bindings--define-key prof-map [prof-pack]
318 '(menu-item "Instrument Package..." elp-instrument-package
319 :help "Instrument for profiling all function that start with a prefix"))
320 (bindings--define-key prof-map [prof-func]
321 '(menu-item "Instrument Function..." elp-instrument-function
322 :help "Instrument a function for profiling"))
323 (bindings--define-key menu-map [lint] (cons "Linting" lint-map))
324 (bindings--define-key lint-map [lint-di]
325 '(menu-item "Lint Directory..." elint-directory
326 :help "Lint a directory"))
327 (bindings--define-key lint-map [lint-f]
328 '(menu-item "Lint File..." elint-file
329 :help "Lint a file"))
330 (bindings--define-key lint-map [lint-b]
331 '(menu-item "Lint Buffer" elint-current-buffer
332 :help "Lint the current buffer"))
333 (bindings--define-key lint-map [lint-d]
334 '(menu-item "Lint Defun" elint-defun
335 :help "Lint the function at point"))
336 (bindings--define-key menu-map [edebug-defun]
337 '(menu-item "Instrument Function for Debugging" edebug-defun
338 :help "Evaluate the top level form point is in, stepping through with Edebug"
339 :keys "C-u C-M-x"))
340 (bindings--define-key menu-map [separator-byte] menu-bar-separator)
341 (bindings--define-key menu-map [disas]
342 '(menu-item "Disassemble Byte Compiled Object..." disassemble
343 :help "Print disassembled code for OBJECT in a buffer"))
344 (bindings--define-key menu-map [byte-recompile]
345 '(menu-item "Byte-recompile Directory..." byte-recompile-directory
346 :help "Recompile every `.el' file in DIRECTORY that needs recompilation"))
347 (bindings--define-key menu-map [emacs-byte-compile-and-load]
348 '(menu-item "Byte-compile and Load" emacs-lisp-byte-compile-and-load
349 :help "Byte-compile the current file (if it has changed), then load compiled code"))
350 (bindings--define-key menu-map [byte-compile]
351 '(menu-item "Byte-compile This File" emacs-lisp-byte-compile
352 :help "Byte compile the file containing the current buffer"))
353 (bindings--define-key menu-map [separator-eval] menu-bar-separator)
354 (bindings--define-key menu-map [ielm]
355 '(menu-item "Interactive Expression Evaluation" ielm
356 :help "Interactively evaluate Emacs Lisp expressions"))
357 (bindings--define-key menu-map [eval-buffer]
358 '(menu-item "Evaluate Buffer" eval-buffer
359 :help "Execute the current buffer as Lisp code"))
360 (bindings--define-key menu-map [eval-region]
361 '(menu-item "Evaluate Region" eval-region
362 :help "Execute the region as Lisp code"
d6a3febd 363 :enable mark-active))
1ec4b7b2
SM
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"
d6a3febd 371 :enable mark-active))
1ec4b7b2
SM
372 (bindings--define-key menu-map [indent-region]
373 '(menu-item "Indent Region" indent-region
374 :help "Indent each nonblank line in the region"
d6a3febd 375 :enable mark-active))
1ec4b7b2
SM
376 (bindings--define-key menu-map [indent-line]
377 '(menu-item "Indent Line" lisp-indent-line))
d6a3febd
MR
378 map)
379 "Keymap for Emacs Lisp mode.
380All commands in `lisp-mode-shared-map' are inherited by this map.")
381
382(defun emacs-lisp-byte-compile ()
383 "Byte compile the file containing the current buffer."
384 (interactive)
385 (if buffer-file-name
386 (byte-compile-file buffer-file-name)
387 (error "The buffer must be saved in a file first")))
388
389(defun emacs-lisp-byte-compile-and-load ()
390 "Byte-compile the current file (if it has changed), then load compiled code."
391 (interactive)
392 (or buffer-file-name
393 (error "The buffer must be saved in a file first"))
394 (require 'bytecomp)
395 ;; Recompile if file or buffer has changed since last compilation.
396 (if (and (buffer-modified-p)
397 (y-or-n-p (format "Save buffer %s first? " (buffer-name))))
398 (save-buffer))
430e7297 399 (byte-recompile-file buffer-file-name nil 0 t))
d6a3febd
MR
400
401(defcustom emacs-lisp-mode-hook nil
402 "Hook run when entering Emacs Lisp mode."
403 :options '(turn-on-eldoc-mode imenu-add-menubar-index checkdoc-minor-mode)
404 :type 'hook
405 :group 'lisp)
406
407(defcustom lisp-mode-hook nil
408 "Hook run when entering Lisp mode."
409 :options '(imenu-add-menubar-index)
410 :type 'hook
411 :group 'lisp)
412
413(defcustom lisp-interaction-mode-hook nil
414 "Hook run when entering Lisp Interaction mode."
415 :options '(turn-on-eldoc-mode)
416 :type 'hook
417 :group 'lisp)
418
10dcc561 419(define-derived-mode emacs-lisp-mode prog-mode "Emacs-Lisp"
d6a3febd
MR
420 "Major mode for editing Lisp code to run in Emacs.
421Commands:
422Delete converts tabs to spaces as it moves back.
423Blank lines separate paragraphs. Semicolons start comments.
a3c40f60 424
d6a3febd
MR
425\\{emacs-lisp-mode-map}
426Entry to this mode calls the value of `emacs-lisp-mode-hook'
427if that value is non-nil."
51ef56c4 428 :group 'lisp
d6a3febd
MR
429 (lisp-mode-variables)
430 (setq imenu-case-fold-search nil)
51ef56c4
SM
431 (add-hook 'completion-at-point-functions
432 'lisp-completion-at-point nil 'local))
d6a3febd
MR
433
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)
1ec4b7b2
SM
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"))
d6a3febd
MR
450 map)
451 "Keymap for ordinary Lisp mode.
452All commands in `lisp-mode-shared-map' are inherited by this map.")
453
10dcc561 454(define-derived-mode lisp-mode prog-mode "Lisp"
d6a3febd
MR
455 "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
456Commands:
457Delete converts tabs to spaces as it moves back.
458Blank lines separate paragraphs. Semicolons start comments.
a3c40f60 459
d6a3febd
MR
460\\{lisp-mode-map}
461Note that `run-lisp' may be used either to start an inferior Lisp job
462or to switch back to an existing one.
463
464Entry to this mode calls the value of `lisp-mode-hook'
465if that value is non-nil."
94686171 466 (lisp-mode-variables nil t)
f3a47002 467 (set (make-local-variable 'find-tag-default-function) 'lisp-find-tag-default)
d6a3febd
MR
468 (make-local-variable 'comment-start-skip)
469 (setq comment-start-skip
470 "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
f3a47002 471 (setq imenu-case-fold-search t))
d6a3febd
MR
472
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))))
479
480;; Used in old LispM code.
481(defalias 'common-lisp-mode 'lisp-mode)
482
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"))
488
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)
51ef56c4 495 (define-key map "\e\t" 'completion-at-point)
d6a3febd 496 (define-key map "\n" 'eval-print-last-sexp)
1ec4b7b2
SM
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"))
d6a3febd
MR
515 map)
516 "Keymap for Lisp Interaction mode.
517All commands in `lisp-mode-shared-map' are inherited by this map.")
518
d6a3febd
MR
519(define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
520 "Major mode for typing and evaluating Lisp forms.
521Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
522before point, and prints its value into the buffer, advancing point.
523Note that printing is controlled by `eval-expression-print-length'
524and `eval-expression-print-level'.
525
526Commands:
527Delete converts tabs to spaces as it moves back.
528Paragraphs are separated only by blank lines.
529Semicolons start comments.
a3c40f60 530
d6a3febd
MR
531\\{lisp-interaction-mode-map}
532Entry to this mode calls the value of `lisp-interaction-mode-hook'
db174434
CY
533if that value is non-nil."
534 :abbrev-table nil)
d6a3febd
MR
535
536(defun eval-print-last-sexp ()
537 "Evaluate sexp before point; print value into current buffer.
538
539If `eval-expression-debug-on-error' is non-nil, which is the default,
540this command arranges for all errors to enter the debugger.
541
542Note that printing the result is controlled by the variables
543`eval-expression-print-length' and `eval-expression-print-level',
544which see."
545 (interactive)
546 (let ((standard-output (current-buffer)))
547 (terpri)
548 (eval-last-sexp t)
549 (terpri)))
550
551
552(defun last-sexp-setup-props (beg end value alt1 alt2)
553 "Set up text properties for the output of `eval-last-sexp-1'.
554BEG and END are the start and end of the output in current-buffer.
555VALUE is the Lisp value printed, ALT1 and ALT2 are strings for the
556alternative 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)))))
569
570
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)))))))
593
594(defun prin1-char (char)
595 "Return a string representing CHAR as a character rather than as an integer.
596If 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
612 "?"
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-?")
621 (t
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))))
629
630
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)))
650
7346a407
CY
651 ;; Skip over hash table read syntax.
652 (and (> (point) (1+ (point-min)))
653 (looking-back "#s" (- (point) 2))
654 (forward-char -2))
655
d6a3febd
MR
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))))
664
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)))))
687
688
689(defun eval-last-sexp-1 (eval-last-sexp-arg-internal)
690 "Evaluate sexp before point; print value in minibuffer.
691With argument, print output into current buffer."
a0ee6f27 692 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
b9598260 693 ;; Setup the lexical environment if lexical-binding is enabled.
06788a55
SM
694 (eval-last-sexp-print-value
695 (eval (eval-sexp-add-defvars (preceding-sexp)) lexical-binding))))
d6a3febd
MR
696
697
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 ))))
719
720
721(defvar eval-last-sexp-fake-value (make-symbol "t"))
722
06788a55
SM
723(defun eval-sexp-add-defvars (exp &optional pos)
724 "Prepend EXP with all the `defvar's that precede it in the buffer.
725POS specifies the starting position where EXP was found and defaults to point."
726 (if (not lexical-binding)
727 exp
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)))))
7200d79c 739
d6a3febd
MR
740(defun eval-last-sexp (eval-last-sexp-arg-internal)
741 "Evaluate sexp before point; print value in minibuffer.
742Interactively, with prefix argument, print output into current buffer.
16ac2e61
GM
743Truncates long output according to the value of the variables
744`eval-expression-print-length' and `eval-expression-print-level'.
d6a3febd
MR
745
746If `eval-expression-debug-on-error' is non-nil, which is the default,
747this 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))))
758
759(defun eval-defun-1 (form)
760 "Treat some expressions specially.
761Reset the `defvar' and `defcustom' variables to the initial value.
762Reinitialize the face according to the `defface' specification."
763 ;; The code in edebug-defun should be consistent with this, but not
53964682 764 ;; the same, since this gets a macroexpanded form.
d6a3febd
MR
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)
a0ee6f27 776 (default-boundp (eval (nth 1 form) lexical-binding)))
d6a3febd 777 ;; Force variable to be bound.
a0ee6f27 778 (set-default (eval (nth 1 form) lexical-binding)
6125983e
AS
779 ;; The value may be quoted with quote or backquote.
780 (eval (eval (nth 2 form) lexical-binding)
781 lexical-binding))
d6a3febd
MR
782 form)
783 ;; `defface' is macroexpanded to `custom-declare-face'.
784 ((eq (car form) 'custom-declare-face)
785 ;; Reset the face.
f4f73198
LMI
786 (let ((face-symbol (eval (nth 1 form) lexical-binding)))
787 (setq face-new-frame-defaults
788 (assq-delete-all face-symbol face-new-frame-defaults))
789 (put face-symbol 'face-defface-spec nil)
790 (put face-symbol 'face-documentation (nth 3 form))
791 ;; Setting `customized-face' to the new spec after calling
792 ;; the form, but preserving the old saved spec in `saved-face',
793 ;; imitates the situation when the new face spec is set
794 ;; temporarily for the current session in the customize
795 ;; buffer, thus allowing `face-user-default-spec' to use the
796 ;; new customized spec instead of the saved spec.
797 ;; Resetting `saved-face' temporarily to nil is needed to let
798 ;; `defface' change the spec, regardless of a saved spec.
799 (prog1 `(prog1 ,form
800 (put ,(nth 1 form) 'saved-face
801 ',(get face-symbol 'saved-face))
802 (put ,(nth 1 form) 'customized-face
803 ,(nth 2 form)))
804 (put face-symbol 'saved-face nil))))
d6a3febd
MR
805 ((eq (car form) 'progn)
806 (cons 'progn (mapcar 'eval-defun-1 (cdr form))))
807 (t form)))
808
809(defun eval-defun-2 ()
810 "Evaluate defun that point is in or before.
811The value is displayed in the minibuffer.
812If the current defun is actually a call to `defvar',
813then reset the variable using the initial value expression
814even if the variable already has some other value.
815\(Normally `defvar' does not change the variable's value
816if it already has a value.\)
817
818With argument, insert value in current buffer after the defun.
819Return the result of evaluation."
820 (interactive "P")
821 ;; FIXME: the print-length/level bindings should only be applied while
822 ;; printing, not while evaluating.
823 (let ((debug-on-error eval-expression-debug-on-error)
824 (print-length eval-expression-print-length)
825 (print-level eval-expression-print-level))
826 (save-excursion
827 ;; Arrange for eval-region to "read" the (possibly) altered form.
828 ;; eval-region handles recording which file defines a function or
829 ;; variable. Re-written using `apply' to avoid capturing
830 ;; variables like `end'.
831 (apply
832 #'eval-region
833 (let ((standard-output t)
834 beg end form)
835 ;; Read the form from the buffer, and record where it ends.
836 (save-excursion
837 (end-of-defun)
838 (beginning-of-defun)
839 (setq beg (point))
e4d4f539 840 (setq form (read (current-buffer)))
d6a3febd
MR
841 (setq end (point)))
842 ;; Alter the form if necessary.
e4d4f539 843 (setq form (eval-sexp-add-defvars (eval-defun-1 (macroexpand form))))
d6a3febd
MR
844 (list beg end standard-output
845 `(lambda (ignore)
846 ;; Skipping to the end of the specified region
847 ;; will make eval-region return.
848 (goto-char ,end)
849 ',form))))))
850 ;; The result of evaluation has been put onto VALUES. So return it.
851 (car values))
852
853(defun eval-defun (edebug-it)
854 "Evaluate the top-level form containing point, or after point.
855
856If the current defun is actually a call to `defvar' or `defcustom',
857evaluating it this way resets the variable using its initial value
858expression even if the variable already has some other value.
859\(Normally `defvar' and `defcustom' do not alter the value if there
860already is one.) In an analogous way, evaluating a `defface'
861overrides any customizations of the face, so that it becomes
862defined exactly as the `defface' expression says.
863
864If `eval-expression-debug-on-error' is non-nil, which is the default,
865this command arranges for all errors to enter the debugger.
866
867With a prefix argument, instrument the code for Edebug.
868
869If acting on a `defun' for FUNCTION, and the function was
870instrumented, `Edebug: FUNCTION' is printed in the minibuffer. If not
871instrumented, just FUNCTION is printed.
872
873If not acting on a `defun', the result of evaluation is displayed in
874the minibuffer. This display is controlled by the variables
875`eval-expression-print-length' and `eval-expression-print-level',
876which see."
877 (interactive "P")
878 (cond (edebug-it
879 (require 'edebug)
880 (eval-defun (not edebug-all-defs)))
881 (t
882 (if (null eval-expression-debug-on-error)
883 (eval-defun-2)
884 (let ((old-value (make-symbol "t")) new-value value)
885 (let ((debug-on-error old-value))
886 (setq value (eval-defun-2))
887 (setq new-value debug-on-error))
888 (unless (eq old-value new-value)
889 (setq debug-on-error new-value))
890 value)))))
891
892;; May still be used by some external Lisp-mode variant.
893(define-obsolete-function-alias 'lisp-comment-indent
894 'comment-indent-default "22.1")
895(define-obsolete-function-alias 'lisp-mode-auto-fill 'do-auto-fill "23.1")
896
897(defcustom lisp-indent-offset nil
898 "If non-nil, indent second line of expressions that many more columns."
899 :group 'lisp
900 :type '(choice (const nil) integer))
3fde45af 901(put 'lisp-indent-offset 'safe-local-variable
d6a3febd
MR
902 (lambda (x) (or (null x) (integerp x))))
903
3fde45af 904(defcustom lisp-indent-function 'lisp-indent-function
c4ea8f00
GM
905 "A function to be called by `calculate-lisp-indent'.
906It indents the arguments of a Lisp function call. This function
907should accept two arguments: the indent-point, and the
908`parse-partial-sexp' state at that position. One option for this
3fde45af
GM
909function is `common-lisp-indent-function'."
910 :type 'function
911 :group 'lisp)
d6a3febd
MR
912
913(defun lisp-indent-line (&optional whole-exp)
914 "Indent current line as Lisp code.
915With argument, indent any additional lines of the same expression
916rigidly along with this one."
917 (interactive "P")
918 (let ((indent (calculate-lisp-indent)) shift-amt end
919 (pos (- (point-max) (point)))
920 (beg (progn (beginning-of-line) (point))))
921 (skip-chars-forward " \t")
922 (if (or (null indent) (looking-at "\\s<\\s<\\s<"))
923 ;; Don't alter indentation of a ;;; comment line
924 ;; or a line that starts in a string.
925 (goto-char (- (point-max) pos))
926 (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
927 ;; Single-semicolon comment lines should be indented
928 ;; as comment lines, not as code.
929 (progn (indent-for-comment) (forward-char -1))
930 (if (listp indent) (setq indent (car indent)))
931 (setq shift-amt (- indent (current-column)))
932 (if (zerop shift-amt)
933 nil
934 (delete-region beg (point))
935 (indent-to indent)))
936 ;; If initial point was within line's indentation,
937 ;; position after the indentation. Else stay at same point in text.
938 (if (> (- (point-max) pos) (point))
939 (goto-char (- (point-max) pos)))
940 ;; If desired, shift remaining lines of expression the same amount.
941 (and whole-exp (not (zerop shift-amt))
942 (save-excursion
943 (goto-char beg)
944 (forward-sexp 1)
945 (setq end (point))
946 (goto-char beg)
947 (forward-line 1)
948 (setq beg (point))
949 (> end beg))
950 (indent-code-rigidly beg end shift-amt)))))
951
952(defvar calculate-lisp-indent-last-sexp)
953
954(defun calculate-lisp-indent (&optional parse-start)
955 "Return appropriate indentation for current line as Lisp code.
956In usual case returns an integer: the column to indent to.
957If the value is nil, that means don't change the indentation
958because the line starts inside a string.
959
960The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
961This means that following lines at the same level of indentation
962should not necessarily be indented the same as this line.
963Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
964is the buffer position of the start of the containing expression."
965 (save-excursion
966 (beginning-of-line)
967 (let ((indent-point (point))
968 state paren-depth
969 ;; setting this to a number inhibits calling hook
970 (desired-indent nil)
971 (retry t)
972 calculate-lisp-indent-last-sexp containing-sexp)
973 (if parse-start
974 (goto-char parse-start)
975 (beginning-of-defun))
976 ;; Find outermost containing sexp
977 (while (< (point) indent-point)
978 (setq state (parse-partial-sexp (point) indent-point 0)))
979 ;; Find innermost containing sexp
980 (while (and retry
981 state
982 (> (setq paren-depth (elt state 0)) 0))
983 (setq retry nil)
984 (setq calculate-lisp-indent-last-sexp (elt state 2))
985 (setq containing-sexp (elt state 1))
986 ;; Position following last unclosed open.
987 (goto-char (1+ containing-sexp))
988 ;; Is there a complete sexp since then?
989 (if (and calculate-lisp-indent-last-sexp
990 (> calculate-lisp-indent-last-sexp (point)))
991 ;; Yes, but is there a containing sexp after that?
992 (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
993 indent-point 0)))
994 (if (setq retry (car (cdr peek))) (setq state peek)))))
995 (if retry
996 nil
997 ;; Innermost containing sexp found
998 (goto-char (1+ containing-sexp))
999 (if (not calculate-lisp-indent-last-sexp)
1000 ;; indent-point immediately follows open paren.
1001 ;; Don't call hook.
1002 (setq desired-indent (current-column))
1003 ;; Find the start of first element of containing sexp.
1004 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1005 (cond ((looking-at "\\s(")
1006 ;; First element of containing sexp is a list.
1007 ;; Indent under that list.
1008 )
1009 ((> (save-excursion (forward-line 1) (point))
1010 calculate-lisp-indent-last-sexp)
1011 ;; This is the first line to start within the containing sexp.
1012 ;; It's almost certainly a function call.
1013 (if (= (point) calculate-lisp-indent-last-sexp)
1014 ;; Containing sexp has nothing before this line
1015 ;; except the first element. Indent under that element.
1016 nil
1017 ;; Skip the first element, find start of second (the first
1018 ;; argument of the function call) and indent under.
1019 (progn (forward-sexp 1)
1020 (parse-partial-sexp (point)
1021 calculate-lisp-indent-last-sexp
1022 0 t)))
1023 (backward-prefix-chars))
1024 (t
1025 ;; Indent beneath first sexp on same line as
1026 ;; `calculate-lisp-indent-last-sexp'. Again, it's
1027 ;; almost certainly a function call.
1028 (goto-char calculate-lisp-indent-last-sexp)
1029 (beginning-of-line)
1030 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
1031 0 t)
1032 (backward-prefix-chars)))))
1033 ;; Point is at the point to indent under unless we are inside a string.
1034 ;; Call indentation hook except when overridden by lisp-indent-offset
1035 ;; or if the desired indentation has already been computed.
1036 (let ((normal-indent (current-column)))
1037 (cond ((elt state 3)
1038 ;; Inside a string, don't change indentation.
1039 nil)
1040 ((and (integerp lisp-indent-offset) containing-sexp)
1041 ;; Indent by constant offset
1042 (goto-char containing-sexp)
1043 (+ (current-column) lisp-indent-offset))
1044 ;; in this case calculate-lisp-indent-last-sexp is not nil
1045 (calculate-lisp-indent-last-sexp
1046 (or
1047 ;; try to align the parameters of a known function
1048 (and lisp-indent-function
1049 (not retry)
1050 (funcall lisp-indent-function indent-point state))
1051 ;; If the function has no special alignment
1052 ;; or it does not apply to this argument,
1053 ;; try to align a constant-symbol under the last
1054 ;; preceding constant symbol, if there is such one of
1055 ;; the last 2 preceding symbols, in the previous
1056 ;; uncommented line.
1057 (and (save-excursion
1058 (goto-char indent-point)
1059 (skip-chars-forward " \t")
1060 (looking-at ":"))
1061 ;; The last sexp may not be at the indentation
1062 ;; where it begins, so find that one, instead.
1063 (save-excursion
1064 (goto-char calculate-lisp-indent-last-sexp)
1065 ;; Handle prefix characters and whitespace
1066 ;; following an open paren. (Bug#1012)
1067 (backward-prefix-chars)
1068 (while (and (not (looking-back "^[ \t]*\\|([ \t]+"))
1069 (or (not containing-sexp)
1070 (< (1+ containing-sexp) (point))))
1071 (forward-sexp -1)
1072 (backward-prefix-chars))
1073 (setq calculate-lisp-indent-last-sexp (point)))
1074 (> calculate-lisp-indent-last-sexp
1075 (save-excursion
1076 (goto-char (1+ containing-sexp))
1077 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1078 (point)))
1079 (let ((parse-sexp-ignore-comments t)
1080 indent)
1081 (goto-char calculate-lisp-indent-last-sexp)
1082 (or (and (looking-at ":")
1083 (setq indent (current-column)))
5ed619e0 1084 (and (< (line-beginning-position)
d6a3febd
MR
1085 (prog2 (backward-sexp) (point)))
1086 (looking-at ":")
1087 (setq indent (current-column))))
1088 indent))
1089 ;; another symbols or constants not preceded by a constant
1090 ;; as defined above.
1091 normal-indent))
1092 ;; in this case calculate-lisp-indent-last-sexp is nil
1093 (desired-indent)
1094 (t
1095 normal-indent))))))
1096
1097(defun lisp-indent-function (indent-point state)
1098 "This function is the normal value of the variable `lisp-indent-function'.
b7556719
GM
1099The function `calculate-lisp-indent' calls this to determine
1100if the arguments of a Lisp function call should be indented specially.
d6a3febd
MR
1101
1102INDENT-POINT is the position where the user typed TAB, or equivalent.
1103Point is located at the point to indent under (for default indentation);
1104STATE is the `parse-partial-sexp' state for that position.
1105
b7556719
GM
1106If the current line is in a call to a Lisp function that has a non-nil
1107property `lisp-indent-function' (or the deprecated `lisp-indent-hook'),
1108it specifies how to indent. The property value can be:
1109
1110* `defun', meaning indent `defun'-style
1111 \(this is also the case if there is no property and the function
1112 has a name that begins with \"def\", and three or more arguments);
1113
d6a3febd 1114* an integer N, meaning indent the first N arguments specially
b7556719 1115 (like ordinary function arguments), and then indent any further
d6a3febd 1116 arguments like a body;
d6a3febd 1117
b7556719
GM
1118* a function to call that returns the indentation (or nil).
1119 `lisp-indent-function' calls this function with the same two arguments
1120 that it itself received.
1121
1122This function returns either the indentation to use, or nil if the
1123Lisp function does not specify a special indentation."
d6a3febd
MR
1124 (let ((normal-indent (current-column)))
1125 (goto-char (1+ (elt state 1)))
1126 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
1127 (if (and (elt state 2)
1128 (not (looking-at "\\sw\\|\\s_")))
1129 ;; car of form doesn't seem to be a symbol
1130 (progn
1131 (if (not (> (save-excursion (forward-line 1) (point))
1132 calculate-lisp-indent-last-sexp))
1133 (progn (goto-char calculate-lisp-indent-last-sexp)
1134 (beginning-of-line)
1135 (parse-partial-sexp (point)
1136 calculate-lisp-indent-last-sexp 0 t)))
1137 ;; Indent under the list or under the first sexp on the same
1138 ;; line as calculate-lisp-indent-last-sexp. Note that first
1139 ;; thing on that line has to be complete sexp since we are
1140 ;; inside the innermost containing sexp.
1141 (backward-prefix-chars)
1142 (current-column))
1143 (let ((function (buffer-substring (point)
1144 (progn (forward-sexp 1) (point))))
1145 method)
7abaf5cc
SM
1146 (setq method (or (function-get (intern-soft function)
1147 'lisp-indent-function)
d6a3febd
MR
1148 (get (intern-soft function) 'lisp-indent-hook)))
1149 (cond ((or (eq method 'defun)
1150 (and (null method)
1151 (> (length function) 3)
1152 (string-match "\\`def" function)))
1153 (lisp-indent-defform state indent-point))
1154 ((integerp method)
1155 (lisp-indent-specform method state
1156 indent-point normal-indent))
1157 (method
1158 (funcall method indent-point state)))))))
1159
1160(defcustom lisp-body-indent 2
1161 "Number of columns to indent the second line of a `(def...)' form."
1162 :group 'lisp
1163 :type 'integer)
1164(put 'lisp-body-indent 'safe-local-variable 'integerp)
1165
1166(defun lisp-indent-specform (count state indent-point normal-indent)
1167 (let ((containing-form-start (elt state 1))
1168 (i count)
1169 body-indent containing-form-column)
1170 ;; Move to the start of containing form, calculate indentation
1171 ;; to use for non-distinguished forms (> count), and move past the
1172 ;; function symbol. lisp-indent-function guarantees that there is at
1173 ;; least one word or symbol character following open paren of containing
1174 ;; form.
1175 (goto-char containing-form-start)
1176 (setq containing-form-column (current-column))
1177 (setq body-indent (+ lisp-body-indent containing-form-column))
1178 (forward-char 1)
1179 (forward-sexp 1)
1180 ;; Now find the start of the last form.
1181 (parse-partial-sexp (point) indent-point 1 t)
1182 (while (and (< (point) indent-point)
1183 (condition-case ()
1184 (progn
1185 (setq count (1- count))
1186 (forward-sexp 1)
1187 (parse-partial-sexp (point) indent-point 1 t))
1188 (error nil))))
1189 ;; Point is sitting on first character of last (or count) sexp.
1190 (if (> count 0)
1191 ;; A distinguished form. If it is the first or second form use double
1192 ;; lisp-body-indent, else normal indent. With lisp-body-indent bound
1193 ;; to 2 (the default), this just happens to work the same with if as
1194 ;; the older code, but it makes unwind-protect, condition-case,
1195 ;; with-output-to-temp-buffer, et. al. much more tasteful. The older,
1196 ;; less hacked, behavior can be obtained by replacing below with
1197 ;; (list normal-indent containing-form-start).
1198 (if (<= (- i count) 1)
1199 (list (+ containing-form-column (* 2 lisp-body-indent))
1200 containing-form-start)
1201 (list normal-indent containing-form-start))
1202 ;; A non-distinguished form. Use body-indent if there are no
1203 ;; distinguished forms and this is the first undistinguished form,
1204 ;; or if this is the first undistinguished form and the preceding
1205 ;; distinguished form has indentation at least as great as body-indent.
1206 (if (or (and (= i 0) (= count 0))
1207 (and (= count 0) (<= body-indent normal-indent)))
1208 body-indent
1209 normal-indent))))
1210
1211(defun lisp-indent-defform (state indent-point)
1212 (goto-char (car (cdr state)))
1213 (forward-line 1)
1214 (if (> (point) (car (cdr (cdr state))))
1215 (progn
1216 (goto-char (car (cdr state)))
1217 (+ lisp-body-indent (current-column)))))
1218
1219
1220;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
1221;; like defun if the first form is placed on the next line, otherwise
1222;; it is indented like any other form (i.e. forms line up under first).
1223
d6a3febd
MR
1224(put 'autoload 'lisp-indent-function 'defun)
1225(put 'progn 'lisp-indent-function 0)
1226(put 'prog1 'lisp-indent-function 1)
1227(put 'prog2 'lisp-indent-function 2)
1228(put 'save-excursion 'lisp-indent-function 0)
d6a3febd
MR
1229(put 'save-restriction 'lisp-indent-function 0)
1230(put 'save-match-data 'lisp-indent-function 0)
1231(put 'save-current-buffer 'lisp-indent-function 0)
d6a3febd
MR
1232(put 'let 'lisp-indent-function 1)
1233(put 'let* 'lisp-indent-function 1)
1234(put 'while 'lisp-indent-function 1)
1235(put 'if 'lisp-indent-function 2)
d6a3febd
MR
1236(put 'catch 'lisp-indent-function 1)
1237(put 'condition-case 'lisp-indent-function 2)
1238(put 'unwind-protect 'lisp-indent-function 1)
1239(put 'with-output-to-temp-buffer 'lisp-indent-function 1)
d6a3febd
MR
1240
1241(defun indent-sexp (&optional endpos)
1242 "Indent each line of the list starting just after point.
1243If optional arg ENDPOS is given, indent each line, stopping when
1244ENDPOS is encountered."
1245 (interactive)
1246 (let ((indent-stack (list nil))
1247 (next-depth 0)
1248 ;; If ENDPOS is non-nil, use nil as STARTING-POINT
1249 ;; so that calculate-lisp-indent will find the beginning of
1250 ;; the defun we are in.
1251 ;; If ENDPOS is nil, it is safe not to scan before point
1252 ;; since every line we indent is more deeply nested than point is.
1253 (starting-point (if endpos nil (point)))
1254 (last-point (point))
1255 last-depth bol outer-loop-done inner-loop-done state this-indent)
1256 (or endpos
1257 ;; Get error now if we don't have a complete sexp after point.
1258 (save-excursion (forward-sexp 1)))
1259 (save-excursion
1260 (setq outer-loop-done nil)
1261 (while (if endpos (< (point) endpos)
1262 (not outer-loop-done))
1263 (setq last-depth next-depth
1264 inner-loop-done nil)
1265 ;; Parse this line so we can learn the state
1266 ;; to indent the next line.
1267 ;; This inner loop goes through only once
1268 ;; unless a line ends inside a string.
1269 (while (and (not inner-loop-done)
1270 (not (setq outer-loop-done (eobp))))
1271 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
1272 nil nil state))
1273 (setq next-depth (car state))
1274 ;; If the line contains a comment other than the sort
1275 ;; that is indented like code,
1276 ;; indent it now with indent-for-comment.
1277 ;; Comments indented like code are right already.
1278 ;; In any case clear the in-comment flag in the state
1279 ;; because parse-partial-sexp never sees the newlines.
1280 (if (car (nthcdr 4 state))
1281 (progn (indent-for-comment)
1282 (end-of-line)
1283 (setcar (nthcdr 4 state) nil)))
1284 ;; If this line ends inside a string,
1285 ;; go straight to next line, remaining within the inner loop,
1286 ;; and turn off the \-flag.
1287 (if (car (nthcdr 3 state))
1288 (progn
1289 (forward-line 1)
1290 (setcar (nthcdr 5 state) nil))
1291 (setq inner-loop-done t)))
1292 (and endpos
1293 (<= next-depth 0)
1294 (progn
1295 (setq indent-stack (nconc indent-stack
1296 (make-list (- next-depth) nil))
1297 last-depth (- last-depth next-depth)
1298 next-depth 0)))
1299 (forward-line 1)
1300 ;; Decide whether to exit.
1301 (if endpos
1302 ;; If we have already reached the specified end,
1303 ;; give up and do not reindent this line.
1304 (if (<= endpos (point))
1305 (setq outer-loop-done t))
1306 ;; If no specified end, we are done if we have finished one sexp.
1307 (if (<= next-depth 0)
1308 (setq outer-loop-done t)))
1309 (unless outer-loop-done
1310 (while (> last-depth next-depth)
1311 (setq indent-stack (cdr indent-stack)
1312 last-depth (1- last-depth)))
1313 (while (< last-depth next-depth)
1314 (setq indent-stack (cons nil indent-stack)
1315 last-depth (1+ last-depth)))
1316 ;; Now indent the next line according
1317 ;; to what we learned from parsing the previous one.
1318 (setq bol (point))
1319 (skip-chars-forward " \t")
1320 ;; But not if the line is blank, or just a comment
1321 ;; (except for double-semi comments; indent them as usual).
1322 (if (or (eobp) (looking-at "\\s<\\|\n"))
1323 nil
1324 (if (and (car indent-stack)
1325 (>= (car indent-stack) 0))
1326 (setq this-indent (car indent-stack))
1327 (let ((val (calculate-lisp-indent
1328 (if (car indent-stack) (- (car indent-stack))
1329 starting-point))))
1330 (if (null val)
1331 (setq this-indent val)
1332 (if (integerp val)
1333 (setcar indent-stack
1334 (setq this-indent val))
1335 (setcar indent-stack (- (car (cdr val))))
1336 (setq this-indent (car val))))))
1337 (if (and this-indent (/= (current-column) this-indent))
1338 (progn (delete-region bol (point))
1339 (indent-to this-indent)))))
1340 (or outer-loop-done
1341 (setq outer-loop-done (= (point) last-point))
1342 (setq last-point (point)))))))
1343
d6a3febd
MR
1344(defun indent-pp-sexp (&optional arg)
1345 "Indent each line of the list starting just after point, or prettyprint it.
1346A prefix argument specifies pretty-printing."
1347 (interactive "P")
1348 (if arg
1349 (save-excursion
1350 (save-restriction
1351 (narrow-to-region (point) (progn (forward-sexp 1) (point)))
1352 (pp-buffer)
1353 (goto-char (point-max))
1354 (if (eq (char-before) ?\n)
1355 (delete-char -1)))))
1356 (indent-sexp))
1357
1358;;;; Lisp paragraph filling commands.
1359
1360(defcustom emacs-lisp-docstring-fill-column 65
1361 "Value of `fill-column' to use when filling a docstring.
1362Any non-integer value means do not use a different value of
1363`fill-column' when filling docstrings."
1364 :type '(choice (integer)
1365 (const :tag "Use the current `fill-column'" t))
1366 :group 'lisp)
1367
1368(defun lisp-fill-paragraph (&optional justify)
1369 "Like \\[fill-paragraph], but handle Emacs Lisp comments and docstrings.
1370If any of the current line is a comment, fill the comment or the
1371paragraph of it that point is in, preserving the comment's indentation
1372and initial semicolons."
1373 (interactive "P")
1374 (or (fill-comment-paragraph justify)
1375 ;; Since fill-comment-paragraph returned nil, that means we're not in
1376 ;; a comment: Point is on a program line; we are interested
1377 ;; particularly in docstring lines.
1378 ;;
1379 ;; We bind `paragraph-start' and `paragraph-separate' temporarily. They
1380 ;; are buffer-local, but we avoid changing them so that they can be set
1381 ;; to make `forward-paragraph' and friends do something the user wants.
1382 ;;
1383 ;; `paragraph-start': The `(' in the character alternative and the
1384 ;; left-singlequote plus `(' sequence after the \\| alternative prevent
1385 ;; sexps and backquoted sexps that follow a docstring from being filled
1386 ;; with the docstring. This setting has the consequence of inhibiting
1387 ;; filling many program lines that are not docstrings, which is sensible,
1388 ;; because the user probably asked to fill program lines by accident, or
1389 ;; expecting indentation (perhaps we should try to do indenting in that
1390 ;; case). The `;' and `:' stop the paragraph being filled at following
1391 ;; comment lines and at keywords (e.g., in `defcustom'). Left parens are
1392 ;; escaped to keep font-locking, filling, & paren matching in the source
1393 ;; file happy.
1394 ;;
1395 ;; `paragraph-separate': A clever regexp distinguishes the first line of
1396 ;; a docstring and identifies it as a paragraph separator, so that it
1397 ;; won't be filled. (Since the first line of documentation stands alone
1398 ;; in some contexts, filling should not alter the contents the author has
1399 ;; chosen.) Only the first line of a docstring begins with whitespace
1400 ;; and a quotation mark and ends with a period or (rarely) a comma.
1401 ;;
1402 ;; The `fill-column' is temporarily bound to
1403 ;; `emacs-lisp-docstring-fill-column' if that value is an integer.
1404 (let ((paragraph-start (concat paragraph-start
1405 "\\|\\s-*\\([(;:\"]\\|`(\\|#'(\\)"))
1406 (paragraph-separate
1407 (concat paragraph-separate "\\|\\s-*\".*[,\\.]$"))
1408 (fill-column (if (and (integerp emacs-lisp-docstring-fill-column)
1409 (derived-mode-p 'emacs-lisp-mode))
1410 emacs-lisp-docstring-fill-column
1411 fill-column)))
1412 (fill-paragraph justify))
1413 ;; Never return nil.
1414 t))
1415
1416(defun indent-code-rigidly (start end arg &optional nochange-regexp)
1417 "Indent all lines of code, starting in the region, sideways by ARG columns.
1418Does not affect lines starting inside comments or strings, assuming that
1419the start of the region is not inside them.
1420
1421Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1422The last is a regexp which, if matched at the beginning of a line,
1423means don't indent that line."
1424 (interactive "r\np")
1425 (let (state)
1426 (save-excursion
1427 (goto-char end)
1428 (setq end (point-marker))
1429 (goto-char start)
1430 (or (bolp)
1431 (setq state (parse-partial-sexp (point)
1432 (progn
1433 (forward-line 1) (point))
1434 nil nil state)))
1435 (while (< (point) end)
1436 (or (car (nthcdr 3 state))
1437 (and nochange-regexp
1438 (looking-at nochange-regexp))
1439 ;; If line does not start in string, indent it
1440 (let ((indent (current-indentation)))
1441 (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1442 (or (eolp)
1443 (indent-to (max 0 (+ indent arg)) 0))))
1444 (setq state (parse-partial-sexp (point)
1445 (progn
1446 (forward-line 1) (point))
1447 nil nil state))))))
1448
1449(provide 'lisp-mode)
1450
d6a3febd 1451;;; lisp-mode.el ends here