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