(vc-cvs-checkout): Fix bug that broke C-x v ~-style checkouts.
[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, 2000 Free Software Foundation, Inc.
4
5 ;; Maintainer: FSF
6 ;; Keywords: lisp, languages
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; The base major mode for editing Lisp code (used also for Emacs Lisp).
28 ;; This mode is documented in the Emacs manual.
29
30 ;;; Code:
31
32 (defvar lisp-mode-abbrev-table nil)
33
34 (defvar emacs-lisp-mode-syntax-table
35 (let ((table (make-syntax-table)))
36 (let ((i 0))
37 (while (< i ?0)
38 (modify-syntax-entry i "_ " table)
39 (setq i (1+ i)))
40 (setq i (1+ ?9))
41 (while (< i ?A)
42 (modify-syntax-entry i "_ " table)
43 (setq i (1+ i)))
44 (setq i (1+ ?Z))
45 (while (< i ?a)
46 (modify-syntax-entry i "_ " table)
47 (setq i (1+ i)))
48 (setq i (1+ ?z))
49 (while (< i 128)
50 (modify-syntax-entry i "_ " table)
51 (setq i (1+ i)))
52 (modify-syntax-entry ? " " table)
53 (modify-syntax-entry ?\t " " table)
54 (modify-syntax-entry ?\f " " table)
55 (modify-syntax-entry ?\n "> " table)
56 ;; Give CR the same syntax as newline, for selective-display.
57 (modify-syntax-entry ?\^m "> " table)
58 (modify-syntax-entry ?\; "< " table)
59 (modify-syntax-entry ?` "' " table)
60 (modify-syntax-entry ?' "' " table)
61 (modify-syntax-entry ?, "' " table)
62 ;; Used to be singlequote; changed for flonums.
63 (modify-syntax-entry ?. "_ " table)
64 (modify-syntax-entry ?# "' " table)
65 (modify-syntax-entry ?\" "\" " table)
66 (modify-syntax-entry ?\\ "\\ " table)
67 (modify-syntax-entry ?\( "() " table)
68 (modify-syntax-entry ?\) ")( " table)
69 (modify-syntax-entry ?\[ "(] " table)
70 (modify-syntax-entry ?\] ")[ " table))
71 table))
72
73 (defvar lisp-mode-syntax-table
74 (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
75 (modify-syntax-entry ?\[ "_ " table)
76 (modify-syntax-entry ?\] "_ " table)
77 (modify-syntax-entry ?# "' 14bn" table)
78 (modify-syntax-entry ?| "\" 23b" table)
79 table))
80
81 (define-abbrev-table 'lisp-mode-abbrev-table ())
82
83 (defvar lisp-imenu-generic-expression
84 (list
85 (list nil
86 (purecopy "^\\s-*(def\\(un\\*?\\|subst\\|macro\\|advice\\|\
87 ine-skeleton\\|ine-minor-mode\\)\\s-+\\(\\sw\\(\\sw\\|\\s_\\)+\\)") 2)
88 (list (purecopy "Variables")
89 (purecopy "^\\s-*(def\\(var\\|const\\|custom\\)\\s-+\
90 \\(\\sw\\(\\sw\\|\\s_\\)+\\)") 2)
91 (list (purecopy "Types")
92 (purecopy "^\\s-*(def\\(group\\|type\\|struct\\|class\\|\
93 ine-condition\\|ine-widget\\|face\\)\\s-+'?\\(\\sw\\(\\sw\\|\\s_\\)+\\)")
94 2))
95
96 "Imenu generic expression for Lisp mode. See `imenu-generic-expression'.")
97
98 (defun lisp-mode-variables (lisp-syntax)
99 (cond (lisp-syntax
100 (set-syntax-table lisp-mode-syntax-table)))
101 (setq local-abbrev-table lisp-mode-abbrev-table)
102 (make-local-variable 'paragraph-start)
103 (setq paragraph-start (concat page-delimiter "\\|$" ))
104 (make-local-variable 'paragraph-separate)
105 (setq paragraph-separate paragraph-start)
106 (make-local-variable 'paragraph-ignore-fill-prefix)
107 (setq paragraph-ignore-fill-prefix t)
108 (make-local-variable 'fill-paragraph-function)
109 (setq fill-paragraph-function 'lisp-fill-paragraph)
110 ;; Adaptive fill mode gets in the way of auto-fill,
111 ;; and should make no difference for explicit fill
112 ;; because lisp-fill-paragraph should do the job.
113 (make-local-variable 'adaptive-fill-mode)
114 (setq adaptive-fill-mode nil)
115 (make-local-variable 'normal-auto-fill-function)
116 (setq normal-auto-fill-function 'lisp-mode-auto-fill)
117 (make-local-variable 'indent-line-function)
118 (setq indent-line-function 'lisp-indent-line)
119 (make-local-variable 'indent-region-function)
120 (setq indent-region-function 'lisp-indent-region)
121 (make-local-variable 'parse-sexp-ignore-comments)
122 (setq parse-sexp-ignore-comments t)
123 (make-local-variable 'outline-regexp)
124 (setq outline-regexp ";;;;* \\|(")
125 (make-local-variable 'outline-level)
126 (setq outline-level 'lisp-outline-level)
127 (make-local-variable 'comment-start)
128 (setq comment-start ";")
129 (make-local-variable 'comment-start-skip)
130 ;; Look within the line for a ; following an even number of backslashes
131 ;; after either a non-backslash or the line beginning.
132 (setq comment-start-skip "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\);+ *")
133 (make-local-variable 'comment-add)
134 (setq comment-add 1) ;default to `;;' in comment-region
135 (make-local-variable 'comment-column)
136 (setq comment-column 40)
137 (make-local-variable 'comment-indent-function)
138 (setq comment-indent-function 'lisp-comment-indent)
139 (make-local-variable 'imenu-generic-expression)
140 (setq imenu-generic-expression lisp-imenu-generic-expression)
141 (make-local-variable 'multibyte-syntax-as-symbol)
142 (setq multibyte-syntax-as-symbol t)
143 (setq font-lock-defaults
144 '((lisp-font-lock-keywords
145 lisp-font-lock-keywords-1 lisp-font-lock-keywords-2)
146 nil nil (("+-*/.<>=!?$%_&~^:" . "w")) beginning-of-defun
147 (font-lock-mark-block-function . mark-defun))))
148
149 (defun lisp-outline-level ()
150 "Lisp mode `outline-level' function."
151 (if (looking-at "(")
152 1000
153 (looking-at outline-regexp)
154 (- (match-end 0) (match-beginning 0))))
155
156 \f
157 (defvar lisp-mode-shared-map
158 (let ((map (make-sparse-keymap)))
159 (define-key map "\e\C-q" 'indent-sexp)
160 (define-key map "\177" 'backward-delete-char-untabify)
161 map)
162 "Keymap for commands shared by all sorts of Lisp modes.")
163
164 (defvar emacs-lisp-mode-map ()
165 "Keymap for Emacs Lisp mode.
166 All commands in `lisp-mode-shared-map' are inherited by this map.")
167
168 (if emacs-lisp-mode-map
169 ()
170 (let ((map (make-sparse-keymap "Emacs-Lisp")))
171 (setq emacs-lisp-mode-map (make-sparse-keymap))
172 (set-keymap-parent emacs-lisp-mode-map lisp-mode-shared-map)
173 (define-key emacs-lisp-mode-map "\e\t" 'lisp-complete-symbol)
174 (define-key emacs-lisp-mode-map "\e\C-x" 'eval-defun)
175 (define-key emacs-lisp-mode-map [menu-bar] (make-sparse-keymap))
176 (define-key emacs-lisp-mode-map [menu-bar emacs-lisp]
177 (cons "Emacs-Lisp" map))
178 (define-key map [edebug-defun]
179 '("Instrument Function for Debugging" . edebug-defun))
180 (define-key map [byte-recompile]
181 '("Byte-recompile Directory..." . byte-recompile-directory))
182 (define-key map [emacs-byte-compile-and-load]
183 '("Byte-compile And Load" . emacs-lisp-byte-compile-and-load))
184 (define-key map [byte-compile]
185 '("Byte-compile This File" . emacs-lisp-byte-compile))
186 (define-key map [separator-eval] '("--"))
187 (define-key map [eval-buffer] '("Evaluate Buffer" . eval-current-buffer))
188 (define-key map [eval-region] '("Evaluate Region" . eval-region))
189 (define-key map [eval-sexp] '("Evaluate Last S-expression" . eval-last-sexp))
190 (define-key map [separator-format] '("--"))
191 (define-key map [comment-region] '("Comment Out Region" . comment-region))
192 (define-key map [indent-region] '("Indent Region" . indent-region))
193 (define-key map [indent-line] '("Indent Line" . lisp-indent-line))
194 (put 'eval-region 'menu-enable 'mark-active)
195 (put 'comment-region 'menu-enable 'mark-active)
196 (put 'indent-region 'menu-enable 'mark-active)))
197
198 (defun emacs-lisp-byte-compile ()
199 "Byte compile the file containing the current buffer."
200 (interactive)
201 (if buffer-file-name
202 (byte-compile-file buffer-file-name)
203 (error "The buffer must be saved in a file first")))
204
205 (defun emacs-lisp-byte-compile-and-load ()
206 "Byte-compile the current file (if it has changed), then load compiled code."
207 (interactive)
208 (or buffer-file-name
209 (error "The buffer must be saved in a file first"))
210 (require 'bytecomp)
211 ;; Recompile if file or buffer has changed since last compilation.
212 (if (and (buffer-modified-p)
213 (y-or-n-p (format "Save buffer %s first? " (buffer-name))))
214 (save-buffer))
215 (let ((compiled-file-name (byte-compile-dest-file buffer-file-name)))
216 (if (file-newer-than-file-p compiled-file-name buffer-file-name)
217 (load-file compiled-file-name)
218 (byte-compile-file buffer-file-name t))))
219
220 (defcustom emacs-lisp-mode-hook nil
221 "Hook run when entering Emacs Lisp mode."
222 :options '(turn-on-eldoc-mode imenu-add-menubar-index checkdoc-minor-mode)
223 :type 'hook
224 :group 'lisp)
225
226 (defcustom lisp-mode-hook nil
227 "Hook run when entering Lisp mode."
228 :options '(imenu-add-menubar-index)
229 :type 'hook
230 :group 'lisp)
231
232 (defcustom lisp-interaction-mode-hook nil
233 "Hook run when entering Lisp Interaction mode."
234 :options '(turn-on-eldoc-mode)
235 :type 'hook
236 :group 'lisp)
237
238 (define-derived-mode emacs-lisp-mode nil "Emacs-Lisp"
239 "Major mode for editing Lisp code to run in Emacs.
240 Commands:
241 Delete converts tabs to spaces as it moves back.
242 Blank lines separate paragraphs. Semicolons start comments.
243 \\{emacs-lisp-mode-map}
244 Entry to this mode calls the value of `emacs-lisp-mode-hook'
245 if that value is non-nil."
246 (lisp-mode-variables nil)
247 (setq imenu-case-fold-search nil))
248
249 (defvar lisp-mode-map
250 (let ((map (make-sparse-keymap)))
251 (set-keymap-parent map lisp-mode-shared-map)
252 (define-key map "\e\C-x" 'lisp-eval-defun)
253 (define-key map "\C-c\C-z" 'run-lisp)
254 map)
255 "Keymap for ordinary Lisp mode.
256 All commands in `lisp-mode-shared-map' are inherited by this map.")
257
258 (define-derived-mode lisp-mode nil "Lisp"
259 "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
260 Commands:
261 Delete converts tabs to spaces as it moves back.
262 Blank lines separate paragraphs. Semicolons start comments.
263 \\{lisp-mode-map}
264 Note that `run-lisp' may be used either to start an inferior Lisp job
265 or to switch back to an existing one.
266
267 Entry to this mode calls the value of `lisp-mode-hook'
268 if that value is non-nil."
269 (lisp-mode-variables t)
270 (setq imenu-case-fold-search t))
271
272 ;; This will do unless inf-lisp.el is loaded.
273 (defun lisp-eval-defun (&optional and-go)
274 "Send the current defun to the Lisp process made by \\[run-lisp]."
275 (interactive)
276 (error "Process lisp does not exist"))
277
278 (defvar lisp-interaction-mode-map
279 (let ((map (make-sparse-keymap)))
280 (set-keymap-parent map lisp-mode-shared-map)
281 (define-key map "\e\C-x" 'eval-defun)
282 (define-key map "\e\t" 'lisp-complete-symbol)
283 (define-key map "\n" 'eval-print-last-sexp)
284 map)
285 "Keymap for Lisp Interaction mode.
286 All commands in `lisp-mode-shared-map' are inherited by this map.")
287
288 (define-derived-mode lisp-interaction-mode emacs-lisp-mode "Lisp Interaction"
289 "Major mode for typing and evaluating Lisp forms.
290 Like Lisp mode except that \\[eval-print-last-sexp] evals the Lisp expression
291 before point, and prints its value into the buffer, advancing point.
292
293 Commands:
294 Delete converts tabs to spaces as it moves back.
295 Paragraphs are separated only by blank lines.
296 Semicolons start comments.
297 \\{lisp-interaction-mode-map}
298 Entry to this mode calls the value of `lisp-interaction-mode-hook'
299 if that value is non-nil.")
300
301 (defun eval-print-last-sexp ()
302 "Evaluate sexp before point; print value into current buffer."
303 (interactive)
304 (let ((standard-output (current-buffer)))
305 (terpri)
306 (eval-last-sexp t)
307 (terpri)))
308 \f
309 (defun eval-last-sexp-1 (eval-last-sexp-arg-internal)
310 "Evaluate sexp before point; print value in minibuffer.
311 With argument, print output into current buffer."
312 (let ((standard-output (if eval-last-sexp-arg-internal (current-buffer) t)))
313 (let ((value
314 (eval (let ((stab (syntax-table))
315 (opoint (point))
316 ignore-quotes
317 expr)
318 (unwind-protect
319 (save-excursion
320 (set-syntax-table emacs-lisp-mode-syntax-table)
321 ;; If this sexp appears to be enclosed in `...'
322 ;; then ignore the surrounding quotes.
323 (setq ignore-quotes
324 (or (eq (following-char) ?\')
325 (eq (preceding-char) ?\')))
326 (forward-sexp -1)
327 ;; If we were after `?\e' (or similar case),
328 ;; use the whole thing, not just the `e'.
329 (when (eq (preceding-char) ?\\)
330 (forward-char -1)
331 (when (eq (preceding-char) ??)
332 (forward-char -1)))
333
334 ;; Skip over `#N='s.
335 (when (eq (preceding-char) ?=)
336 (let (labeled-p)
337 (save-excursion
338 (skip-chars-backward "0-9#=")
339 (setq labeled-p (looking-at "\\(#[0-9]+=\\)+")))
340 (when labeled-p
341 (forward-sexp -1))))
342
343 (save-restriction
344 ;; vladimir@cs.ualberta.ca 30-Jul-1997: skip ` in
345 ;; `variable' so that the value is returned, not the
346 ;; name
347 (if (and ignore-quotes
348 (eq (following-char) ?`))
349 (forward-char))
350 (narrow-to-region (point-min) opoint)
351 (setq expr (read (current-buffer)))
352 ;; If it's an (interactive ...) form, it's more
353 ;; useful to show how an interactive call would
354 ;; use it.
355 (and (consp expr)
356 (eq (car expr) 'interactive)
357 (setq expr
358 (list 'call-interactively
359 (list 'quote
360 (list 'lambda
361 '(&rest args)
362 expr
363 'args)))))
364 expr))
365 (set-syntax-table stab))))))
366 (let ((print-length eval-expression-print-length)
367 (print-level eval-expression-print-level))
368 (prin1 value)))))
369
370 (defun eval-last-sexp (eval-last-sexp-arg-internal)
371 "Evaluate sexp before point; print value in minibuffer.
372 With argument, print output into current buffer."
373 (interactive "P")
374 (if (null eval-expression-debug-on-error)
375 (eval-last-sexp-1 eval-last-sexp-arg-internal)
376 (let ((old-value (make-symbol "t")) new-value value)
377 (let ((debug-on-error old-value))
378 (setq value (eval-last-sexp-1 eval-last-sexp-arg-internal))
379 (setq new-value debug-on-error))
380 (unless (eq old-value new-value)
381 (setq debug-on-error new-value))
382 value)))
383
384 (defun eval-defun-1 (form)
385 "Change defvar into defconst within FORM.
386 Likewise for other constructs as necessary."
387 ;; The code in edebug-defun should be consistent with this, but not
388 ;; the same, since this gets a macroexpended form.
389 (cond ((and (eq (car form) 'defvar)
390 (cdr-safe (cdr-safe form)))
391 ;; Force variable to be bound.
392 (cons 'defconst (cdr form)))
393 ;; `defcustom' is now macroexpanded to
394 ;; `custom-declare-variable' with a quoted value arg.
395 ((and (eq (car form) 'custom-declare-variable)
396 (default-boundp (eval (nth 1 form))))
397 ;; Force variable to be bound.
398 (set-default (eval (nth 1 form)) (eval (nth 1 (nth 2 form))))
399 form)
400 ((eq (car form) 'progn)
401 (cons 'progn (mapcar 'eval-defun-1 (cdr form))))
402 (t form)))
403
404 (defun eval-defun-2 ()
405 "Evaluate defun that point is in or before.
406 The value is displayed in the minibuffer.
407 If the current defun is actually a call to `defvar',
408 then reset the variable using the initial value expression
409 even if the variable already has some other value.
410 \(Normally `defvar' does not change the variable's value
411 if it already has a value.\)
412
413 With argument, insert value in current buffer after the defun.
414 Return the result of evaluation."
415 (interactive "P")
416 (let ((debug-on-error eval-expression-debug-on-error)
417 (print-length eval-expression-print-length)
418 (print-level eval-expression-print-level))
419 (save-excursion
420 ;; Arrange for eval-region to "read" the (possibly) altered form.
421 ;; eval-region handles recording which file defines a function or
422 ;; variable. Re-written using `apply' to avoid capturing
423 ;; variables like `end'.
424 (apply
425 #'eval-region
426 (let ((standard-output t)
427 beg end form)
428 ;; Read the form from the buffer, and record where it ends.
429 (save-excursion
430 (end-of-defun)
431 (beginning-of-defun)
432 (setq beg (point))
433 (setq form (read (current-buffer)))
434 (setq end (point)))
435 ;; Alter the form if necessary, changing defvar into defconst, etc.
436 (setq form (eval-defun-1 (macroexpand form)))
437 (list beg end standard-output
438 `(lambda (ignore)
439 ;; Skipping to the end of the specified region
440 ;; will make eval-region return.
441 (goto-char ,end)
442 ',form))))))
443 ;; The result of evaluation has been put onto VALUES. So return it.
444 (car values))
445
446 (defun eval-defun (edebug-it)
447 "Evaluate the top-level form containing point, or after point.
448
449 If the current defun is actually a call to `defvar', then reset the
450 variable using its initial value expression even if the variable
451 already has some other value. (Normally `defvar' does not change the
452 variable's value if it already has a value.)
453
454 With a prefix argument, instrument the code for Edebug.
455
456 If acting on a `defun' for FUNCTION, and the function was
457 instrumented, `Edebug: FUNCTION' is printed in the minibuffer. If not
458 instrumented, just FUNCTION is printed.
459
460 If not acting on a `defun', the result of evaluation is displayed in
461 the minibuffer."
462 (interactive "P")
463 (cond (edebug-it
464 (require 'edebug)
465 (eval-defun (not edebug-all-defs)))
466 (t
467 (if (null eval-expression-debug-on-error)
468 (eval-defun-2)
469 (let ((old-value (make-symbol "t")) new-value value)
470 (let ((debug-on-error old-value))
471 (setq value (eval-defun-2))
472 (setq new-value debug-on-error))
473 (unless (eq old-value new-value)
474 (setq debug-on-error new-value))
475 value)))))
476
477 \f
478 (defun lisp-comment-indent ()
479 (if (looking-at "\\s<\\s<\\s<")
480 (current-column)
481 (if (looking-at "\\s<\\s<")
482 (let ((tem (or (calculate-lisp-indent) (current-column))))
483 (if (listp tem) (car tem) tem))
484 (skip-chars-backward " \t")
485 (max (if (bolp) 0 (1+ (current-column)))
486 comment-column))))
487
488 (defun lisp-mode-auto-fill ()
489 (if (> (current-column) (current-fill-column))
490 (if (save-excursion
491 (nth 4 (parse-partial-sexp (save-excursion
492 (beginning-of-defun)
493 (point))
494 (point))))
495 (do-auto-fill)
496 (let ((comment-start nil) (comment-start-skip nil))
497 (do-auto-fill)))))
498
499 (defvar lisp-indent-offset nil)
500 (defvar lisp-indent-function 'lisp-indent-function)
501
502 (defun lisp-indent-line (&optional whole-exp)
503 "Indent current line as Lisp code.
504 With argument, indent any additional lines of the same expression
505 rigidly along with this one."
506 (interactive "P")
507 (let ((indent (calculate-lisp-indent)) shift-amt beg end
508 (pos (- (point-max) (point))))
509 (beginning-of-line)
510 (setq beg (point))
511 (skip-chars-forward " \t")
512 (if (or (null indent) (looking-at "\\s<\\s<\\s<"))
513 ;; Don't alter indentation of a ;;; comment line
514 ;; or a line that starts in a string.
515 (goto-char (- (point-max) pos))
516 (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
517 ;; Single-semicolon comment lines should be indented
518 ;; as comment lines, not as code.
519 (progn (indent-for-comment) (forward-char -1))
520 (if (listp indent) (setq indent (car indent)))
521 (setq shift-amt (- indent (current-column)))
522 (if (zerop shift-amt)
523 nil
524 (delete-region beg (point))
525 (indent-to indent)))
526 ;; If initial point was within line's indentation,
527 ;; position after the indentation. Else stay at same point in text.
528 (if (> (- (point-max) pos) (point))
529 (goto-char (- (point-max) pos)))
530 ;; If desired, shift remaining lines of expression the same amount.
531 (and whole-exp (not (zerop shift-amt))
532 (save-excursion
533 (goto-char beg)
534 (forward-sexp 1)
535 (setq end (point))
536 (goto-char beg)
537 (forward-line 1)
538 (setq beg (point))
539 (> end beg))
540 (indent-code-rigidly beg end shift-amt)))))
541
542 (defvar calculate-lisp-indent-last-sexp)
543
544 (defun calculate-lisp-indent (&optional parse-start)
545 "Return appropriate indentation for current line as Lisp code.
546 In usual case returns an integer: the column to indent to.
547 If the value is nil, that means don't change the indentation
548 because the line starts inside a string.
549
550 The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
551 This means that following lines at the same level of indentation
552 should not necessarily be indented the same as this line.
553 Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
554 is the buffer position of the start of the containing expression."
555 (save-excursion
556 (beginning-of-line)
557 (let ((indent-point (point))
558 state paren-depth
559 ;; setting this to a number inhibits calling hook
560 (desired-indent nil)
561 (retry t)
562 calculate-lisp-indent-last-sexp containing-sexp)
563 (if parse-start
564 (goto-char parse-start)
565 (beginning-of-defun))
566 ;; Find outermost containing sexp
567 (while (< (point) indent-point)
568 (setq state (parse-partial-sexp (point) indent-point 0)))
569 ;; Find innermost containing sexp
570 (while (and retry
571 state
572 (> (setq paren-depth (elt state 0)) 0))
573 (setq retry nil)
574 (setq calculate-lisp-indent-last-sexp (elt state 2))
575 (setq containing-sexp (elt state 1))
576 ;; Position following last unclosed open.
577 (goto-char (1+ containing-sexp))
578 ;; Is there a complete sexp since then?
579 (if (and calculate-lisp-indent-last-sexp
580 (> calculate-lisp-indent-last-sexp (point)))
581 ;; Yes, but is there a containing sexp after that?
582 (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
583 indent-point 0)))
584 (if (setq retry (car (cdr peek))) (setq state peek)))))
585 (if retry
586 nil
587 ;; Innermost containing sexp found
588 (goto-char (1+ containing-sexp))
589 (if (not calculate-lisp-indent-last-sexp)
590 ;; indent-point immediately follows open paren.
591 ;; Don't call hook.
592 (setq desired-indent (current-column))
593 ;; Find the start of first element of containing sexp.
594 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
595 (cond ((looking-at "\\s(")
596 ;; First element of containing sexp is a list.
597 ;; Indent under that list.
598 )
599 ((> (save-excursion (forward-line 1) (point))
600 calculate-lisp-indent-last-sexp)
601 ;; This is the first line to start within the containing sexp.
602 ;; It's almost certainly a function call.
603 (if (= (point) calculate-lisp-indent-last-sexp)
604 ;; Containing sexp has nothing before this line
605 ;; except the first element. Indent under that element.
606 nil
607 ;; Skip the first element, find start of second (the first
608 ;; argument of the function call) and indent under.
609 (progn (forward-sexp 1)
610 (parse-partial-sexp (point)
611 calculate-lisp-indent-last-sexp
612 0 t)))
613 (backward-prefix-chars))
614 (t
615 ;; Indent beneath first sexp on same line as
616 ;; `calculate-lisp-indent-last-sexp'. Again, it's
617 ;; almost certainly a function call.
618 (goto-char calculate-lisp-indent-last-sexp)
619 (beginning-of-line)
620 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
621 0 t)
622 (backward-prefix-chars)))))
623 ;; Point is at the point to indent under unless we are inside a string.
624 ;; Call indentation hook except when overridden by lisp-indent-offset
625 ;; or if the desired indentation has already been computed.
626 (let ((normal-indent (current-column)))
627 (cond ((elt state 3)
628 ;; Inside a string, don't change indentation.
629 nil)
630 ((and (integerp lisp-indent-offset) containing-sexp)
631 ;; Indent by constant offset
632 (goto-char containing-sexp)
633 (+ (current-column) lisp-indent-offset))
634 (desired-indent)
635 ((and (boundp 'lisp-indent-function)
636 lisp-indent-function
637 (not retry))
638 (or (funcall lisp-indent-function indent-point state)
639 normal-indent))
640 (t
641 normal-indent))))))
642
643 (defun lisp-indent-function (indent-point state)
644 (let ((normal-indent (current-column)))
645 (goto-char (1+ (elt state 1)))
646 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
647 (if (and (elt state 2)
648 (not (looking-at "\\sw\\|\\s_")))
649 ;; car of form doesn't seem to be a a symbol
650 (progn
651 (if (not (> (save-excursion (forward-line 1) (point))
652 calculate-lisp-indent-last-sexp))
653 (progn (goto-char calculate-lisp-indent-last-sexp)
654 (beginning-of-line)
655 (parse-partial-sexp (point)
656 calculate-lisp-indent-last-sexp 0 t)))
657 ;; Indent under the list or under the first sexp on the same
658 ;; line as calculate-lisp-indent-last-sexp. Note that first
659 ;; thing on that line has to be complete sexp since we are
660 ;; inside the innermost containing sexp.
661 (backward-prefix-chars)
662 (current-column))
663 (let ((function (buffer-substring (point)
664 (progn (forward-sexp 1) (point))))
665 method)
666 (setq method (or (get (intern-soft function) 'lisp-indent-function)
667 (get (intern-soft function) 'lisp-indent-hook)))
668 (cond ((or (eq method 'defun)
669 (and (null method)
670 (> (length function) 3)
671 (string-match "\\`def" function)))
672 (lisp-indent-defform state indent-point))
673 ((integerp method)
674 (lisp-indent-specform method state
675 indent-point normal-indent))
676 (method
677 (funcall method state indent-point)))))))
678
679 (defvar lisp-body-indent 2
680 "Number of columns to indent the second line of a `(def...)' form.")
681
682 (defun lisp-indent-specform (count state indent-point normal-indent)
683 (let ((containing-form-start (elt state 1))
684 (i count)
685 body-indent containing-form-column)
686 ;; Move to the start of containing form, calculate indentation
687 ;; to use for non-distinguished forms (> count), and move past the
688 ;; function symbol. lisp-indent-function guarantees that there is at
689 ;; least one word or symbol character following open paren of containing
690 ;; form.
691 (goto-char containing-form-start)
692 (setq containing-form-column (current-column))
693 (setq body-indent (+ lisp-body-indent containing-form-column))
694 (forward-char 1)
695 (forward-sexp 1)
696 ;; Now find the start of the last form.
697 (parse-partial-sexp (point) indent-point 1 t)
698 (while (and (< (point) indent-point)
699 (condition-case ()
700 (progn
701 (setq count (1- count))
702 (forward-sexp 1)
703 (parse-partial-sexp (point) indent-point 1 t))
704 (error nil))))
705 ;; Point is sitting on first character of last (or count) sexp.
706 (if (> count 0)
707 ;; A distinguished form. If it is the first or second form use double
708 ;; lisp-body-indent, else normal indent. With lisp-body-indent bound
709 ;; to 2 (the default), this just happens to work the same with if as
710 ;; the older code, but it makes unwind-protect, condition-case,
711 ;; with-output-to-temp-buffer, et. al. much more tasteful. The older,
712 ;; less hacked, behavior can be obtained by replacing below with
713 ;; (list normal-indent containing-form-start).
714 (if (<= (- i count) 1)
715 (list (+ containing-form-column (* 2 lisp-body-indent))
716 containing-form-start)
717 (list normal-indent containing-form-start))
718 ;; A non-distinguished form. Use body-indent if there are no
719 ;; distinguished forms and this is the first undistinguished form,
720 ;; or if this is the first undistinguished form and the preceding
721 ;; distinguished form has indentation at least as great as body-indent.
722 (if (or (and (= i 0) (= count 0))
723 (and (= count 0) (<= body-indent normal-indent)))
724 body-indent
725 normal-indent))))
726
727 (defun lisp-indent-defform (state indent-point)
728 (goto-char (car (cdr state)))
729 (forward-line 1)
730 (if (> (point) (car (cdr (cdr state))))
731 (progn
732 (goto-char (car (cdr state)))
733 (+ lisp-body-indent (current-column)))))
734
735 \f
736 ;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
737 ;; like defun if the first form is placed on the next line, otherwise
738 ;; it is indented like any other form (i.e. forms line up under first).
739
740 (put 'lambda 'lisp-indent-function 'defun)
741 (put 'autoload 'lisp-indent-function 'defun)
742 (put 'progn 'lisp-indent-function 0)
743 (put 'prog1 'lisp-indent-function 1)
744 (put 'prog2 'lisp-indent-function 2)
745 (put 'save-excursion 'lisp-indent-function 0)
746 (put 'save-window-excursion 'lisp-indent-function 0)
747 (put 'save-selected-window 'lisp-indent-function 0)
748 (put 'save-restriction 'lisp-indent-function 0)
749 (put 'save-match-data 'lisp-indent-function 0)
750 (put 'save-current-buffer 'lisp-indent-function 0)
751 (put 'with-current-buffer 'lisp-indent-function 1)
752 (put 'combine-after-change-calls 'lisp-indent-function 0)
753 (put 'with-output-to-string 'lisp-indent-function 0)
754 (put 'with-temp-file 'lisp-indent-function 1)
755 (put 'with-temp-buffer 'lisp-indent-function 0)
756 (put 'with-temp-message 'lisp-indent-function 1)
757 (put 'with-syntax-table 'lisp-indent-function 1)
758 (put 'let 'lisp-indent-function 1)
759 (put 'let* 'lisp-indent-function 1)
760 (put 'while 'lisp-indent-function 1)
761 (put 'if 'lisp-indent-function 2)
762 (put 'catch 'lisp-indent-function 1)
763 (put 'condition-case 'lisp-indent-function 2)
764 (put 'unwind-protect 'lisp-indent-function 1)
765 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
766 (put 'eval-after-load 'lisp-indent-function 1)
767 (put 'dolist 'lisp-indent-function 1)
768 (put 'dotimes 'lisp-indent-function 1)
769 (put 'when 'lisp-indent-function 1)
770 (put 'unless 'lisp-indent-function 1)
771
772 (defun indent-sexp (&optional endpos)
773 "Indent each line of the list starting just after point.
774 If optional arg ENDPOS is given, indent each line, stopping when
775 ENDPOS is encountered."
776 (interactive)
777 (let ((indent-stack (list nil))
778 (next-depth 0)
779 ;; If ENDPOS is non-nil, use nil as STARTING-POINT
780 ;; so that calculate-lisp-indent will find the beginning of
781 ;; the defun we are in.
782 ;; If ENDPOS is nil, it is safe not to scan before point
783 ;; since every line we indent is more deeply nested than point is.
784 (starting-point (if endpos nil (point)))
785 (last-point (point))
786 last-depth bol outer-loop-done inner-loop-done state this-indent)
787 (or endpos
788 ;; Get error now if we don't have a complete sexp after point.
789 (save-excursion (forward-sexp 1)))
790 (save-excursion
791 (setq outer-loop-done nil)
792 (while (if endpos (< (point) endpos)
793 (not outer-loop-done))
794 (setq last-depth next-depth
795 inner-loop-done nil)
796 ;; Parse this line so we can learn the state
797 ;; to indent the next line.
798 ;; This inner loop goes through only once
799 ;; unless a line ends inside a string.
800 (while (and (not inner-loop-done)
801 (not (setq outer-loop-done (eobp))))
802 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
803 nil nil state))
804 (setq next-depth (car state))
805 ;; If the line contains a comment other than the sort
806 ;; that is indented like code,
807 ;; indent it now with indent-for-comment.
808 ;; Comments indented like code are right already.
809 ;; In any case clear the in-comment flag in the state
810 ;; because parse-partial-sexp never sees the newlines.
811 (if (car (nthcdr 4 state))
812 (progn (indent-for-comment)
813 (end-of-line)
814 (setcar (nthcdr 4 state) nil)))
815 ;; If this line ends inside a string,
816 ;; go straight to next line, remaining within the inner loop,
817 ;; and turn off the \-flag.
818 (if (car (nthcdr 3 state))
819 (progn
820 (forward-line 1)
821 (setcar (nthcdr 5 state) nil))
822 (setq inner-loop-done t)))
823 (and endpos
824 (<= next-depth 0)
825 (progn
826 (setq indent-stack (nconc indent-stack
827 (make-list (- next-depth) nil))
828 last-depth (- last-depth next-depth)
829 next-depth 0)))
830 (or outer-loop-done endpos
831 (setq outer-loop-done (<= next-depth 0)))
832 (if outer-loop-done
833 (forward-line 1)
834 (while (> last-depth next-depth)
835 (setq indent-stack (cdr indent-stack)
836 last-depth (1- last-depth)))
837 (while (< last-depth next-depth)
838 (setq indent-stack (cons nil indent-stack)
839 last-depth (1+ last-depth)))
840 ;; Now go to the next line and indent it according
841 ;; to what we learned from parsing the previous one.
842 (forward-line 1)
843 (setq bol (point))
844 (skip-chars-forward " \t")
845 ;; But not if the line is blank, or just a comment
846 ;; (except for double-semi comments; indent them as usual).
847 (if (or (eobp) (looking-at "\\s<\\|\n"))
848 nil
849 (if (and (car indent-stack)
850 (>= (car indent-stack) 0))
851 (setq this-indent (car indent-stack))
852 (let ((val (calculate-lisp-indent
853 (if (car indent-stack) (- (car indent-stack))
854 starting-point))))
855 (if (null val)
856 (setq this-indent val)
857 (if (integerp val)
858 (setcar indent-stack
859 (setq this-indent val))
860 (setcar indent-stack (- (car (cdr val))))
861 (setq this-indent (car val))))))
862 (if (and this-indent (/= (current-column) this-indent))
863 (progn (delete-region bol (point))
864 (indent-to this-indent)))))
865 (or outer-loop-done
866 (setq outer-loop-done (= (point) last-point))
867 (setq last-point (point)))))))
868
869 (defun lisp-indent-region (start end)
870 "Indent every line whose first char is between START and END inclusive."
871 (save-excursion
872 (let ((endmark (copy-marker end)))
873 (goto-char start)
874 (and (bolp) (not (eolp))
875 (lisp-indent-line))
876 (indent-sexp endmark)
877 (set-marker endmark nil))))
878 \f
879 ;;;; Lisp paragraph filling commands.
880
881 (defun lisp-fill-paragraph (&optional justify)
882 "Like \\[fill-paragraph], but handle Emacs Lisp comments.
883 If any of the current line is a comment, fill the comment or the
884 paragraph of it that point is in, preserving the comment's indentation
885 and initial semicolons."
886 (interactive "P")
887 (let (
888 ;; Non-nil if the current line contains a comment.
889 has-comment
890
891 ;; Non-nil if the current line contains code and a comment.
892 has-code-and-comment
893
894 ;; If has-comment, the appropriate fill-prefix for the comment.
895 comment-fill-prefix
896 )
897
898 ;; Figure out what kind of comment we are looking at.
899 (save-excursion
900 (beginning-of-line)
901 (cond
902
903 ;; A line with nothing but a comment on it?
904 ((looking-at "[ \t]*;[; \t]*")
905 (setq has-comment t
906 comment-fill-prefix (buffer-substring (match-beginning 0)
907 (match-end 0))))
908
909 ;; A line with some code, followed by a comment? Remember that the
910 ;; semi which starts the comment shouldn't be part of a string or
911 ;; character.
912 ((condition-case nil
913 (save-restriction
914 (narrow-to-region (point-min)
915 (save-excursion (end-of-line) (point)))
916 (while (not (looking-at ";\\|$"))
917 (skip-chars-forward "^;\n\"\\\\?")
918 (cond
919 ((eq (char-after (point)) ?\\) (forward-char 2))
920 ((memq (char-after (point)) '(?\" ??)) (forward-sexp 1))))
921 (looking-at ";+[\t ]*"))
922 (error nil))
923 (setq has-comment t has-code-and-comment t)
924 (setq comment-fill-prefix
925 (concat (make-string (/ (current-column) 8) ?\t)
926 (make-string (% (current-column) 8) ?\ )
927 (buffer-substring (match-beginning 0) (match-end 0)))))))
928
929 (if (not has-comment)
930 ;; `paragraph-start' is set here (not in the buffer-local
931 ;; variable so that `forward-paragraph' et al work as
932 ;; expected) so that filling (doc) strings works sensibly.
933 ;; Adding the opening paren to avoid the following sexp being
934 ;; filled means that sexps generally aren't filled as normal
935 ;; text, which is probably sensible. The `;' and `:' stop the
936 ;; filled para at following comment lines and keywords
937 ;; (typically in `defcustom').
938 (let ((paragraph-start (concat paragraph-start
939 "\\|\\s-*[\(;:\"]")))
940 (fill-paragraph justify))
941
942 ;; Narrow to include only the comment, and then fill the region.
943 (save-excursion
944 (save-restriction
945 (beginning-of-line)
946 (narrow-to-region
947 ;; Find the first line we should include in the region to fill.
948 (save-excursion
949 (while (and (zerop (forward-line -1))
950 (looking-at "^[ \t]*;")))
951 ;; We may have gone too far. Go forward again.
952 (or (looking-at ".*;")
953 (forward-line 1))
954 (point))
955 ;; Find the beginning of the first line past the region to fill.
956 (save-excursion
957 (while (progn (forward-line 1)
958 (looking-at "^[ \t]*;")))
959 (point)))
960
961 ;; Lines with only semicolons on them can be paragraph boundaries.
962 (let* ((paragraph-start (concat paragraph-start "\\|[ \t;]*$"))
963 (paragraph-separate (concat paragraph-start "\\|[ \t;]*$"))
964 (paragraph-ignore-fill-prefix nil)
965 (fill-prefix comment-fill-prefix)
966 (after-line (if has-code-and-comment
967 (save-excursion
968 (forward-line 1) (point))))
969 (end (progn
970 (forward-paragraph)
971 (or (bolp) (newline 1))
972 (point)))
973 ;; If this comment starts on a line with code,
974 ;; include that like in the filling.
975 (beg (progn (backward-paragraph)
976 (if (eq (point) after-line)
977 (forward-line -1))
978 (point))))
979 (fill-region-as-paragraph beg end
980 justify nil
981 (save-excursion
982 (goto-char beg)
983 (if (looking-at fill-prefix)
984 nil
985 (re-search-forward comment-start-skip)
986 (point))))))))
987 t))
988 \f
989 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
990 "Indent all lines of code, starting in the region, sideways by ARG columns.
991 Does not affect lines starting inside comments or strings, assuming that
992 the start of the region is not inside them.
993
994 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
995 The last is a regexp which, if matched at the beginning of a line,
996 means don't indent that line."
997 (interactive "r\np")
998 (let (state)
999 (save-excursion
1000 (goto-char end)
1001 (setq end (point-marker))
1002 (goto-char start)
1003 (or (bolp)
1004 (setq state (parse-partial-sexp (point)
1005 (progn
1006 (forward-line 1) (point))
1007 nil nil state)))
1008 (while (< (point) end)
1009 (or (car (nthcdr 3 state))
1010 (and nochange-regexp
1011 (looking-at nochange-regexp))
1012 ;; If line does not start in string, indent it
1013 (let ((indent (current-indentation)))
1014 (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1015 (or (eolp)
1016 (indent-to (max 0 (+ indent arg)) 0))))
1017 (setq state (parse-partial-sexp (point)
1018 (progn
1019 (forward-line 1) (point))
1020 nil nil state))))))
1021
1022 (provide 'lisp-mode)
1023
1024 ;;; lisp-mode.el ends here