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