Initial Commit
[packages] / xemacs-packages / prog-modes / cl-indent.el
1 ;;; cl-indent.el --- enhanced lisp-indent mode
2
3 ;; Copyright (C) 2011 Didier Verna
4 ;; Copyright (C) 1987, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
5 ;;   2008, 2009, 2010, 2011 Free Software Foundation, Inc.
6
7 ;; Author: Richard Mlynarik <mly@eddie.mit.edu>
8 ;; Created: July 1987
9 ;; Maintainer: FSF
10 ;; Keywords: lisp, tools
11
12 ;; This file is part of XEmacs.
13
14 ;; XEmacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; XEmacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Synched up with: GNU Emacs 23.3.1
28 ;;; Plus:
29 ;;; - Enhancements on defmethod and lambda-lists indentation by Didier Verna.
30 ;;; - Enhancements on LOOP indentation merged from Slime.
31 ;;; - Support for IF* and a test suite from Nikodemus Siivola.
32
33 ;;; Commentary:
34
35 ;; This package supplies a single entry point, common-lisp-indent-function,
36 ;; which performs indentation in the preferred style for Common Lisp code.
37 ;; To enable it:
38 ;;
39 ;; (setq lisp-indent-function 'common-lisp-indent-function)
40
41 ;;; Code:
42
43 (defgroup lisp-indent nil
44   "Indentation in Lisp."
45   :group 'lisp)
46
47
48 (defcustom lisp-indent-maximum-backtracking 3
49   "Maximum depth to backtrack out from a sublist for structured indentation.
50 If this variable is 0, no backtracking will occur and forms such as `flet'
51 may not be correctly indented."
52   :type 'integer
53   :group 'lisp-indent)
54
55 (defcustom lisp-tag-indentation 1
56   "Indentation of tags relative to containing list.
57 This variable is used by the function `lisp-indent-tagbody'."
58   :type 'integer
59   :group 'lisp-indent)
60
61 (defcustom lisp-tag-body-indentation 3
62   "Indentation of non-tagged lines relative to containing list.
63 This variable is used by the function `lisp-indent-tagbody' to indent normal
64 lines (lines without tags).
65 The indentation is relative to the indentation of the parenthesis enclosing
66 the special form.  If the value is t, the body of tags will be indented
67 as a block at the same indentation as the first s-expression following
68 the tag.  In this case, any forms before the first tag are indented
69 by `lisp-body-indent'."
70   :type 'integer
71   :group 'lisp-indent)
72
73 (defcustom lisp-backquote-indentation t
74   "Whether or not to indent backquoted lists as code.
75 If nil, indent backquoted lists as data, i.e., like quoted lists."
76   :type 'boolean
77   :group 'lisp-indent)
78
79 (defcustom lisp-loop-indent-subclauses t
80   "Whether or not to indent loop subclauses."
81   :type 'boolean
82   :group 'lisp-indent)
83
84 (defcustom lisp-simple-loop-indentation 2
85   "Indentation of forms in simple loop forms."
86   :type 'integer
87   :group 'lisp-indent)
88
89 (defcustom lisp-lambda-list-keyword-alignment nil
90   "Whether to vertically align lambda-list keywords together.
91 If nil (the default), keyworded lambda-list parts are aligned
92 with the initial mandatory arguments, like this:
93
94 \(defun foo (arg1 arg2 &rest rest
95             &key key1 key2)
96   #|...|#)
97
98 If non-nil, alignment is done with the first keyword
99 \(or falls back to the previous case), as in:
100
101 \(defun foo (arg1 arg2 &rest rest
102                       &key key1 key2)
103   #|...|#)"
104   :type 'boolean
105   :group 'lisp-indent)
106
107 (defcustom lisp-lambda-list-keyword-parameter-indentation 2
108   "Indentation of lambda list keyword parameters.
109 See `lisp-lambda-list-keyword-parameter-alignment'
110 for more information."
111   :type 'integer
112   :group 'lisp-indent)
113
114 (defcustom lisp-lambda-list-keyword-parameter-alignment nil
115   "Whether to vertically align lambda-list keyword parameters together.
116 If nil (the default), the parameters are aligned
117 with their corresponding keyword, plus the value of
118 `lisp-lambda-list-keyword-parameter-indentation', like this:
119
120 \(defun foo (arg1 arg2 &key key1 key2
121                         key3 key4)
122   #|...|#)
123
124 If non-nil, alignment is done with the first parameter
125 \(or falls back to the previous case), as in:
126
127 \(defun foo (arg1 arg2 &key key1 key2
128                             key3 key4)
129   #|...|#)"
130   :type 'boolean
131   :group 'lisp-indent)
132
133 \f
134 (defvar lisp-indent-defun-method '(4 &lambda &body)
135   "Defun-like indentation method.
136 This applies when the value of the `common-lisp-indent-function' property
137 is set to `defun'.")
138
139 ;;;; LOOP indentation, the simple version
140
141 (defun common-lisp-loop-type (loop-start)
142   "Returns the type of the loop form at LOOP-START.
143 Possible types are SIMPLE, EXTENDED, and EXTENDED/SPLIT.
144 EXTENDED/SPLIT refers to extended loops whose body does
145 not start on the same line as the opening parenthesis of
146 the loop."
147   (condition-case ()
148       (save-excursion
149         (goto-char loop-start)
150         (let ((line (line-number-at-pos)))
151           (forward-char 1)
152           (forward-sexp 2)
153           (backward-sexp 1)
154           (if (looking-at "\\sw")
155               (if (= line (line-number-at-pos))
156                   'extended
157                 'extended/split)
158             'simple)))
159     (error 'simple)))
160
161 (defun common-lisp-loop-part-indentation (indent-point state)
162   "Compute the indentation of loop form constituents."
163   (let* ((loop-start (elt state 1))
164          (type (common-lisp-loop-type loop-start))
165          (loop-indentation (save-excursion
166                              (goto-char loop-start)
167                              (if (eq 'extended/split type)
168                                  (- (current-column) 4)
169                                (current-column)))))
170     (goto-char indent-point)
171     (beginning-of-line)
172     (cond ((eq 'simple type)
173            (+ loop-indentation lisp-simple-loop-indentation))
174           ((looking-at "^\\s-*\\(:?\\sw+\\|;\\)")
175            (list (+ loop-indentation 6) loop-start))
176           (t
177            (list (+ loop-indentation 9) loop-start)))))
178
179 ;;;###autoload
180 (defun common-lisp-indent-function (indent-point state)
181   "Function to indent the arguments of a Lisp function call.
182 This is suitable for use as the value of the variable
183 `lisp-indent-function'.  INDENT-POINT is the point at which the
184 indentation function is called, and STATE is the
185 `parse-partial-sexp' state at that position.  Browse the
186 `lisp-indent' customize group for options affecting the behavior
187 of this function.
188
189 If the indentation point is in a call to a Lisp function, that
190 function's common-lisp-indent-function property specifies how
191 this function should indent it.  Possible values for this
192 property are:
193
194 * defun, meaning indent according to `lisp-indent-defun-method';
195   i.e., like (4 &lambda &body), as explained below.
196
197 * any other symbol, meaning a function to call.  The function should
198   take the arguments: PATH STATE INDENT-POINT SEXP-COLUMN NORMAL-INDENT.
199   PATH is a list of integers describing the position of point in terms of
200   list-structure with respect to the containing lists.  For example, in
201   ((a b c (d foo) f) g), foo has a path of (0 3 1).  In other words,
202   to reach foo take the 0th element of the outermost list, then
203   the 3rd element of the next list, and finally the 1st element.
204   STATE and INDENT-POINT are as in the arguments to
205   `common-lisp-indent-function'.  SEXP-COLUMN is the column of
206   the open parenthesis of the innermost containing list.
207   NORMAL-INDENT is the column the indentation point was
208   originally in.  This function should behave like `lisp-indent-259'.
209
210 * an integer N, meaning indent the first N arguments like
211   function arguments, and any further arguments like a body.
212   This is equivalent to (4 4 ... &body).
213
214 * a list.  The list element in position M specifies how to indent the Mth
215   function argument.  If there are fewer elements than function arguments,
216   the last list element applies to all remaining arguments.  The accepted
217   list elements are:
218
219   * nil, meaning the default indentation.
220
221   * an integer, specifying an explicit indentation.
222
223   * &lambda.  Indent the argument (which may be a list) by 4.
224
225   * &rest.  When used, this must be the penultimate element.  The
226     element after this one applies to all remaining arguments.
227
228   * &body.  This is equivalent to &rest lisp-body-indent, i.e., indent
229     all remaining elements by `lisp-body-indent'.
230
231   * &whole.  This must be followed by nil, an integer, or a
232     function symbol.  This indentation is applied to the
233     associated argument, and as a base indent for all remaining
234     arguments.  For example, an integer P means indent this
235     argument by P, and all remaining arguments by P, plus the
236     value specified by their associated list element.
237
238   * a symbol.  A function to call, with the 6 arguments specified above.
239
240   * a list, with elements as described above.  This applies when the
241     associated function argument is itself a list.  Each element of the list
242     specifies how to indent the associated argument.
243
244 For example, the function `case' has an indent property
245 \(4 &rest (&whole 2 &rest 1)), meaning:
246   * indent the first argument by 4.
247   * arguments after the first should be lists, and there may be any number
248     of them.  The first list element has an offset of 2, all the rest
249     have an offset of 2+1=3."
250   (common-lisp-indent-function-1 indent-point state))
251
252
253 (defun common-lisp-indent-function-1 (indent-point state)
254   (let ((normal-indent (current-column)))
255     ;; Walk up list levels until we see something
256     ;;  which does special things with subforms.
257     (let ((depth 0)
258           ;; Path describes the position of point in terms of
259           ;;  list-structure with respect to containing lists.
260           ;; `foo' has a path of (0 3 1) in `((a b c (d foo) f) g)'.
261           (path ())
262           ;; set non-nil when somebody works out the indentation to use
263           calculated
264           ;; If non-nil, this is an indentation to use
265           ;; if nothing else specifies it more firmly.
266           tentative-calculated
267           (last-point indent-point)
268           ;; the position of the open-paren of the innermost containing list
269           (containing-form-start (elt state 1))
270           ;; the column of the above
271           sexp-column)
272       ;; Move to start of innermost containing list
273       (goto-char containing-form-start)
274       (setq sexp-column (current-column))
275
276       ;; Look over successively less-deep containing forms
277       (while (and (not calculated)
278                   (< depth lisp-indent-maximum-backtracking))
279         (let ((containing-sexp (point)))
280           (forward-char 1)
281           (parse-partial-sexp (point) indent-point 1 t)
282           ;; Move to the car of the relevant containing form
283           (let (tem function method tentative-defun)
284             (if (not (looking-at "\\sw\\|\\s_"))
285                 ;; This form doesn't seem to start with a symbol
286                 (setq function nil method nil)
287               (setq tem (point))
288               (forward-sexp 1)
289               (setq function (downcase (buffer-substring-no-properties
290                                         tem (point))))
291               (goto-char tem)
292               (setq tem (intern-soft function)
293                     method (get tem 'common-lisp-indent-function))
294               (cond ((and (null method)
295                           (string-match ":[^:]+" function))
296                      ;; The pleblisp package feature
297                      (setq function (substring function
298                                                (1+ (match-beginning 0)))
299                            method (get (intern-soft function)
300                                        'common-lisp-indent-function)))
301                     ((and (null method))
302                      ;; backwards compatibility
303                      (setq method (get tem 'lisp-indent-function)))))
304             (let ((n 0))
305               ;; How far into the containing form is the current form?
306               (if (< (point) indent-point)
307                   (while (condition-case ()
308                              (progn
309                                (forward-sexp 1)
310                                (if (>= (point) indent-point)
311                                    nil
312                                  (parse-partial-sexp (point)
313                                                      indent-point 1 t)
314                                  (setq n (1+ n))
315                                  t))
316                            (error nil))))
317               (setq path (cons n path)))
318
319             ;; backwards compatibility.
320             (cond ((null function))
321                   ((null method)
322                    (when (null (cdr path))
323                      ;; (package prefix was stripped off above)
324                      (cond ((and (string-match "\\`def" function)
325                                  (not (string-match "\\`default" function)))
326                             (setq tentative-defun t))
327                            ((string-match
328                              (eval-when-compile
329                               (concat "\\`\\("
330                                       (regexp-opt '("with" "without" "do"))
331                                       "\\)-"))
332                              function)
333                             (setq method '(&lambda &body))))))
334                   ;; backwards compatibility.  Bletch.
335                   ((eq method 'defun)
336                    (setq method lisp-indent-defun-method)))
337
338             (cond ((and (or (eq (char-after (1- containing-sexp)) ?\')
339                             (and (not lisp-backquote-indentation)
340                                  (eq (char-after (1- containing-sexp)) ?\`)))
341                         (not (eq (char-after (- containing-sexp 2)) ?\#)))
342                    ;; No indentation for "'(...)" elements
343                    (setq calculated (1+ sexp-column)))
344                   ((save-excursion
345                      (goto-char indent-point)
346                      (backward-sexp)
347                      (let ((xxx (buffer-substring-no-properties
348                                  (point) (+ (point) 3))))
349                        (and (eq ?\# (elt xxx 0))
350                             (or (member (elt xxx 1) '(?\+ ?\-))
351                                 (and (eq ?\! (elt xxx 1))
352                                      (member (elt xxx 2) '(?\+ ?\-)))))))
353                    normal-indent)
354                   ((eq (char-after (1- containing-sexp)) ?\#)
355                    ;; "#(...)"
356                    (setq calculated (1+ sexp-column)))
357                   ((null method)
358                    ;; If this looks like a call to a `def...' form,
359                    ;; think about indenting it as one, but do it
360                    ;; tentatively for cases like
361                    ;; (flet ((defunp ()
362                    ;;          nil)))
363                    ;; Set both normal-indent and tentative-calculated.
364                    ;; The latter ensures this value gets used
365                    ;; if there are no relevant containing constructs.
366                    ;; The former ensures this value gets used
367                    ;; if there is a relevant containing construct
368                    ;; but we are nested within the structure levels
369                    ;; that it specifies indentation for.
370                    (if tentative-defun
371                        (setq tentative-calculated
372                              (common-lisp-indent-call-method
373                               function lisp-indent-defun-method
374                               path state indent-point
375                               sexp-column normal-indent)
376                              normal-indent tentative-calculated)))
377                   ((integerp method)
378                    ;; convenient top-level hack.
379                    ;;  (also compatible with lisp-indent-function)
380                    ;; The number specifies how many `distinguished'
381                    ;;  forms there are before the body starts
382                    ;; Equivalent to (4 4 ... &body)
383                    (setq calculated (cond ((cdr path)
384                                            normal-indent)
385                                           ((<= (car path) method)
386                                            ;; `distinguished' form
387                                            (list (+ sexp-column 4)
388                                                  containing-form-start))
389                                           ((= (car path) (1+ method))
390                                            ;; first body form.
391                                            (+ sexp-column lisp-body-indent))
392                                           (t
393                                            ;; other body form
394                                            normal-indent))))
395                   (t
396                    (setq calculated
397                          (common-lisp-indent-call-method
398                           function method path state indent-point
399                           sexp-column normal-indent)))))
400           (goto-char containing-sexp)
401           (setq last-point containing-sexp)
402           (unless calculated
403             (condition-case ()
404                 (progn (backward-up-list 1)
405                        (setq depth (1+ depth)))
406               (error (setq depth lisp-indent-maximum-backtracking))))))
407       (or calculated tentative-calculated))))
408
409
410 (defun common-lisp-indent-call-method (function method path state indent-point
411                                        sexp-column normal-indent)
412   (let ((lisp-indent-error-function function))
413     (if (symbolp method)
414         (funcall method
415                  path state indent-point
416                  sexp-column normal-indent)
417       (lisp-indent-259 method path state indent-point
418                        sexp-column normal-indent))))
419
420 ;; Dynamically bound in common-lisp-indent-call-method.
421 (defvar lisp-indent-error-function)
422
423 (defun lisp-indent-report-bad-format (m)
424   (error "%s has a badly-formed %s property: %s"
425          ;; Love those free variable references!!
426          lisp-indent-error-function 'common-lisp-indent-function m))
427
428
429 ;; Lambda-list indentation is now done in LISP-INDENT-LAMBDA-LIST.
430 ;; See also `lisp-lambda-list-keyword-alignment',
431 ;; `lisp-lambda-list-keyword-parameter-alignment' and
432 ;; `lisp-lambda-list-keyword-parameter-indentation' -- dvl
433
434 (defvar lisp-indent-lambda-list-keywords-regexp
435   "&\\(\
436 optional\\|rest\\|key\\|allow-other-keys\\|aux\\|whole\\|body\\|environment\
437 \\|more\\)\\([ \t]\\|$\\)"
438   "Regular expression matching lambda-list keywords.")
439
440 ;; #### NOTE: the two functions below won't handle the presence of comments
441 ;; correctly, although this is really a problem with FORWARD-SEXP and
442 ;; BACKWARD-SEXP. -- dvl
443
444 (defun lisp-lambda-list-first-keyword-column (start limit)
445   "Return the column number of the first keyword in a lambda-list.
446 The keyword is searched from START forward to LIMIT across s-expressions.
447 Return its column number if found, or nil."
448   (save-excursion
449     (goto-char start)
450     (skip-chars-forward " \t\n")
451     (save-match-data
452       (condition-case nil
453           (progn
454             (while (not (looking-at lisp-indent-lambda-list-keywords-regexp))
455               (forward-sexp)
456               (skip-chars-forward " \t\n")
457               (when (>= (point) limit)
458                 (error 'scan-error)))
459             (when (looking-at lisp-indent-lambda-list-keywords-regexp)
460               (current-column)))
461         (scan-error nil)))))
462
463 (defun lisp-lambda-list-keyword-parameter-column (end)
464   "Return the indentation column of a keyword parameter in a lambda-list.
465 The corresponding keyword is searched from END back across s-expressions.
466 If not found, return nil. Otherwise, return the appropriate column,
467 according to `lisp-lambda-list-keyword-parameter-indentation' and
468 `lisp-lambda-list-keyword-parameter-alignment'."
469   (save-excursion
470     (goto-char end)
471     (forward-line -1)
472     (end-of-line)
473     (save-match-data
474       (condition-case nil
475           (progn
476             (backward-sexp)
477             (while (not (looking-at lisp-indent-lambda-list-keywords-regexp))
478               (backward-sexp))
479             (when (looking-at lisp-indent-lambda-list-keywords-regexp)
480               (let* ((posn (current-column))
481                      (indented-posn
482                       (+ posn
483                          lisp-lambda-list-keyword-parameter-indentation)))
484                 (forward-sexp)
485                 (skip-chars-forward " \t")
486                 (if (eolp)
487                     indented-posn
488                   (if lisp-lambda-list-keyword-parameter-alignment
489                       (current-column)
490                     indented-posn)))))
491         (scan-error nil)))))
492
493 (defun lisp-indent-lambda-list
494     (indent-point sexp-column containing-form-start)
495   (let (limit)
496     (cond ((save-excursion
497              (goto-char indent-point)
498              (back-to-indentation)
499              (setq limit (point))
500              (looking-at lisp-indent-lambda-list-keywords-regexp))
501            ;; We're facing a lambda-list keyword.
502            (if lisp-lambda-list-keyword-alignment
503                ;; Align to the first keyword if any, or to the beginning of
504                ;; the lambda-list.
505                (or (lisp-lambda-list-first-keyword-column
506                     (1+ containing-form-start) limit)
507                    (1+ sexp-column))
508              ;; Align to the beginning of the lambda-list.
509              (1+ sexp-column)))
510           (t
511            ;; We're facing a parameter. Align as a keyword parameter if that
512            ;; is the case, or to the beginning of the lambda-list.
513            (or (lisp-lambda-list-keyword-parameter-column indent-point)
514                (1+ sexp-column))))))
515
516 ;; Blame the crufty control structure on dynamic scoping
517 ;;  -- not on me!
518 (defun lisp-indent-259
519     (method path state indent-point sexp-column normal-indent)
520   (catch 'exit
521     (let ((p path)
522           (containing-form-start (elt state 1))
523           n tem tail)
524       ;; Isn't tail-recursion wonderful?
525       (while p
526         ;; This while loop is for destructuring.
527         ;; p is set to (cdr p) each iteration.
528         (if (not (consp method)) (lisp-indent-report-bad-format method))
529         (setq n (1- (car p))
530               p (cdr p)
531               tail nil)
532         (while n
533           ;; This while loop is for advancing along a method
534           ;; until the relevant (possibly &rest/&body) pattern
535           ;; is reached.
536           ;; n is set to (1- n) and method to (cdr method)
537           ;; each iteration.
538           (setq tem (car method))
539
540           (or (eq tem 'nil)             ;default indentation
541               (eq tem '&lambda)         ;lambda list
542               (and (eq tem '&body) (null (cdr method)))
543               (and (eq tem '&rest)
544                    (consp (cdr method))
545                    (null (cddr method)))
546               (integerp tem)            ;explicit indentation specified
547               (and (consp tem)          ;destructuring
548                    (eq (car tem) '&whole)
549                    (or (symbolp (cadr tem))
550                        (integerp (cadr tem))))
551               (and (symbolp tem)        ;a function to call to do the work.
552                    (null (cdr method)))
553               (lisp-indent-report-bad-format method))
554
555           (cond ((eq tem '&body)
556                  ;; &body means (&rest <lisp-body-indent>)
557                  (throw 'exit
558                    (if (and (= n 0)     ;first body form
559                             (null p))   ;not in subforms
560                        (+ sexp-column
561                           lisp-body-indent)
562                        normal-indent)))
563                 ((eq tem '&rest)
564                  ;; this pattern holds for all remaining forms
565                  (setq tail (> n 0)
566                        n 0
567                        method (cdr method)))
568                 ((> n 0)
569                  ;; try next element of pattern
570                  (setq n (1- n)
571                        method (cdr method))
572                  (if (< n 0)
573                      ;; Too few elements in pattern.
574                      (throw 'exit normal-indent)))
575                 ((eq tem 'nil)
576                  (throw 'exit (if (consp normal-indent)
577                                   normal-indent
578                                 (list normal-indent containing-form-start))))
579                 ((eq tem '&lambda)
580                  (throw 'exit
581                         (cond ((null p)
582                                (list (+ sexp-column 4) containing-form-start))
583                               (t
584                                ;; Indentation within a lambda-list. -- dvl
585                                (list (lisp-indent-lambda-list
586                                       indent-point
587                                       sexp-column
588                                       containing-form-start)
589                                      containing-form-start)))))
590                 ((integerp tem)
591                  (throw 'exit
592                    (if (null p)         ;not in subforms
593                        (list (+ sexp-column tem) containing-form-start)
594                        normal-indent)))
595                 ((symbolp tem)          ;a function to call
596                  (throw 'exit
597                    (funcall tem path state indent-point
598                             sexp-column normal-indent)))
599                 (t
600                  ;; must be a destructing frob
601                  (if (not (null p))
602                      ;; descend
603                (setq method (cddr tem)
604                            n nil)
605                (setq tem (cadr tem))
606                    (throw 'exit
607                      (cond (tail
608                             normal-indent)
609                            ((eq tem 'nil)
610                             (list normal-indent
611                                   containing-form-start))
612                            ((integerp tem)
613                             (list (+ sexp-column tem)
614                                   containing-form-start))
615                            (t
616                             (funcall tem path state indent-point
617                                      sexp-column normal-indent))))))))))))
618 \f
619 (defun lisp-indent-tagbody (path state indent-point sexp-column normal-indent)
620   (if (not (null (cdr path)))
621       normal-indent
622     (save-excursion
623       (goto-char indent-point)
624       (back-to-indentation)
625       (list (cond ((looking-at "\\sw\\|\\s_")
626                    ;; a tagbody tag
627                    (+ sexp-column lisp-tag-indentation))
628                   ((integerp lisp-tag-body-indentation)
629                    (+ sexp-column lisp-tag-body-indentation))
630                   ((eq lisp-tag-body-indentation 't)
631                    (condition-case ()
632                        (progn (backward-sexp 1) (current-column))
633                      (error (1+ sexp-column))))
634                   (t (+ sexp-column lisp-body-indent)))
635 ;            (cond ((integerp lisp-tag-body-indentation)
636 ;                   (+ sexp-column lisp-tag-body-indentation))
637 ;                  ((eq lisp-tag-body-indentation 't)
638 ;                   normal-indent)
639 ;                  (t
640 ;                   (+ sexp-column lisp-body-indent)))
641             (elt state 1)
642             ))))
643
644 (defun lisp-indent-do (path state indent-point sexp-column normal-indent)
645   (if (>= (car path) 3)
646       (let ((lisp-tag-body-indentation lisp-body-indent))
647         (funcall (function lisp-indent-tagbody)
648                  path state indent-point sexp-column normal-indent))
649     (funcall (function lisp-indent-259)
650              '((&whole nil &rest
651                 ;; the following causes weird indentation
652                 ;;(&whole 1 1 2 nil)
653                 )
654                (&whole nil &rest 1))
655              path state indent-point sexp-column normal-indent)))
656
657
658 ;; LISP-INDENT-DEFMETHOD now supports the presence of more than one method
659 ;; qualifier and indents the method's lambda list properly. -- dvl
660 (defun lisp-indent-defmethod
661     (path state indent-point sexp-column normal-indent)
662   (lisp-indent-259
663    (let ((nqual 0))
664      (if (and (>= (car path) 3)
665               (save-excursion
666                 (beginning-of-defun)
667                 (forward-char 1)
668                 (forward-sexp 2)
669                 (skip-chars-forward " \t\n")
670                 (while (looking-at "\\sw\\|\\s_")
671                   (incf nqual)
672                   (forward-sexp)
673                   (skip-chars-forward " \t\n"))
674                 (> nqual 0)))
675          (append '(4) (make-list nqual 4) '(&lambda &body))
676          (get 'defun 'common-lisp-indent-function)))
677    path state indent-point sexp-column normal-indent))
678
679
680 (defun lisp-indent-function-lambda-hack (path state indent-point
681                                          sexp-column normal-indent)
682   ;; indent (function (lambda () <newline> <body-forms>)) kludgily.
683   (if (or (cdr path) ; wtf?
684           (> (car path) 3))
685       ;; line up under previous body form
686       normal-indent
687     ;; line up under function rather than under lambda in order to
688     ;;  conserve horizontal space.  (Which is what #' is for.)
689     (condition-case ()
690         (save-excursion
691           (backward-up-list 2)
692           (forward-char 1)
693           (if (looking-at "\\(lisp:+\\)?function\\(\\Sw\\|\\S_\\)")
694               (+ lisp-body-indent -1 (current-column))
695               (+ sexp-column lisp-body-indent)))
696        (error (+ sexp-column lisp-body-indent)))))
697
698 (defun lisp-indent-loop (path state indent-point sexp-column normal-indent)
699   (if lisp-loop-indent-subclauses
700       (list (common-lisp-indent-loop-macro-1 state indent-point)
701             (common-lisp-indent-parse-state-start state))
702     (common-lisp-loop-part-indentation indent-point state)))
703
704 ;;;; LOOP indentation, the complex version -- handles subclause indentation
705
706 ;; Regexps matching various varieties of loop macro keyword ...
707 (defvar common-lisp-indent-body-introducing-loop-macro-keyword
708   "do\\|finally\\|initially"
709   "Regexp matching loop macro keywords which introduce body-forms.")
710
711 ;; This is so "and when" and "else when" get handled right
712 ;; (not to mention "else do" !!!)
713 (defvar common-lisp-indent-prefix-loop-macro-keyword
714   "and\\|else"
715   "Regexp matching loop macro keywords which are prefixes.")
716
717 (defvar common-lisp-indent-clause-joining-loop-macro-keyword
718   "and"
719   "Regexp matching 'and', and anything else there ever comes to be like it.")
720
721 ;; This is handled right, but it's incomplete ...
722 ;; (It could probably get arbitrarily long if I did *every* iteration-path)
723 (defvar common-lisp-indent-indented-loop-macro-keyword
724   "into\\|by\\|upto\\|downto\\|above\\|below\\|on\\|being\\|=\\|first\\|then\\|from\\|to"
725   "Regexp matching keywords introducing loop subclauses.
726 Always indented two.")
727
728 (defvar common-lisp-indent-indenting-loop-macro-keyword
729   "when\\|unless\\|if"
730   "Regexp matching keywords introducing conditional clauses.
731 Cause subsequent clauses to be indented.")
732
733 (defvar common-lisp-indent-loop-macro-else-keyword "else")
734
735 ;;; Attempt to indent the loop macro ...
736
737 (defun common-lisp-indent-parse-state-depth (parse-state)
738   (car parse-state))
739
740 (defun common-lisp-indent-parse-state-start (parse-state)
741   (car (cdr parse-state)))
742
743 (defun common-lisp-indent-parse-state-prev (parse-state)
744   (car (cdr (cdr parse-state))))
745
746 (defun common-lisp-indent-loop-macro-1 (parse-state indent-point)
747   (catch 'return-indentation
748     (save-excursion
749       ;; Find first clause of loop macro, and use it to establish
750       ;; base column for indentation
751       (goto-char (common-lisp-indent-parse-state-start parse-state))
752       (let ((loop-start-column (current-column)))
753         (common-lisp-indent-loop-advance-past-keyword-on-line)
754
755         (when (eolp)
756           (forward-line 1)
757           (end-of-line)
758           ;; If indenting first line after "(loop <newline>"
759           ;; cop out ...
760           (if (<= indent-point (point))
761               (throw 'return-indentation (+ 2 loop-start-column)))
762           (back-to-indentation))
763
764         (let* ((case-fold-search t)
765                (loop-macro-first-clause (point))
766                (previous-expression-start
767                 (common-lisp-indent-parse-state-prev parse-state))
768                (default-value (current-column))
769                (loop-body-p nil)
770                (loop-body-indentation nil)
771                (indented-clause-indentation (+ 2 default-value)))
772           ;; Determine context of this loop clause, starting with the
773           ;; expression immediately preceding the line we're trying to indent
774           (goto-char previous-expression-start)
775
776           ;; Handle a body-introducing-clause which ends a line specially.
777           (if (looking-at
778                common-lisp-indent-body-introducing-loop-macro-keyword)
779               (let ((keyword-position (current-column)))
780                 (setq loop-body-p t)
781                 (setq loop-body-indentation
782                       (if (common-lisp-indent-loop-advance-past-keyword-on-line)
783                           (current-column)
784                         (back-to-indentation)
785                         (if (/= (current-column) keyword-position)
786                             (+ 2 (current-column))
787                           (+ keyword-position 3)))))
788
789             (back-to-indentation)
790             (if (< (point) loop-macro-first-clause)
791                 (goto-char loop-macro-first-clause))
792             ;; If there's an "and" or "else," advance over it.
793             ;; If it is alone on the line, the next "cond" will treat it
794             ;; as if there were a "when" and indent under it ...
795             (let ((exit nil))
796               (while (and (null exit)
797                           (looking-at
798                            common-lisp-indent-prefix-loop-macro-keyword))
799                 (if (null
800                      (common-lisp-indent-loop-advance-past-keyword-on-line))
801                     (progn (setq exit t)
802                            (back-to-indentation)))))
803
804             ;; Found start of loop clause preceding the one we're trying to
805             ;; indent. Glean context ...
806             (cond
807              ((looking-at "(")
808               ;; We're in the middle of a clause body ...
809               (setq loop-body-p t)
810               (setq loop-body-indentation (current-column)))
811              ((looking-at
812                common-lisp-indent-body-introducing-loop-macro-keyword)
813               (setq loop-body-p t)
814               ;; Know there's something else on the line (or would
815               ;; have been caught above)
816               (common-lisp-indent-loop-advance-past-keyword-on-line)
817               (setq loop-body-indentation (current-column)))
818              (t
819               (setq loop-body-p nil)
820               (if (or (looking-at
821                        common-lisp-indent-indenting-loop-macro-keyword)
822                       (looking-at
823                        common-lisp-indent-prefix-loop-macro-keyword))
824                   (setq default-value (+ 2 (current-column))))
825               (setq indented-clause-indentation (+ 2 (current-column)))
826               ;; We still need loop-body-indentation for "syntax errors" ...
827               (goto-char previous-expression-start)
828               (setq loop-body-indentation (current-column)))))
829
830           ;; Go to first non-blank character of the line we're trying to
831           ;; indent. (if none, wind up poised on the new-line ...)
832           (goto-char indent-point)
833           (back-to-indentation)
834           (cond
835            ((looking-at "(")
836             ;; Clause body ...
837             loop-body-indentation)
838            ((or (eolp) (looking-at ";"))
839             ;; Blank line.  If body-p, indent as body, else indent as
840             ;; vanilla clause.
841             (if loop-body-p
842                 loop-body-indentation
843               default-value))
844            ((looking-at common-lisp-indent-indented-loop-macro-keyword)
845             indented-clause-indentation)
846            ((looking-at common-lisp-indent-clause-joining-loop-macro-keyword)
847             (let ((stolen-indent-column nil))
848               (forward-line -1)
849               (while (and (null stolen-indent-column)
850                           (> (point) loop-macro-first-clause))
851                 (back-to-indentation)
852                 (if (and (< (current-column) loop-body-indentation)
853                          (looking-at "\\sw"))
854                     (progn
855                       (if (looking-at
856                            common-lisp-indent-loop-macro-else-keyword)
857                           (common-lisp-indent-loop-advance-past-keyword-on-line))
858                       (setq stolen-indent-column
859                             (current-column)))
860                   (forward-line -1)))
861               (if stolen-indent-column
862                   stolen-indent-column
863                 default-value)))
864            (t default-value)))))))
865
866 (defun common-lisp-indent-loop-advance-past-keyword-on-line ()
867   (forward-word 1)
868   (while (and (looking-at "\\s-") (not (eolp)))
869     (forward-char 1))
870   (if (eolp)
871       nil
872     (current-column)))
873
874 ;;;; IF* is not standard, but a plague upon the land
875 ;;;; ...let's at least try to indent it.
876
877 (defvar common-lisp-indent-if*-keyword
878   "threnret\\|elseif\\|then\\|else"
879   "Regexp matching if* keywords")
880
881 (defun common-lisp-indent-if*
882     (path parse-state indent-point sexp-column normal-indent)
883   (list (common-lisp-indent-if*-1 parse-state indent-point)
884         (common-lisp-indent-parse-state-start parse-state)))
885
886 (defun common-lisp-indent-if*-1 (parse-state indent-point)
887   (catch 'return-indentation
888     (save-excursion
889       ;; Find first clause of if* macro, and use it to establish
890       ;; base column for indentation
891       (goto-char (common-lisp-indent-parse-state-start parse-state))
892       (let ((if*-start-column (current-column)))
893         (common-lisp-indent-if*-advance-past-keyword-on-line)
894         (let* ((case-fold-search t)
895                (if*-first-clause (point))
896                (previous-expression-start
897                 (common-lisp-indent-parse-state-prev parse-state))
898                (default-value (current-column))
899                (if*-body-p nil)
900                (if*-body-indentation nil))
901           ;; Determine context of this if* clause, starting with the
902           ;; expression immediately preceding the line we're trying to indent
903           (goto-char previous-expression-start)
904           ;; Handle a body-introducing-clause which ends a line specially.
905           (back-to-indentation)
906           (if (< (point) if*-first-clause)
907               (goto-char if*-first-clause))
908           ;; Found start of if* clause preceding the one we're trying to indent.
909           ;; Glean context ...
910           (cond
911            ((looking-at common-lisp-indent-if*-keyword)
912             (setq if*-body-p t)
913             ;; Know there's something else on the line (or would
914             ;; have been caught above)
915             (common-lisp-indent-if*-advance-past-keyword-on-line)
916             (setq if*-body-indentation (current-column)))
917            ((looking-at "#'\\|'\\|(")
918             ;; We're in the middle of a clause body ...
919             (setq if*-body-p t)
920             (setq if*-body-indentation (current-column)))
921            (t
922             (setq if*-body-p nil)
923             ;; We still need if*-body-indentation for "syntax errors" ...
924             (goto-char previous-expression-start)
925             (setq if*-body-indentation (current-column))))
926
927           ;; Go to first non-blank character of the line we're trying to indent.
928           ;; (if none, wind up poised on the new-line ...)
929           (goto-char indent-point)
930           (back-to-indentation)
931           (cond
932            ((or (eolp) (looking-at ";"))
933             ;; Blank line.  If body-p, indent as body, else indent as
934             ;; vanilla clause.
935             (if if*-body-p
936                 if*-body-indentation
937               default-value))
938            ((not (looking-at common-lisp-indent-if*-keyword))
939             ;; Clause body ...
940             if*-body-indentation)
941            (t
942             (- (+ 7 if*-start-column)
943                (- (match-end 0) (match-beginning 0))))))))))
944
945 (defun common-lisp-indent-if*-advance-past-keyword-on-line ()
946   (forward-word 1)
947   (block move-forward
948     (while (and (looking-at "\\s-") (not (eolp)))
949       (forward-char 1)))
950   (if (eolp)
951       nil
952     (current-column)))
953
954 \f
955 ;;;; Indentation specs for standard symbols, and a few semistandard ones.
956 (let ((l '((block 1)
957            (case        (4 &rest (&whole 2 &rest 1)))
958            (ccase . case)
959            (ecase . case)
960            (typecase . case)
961            (etypecase . case)
962            (ctypecase . case)
963            (catch 1)
964            (cond        (&rest (&whole 2 &rest 1)))
965            (defvar      (4 2 2))
966            (defclass    (6 4 (&whole 2 &rest 1) (&whole 2 &rest 1)))
967            (defconstant . defvar)
968            (defcustom   (4 2 2 2))
969            (defparameter . defvar)
970            (defconst     . defcustom)
971            (define-condition  . defclass)
972            (define-modify-macro (4 &lambda &body))
973            (defsetf     (4 &lambda 4 &body))
974            (defun       (4 &lambda &body))
975            (defgeneric  (4 &lambda &body))
976            (define-setf-method . defun)
977            (define-setf-expander . defun)
978            (defmacro . defun)
979            (defsubst . defun)
980            (deftype . defun)
981            (defmethod   lisp-indent-defmethod)
982            (defpackage  (4 2))
983            (defstruct   ((&whole 4 &rest (&whole 2 &rest 1))
984                          &rest (&whole 2 &rest 1)))
985            (destructuring-bind
986                         ((&whole 6 &rest 1) 4 &body))
987            (do          lisp-indent-do)
988            (do* . do)
989            (dolist      ((&whole 4 2 1) &body))
990            (dotimes . dolist)
991            (eval-when   1)
992            (flet        ((&whole 4 &rest (&whole 1 &lambda &body)) &body))
993            (labels . flet)
994            (macrolet . flet)
995            (generic-flet . flet)
996            (generic-labels . flet)
997            (handler-case (4 &rest (&whole 2 &lambda &body)))
998            (restart-case . handler-case)
999            ;; `else-body' style
1000            (if          (nil nil &body))
1001            ;; single-else style (then and else equally indented)
1002            (if          (&rest nil))
1003            (if*         common-lisp-indent-if*)
1004            (lambda      (&lambda &rest lisp-indent-function-lambda-hack))
1005            (let         ((&whole 4 &rest (&whole 1 1 2)) &body))
1006            (let* . let)
1007            (compiler-let . let) ;barf
1008            (handler-bind . let)
1009            (restart-bind . let)
1010            (locally 1)
1011            (loop           lisp-indent-loop)
1012            (:method (&lambda &body)) ; in `defgeneric'
1013            (multiple-value-bind ((&whole 6 &rest 1) 4 &body))
1014            (multiple-value-call (4 &body))
1015            (multiple-value-prog1 1)
1016            (multiple-value-setq (4 2))
1017            (multiple-value-setf . multiple-value-setq)
1018            (pprint-logical-block (4 2))
1019            (print-unreadable-object ((&whole 4 1 &rest 1) &body))
1020            ;; Combines the worst features of BLOCK, LET and TAGBODY
1021            (prog        (&lambda &rest lisp-indent-tagbody))
1022            (prog* . prog)
1023            (prog1 1)
1024            (prog2 2)
1025            (progn 0)
1026            (progv       (4 4 &body))
1027            (return 0)
1028            (return-from (nil &body))
1029            (symbol-macrolet . let)
1030            (tagbody     lisp-indent-tagbody)
1031            (throw 1)
1032            (unless 1)
1033            (unwind-protect (5 &body))
1034            (when 1)
1035            (with-accessors . multiple-value-bind)
1036            (with-condition-restarts . multiple-value-bind)
1037            (with-output-to-string (4 2))
1038            (with-slots . multiple-value-bind)
1039            (with-standard-io-syntax (2)))))
1040   (dolist (el l)
1041     (put (car el) 'common-lisp-indent-function
1042          (if (symbolp (cdr el))
1043              (get (cdr el) 'common-lisp-indent-function)
1044              (car (cdr el))))))
1045
1046 (defun test-lisp-indent (tests)
1047   (let ((ok 0))
1048     (dolist (test tests)
1049      (with-temp-buffer
1050        (lisp-mode)
1051        (setq indent-tabs-mode nil)
1052        (when (consp test)
1053          (dolist (bind (first test))
1054            (make-variable-buffer-local (first bind))
1055            (set (first bind) (second bind)))
1056          (setf test (second test)))
1057        (insert test)
1058        (goto-char 0)
1059        (skip-chars-forward " \t\n")
1060        ;; Mess up the indentation so we know reindentation works
1061        (let ((mess nil))
1062          (save-excursion
1063            (while (not (eobp))
1064              (forward-line 1)
1065              (ignore-errors (delete-char 1) (setf mess t))))
1066          (if (not mess)
1067              (error "Couldn't mess up indentation?")))
1068        (indent-sexp)
1069        (if (equal (buffer-string) test)
1070            (incf ok)
1071            (error "Bad indentation.\nWanted: %s\nGot: %s"
1072                   test
1073                   (buffer-string)))))
1074     ok))
1075
1076 ;; (run-lisp-indent-tests)
1077
1078 (defun run-lisp-indent-tests ()
1079   (test-lisp-indent
1080    '("
1081  (defun foo ()
1082    t)"
1083      (((lisp-lambda-list-keyword-parameter-alignment nil)
1084        (lisp-lambda-list-keyword-alignment nil))
1085       "
1086  (defun foo (foo &optional opt1
1087                    opt2
1088              &rest rest)
1089    (list foo opt1 opt2
1090          rest))")
1091      (((lisp-lambda-list-keyword-parameter-alignment t)
1092        (lisp-lambda-list-keyword-alignment nil))
1093       "
1094  (defun foo (foo &optional opt1
1095                            opt2
1096              &rest rest)
1097    (list foo opt1 opt2
1098          rest))")
1099      (((lisp-lambda-list-keyword-parameter-alignment nil)
1100        (lisp-lambda-list-keyword-alignment t))
1101       "
1102  (defun foo (foo &optional opt1
1103                    opt2
1104                  &rest rest)
1105    (list foo opt1 opt2
1106          rest))")
1107      (((lisp-lambda-list-keyword-parameter-alignment t)
1108        (lisp-lambda-list-keyword-alignment t))
1109       "
1110  (defun foo (foo &optional opt1
1111                            opt2
1112                  &rest rest)
1113    (list foo opt1 opt2
1114          rest))")
1115      (((lisp-lambda-list-keyword-parameter-alignment nil)
1116        (lisp-lambda-list-keyword-alignment nil))
1117       "
1118  (defmacro foo ((foo &optional opt1
1119                        opt2
1120                  &rest rest))
1121    (list foo opt1 opt2
1122          rest))")
1123      (((lisp-lambda-list-keyword-parameter-alignment t)
1124        (lisp-lambda-list-keyword-alignment nil))
1125       "
1126  (defmacro foo ((foo &optional opt1
1127                                opt2
1128                  &rest rest))
1129    (list foo opt1 opt2
1130          rest))")
1131      (((lisp-lambda-list-keyword-parameter-alignment nil)
1132        (lisp-lambda-list-keyword-alignment t))
1133       "
1134  (defmacro foo ((foo &optional opt1
1135                        opt2
1136                      &rest rest))
1137    (list foo opt1 opt2
1138          rest))")
1139      (((lisp-lambda-list-keyword-parameter-alignment t)
1140        (lisp-lambda-list-keyword-alignment t))
1141       "
1142  (defmacro foo ((foo &optional opt1
1143                                opt2
1144                      &rest rest))
1145    (list foo opt1 opt2
1146          rest))")
1147      "
1148   (let ((x y)
1149         (foo #-foo (no-foo)
1150              #+foo (yes-foo))
1151         (bar #-bar
1152              (no-bar)
1153              #+bar
1154              (yes-bar)))
1155     (list foo bar
1156           x))"
1157      "
1158   (loop for i from 0 below 2
1159         for j from 0 below 2
1160         when foo
1161           do (fubar)
1162              (bar)
1163              (moo)
1164           and collect cash
1165                 into honduras
1166         else do ;; this is the body of the first else
1167                 ;; the body is ...
1168                 (indented to the above comment)
1169                 (ZMACS gets this wrong)
1170              and do this
1171              and do that
1172              and when foo
1173                    do the-other
1174                    and cry
1175         when this-is-a-short-condition do
1176           (body code of the when)
1177         when here's something I used to botch do (here is a body)
1178                                                  (rest of body indented same)
1179         do
1180            (exdented loop body)
1181            (I'm not sure I like this but it's compatible)
1182         when funny-predicate do ;; Here's a comment
1183                                 (body filled to comment))"
1184      "
1185   (defun foo (x)
1186     (tagbody
1187      foo
1188        (bar)
1189      baz
1190        (when (losing)
1191          (with-big-loser
1192              (yow)
1193            ((lambda ()
1194               foo)
1195             big)))
1196        (flet ((foo (bar baz zap)
1197                 (zip))
1198               (zot ()
1199                 quux))
1200          (do ()
1201              ((lose)
1202               (foo 1))
1203            (quux)
1204           foo
1205            (lose))
1206          (cond ((x)
1207                 (win 1 2
1208                      (foo)))
1209                (t
1210                 (lose
1211                  3))))))"
1212      "
1213   (if* (eq t nil)
1214      then ()
1215           ()
1216    elseif (dsf)
1217      thenret x
1218      else (balbkj)
1219           (sdf))")))
1220
1221 \f
1222
1223 ;(put 'while    'common-lisp-indent-function 1)
1224 ;(put 'defwrapper'common-lisp-indent-function ...)
1225 ;(put 'def 'common-lisp-indent-function ...)
1226 ;(put 'defflavor        'common-lisp-indent-function ...)
1227 ;(put 'defsubst 'common-lisp-indent-function ...)
1228
1229 ;(put 'with-restart 'common-lisp-indent-function '((1 4 ((* 1))) (2 &body)))
1230 ;(put 'restart-case 'common-lisp-indent-function '((1 4) (* 2 ((0 1) (* 1)))))
1231 ;(put 'define-condition 'common-lisp-indent-function '((1 6) (2 6 ((&whole 1))) (3 4 ((&whole 1))) (4 &body)))
1232 ;(put 'with-condition-handler 'common-lisp-indent-function '((1 4 ((* 1))) (2 &body)))
1233 ;(put 'condition-case 'common-lisp-indent-function '((1 4) (* 2 ((0 1) (1 3) (2 &body)))))
1234 ;(put 'defclass 'common-lisp-indent-function '((&whole 2 &rest (&whole 2 &rest 1) &rest (&whole 2 &rest 1)))
1235 ;(put 'defgeneric 'common-lisp-indent-function 'defun)
1236
1237 ;;; cl-indent.el ends here