* lisp/emacs-lisp/lisp-mode.el: Don't highlight \( at BOL
[emacs.git] / lisp / emacs-lisp / lisp-mode.el
blobb7a5eb774da04e2200da200e82bc3774c5f007d3
1 ;;; lisp-mode.el --- Lisp mode, and its idiosyncratic commands -*- lexical-binding:t -*-
3 ;; Copyright (C) 1985-1986, 1999-2017 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: lisp, languages
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; The base major mode for editing Lisp code (used also for Emacs Lisp).
27 ;; This mode is documented in the Emacs manual.
29 ;;; Code:
31 (eval-when-compile (require 'cl-lib))
33 (defvar font-lock-comment-face)
34 (defvar font-lock-doc-face)
35 (defvar font-lock-keywords-case-fold-search)
36 (defvar font-lock-string-face)
38 (define-abbrev-table 'lisp-mode-abbrev-table ()
39 "Abbrev table for Lisp mode.")
41 (defvar lisp--mode-syntax-table
42 (let ((table (make-syntax-table))
43 (i 0))
44 (while (< i ?0)
45 (modify-syntax-entry i "_ " table)
46 (setq i (1+ i)))
47 (setq i (1+ ?9))
48 (while (< i ?A)
49 (modify-syntax-entry i "_ " table)
50 (setq i (1+ i)))
51 (setq i (1+ ?Z))
52 (while (< i ?a)
53 (modify-syntax-entry i "_ " table)
54 (setq i (1+ i)))
55 (setq i (1+ ?z))
56 (while (< i 128)
57 (modify-syntax-entry i "_ " table)
58 (setq i (1+ i)))
59 (modify-syntax-entry ?\s " " table)
60 ;; Non-break space acts as whitespace.
61 (modify-syntax-entry ?\xa0 " " table)
62 (modify-syntax-entry ?\t " " table)
63 (modify-syntax-entry ?\f " " table)
64 (modify-syntax-entry ?\n "> " table)
65 ;; This is probably obsolete since nowadays such features use overlays.
66 ;; ;; Give CR the same syntax as newline, for selective-display.
67 ;; (modify-syntax-entry ?\^m "> " table)
68 (modify-syntax-entry ?\; "< " table)
69 (modify-syntax-entry ?` "' " table)
70 (modify-syntax-entry ?' "' " table)
71 (modify-syntax-entry ?, "' " table)
72 (modify-syntax-entry ?@ "_ p" table)
73 ;; Used to be singlequote; changed for flonums.
74 (modify-syntax-entry ?. "_ " table)
75 (modify-syntax-entry ?# "' " table)
76 (modify-syntax-entry ?\" "\" " table)
77 (modify-syntax-entry ?\\ "\\ " table)
78 (modify-syntax-entry ?\( "() " table)
79 (modify-syntax-entry ?\) ")( " table)
80 table)
81 "Parent syntax table used in Lisp modes.")
83 (defvar lisp-mode-syntax-table
84 (let ((table (make-syntax-table lisp--mode-syntax-table)))
85 (modify-syntax-entry ?\[ "_ " table)
86 (modify-syntax-entry ?\] "_ " table)
87 (modify-syntax-entry ?# "' 14" table)
88 (modify-syntax-entry ?| "\" 23bn" table)
89 table)
90 "Syntax table used in `lisp-mode'.")
92 (eval-and-compile
93 (defconst lisp-mode-symbol-regexp "\\(?:\\sw\\|\\s_\\|\\\\.\\)+"))
95 (defvar lisp-imenu-generic-expression
96 (list
97 (list nil
98 (purecopy (concat "^\\s-*("
99 (eval-when-compile
100 (regexp-opt
101 '("defun" "defmacro"
102 ;; Elisp.
103 "defun*" "defsubst" "define-inline"
104 "define-advice" "defadvice" "define-skeleton"
105 "define-compilation-mode" "define-minor-mode"
106 "define-global-minor-mode"
107 "define-globalized-minor-mode"
108 "define-derived-mode" "define-generic-mode"
109 "ert-deftest"
110 "cl-defun" "cl-defsubst" "cl-defmacro"
111 "cl-define-compiler-macro" "cl-defgeneric"
112 "cl-defmethod"
113 ;; CL.
114 "define-compiler-macro" "define-modify-macro"
115 "defsetf" "define-setf-expander"
116 "define-method-combination"
117 ;; CLOS and EIEIO
118 "defgeneric" "defmethod")
120 "\\s-+\\(" lisp-mode-symbol-regexp "\\)"))
122 (list (purecopy "Variables")
123 (purecopy (concat "^\\s-*("
124 (eval-when-compile
125 (regexp-opt
126 '(;; Elisp
127 "defconst" "defcustom"
128 ;; CL
129 "defconstant"
130 "defparameter" "define-symbol-macro")
132 "\\s-+\\(" lisp-mode-symbol-regexp "\\)"))
134 ;; For `defvar'/`defvar-local', we ignore (defvar FOO) constructs.
135 (list (purecopy "Variables")
136 (purecopy (concat "^\\s-*(defvar\\(?:-local\\)?\\s-+\\("
137 lisp-mode-symbol-regexp "\\)"
138 "[[:space:]\n]+[^)]"))
140 (list (purecopy "Types")
141 (purecopy (concat "^\\s-*("
142 (eval-when-compile
143 (regexp-opt
144 '(;; Elisp
145 "defgroup" "deftheme"
146 "define-widget" "define-error"
147 "defface" "cl-deftype" "cl-defstruct"
148 ;; CL
149 "deftype" "defstruct"
150 "define-condition" "defpackage"
151 ;; CLOS and EIEIO
152 "defclass")
154 "\\s-+'?\\(" lisp-mode-symbol-regexp "\\)"))
157 "Imenu generic expression for Lisp mode. See `imenu-generic-expression'.")
159 ;; This was originally in autoload.el and is still used there.
160 (put 'autoload 'doc-string-elt 3)
161 (put 'defmethod 'doc-string-elt 3)
162 (put 'defvar 'doc-string-elt 3)
163 (put 'defconst 'doc-string-elt 3)
164 (put 'defalias 'doc-string-elt 3)
165 (put 'defvaralias 'doc-string-elt 3)
166 (put 'define-category 'doc-string-elt 2)
168 (defvar lisp-doc-string-elt-property 'doc-string-elt
169 "The symbol property that holds the docstring position info.")
171 (defconst lisp-prettify-symbols-alist '(("lambda" . ?λ))
172 "Alist of symbol/\"pretty\" characters to be displayed.")
174 ;;;; Font-lock support.
176 (defun lisp--match-hidden-arg (limit)
177 (let ((res nil))
178 (while
179 (let ((ppss (parse-partial-sexp (line-beginning-position)
180 (line-end-position)
181 -1)))
182 (skip-syntax-forward " )")
183 (if (or (>= (car ppss) 0)
184 (looking-at ";\\|$"))
185 (progn
186 (forward-line 1)
187 (< (point) limit))
188 (looking-at ".*") ;Set the match-data.
189 (forward-line 1)
190 (setq res (point))
191 nil)))
192 res))
194 (defun lisp--el-non-funcall-position-p (pos)
195 "Heuristically determine whether POS is an evaluated position."
196 (save-match-data
197 (save-excursion
198 (ignore-errors
199 (goto-char pos)
200 (or (eql (char-before) ?\')
201 (let* ((ppss (syntax-ppss))
202 (paren-posns (nth 9 ppss))
203 (parent
204 (when paren-posns
205 (goto-char (car (last paren-posns))) ;(up-list -1)
206 (cond
207 ((ignore-errors
208 (and (eql (char-after) ?\()
209 (when (cdr paren-posns)
210 (goto-char (car (last paren-posns 2)))
211 (looking-at "(\\_<let\\*?\\_>"))))
212 (goto-char (match-end 0))
213 'let)
214 ((looking-at
215 (rx "("
216 (group-n 1 (+ (or (syntax w) (syntax _))))
217 symbol-end))
218 (prog1 (intern-soft (match-string-no-properties 1))
219 (goto-char (match-end 1))))))))
220 (or (eq parent 'declare)
221 (and (eq parent 'let)
222 (progn
223 (forward-sexp 1)
224 (< pos (point))))
225 (and (eq parent 'condition-case)
226 (progn
227 (forward-sexp 2)
228 (< (point) pos))))))))))
230 (defun lisp--el-match-keyword (limit)
231 ;; FIXME: Move to elisp-mode.el.
232 (catch 'found
233 (while (re-search-forward
234 (eval-when-compile
235 (concat "(\\(" lisp-mode-symbol-regexp "\\)\\_>"))
236 limit t)
237 (let ((sym (intern-soft (match-string 1))))
238 (when (or (special-form-p sym)
239 (and (macrop sym)
240 (not (get sym 'no-font-lock-keyword))
241 (not (lisp--el-non-funcall-position-p
242 (match-beginning 0)))))
243 (throw 'found t))))))
245 (defmacro let-when-compile (bindings &rest body)
246 "Like `let*', but allow for compile time optimization.
247 Use BINDINGS as in regular `let*', but in BODY each usage should
248 be wrapped in `eval-when-compile'.
249 This will generate compile-time constants from BINDINGS."
250 (declare (indent 1) (debug let))
251 (letrec ((loop
252 (lambda (bindings)
253 (if (null bindings)
254 (macroexpand-all (macroexp-progn body)
255 macroexpand-all-environment)
256 (let ((binding (pop bindings)))
257 (cl-progv (list (car binding))
258 (list (eval (nth 1 binding) t))
259 (funcall loop bindings)))))))
260 (funcall loop bindings)))
262 (defun elisp--font-lock-backslash ()
263 (let* ((beg0 (match-beginning 0))
264 (end0 (match-end 0))
265 (ppss (save-excursion (syntax-ppss beg0))))
266 (and (nth 3 ppss) ;Inside a string.
267 (not (nth 5 ppss)) ;The \ is not itself \-escaped.
268 ;; Don't highlight the \( introduced because of
269 ;; `open-paren-in-column-0-is-defun-start'.
270 (not (eq ?\n (char-before beg0)))
271 (equal (ignore-errors
272 (car (read-from-string
273 (format "\"%s\""
274 (buffer-substring-no-properties
275 beg0 end0)))))
276 (buffer-substring-no-properties (1+ beg0) end0))
277 `(face ,font-lock-warning-face
278 help-echo "This \\ has no effect"))))
280 (let-when-compile
281 ((lisp-fdefs '("defmacro" "defun"))
282 (lisp-vdefs '("defvar"))
283 (lisp-kw '("cond" "if" "while" "let" "let*" "progn" "prog1"
284 "prog2" "lambda" "unwind-protect" "condition-case"
285 "when" "unless" "with-output-to-string"
286 "ignore-errors" "dotimes" "dolist" "declare"))
287 (lisp-errs '("warn" "error" "signal"))
288 ;; Elisp constructs. Now they are update dynamically
289 ;; from obarray but they are also used for setting up
290 ;; the keywords for Common Lisp.
291 (el-fdefs '("defsubst" "cl-defsubst" "define-inline"
292 "define-advice" "defadvice" "defalias"
293 "define-derived-mode" "define-minor-mode"
294 "define-generic-mode" "define-global-minor-mode"
295 "define-globalized-minor-mode" "define-skeleton"
296 "define-widget" "ert-deftest"))
297 (el-vdefs '("defconst" "defcustom" "defvaralias" "defvar-local"
298 "defface"))
299 (el-tdefs '("defgroup" "deftheme"))
300 (el-errs '("user-error"))
301 ;; Common-Lisp constructs supported by EIEIO. FIXME: namespace.
302 (eieio-fdefs '("defgeneric" "defmethod"))
303 (eieio-tdefs '("defclass"))
304 ;; Common-Lisp constructs supported by cl-lib.
305 (cl-lib-fdefs '("defmacro" "defsubst" "defun" "defmethod" "defgeneric"))
306 (cl-lib-tdefs '("defstruct" "deftype"))
307 (cl-lib-errs '("assert" "check-type"))
308 ;; Common-Lisp constructs not supported by cl-lib.
309 (cl-fdefs '("defsetf" "define-method-combination"
310 "define-condition" "define-setf-expander"
311 ;; "define-function"??
312 "define-compiler-macro" "define-modify-macro"))
313 (cl-vdefs '("define-symbol-macro" "defconstant" "defparameter"))
314 (cl-tdefs '("defpackage" "defstruct" "deftype"))
315 (cl-kw '("block" "break" "case" "ccase" "compiler-let" "ctypecase"
316 "declaim" "destructuring-bind" "do" "do*"
317 "ecase" "etypecase" "eval-when" "flet" "flet*"
318 "go" "handler-case" "handler-bind" "in-package" ;; "inline"
319 "labels" "letf" "locally" "loop"
320 "macrolet" "multiple-value-bind" "multiple-value-prog1"
321 "proclaim" "prog" "prog*" "progv"
322 "restart-case" "restart-bind" "return" "return-from"
323 "symbol-macrolet" "tagbody" "the" "typecase"
324 "with-accessors" "with-compilation-unit"
325 "with-condition-restarts" "with-hash-table-iterator"
326 "with-input-from-string" "with-open-file"
327 "with-open-stream" "with-package-iterator"
328 "with-simple-restart" "with-slots" "with-standard-io-syntax"))
329 (cl-errs '("abort" "cerror")))
330 (let ((vdefs (eval-when-compile
331 (append lisp-vdefs el-vdefs cl-vdefs)))
332 (tdefs (eval-when-compile
333 (append el-tdefs eieio-tdefs cl-tdefs cl-lib-tdefs
334 (mapcar (lambda (s) (concat "cl-" s)) cl-lib-tdefs))))
335 ;; Elisp and Common Lisp definers.
336 (el-defs-re (eval-when-compile
337 (regexp-opt (append lisp-fdefs lisp-vdefs
338 el-fdefs el-vdefs el-tdefs
339 (mapcar (lambda (s) (concat "cl-" s))
340 (append cl-lib-fdefs cl-lib-tdefs))
341 eieio-fdefs eieio-tdefs)
342 t)))
343 (cl-defs-re (eval-when-compile
344 (regexp-opt (append lisp-fdefs lisp-vdefs
345 cl-lib-fdefs cl-lib-tdefs
346 eieio-fdefs eieio-tdefs
347 cl-fdefs cl-vdefs cl-tdefs)
348 t)))
349 ;; Common Lisp keywords (Elisp keywords are handled dynamically).
350 (cl-kws-re (eval-when-compile
351 (regexp-opt (append lisp-kw cl-kw) t)))
352 ;; Elisp and Common Lisp "errors".
353 (el-errs-re (eval-when-compile
354 (regexp-opt (append (mapcar (lambda (s) (concat "cl-" s))
355 cl-lib-errs)
356 lisp-errs el-errs)
357 t)))
358 (cl-errs-re (eval-when-compile
359 (regexp-opt (append lisp-errs cl-lib-errs cl-errs) t))))
360 (dolist (v vdefs)
361 (put (intern v) 'lisp-define-type 'var))
362 (dolist (v tdefs)
363 (put (intern v) 'lisp-define-type 'type))
365 (define-obsolete-variable-alias 'lisp-font-lock-keywords-1
366 'lisp-el-font-lock-keywords-1 "24.4")
367 (defconst lisp-el-font-lock-keywords-1
368 `( ;; Definitions.
369 (,(concat "(" el-defs-re "\\_>"
370 ;; Any whitespace and defined object.
371 "[ \t']*"
372 "\\(([ \t']*\\)?" ;; An opening paren.
373 "\\(\\(setf\\)[ \t]+" lisp-mode-symbol-regexp
374 "\\|" lisp-mode-symbol-regexp "\\)?")
375 (1 font-lock-keyword-face)
376 (3 (let ((type (get (intern-soft (match-string 1)) 'lisp-define-type)))
377 (cond ((eq type 'var) font-lock-variable-name-face)
378 ((eq type 'type) font-lock-type-face)
379 ;; If match-string 2 is non-nil, we encountered a
380 ;; form like (defalias (intern (concat s "-p"))),
381 ;; unless match-string 4 is also there. Then its a
382 ;; defmethod with (setf foo) as name.
383 ((or (not (match-string 2)) ;; Normal defun.
384 (and (match-string 2) ;; Setf method.
385 (match-string 4)))
386 font-lock-function-name-face)))
387 nil t))
388 ;; Emacs Lisp autoload cookies. Supports the slightly different
389 ;; forms used by mh-e, calendar, etc.
390 ("^;;;###\\([-a-z]*autoload\\)" 1 font-lock-warning-face prepend))
391 "Subdued level highlighting for Emacs Lisp mode.")
393 (defconst lisp-cl-font-lock-keywords-1
394 `( ;; Definitions.
395 (,(concat "(" cl-defs-re "\\_>"
396 ;; Any whitespace and defined object.
397 "[ \t']*"
398 "\\(([ \t']*\\)?" ;; An opening paren.
399 "\\(\\(setf\\)[ \t]+" lisp-mode-symbol-regexp
400 "\\|" lisp-mode-symbol-regexp "\\)?")
401 (1 font-lock-keyword-face)
402 (3 (let ((type (get (intern-soft (match-string 1)) 'lisp-define-type)))
403 (cond ((eq type 'var) font-lock-variable-name-face)
404 ((eq type 'type) font-lock-type-face)
405 ((or (not (match-string 2)) ;; Normal defun.
406 (and (match-string 2) ;; Setf function.
407 (match-string 4)))
408 font-lock-function-name-face)))
409 nil t)))
410 "Subdued level highlighting for Lisp modes.")
412 (define-obsolete-variable-alias 'lisp-font-lock-keywords-2
413 'lisp-el-font-lock-keywords-2 "24.4")
414 (defconst lisp-el-font-lock-keywords-2
415 (append
416 lisp-el-font-lock-keywords-1
417 `( ;; Regexp negated char group.
418 ("\\[\\(\\^\\)" 1 font-lock-negation-char-face prepend)
419 ;; Erroneous structures.
420 (,(concat "(" el-errs-re "\\_>")
421 (1 font-lock-warning-face))
422 ;; Control structures. Common Lisp forms.
423 (lisp--el-match-keyword . 1)
424 ;; Exit/Feature symbols as constants.
425 (,(concat "(\\(catch\\|throw\\|featurep\\|provide\\|require\\)\\_>"
426 "[ \t']*\\(" lisp-mode-symbol-regexp "\\)?")
427 (1 font-lock-keyword-face)
428 (2 font-lock-constant-face nil t))
429 ;; Words inside \\[] tend to be for `substitute-command-keys'.
430 (,(concat "\\\\\\\\\\[\\(" lisp-mode-symbol-regexp "\\)\\]")
431 (1 font-lock-constant-face prepend))
432 ;; Ineffective backslashes (typically in need of doubling).
433 ("\\(\\\\\\)\\([^\"\\]\\)"
434 (1 (elisp--font-lock-backslash) prepend))
435 ;; Words inside ‘’ and `' tend to be symbol names.
436 (,(concat "[`‘]\\(\\(?:\\sw\\|\\s_\\|\\\\.\\)"
437 lisp-mode-symbol-regexp "\\)['’]")
438 (1 font-lock-constant-face prepend))
439 ;; Constant values.
440 (,(concat "\\_<:" lisp-mode-symbol-regexp "\\_>")
441 (0 font-lock-builtin-face))
442 ;; ELisp and CLisp `&' keywords as types.
443 (,(concat "\\_<\\&" lisp-mode-symbol-regexp "\\_>")
444 . font-lock-type-face)
445 ;; ELisp regexp grouping constructs
446 (,(lambda (bound)
447 (catch 'found
448 ;; The following loop is needed to continue searching after matches
449 ;; that do not occur in strings. The associated regexp matches one
450 ;; of `\\\\' `\\(' `\\(?:' `\\|' `\\)'. `\\\\' has been included to
451 ;; avoid highlighting, for example, `\\(' in `\\\\('.
452 (while (re-search-forward "\\(\\\\\\\\\\)\\(?:\\(\\\\\\\\\\)\\|\\((\\(?:\\?[0-9]*:\\)?\\|[|)]\\)\\)" bound t)
453 (unless (match-beginning 2)
454 (let ((face (get-text-property (1- (point)) 'face)))
455 (when (or (and (listp face)
456 (memq 'font-lock-string-face face))
457 (eq 'font-lock-string-face face))
458 (throw 'found t)))))))
459 (1 'font-lock-regexp-grouping-backslash prepend)
460 (3 'font-lock-regexp-grouping-construct prepend))
461 ;; This is too general -- rms.
462 ;; A user complained that he has functions whose names start with `do'
463 ;; and that they get the wrong color.
464 ;; ;; CL `with-' and `do-' constructs
465 ;;("(\\(\\(do-\\|with-\\)\\(\\s_\\|\\w\\)*\\)" 1 font-lock-keyword-face)
466 (lisp--match-hidden-arg
467 (0 '(face font-lock-warning-face
468 help-echo "Hidden behind deeper element; move to another line?")))
470 "Gaudy level highlighting for Emacs Lisp mode.")
472 (defconst lisp-cl-font-lock-keywords-2
473 (append
474 lisp-cl-font-lock-keywords-1
475 `( ;; Regexp negated char group.
476 ("\\[\\(\\^\\)" 1 font-lock-negation-char-face prepend)
477 ;; Control structures. Common Lisp forms.
478 (,(concat "(" cl-kws-re "\\_>") . 1)
479 ;; Exit/Feature symbols as constants.
480 (,(concat "(\\(catch\\|throw\\|provide\\|require\\)\\_>"
481 "[ \t']*\\(" lisp-mode-symbol-regexp "\\)?")
482 (1 font-lock-keyword-face)
483 (2 font-lock-constant-face nil t))
484 ;; Erroneous structures.
485 (,(concat "(" cl-errs-re "\\_>")
486 (1 font-lock-warning-face))
487 ;; Words inside ‘’ and `' tend to be symbol names.
488 (,(concat "[`‘]\\(\\(?:\\sw\\|\\s_\\|\\\\.\\)"
489 lisp-mode-symbol-regexp "\\)['’]")
490 (1 font-lock-constant-face prepend))
491 ;; Constant values.
492 (,(concat "\\_<:" lisp-mode-symbol-regexp "\\_>")
493 (0 font-lock-builtin-face))
494 ;; ELisp and CLisp `&' keywords as types.
495 (,(concat "\\_<\\&" lisp-mode-symbol-regexp "\\_>")
496 . font-lock-type-face)
497 ;; This is too general -- rms.
498 ;; A user complained that he has functions whose names start with `do'
499 ;; and that they get the wrong color.
500 ;; ;; CL `with-' and `do-' constructs
501 ;;("(\\(\\(do-\\|with-\\)\\(\\s_\\|\\w\\)*\\)" 1 font-lock-keyword-face)
502 (lisp--match-hidden-arg
503 (0 '(face font-lock-warning-face
504 help-echo "Hidden behind deeper element; move to another line?")))
506 "Gaudy level highlighting for Lisp modes.")))
508 (define-obsolete-variable-alias 'lisp-font-lock-keywords
509 'lisp-el-font-lock-keywords "24.4")
510 (defvar lisp-el-font-lock-keywords lisp-el-font-lock-keywords-1
511 "Default expressions to highlight in Emacs Lisp mode.")
512 (defvar lisp-cl-font-lock-keywords lisp-cl-font-lock-keywords-1
513 "Default expressions to highlight in Lisp modes.")
515 (defun lisp-string-in-doc-position-p (listbeg startpos)
516 "Return true if a doc string may occur at STARTPOS inside a list.
517 LISTBEG is the position of the start of the innermost list
518 containing STARTPOS."
519 (let* ((firstsym (and listbeg
520 (save-excursion
521 (goto-char listbeg)
522 (and (looking-at
523 (eval-when-compile
524 (concat "([ \t\n]*\\("
525 lisp-mode-symbol-regexp "\\)")))
526 (match-string 1)))))
527 (docelt (and firstsym
528 (function-get (intern-soft firstsym)
529 lisp-doc-string-elt-property))))
530 (and docelt
531 ;; It's a string in a form that can have a docstring.
532 ;; Check whether it's in docstring position.
533 (save-excursion
534 (when (functionp docelt)
535 (goto-char (match-end 1))
536 (setq docelt (funcall docelt)))
537 (goto-char listbeg)
538 (forward-char 1)
539 (condition-case nil
540 (while (and (> docelt 0) (< (point) startpos)
541 (progn (forward-sexp 1) t))
542 (setq docelt (1- docelt)))
543 (error nil))
544 (and (zerop docelt) (<= (point) startpos)
545 (progn (forward-comment (point-max)) t)
546 (= (point) startpos))))))
548 (defun lisp-string-after-doc-keyword-p (listbeg startpos)
549 "Return true if `:documentation' symbol ends at STARTPOS inside a list.
550 LISTBEG is the position of the start of the innermost list
551 containing STARTPOS."
552 (and listbeg ; We are inside a Lisp form.
553 (save-excursion
554 (goto-char startpos)
555 (ignore-errors
556 (progn (backward-sexp 1)
557 (looking-at ":documentation\\_>"))))))
559 (defun lisp-font-lock-syntactic-face-function (state)
560 "Return syntactic face function for the position represented by STATE.
561 STATE is a `parse-partial-sexp' state, and the returned function is the
562 Lisp font lock syntactic face function."
563 (if (nth 3 state)
564 ;; This might be a (doc)string or a |...| symbol.
565 (let ((startpos (nth 8 state)))
566 (if (eq (char-after startpos) ?|)
567 ;; This is not a string, but a |...| symbol.
569 (let ((listbeg (nth 1 state)))
570 (if (or (lisp-string-in-doc-position-p listbeg startpos)
571 (lisp-string-after-doc-keyword-p listbeg startpos))
572 font-lock-doc-face
573 font-lock-string-face))))
574 font-lock-comment-face))
576 (defun lisp-mode-variables (&optional lisp-syntax keywords-case-insensitive
577 elisp)
578 "Common initialization routine for lisp modes.
579 The LISP-SYNTAX argument is used by code in inf-lisp.el and is
580 \(uselessly) passed from pp.el, chistory.el, gnus-kill.el and
581 score-mode.el. KEYWORDS-CASE-INSENSITIVE non-nil means that for
582 font-lock keywords will not be case sensitive."
583 (when lisp-syntax
584 (set-syntax-table lisp-mode-syntax-table))
585 (setq-local paragraph-ignore-fill-prefix t)
586 (setq-local fill-paragraph-function 'lisp-fill-paragraph)
587 ;; Adaptive fill mode gets the fill wrong for a one-line paragraph made of
588 ;; a single docstring. Let's fix it here.
589 (setq-local adaptive-fill-function
590 (lambda () (if (looking-at "\\s-+\"[^\n\"]+\"\\s-*$") "")))
591 ;; Adaptive fill mode gets in the way of auto-fill,
592 ;; and should make no difference for explicit fill
593 ;; because lisp-fill-paragraph should do the job.
594 ;; I believe that newcomment's auto-fill code properly deals with it -stef
595 ;;(set (make-local-variable 'adaptive-fill-mode) nil)
596 (setq-local indent-line-function 'lisp-indent-line)
597 (setq-local outline-regexp ";;;\\(;* [^ \t\n]\\|###autoload\\)\\|(")
598 (setq-local outline-level 'lisp-outline-level)
599 (setq-local add-log-current-defun-function #'lisp-current-defun-name)
600 (setq-local comment-start ";")
601 (setq-local comment-start-skip ";+ *")
602 (setq-local comment-add 1) ;default to `;;' in comment-region
603 (setq-local comment-column 40)
604 (setq-local comment-use-syntax t)
605 (setq-local imenu-generic-expression lisp-imenu-generic-expression)
606 (setq-local multibyte-syntax-as-symbol t)
607 ;; (setq-local syntax-begin-function 'beginning-of-defun) ;;Bug#16247.
608 (setq font-lock-defaults
609 `(,(if elisp '(lisp-el-font-lock-keywords
610 lisp-el-font-lock-keywords-1
611 lisp-el-font-lock-keywords-2)
612 '(lisp-cl-font-lock-keywords
613 lisp-cl-font-lock-keywords-1
614 lisp-cl-font-lock-keywords-2))
615 nil ,keywords-case-insensitive nil nil
616 (font-lock-mark-block-function . mark-defun)
617 (font-lock-extra-managed-props help-echo)
618 (font-lock-syntactic-face-function
619 . lisp-font-lock-syntactic-face-function)))
620 (setq-local prettify-symbols-alist lisp-prettify-symbols-alist)
621 (setq-local electric-pair-skip-whitespace 'chomp)
622 (setq-local electric-pair-open-newline-between-pairs nil))
624 (defun lisp-outline-level ()
625 "Lisp mode `outline-level' function."
626 (let ((len (- (match-end 0) (match-beginning 0))))
627 (if (looking-at "(\\|;;;###autoload")
628 1000
629 len)))
631 (defun lisp-current-defun-name ()
632 "Return the name of the defun at point, or nil."
633 (save-excursion
634 (let ((location (point)))
635 ;; If we are now precisely at the beginning of a defun, make sure
636 ;; beginning-of-defun finds that one rather than the previous one.
637 (or (eobp) (forward-char 1))
638 (beginning-of-defun)
639 ;; Make sure we are really inside the defun found, not after it.
640 (when (and (looking-at "\\s(")
641 (progn (end-of-defun)
642 (< location (point)))
643 (progn (forward-sexp -1)
644 (>= location (point))))
645 (if (looking-at "\\s(")
646 (forward-char 1))
647 ;; Skip the defining construct name, typically "defun" or
648 ;; "defvar".
649 (forward-sexp 1)
650 ;; The second element is usually a symbol being defined. If it
651 ;; is not, use the first symbol in it.
652 (skip-chars-forward " \t\n'(")
653 (buffer-substring-no-properties (point)
654 (progn (forward-sexp 1)
655 (point)))))))
657 (defvar lisp-mode-shared-map
658 (let ((map (make-sparse-keymap)))
659 (set-keymap-parent map prog-mode-map)
660 (define-key map "\e\C-q" 'indent-sexp)
661 (define-key map "\177" 'backward-delete-char-untabify)
662 ;; This gets in the way when viewing a Lisp file in view-mode. As
663 ;; long as [backspace] is mapped into DEL via the
664 ;; function-key-map, this should remain disabled!!
665 ;;;(define-key map [backspace] 'backward-delete-char-untabify)
666 map)
667 "Keymap for commands shared by all sorts of Lisp modes.")
669 (defcustom lisp-mode-hook nil
670 "Hook run when entering Lisp mode."
671 :options '(imenu-add-menubar-index)
672 :type 'hook
673 :group 'lisp)
675 (defcustom lisp-interaction-mode-hook nil
676 "Hook run when entering Lisp Interaction mode."
677 :options '(eldoc-mode)
678 :type 'hook
679 :group 'lisp)
681 ;;; Generic Lisp mode.
683 (defvar lisp-mode-map
684 (let ((map (make-sparse-keymap))
685 (menu-map (make-sparse-keymap "Lisp")))
686 (set-keymap-parent map lisp-mode-shared-map)
687 (define-key map "\e\C-x" 'lisp-eval-defun)
688 (define-key map "\C-c\C-z" 'run-lisp)
689 (bindings--define-key map [menu-bar lisp] (cons "Lisp" menu-map))
690 (bindings--define-key menu-map [run-lisp]
691 '(menu-item "Run inferior Lisp" run-lisp
692 :help "Run an inferior Lisp process, input and output via buffer `*inferior-lisp*'"))
693 (bindings--define-key menu-map [ev-def]
694 '(menu-item "Eval defun" lisp-eval-defun
695 :help "Send the current defun to the Lisp process made by M-x run-lisp"))
696 (bindings--define-key menu-map [ind-sexp]
697 '(menu-item "Indent sexp" indent-sexp
698 :help "Indent each line of the list starting just after point"))
699 map)
700 "Keymap for ordinary Lisp mode.
701 All commands in `lisp-mode-shared-map' are inherited by this map.")
703 (define-derived-mode lisp-mode prog-mode "Lisp"
704 "Major mode for editing Lisp code for Lisps other than GNU Emacs Lisp.
705 Commands:
706 Delete converts tabs to spaces as it moves back.
707 Blank lines separate paragraphs. Semicolons start comments.
709 \\{lisp-mode-map}
710 Note that `run-lisp' may be used either to start an inferior Lisp job
711 or to switch back to an existing one."
712 (lisp-mode-variables nil t)
713 (setq-local find-tag-default-function 'lisp-find-tag-default)
714 (setq-local comment-start-skip
715 "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
716 (setq imenu-case-fold-search t))
718 (defun lisp-find-tag-default ()
719 (let ((default (find-tag-default)))
720 (when (stringp default)
721 (if (string-match ":+" default)
722 (substring default (match-end 0))
723 default))))
725 ;; Used in old LispM code.
726 (defalias 'common-lisp-mode 'lisp-mode)
728 ;; This will do unless inf-lisp.el is loaded.
729 (defun lisp-eval-defun (&optional _and-go)
730 "Send the current defun to the Lisp process made by \\[run-lisp]."
731 (interactive)
732 (error "Process lisp does not exist"))
734 ;; May still be used by some external Lisp-mode variant.
735 (define-obsolete-function-alias 'lisp-comment-indent
736 'comment-indent-default "22.1")
737 (define-obsolete-function-alias 'lisp-mode-auto-fill 'do-auto-fill "23.1")
739 (defcustom lisp-indent-offset nil
740 "If non-nil, indent second line of expressions that many more columns."
741 :group 'lisp
742 :type '(choice (const nil) integer))
743 (put 'lisp-indent-offset 'safe-local-variable
744 (lambda (x) (or (null x) (integerp x))))
746 (defcustom lisp-indent-function 'lisp-indent-function
747 "A function to be called by `calculate-lisp-indent'.
748 It indents the arguments of a Lisp function call. This function
749 should accept two arguments: the indent-point, and the
750 `parse-partial-sexp' state at that position. One option for this
751 function is `common-lisp-indent-function'."
752 :type 'function
753 :group 'lisp)
755 (defun lisp-indent-line (&optional _whole-exp)
756 "Indent current line as Lisp code.
757 With argument, indent any additional lines of the same expression
758 rigidly along with this one."
759 (interactive "P")
760 (let ((indent (calculate-lisp-indent)) shift-amt
761 (pos (- (point-max) (point)))
762 (beg (progn (beginning-of-line) (point))))
763 (skip-chars-forward " \t")
764 (if (or (null indent) (looking-at "\\s<\\s<\\s<"))
765 ;; Don't alter indentation of a ;;; comment line
766 ;; or a line that starts in a string.
767 ;; FIXME: inconsistency: comment-indent moves ;;; to column 0.
768 (goto-char (- (point-max) pos))
769 (if (and (looking-at "\\s<") (not (looking-at "\\s<\\s<")))
770 ;; Single-semicolon comment lines should be indented
771 ;; as comment lines, not as code.
772 (progn (indent-for-comment) (forward-char -1))
773 (if (listp indent) (setq indent (car indent)))
774 (setq shift-amt (- indent (current-column)))
775 (if (zerop shift-amt)
777 (delete-region beg (point))
778 (indent-to indent)))
779 ;; If initial point was within line's indentation,
780 ;; position after the indentation. Else stay at same point in text.
781 (if (> (- (point-max) pos) (point))
782 (goto-char (- (point-max) pos))))))
784 (defvar calculate-lisp-indent-last-sexp)
786 (defun calculate-lisp-indent (&optional parse-start)
787 "Return appropriate indentation for current line as Lisp code.
788 In usual case returns an integer: the column to indent to.
789 If the value is nil, that means don't change the indentation
790 because the line starts inside a string.
792 The value can also be a list of the form (COLUMN CONTAINING-SEXP-START).
793 This means that following lines at the same level of indentation
794 should not necessarily be indented the same as this line.
795 Then COLUMN is the column to indent to, and CONTAINING-SEXP-START
796 is the buffer position of the start of the containing expression."
797 (save-excursion
798 (beginning-of-line)
799 (let ((indent-point (point))
800 state
801 ;; setting this to a number inhibits calling hook
802 (desired-indent nil)
803 (retry t)
804 calculate-lisp-indent-last-sexp containing-sexp)
805 (if parse-start
806 (goto-char parse-start)
807 (beginning-of-defun))
808 ;; Find outermost containing sexp
809 (while (< (point) indent-point)
810 (setq state (parse-partial-sexp (point) indent-point 0)))
811 ;; Find innermost containing sexp
812 (while (and retry
813 state
814 (> (elt state 0) 0))
815 (setq retry nil)
816 (setq calculate-lisp-indent-last-sexp (elt state 2))
817 (setq containing-sexp (elt state 1))
818 ;; Position following last unclosed open.
819 (goto-char (1+ containing-sexp))
820 ;; Is there a complete sexp since then?
821 (if (and calculate-lisp-indent-last-sexp
822 (> calculate-lisp-indent-last-sexp (point)))
823 ;; Yes, but is there a containing sexp after that?
824 (let ((peek (parse-partial-sexp calculate-lisp-indent-last-sexp
825 indent-point 0)))
826 (if (setq retry (car (cdr peek))) (setq state peek)))))
827 (if retry
829 ;; Innermost containing sexp found
830 (goto-char (1+ containing-sexp))
831 (if (not calculate-lisp-indent-last-sexp)
832 ;; indent-point immediately follows open paren.
833 ;; Don't call hook.
834 (setq desired-indent (current-column))
835 ;; Find the start of first element of containing sexp.
836 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
837 (cond ((looking-at "\\s(")
838 ;; First element of containing sexp is a list.
839 ;; Indent under that list.
841 ((> (save-excursion (forward-line 1) (point))
842 calculate-lisp-indent-last-sexp)
843 ;; This is the first line to start within the containing sexp.
844 ;; It's almost certainly a function call.
845 (if (= (point) calculate-lisp-indent-last-sexp)
846 ;; Containing sexp has nothing before this line
847 ;; except the first element. Indent under that element.
849 ;; Skip the first element, find start of second (the first
850 ;; argument of the function call) and indent under.
851 (progn (forward-sexp 1)
852 (parse-partial-sexp (point)
853 calculate-lisp-indent-last-sexp
854 0 t)))
855 (backward-prefix-chars))
857 ;; Indent beneath first sexp on same line as
858 ;; `calculate-lisp-indent-last-sexp'. Again, it's
859 ;; almost certainly a function call.
860 (goto-char calculate-lisp-indent-last-sexp)
861 (beginning-of-line)
862 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp
863 0 t)
864 (backward-prefix-chars)))))
865 ;; Point is at the point to indent under unless we are inside a string.
866 ;; Call indentation hook except when overridden by lisp-indent-offset
867 ;; or if the desired indentation has already been computed.
868 (let ((normal-indent (current-column)))
869 (cond ((elt state 3)
870 ;; Inside a string, don't change indentation.
871 nil)
872 ((and (integerp lisp-indent-offset) containing-sexp)
873 ;; Indent by constant offset
874 (goto-char containing-sexp)
875 (+ (current-column) lisp-indent-offset))
876 ;; in this case calculate-lisp-indent-last-sexp is not nil
877 (calculate-lisp-indent-last-sexp
879 ;; try to align the parameters of a known function
880 (and lisp-indent-function
881 (not retry)
882 (funcall lisp-indent-function indent-point state))
883 ;; If the function has no special alignment
884 ;; or it does not apply to this argument,
885 ;; try to align a constant-symbol under the last
886 ;; preceding constant symbol, if there is such one of
887 ;; the last 2 preceding symbols, in the previous
888 ;; uncommented line.
889 (and (save-excursion
890 (goto-char indent-point)
891 (skip-chars-forward " \t")
892 (looking-at ":"))
893 ;; The last sexp may not be at the indentation
894 ;; where it begins, so find that one, instead.
895 (save-excursion
896 (goto-char calculate-lisp-indent-last-sexp)
897 ;; Handle prefix characters and whitespace
898 ;; following an open paren. (Bug#1012)
899 (backward-prefix-chars)
900 (while (not (or (looking-back "^[ \t]*\\|([ \t]+"
901 (line-beginning-position))
902 (and containing-sexp
903 (>= (1+ containing-sexp) (point)))))
904 (forward-sexp -1)
905 (backward-prefix-chars))
906 (setq calculate-lisp-indent-last-sexp (point)))
907 (> calculate-lisp-indent-last-sexp
908 (save-excursion
909 (goto-char (1+ containing-sexp))
910 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
911 (point)))
912 (let ((parse-sexp-ignore-comments t)
913 indent)
914 (goto-char calculate-lisp-indent-last-sexp)
915 (or (and (looking-at ":")
916 (setq indent (current-column)))
917 (and (< (line-beginning-position)
918 (prog2 (backward-sexp) (point)))
919 (looking-at ":")
920 (setq indent (current-column))))
921 indent))
922 ;; another symbols or constants not preceded by a constant
923 ;; as defined above.
924 normal-indent))
925 ;; in this case calculate-lisp-indent-last-sexp is nil
926 (desired-indent)
928 normal-indent))))))
930 (defun lisp-indent-function (indent-point state)
931 "This function is the normal value of the variable `lisp-indent-function'.
932 The function `calculate-lisp-indent' calls this to determine
933 if the arguments of a Lisp function call should be indented specially.
935 INDENT-POINT is the position at which the line being indented begins.
936 Point is located at the point to indent under (for default indentation);
937 STATE is the `parse-partial-sexp' state for that position.
939 If the current line is in a call to a Lisp function that has a non-nil
940 property `lisp-indent-function' (or the deprecated `lisp-indent-hook'),
941 it specifies how to indent. The property value can be:
943 * `defun', meaning indent `defun'-style
944 (this is also the case if there is no property and the function
945 has a name that begins with \"def\", and three or more arguments);
947 * an integer N, meaning indent the first N arguments specially
948 (like ordinary function arguments), and then indent any further
949 arguments like a body;
951 * a function to call that returns the indentation (or nil).
952 `lisp-indent-function' calls this function with the same two arguments
953 that it itself received.
955 This function returns either the indentation to use, or nil if the
956 Lisp function does not specify a special indentation."
957 (let ((normal-indent (current-column)))
958 (goto-char (1+ (elt state 1)))
959 (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
960 (if (and (elt state 2)
961 (not (looking-at "\\sw\\|\\s_")))
962 ;; car of form doesn't seem to be a symbol
963 (progn
964 (if (not (> (save-excursion (forward-line 1) (point))
965 calculate-lisp-indent-last-sexp))
966 (progn (goto-char calculate-lisp-indent-last-sexp)
967 (beginning-of-line)
968 (parse-partial-sexp (point)
969 calculate-lisp-indent-last-sexp 0 t)))
970 ;; Indent under the list or under the first sexp on the same
971 ;; line as calculate-lisp-indent-last-sexp. Note that first
972 ;; thing on that line has to be complete sexp since we are
973 ;; inside the innermost containing sexp.
974 (backward-prefix-chars)
975 (current-column))
976 (let ((function (buffer-substring (point)
977 (progn (forward-sexp 1) (point))))
978 method)
979 (setq method (or (function-get (intern-soft function)
980 'lisp-indent-function)
981 (get (intern-soft function) 'lisp-indent-hook)))
982 (cond ((or (eq method 'defun)
983 (and (null method)
984 (> (length function) 3)
985 (string-match "\\`def" function)))
986 (lisp-indent-defform state indent-point))
987 ((integerp method)
988 (lisp-indent-specform method state
989 indent-point normal-indent))
990 (method
991 (funcall method indent-point state)))))))
993 (defcustom lisp-body-indent 2
994 "Number of columns to indent the second line of a `(def...)' form."
995 :group 'lisp
996 :type 'integer)
997 (put 'lisp-body-indent 'safe-local-variable 'integerp)
999 (defun lisp-indent-specform (count state indent-point normal-indent)
1000 (let ((containing-form-start (elt state 1))
1001 (i count)
1002 body-indent containing-form-column)
1003 ;; Move to the start of containing form, calculate indentation
1004 ;; to use for non-distinguished forms (> count), and move past the
1005 ;; function symbol. lisp-indent-function guarantees that there is at
1006 ;; least one word or symbol character following open paren of containing
1007 ;; form.
1008 (goto-char containing-form-start)
1009 (setq containing-form-column (current-column))
1010 (setq body-indent (+ lisp-body-indent containing-form-column))
1011 (forward-char 1)
1012 (forward-sexp 1)
1013 ;; Now find the start of the last form.
1014 (parse-partial-sexp (point) indent-point 1 t)
1015 (while (and (< (point) indent-point)
1016 (condition-case ()
1017 (progn
1018 (setq count (1- count))
1019 (forward-sexp 1)
1020 (parse-partial-sexp (point) indent-point 1 t))
1021 (error nil))))
1022 ;; Point is sitting on first character of last (or count) sexp.
1023 (if (> count 0)
1024 ;; A distinguished form. If it is the first or second form use double
1025 ;; lisp-body-indent, else normal indent. With lisp-body-indent bound
1026 ;; to 2 (the default), this just happens to work the same with if as
1027 ;; the older code, but it makes unwind-protect, condition-case,
1028 ;; with-output-to-temp-buffer, et. al. much more tasteful. The older,
1029 ;; less hacked, behavior can be obtained by replacing below with
1030 ;; (list normal-indent containing-form-start).
1031 (if (<= (- i count) 1)
1032 (list (+ containing-form-column (* 2 lisp-body-indent))
1033 containing-form-start)
1034 (list normal-indent containing-form-start))
1035 ;; A non-distinguished form. Use body-indent if there are no
1036 ;; distinguished forms and this is the first undistinguished form,
1037 ;; or if this is the first undistinguished form and the preceding
1038 ;; distinguished form has indentation at least as great as body-indent.
1039 (if (or (and (= i 0) (= count 0))
1040 (and (= count 0) (<= body-indent normal-indent)))
1041 body-indent
1042 normal-indent))))
1044 (defun lisp-indent-defform (state _indent-point)
1045 (goto-char (car (cdr state)))
1046 (forward-line 1)
1047 (if (> (point) (car (cdr (cdr state))))
1048 (progn
1049 (goto-char (car (cdr state)))
1050 (+ lisp-body-indent (current-column)))))
1053 ;; (put 'progn 'lisp-indent-function 0), say, causes progn to be indented
1054 ;; like defun if the first form is placed on the next line, otherwise
1055 ;; it is indented like any other form (i.e. forms line up under first).
1057 (put 'autoload 'lisp-indent-function 'defun) ;Elisp
1058 (put 'progn 'lisp-indent-function 0)
1059 (put 'prog1 'lisp-indent-function 1)
1060 (put 'prog2 'lisp-indent-function 2)
1061 (put 'save-excursion 'lisp-indent-function 0) ;Elisp
1062 (put 'save-restriction 'lisp-indent-function 0) ;Elisp
1063 (put 'save-current-buffer 'lisp-indent-function 0) ;Elisp
1064 (put 'let 'lisp-indent-function 1)
1065 (put 'let* 'lisp-indent-function 1)
1066 (put 'while 'lisp-indent-function 1)
1067 (put 'if 'lisp-indent-function 2)
1068 (put 'catch 'lisp-indent-function 1)
1069 (put 'condition-case 'lisp-indent-function 2)
1070 (put 'handler-case 'lisp-indent-function 1) ;CL
1071 (put 'handler-bind 'lisp-indent-function 1) ;CL
1072 (put 'unwind-protect 'lisp-indent-function 1)
1073 (put 'with-output-to-temp-buffer 'lisp-indent-function 1)
1075 (defun indent-sexp (&optional endpos)
1076 "Indent each line of the list starting just after point.
1077 If optional arg ENDPOS is given, indent each line, stopping when
1078 ENDPOS is encountered."
1079 (interactive)
1080 (let* ((indent-stack (list nil))
1081 ;; If ENDPOS is non-nil, use beginning of defun as STARTING-POINT.
1082 ;; If ENDPOS is nil, it is safe not to scan before point
1083 ;; since every line we indent is more deeply nested than point is.
1084 (starting-point (save-excursion (if endpos (beginning-of-defun))
1085 (point)))
1086 ;; Use `syntax-ppss' to get initial state so we don't get
1087 ;; confused by starting inside a string. We don't use
1088 ;; `syntax-ppss' in the loop, because this is measurably
1089 ;; slower when we're called on a long list.
1090 (state (syntax-ppss))
1091 (init-depth (car state))
1092 (next-depth init-depth)
1093 (last-depth init-depth)
1094 (last-syntax-point (point))
1095 (real-endpos endpos))
1096 (unless endpos
1097 ;; Get error now if we don't have a complete sexp after point.
1098 (save-excursion (forward-sexp 1)
1099 ;; We need a marker because we modify the buffer
1100 ;; text preceding endpos.
1101 (setq endpos (point-marker))))
1102 (save-excursion
1103 (while (< (point) endpos)
1104 ;; Parse this line so we can learn the state to indent the
1105 ;; next line.
1106 (while (progn
1107 (setq state (parse-partial-sexp
1108 last-syntax-point (progn (end-of-line) (point))
1109 nil nil state))
1110 ;; Skip over newlines within strings.
1111 (nth 3 state))
1112 (setq state (parse-partial-sexp (point) (point-max)
1113 nil nil state 'syntax-table))
1114 (setq last-syntax-point (point)))
1115 (setq next-depth (car state))
1116 ;; If the line contains a comment indent it now with
1117 ;; `indent-for-comment'.
1118 (when (nth 4 state)
1119 (indent-for-comment)
1120 (end-of-line))
1121 (setq last-syntax-point (point))
1122 (when (< next-depth init-depth)
1123 (setq indent-stack (nconc indent-stack
1124 (make-list (- init-depth next-depth) nil))
1125 last-depth (- last-depth next-depth)
1126 next-depth init-depth))
1127 (forward-line 1)
1128 (when (and (not real-endpos) (<= next-depth init-depth))
1129 (goto-char endpos))
1130 (when (< (point) endpos)
1131 (let ((depth-delta (- next-depth last-depth)))
1132 (cond ((< depth-delta 0)
1133 (setq indent-stack (nthcdr (- depth-delta) indent-stack)))
1134 ((> depth-delta 0)
1135 (setq indent-stack (nconc (make-list depth-delta nil)
1136 indent-stack))))
1137 (setq last-depth next-depth))
1138 ;; Now indent the next line according
1139 ;; to what we learned from parsing the previous one.
1140 (skip-chars-forward " \t")
1141 ;; But not if the line is blank, or just a comment (we
1142 ;; already called `indent-for-comment' above).
1143 (unless (or (eolp) (eq (char-syntax (char-after)) ?<))
1144 (let ((this-indent (car indent-stack)))
1145 (when (listp this-indent)
1146 (let ((val (calculate-lisp-indent
1147 (or (car this-indent) starting-point))))
1148 (setq
1149 this-indent
1150 (cond ((integerp val)
1151 (setf (car indent-stack) val))
1152 ((consp val) ; (COLUMN CONTAINING-SEXP-START)
1153 (setf (car indent-stack) (cdr val))
1154 (car val))
1155 ;; `calculate-lisp-indent' only returns nil
1156 ;; when we're in a string, but this won't
1157 ;; happen because we skip strings above.
1158 (t (error "This shouldn't happen!"))))))
1159 (indent-line-to this-indent))))))))
1161 (defun indent-pp-sexp (&optional arg)
1162 "Indent each line of the list starting just after point, or prettyprint it.
1163 A prefix argument specifies pretty-printing."
1164 (interactive "P")
1165 (if arg
1166 (save-excursion
1167 (save-restriction
1168 (narrow-to-region (point) (progn (forward-sexp 1) (point)))
1169 (pp-buffer)
1170 (goto-char (point-max))
1171 (if (eq (char-before) ?\n)
1172 (delete-char -1)))))
1173 (indent-sexp))
1175 ;;;; Lisp paragraph filling commands.
1177 (defcustom emacs-lisp-docstring-fill-column 65
1178 "Value of `fill-column' to use when filling a docstring.
1179 Any non-integer value means do not use a different value of
1180 `fill-column' when filling docstrings."
1181 :type '(choice (integer)
1182 (const :tag "Use the current `fill-column'" t))
1183 :group 'lisp)
1184 (put 'emacs-lisp-docstring-fill-column 'safe-local-variable
1185 (lambda (x) (or (eq x t) (integerp x))))
1187 (defun lisp-fill-paragraph (&optional justify)
1188 "Like \\[fill-paragraph], but handle Emacs Lisp comments and docstrings.
1189 If any of the current line is a comment, fill the comment or the
1190 paragraph of it that point is in, preserving the comment's indentation
1191 and initial semicolons."
1192 (interactive "P")
1193 (or (fill-comment-paragraph justify)
1194 ;; Since fill-comment-paragraph returned nil, that means we're not in
1195 ;; a comment: Point is on a program line; we are interested
1196 ;; particularly in docstring lines.
1198 ;; We bind `paragraph-start' and `paragraph-separate' temporarily. They
1199 ;; are buffer-local, but we avoid changing them so that they can be set
1200 ;; to make `forward-paragraph' and friends do something the user wants.
1202 ;; `paragraph-start': The `(' in the character alternative and the
1203 ;; left-singlequote plus `(' sequence after the \\| alternative prevent
1204 ;; sexps and backquoted sexps that follow a docstring from being filled
1205 ;; with the docstring. This setting has the consequence of inhibiting
1206 ;; filling many program lines that are not docstrings, which is sensible,
1207 ;; because the user probably asked to fill program lines by accident, or
1208 ;; expecting indentation (perhaps we should try to do indenting in that
1209 ;; case). The `;' and `:' stop the paragraph being filled at following
1210 ;; comment lines and at keywords (e.g., in `defcustom'). Left parens are
1211 ;; escaped to keep font-locking, filling, & paren matching in the source
1212 ;; file happy.
1214 ;; `paragraph-separate': A clever regexp distinguishes the first line of
1215 ;; a docstring and identifies it as a paragraph separator, so that it
1216 ;; won't be filled. (Since the first line of documentation stands alone
1217 ;; in some contexts, filling should not alter the contents the author has
1218 ;; chosen.) Only the first line of a docstring begins with whitespace
1219 ;; and a quotation mark and ends with a period or (rarely) a comma.
1221 ;; The `fill-column' is temporarily bound to
1222 ;; `emacs-lisp-docstring-fill-column' if that value is an integer.
1223 (let ((paragraph-start
1224 (concat paragraph-start
1225 (format "\\|\\s-*\\([(;%s\"]\\|`(\\|#'(\\)"
1226 ;; If we're inside a string (like the doc
1227 ;; string), don't consider a colon to be
1228 ;; a paragraph-start character.
1229 (if (nth 3 (syntax-ppss))
1231 ":"))))
1232 (paragraph-separate
1233 (concat paragraph-separate "\\|\\s-*\".*[,\\.]$"))
1234 (fill-column (if (and (integerp emacs-lisp-docstring-fill-column)
1235 (derived-mode-p 'emacs-lisp-mode))
1236 emacs-lisp-docstring-fill-column
1237 fill-column)))
1238 (fill-paragraph justify))
1239 ;; Never return nil.
1242 (defun indent-code-rigidly (start end arg &optional nochange-regexp)
1243 "Indent all lines of code, starting in the region, sideways by ARG columns.
1244 Does not affect lines starting inside comments or strings, assuming that
1245 the start of the region is not inside them.
1247 Called from a program, takes args START, END, COLUMNS and NOCHANGE-REGEXP.
1248 The last is a regexp which, if matched at the beginning of a line,
1249 means don't indent that line."
1250 (interactive "r\np")
1251 (let (state)
1252 (save-excursion
1253 (goto-char end)
1254 (setq end (point-marker))
1255 (goto-char start)
1256 (or (bolp)
1257 (setq state (parse-partial-sexp (point)
1258 (progn
1259 (forward-line 1) (point))
1260 nil nil state)))
1261 (while (< (point) end)
1262 (or (car (nthcdr 3 state))
1263 (and nochange-regexp
1264 (looking-at nochange-regexp))
1265 ;; If line does not start in string, indent it
1266 (let ((indent (current-indentation)))
1267 (delete-region (point) (progn (skip-chars-forward " \t") (point)))
1268 (or (eolp)
1269 (indent-to (max 0 (+ indent arg)) 0))))
1270 (setq state (parse-partial-sexp (point)
1271 (progn
1272 (forward-line 1) (point))
1273 nil nil state))))))
1275 (provide 'lisp-mode)
1277 ;;; lisp-mode.el ends here