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