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