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