]> git.donarmstrong.com Git - lilypond.git/blob - lilypond-indent.el
Match one-character brackets without two-character brackets.
[lilypond.git] / lilypond-indent.el
1 ;;; lilypond-indent.el --- Auto-indentation for lilypond code
2 ;;;
3 ;;; Chris Jackson <chris@fluffhouse.org.uk>
4 ;;; some code is taken from ESS (Emacs Speaks Statistics) S-mode by A.J.Rossini <rossini@biostat.washington.edu>
5
6 ;;; Variables for customising indentation style
7
8 ;;; TODO:
9 ;;;    * emulate show-paren-mode, i.e., highlight the matching bracket if
10 ;;;      - the cursor is on the matching opening bracket
11 ;;;      - the cursor is after the matching closing bracket
12 ;;;    * separate '('- and ')'-slurs from '\('- and '\)'-slurs.
13 ;;;    * separate '['- and ']'-slurs from '\['- and '\]'-slurs.
14
15 (defcustom LilyPond-indent-level 4
16   "*Indentation of lilypond statements with respect to containing block.")
17
18 (defcustom LilyPond-brace-offset 0
19   "*Extra indentation for open braces.
20 Compares with other text in same context.")
21
22 (defcustom LilyPond-angle-offset 0
23   "*Extra indentation for open angled brackets .
24 Compares with other text in same context.")
25
26 (defcustom LilyPond-square-offset 0
27   "*Extra indentation for open square brackets .
28 Compares with other text in same context.")
29
30 (defcustom LilyPond-scheme-paren-offset 0
31   "*Extra indentation for open scheme parens .
32 Compares with other text in same context.")
33
34 (defcustom LilyPond-close-brace-offset 0
35   "*Extra indentation for closing braces.")
36
37 (defcustom LilyPond-close-angle-offset 0
38   "*Extra indentation for closing angle brackets.")
39
40 (defcustom LilyPond-close-square-offset 0
41   "*Extra indentation for closing square brackets.")
42
43 (defcustom LilyPond-close-scheme-paren-offset 0
44   "*Extra indentation for closing scheme parens.")
45
46 (defcustom LilyPond-fancy-comments t
47   "*Non-nil means distiguish between %, %%, and %%% for indentation.")
48
49
50 (defun LilyPond-calculate-indent ()
51   "Return appropriate indentation for current line as lilypond code.
52 In usual case returns an integer: the column to indent to.
53 Returns nil if line starts inside a string"
54   (save-excursion
55     (beginning-of-line)
56     (let ((indent-point (point))
57           (case-fold-search nil)
58           state)
59       (setq containing-sexp (save-excursion (LilyPond-beginning-of-containing-sexp)))
60       (beginning-of-defun)
61       (while (< (point) indent-point)
62         (setq state (parse-partial-sexp (point) indent-point 0)))
63       ;; (setq containing-sexp (car (cdr state))) is the traditional way for languages
64       ;; with simpler parenthesis delimiters
65       (cond ((nth 3 state) 
66              ;; point is in the middle of a string 
67              nil)
68             ((nth 4 state)
69              ;; point is in the middle of a block comment
70              (LilyPond-calculate-indent-within-blockcomment))
71             ((null containing-sexp)
72              ;; Line is at top level - no indent
73              (beginning-of-line)
74              0)
75             (t
76              ;; Find previous non-comment character.
77              (goto-char indent-point)
78              (LilyPond-backward-to-noncomment containing-sexp)
79              ;; Now we get the answer.
80              ;; Position following last unclosed open.
81              (goto-char containing-sexp)
82              (or
83               ;; Is line first statement after an open brace or bracket?
84               ;; If no, find that first statement and indent like it.
85               (save-excursion
86                 (forward-char 1)
87                 ;; Skip over comments following open brace.
88                 (skip-chars-forward " \t\n")
89                 (cond ((looking-at "%{")
90                        (while  (progn 
91                                  (and (not (looking-at "%}"))
92                                       (< (point) (point-max))))
93                          (forward-line 1)
94                          (skip-chars-forward " \t\n"))
95                        (forward-line 1)
96                        (skip-chars-forward " \t\n"))
97                       ((looking-at "%")
98                        (while (progn (skip-chars-forward " \t\n")
99                                      (looking-at "%"))
100                          (forward-line 1))))
101                 ;; The first following code counts
102                 ;; if it is before the line we want to indent.
103                 (and (< (point) indent-point)
104                      (current-column)))
105               ;; If no previous statement,
106               ;; indent it relative to line brace is on.
107               ;; For open brace in column zero, don't let statement
108               ;; start there too.  If LilyPond-indent-level is zero, use
109               ;; LilyPond-brace-offset instead
110               (+ (if (and (bolp) (zerop LilyPond-indent-level))
111                      (cond ((= (following-char) ?{) 
112                             LilyPond-brace-offset)
113                            ((= (following-char) ?<) 
114                             LilyPond-angle-offset)
115                            ((= (following-char) ?[) 
116                             LilyPond-square-offset)
117                            ((= (following-char) ?\))
118                             LilyPond-scheme-paren-offset)
119                            (t
120                             0))
121                    LilyPond-indent-level)
122                  (progn
123                    (skip-chars-backward " \t")
124                    (current-indentation)))))))))
125
126
127
128 (defun LilyPond-indent-line ()
129   "Indent current line as lilypond code.
130 Return the amount the indentation changed by."
131   (let ((indent (LilyPond-calculate-indent))
132         beg shift-amt
133         (case-fold-search nil)
134         (pos (- (point-max) (point))))
135     (beginning-of-line)
136     (setq beg (point))
137     (cond ((eq indent nil)
138            (setq indent (current-indentation)))
139           (t
140            (skip-chars-forward " \t")
141            (if (and LilyPond-fancy-comments (looking-at "%%%\\|%{\\|%}"))
142                (setq indent 0))
143            (if (and LilyPond-fancy-comments
144                     (looking-at "%")
145                     (not (looking-at "%%\\|%{\\|%}")))
146                (setq indent comment-column)
147              (if (eq indent t) (setq indent 0))
148              (if (listp indent) (setq indent (car indent)))
149              (cond
150               ((= (following-char) ?})
151                (setq indent  (+ indent (- LilyPond-close-brace-offset LilyPond-indent-level))))
152               ((= (following-char) ?>)
153                (setq indent  (+ indent (- LilyPond-close-angle-offset LilyPond-indent-level))))
154               ((= (following-char) ?])
155                (setq indent  (+ indent (- LilyPond-close-square-offset LilyPond-indent-level))))
156               ((and (= (following-char) ?\)) (LilyPond-inside-scheme-p))
157                (setq indent  (+ indent (- LilyPond-close-scheme-paren-offset LilyPond-indent-level))))
158               ((= (following-char) ?{)
159                (setq indent  (+ indent LilyPond-brace-offset)))
160               ((= (following-char) ?<)
161                (setq indent  (+ indent LilyPond-angle-offset)))
162               ((= (following-char) ?[)
163                (setq indent  (+ indent LilyPond-square-offset)))
164               ((and (= (following-char) ?\() (LilyPond-inside-scheme-p))
165                (setq indent  (+ indent LilyPond-scheme-paren-offset)))
166               ))))
167     (skip-chars-forward " \t")
168     (setq shift-amt (- indent (current-column)))
169     (if (zerop shift-amt)
170         (if (> (- (point-max) pos) (point))
171             (goto-char (- (point-max) pos)))
172       (delete-region beg (point))
173       (indent-to indent)
174       ;; If initial point was within line's indentation,
175       ;; position after the indentation.
176       ;; Else stay at same point in text.
177       (if (> (- (point-max) pos) (point))
178           (goto-char (- (point-max) pos))))
179     shift-amt))
180
181
182 (defun LilyPond-inside-comment-p ()
183   "Return non-nil if point is inside a line or block comment"
184   (setq this-point (point))
185   (or (save-excursion (beginning-of-line)
186                       (skip-chars-forward " \t")
187                       (looking-at "%"))
188       (save-excursion 
189         ;; point is in the middle of a block comment
190         (setq lastopen  (save-excursion (re-search-backward "%{[ \\t]*" (point-min) t)))
191         (setq lastclose (save-excursion (re-search-backward "%}[ \\t]*" (point-min) t)))
192         (if (or (and (= (char-before) ?%) (= (char-after) ?{))
193                 (and (= (char-after)  ?%) (= (char-after (1+ (point))) ?{)))
194             (setq lastopen (save-excursion (backward-char) (point))))
195         (and 
196          lastopen
197          (or (not lastclose)
198              (<= lastclose lastopen))))
199       ))
200
201
202 (defun LilyPond-inside-string-or-comment-p ()
203   "Test if point is inside a string or a comment"
204   (setq this-point (point))
205   (or (save-excursion (beginning-of-line)
206                       (skip-chars-forward " \t")
207                       (looking-at "%"))
208       (save-excursion 
209         (beginning-of-defun)
210         (while (< (point) this-point)
211           (setq state (parse-partial-sexp (point) this-point 0)))
212         (cond ((nth 3 state) 
213                ;; point is in the middle of a string 
214                t )
215               ((nth 4 state)
216                ;; point is in the middle of a block comment
217                t ) 
218               (t
219                nil)))))
220
221
222 (defun LilyPond-backward-over-blockcomments (lim)
223   "Move point back to closest non-whitespace character not part of a block comment"
224   (setq lastopen  (save-excursion (re-search-backward "%{[ \\t]*" lim t)))
225   (setq lastclose (save-excursion (re-search-backward "%}[ \\t]*" lim t)))
226   (if lastopen
227       (if lastclose
228           (if (<= lastclose lastopen)
229               (goto-char lastopen))
230         (goto-char lastopen)))
231   (skip-chars-backward " %\t\n\f"))
232
233
234 (defun LilyPond-backward-over-linecomments (lim)
235   "Move point back to the closest non-whitespace character not part of a line comment.
236 Argument LIM limit."
237   (let (opoint stop)
238     (while (not stop)
239       (skip-chars-backward " \t\n\f" lim)
240       (setq opoint (point))
241       (beginning-of-line)
242       (search-forward "%" opoint 'move)
243       (skip-chars-backward " \t%")
244       (setq stop (or (/= (preceding-char) ?\n) (<= (point) lim)))
245       (if stop (point)
246         (beginning-of-line)))))
247
248
249 (defun LilyPond-backward-to-noncomment (lim)
250   "Move point back to closest non-whitespace character not part of a comment"
251   (LilyPond-backward-over-linecomments lim)
252   (LilyPond-backward-over-blockcomments lim))
253
254
255 (defun LilyPond-calculate-indent-within-blockcomment ()
256   "Return the indentation amount for line inside a block comment."
257   (let (end percent-start)
258     (save-excursion
259       (beginning-of-line)
260       (skip-chars-forward " \t")
261       (skip-chars-backward " \t\n")
262       (setq end (point))
263       (beginning-of-line)
264       (skip-chars-forward " \t")
265       (and (re-search-forward "%{[ \t]*" end t)
266            (goto-char (1+ (match-beginning 0))))
267       (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\%))
268           (1+ (current-column))
269         (current-column)))))
270
271
272 ;; Key:   Type of bracket (character). 
273 ;; Value: Pair of regexps representing the corresponding open and close bracket
274 ;; () are treated specially (need to indent in Scheme but not in music)
275
276 (defconst LilyPond-parens-regexp-alist
277   `( ( ?>  .  ("\\([^\\]\\|^\\)<" . "[^ \\n\\t_^-]\\s-*>\\|[_^-]\\s-*[-^]\\s-*>"))
278      ;; a b c->, a b c^> and a b c_> are not close-angle-brackets, they're accents
279      ;; but a b c^-> and a b c^^> are close brackets with tenuto/marcato before them
280      ;; also \> and \< are hairpins
281      ( ?}  .  ("{" . "}"))
282      ;; ligatures  '\[ ... \]' are skipped in the following expression
283      ( ?]  .  ("\\([^\\]\\|^\\)[[]" . "\\([^\\]\\|^\\)[]]"))
284      ))
285
286
287 (defconst LilyPond-parens-alist
288   `( ( ?<  .  ?> )    
289      ( ?{  .  ?} )    
290      ( ?[  .  ?] )
291      ( ?\(  .  ?\) )
292      ))
293
294
295 (defun LilyPond-matching-paren (bracket-type)
296   "Returns the open corresponding to the close specified by bracket-type, or vice versa"
297   (cond ( (memq bracket-type (mapcar 'car LilyPond-parens-alist))
298           (cdr (assoc bracket-type LilyPond-parens-alist)) )
299         ( (memq bracket-type (mapcar 'cdr LilyPond-parens-alist))
300           (car (rassoc bracket-type LilyPond-parens-alist)) )
301         nil))
302
303
304 (defun LilyPond-beginning-of-containing-sexp (&optional bracket-type slur-paren-p)
305   "Move point to the beginning of the deepest parenthesis pair enclosing point. 
306
307 If the optional argument bracket-type, a character representing a
308 close bracket such as ) or }, is specified, then the parenthesis pairs
309 searched are limited to this type.
310
311 If the optional argument slur-paren-p is non-nil, then slur
312 parentheses () are considered as matching pairs. Otherwise Scheme
313 parentheses are considered to be matching pairs, but slurs are not.
314 slur-paren-p defaults to nil.
315 "
316 ;;; An user does not call this function directly, or by a key sequence.
317   ;;  (interactive)
318   (let ( (level 1) 
319          (regexp-alist LilyPond-parens-regexp-alist) 
320          (oldpos (point) ) )
321     (if (LilyPond-inside-scheme-p)
322         (setq paren-regexp "(\\|)")
323       (if slur-paren-p
324           ;; expressional slurs  '\( ... \)' are not taken into account
325           (setq regexp-alist (cons '( ?\) . ("\\([^\\]\\|^\\)(" . "\\([^\\]\\|^\\))")) regexp-alist)))
326       (if (memq bracket-type (mapcar 'car regexp-alist))
327           (progn (setq paren-regexp (cdr (assoc bracket-type regexp-alist)))
328                  (setq paren-regexp (concat (car paren-regexp) "\\|" (cdr paren-regexp))))
329         (setq paren-regexp (concat (mapconcat 'car (mapcar 'cdr regexp-alist) "\\|") "\\|"
330                                    (mapconcat 'cdr (mapcar 'cdr regexp-alist) "\\|")))))
331     (while (and (> level 0) 
332                 (re-search-backward paren-regexp nil t)
333                 (setq match (char-before (match-end 0))))
334       (if (not (save-excursion (goto-char (match-end 0)) 
335                                (LilyPond-inside-string-or-comment-p)))
336           (if (memq match '(?} ?> ?] ?\)))
337               (progn (setq level (1+ level))
338                      (if (and (= match ?>) 
339                               (looking-at ".\\s-+>\\|\\({\\|}\\|<\\|>\\|(\\|)\\|[][]\\)>"))
340                          (forward-char 1)))
341             (progn (setq level (1- level))
342                    (if (and (= match ?<)
343                             (looking-at ".\\s-+<\\|\\({\\|}\\|<\\|>\\|(\\|)\\|[][]\\)<"))
344                        (forward-char 1))))))
345     ;; somehow here two-char brackets \<, \>, \[, \], \(, \) are handled
346     (if (looking-at ".<\\|.>\\|.[][)(]") (forward-char 1))
347     (if (= level 0) 
348         (point)
349       (progn (goto-char oldpos)
350              nil))))
351
352
353 (defun LilyPond-inside-scheme-p ()
354   "Tests if point is inside embedded Scheme code"
355 ;;; An user does not call this function directly, or by a key sequence.
356   ;;  (interactive)
357   (let ( (test-point (point))
358          (level 0) )
359     (save-excursion 
360       (if (or (and (/= (point) (point-max))
361                    (= (char-after (point)) ?\()
362                    (or (= (char-after (- (point) 1)) ?#)
363                        (and (= (char-after (- (point) 2)) ?#)
364                             (= (char-after (- (point) 1)) ?`))))
365               (and (re-search-backward "#(\\|#`(" nil t)
366                    (progn 
367                      (search-forward "(")
368                      (setq level 1)
369                      (while (and (> level 0)
370                                  (re-search-forward "(\\|)" test-point t)
371                                  (setq match (char-after (match-beginning 0)))
372                                  (<= (point) test-point))
373                        (if (= match ?\()
374                            (setq level (1+ level))
375                          (setq level (1- level))))
376                      (> level 0))))
377           t
378         nil))))
379
380
381 ;;; Largely taken from the 'blink-matching-open' in lisp/simple.el in
382 ;;; the Emacs distribution.
383
384 (defun LilyPond-blink-matching-open (bracket-type char-before-bracket-type)
385   "Move cursor momentarily to the beginning of the sexp before
386 point. In lilypond files this is used for closing ), ], } and >, whereas the
387 builtin 'blink-matching-open' is not used. In syntax table, see
388 `lilypond-font-lock.el', all brackets are punctuation characters."
389 ;;; An user does not call this function directly, or by a key sequence.
390   ;;  (interactive)
391   (let ( (oldpos (point))
392          (level 0) 
393          (mismatch) )
394     (if (eq char-before-bracket-type ?\\)
395         (if (eq bracket-type ?])
396             (message "trying to match ligatures \\[ ... \\]")
397           (message "trying to match slurs \\( ... \\)")))
398     (save-restriction
399       (if blink-matching-paren-distance
400           (narrow-to-region (max (point-min)
401                                  (- (point) blink-matching-paren-distance))
402                             oldpos)))
403     (if (memq bracket-type '(?> ?} ?]))
404         ;; < { [ need to be mutually balanced and nested, so search backwards for both of these bracket types 
405         (LilyPond-beginning-of-containing-sexp nil nil)  
406       ;; whereas ( ) slurs within music don't, so only need to search for ( )
407       (LilyPond-beginning-of-containing-sexp bracket-type t))
408     (setq blinkpos (point))
409     (setq mismatch
410           (or (null (LilyPond-matching-paren (char-after blinkpos)))
411               (/= (char-after oldpos)
412                   (LilyPond-matching-paren (char-after blinkpos)))))
413     (if mismatch (progn (setq blinkpos nil)
414                         (message "Mismatched parentheses")))
415     (if blinkpos
416         (if (pos-visible-in-window-p)
417             (and blink-matching-paren-on-screen
418                  (sit-for blink-matching-delay))
419           (message
420            "Matches %s"
421            ;; Show what precedes the open in its line, if anything.
422            (if (save-excursion
423                  (skip-chars-backward " \t")
424                  (not (bolp)))
425                (buffer-substring (progn (beginning-of-line) (point))
426                                  (1+ blinkpos))
427              ;; Show what follows the open in its line, if anything.
428              (if (save-excursion
429                    (forward-char 1)
430                    (skip-chars-forward " \t")
431                    (not (eolp)))
432                  (buffer-substring blinkpos
433                                    (progn (end-of-line) (point)))
434                ;; Otherwise show the previous nonblank line,
435                ;; if there is one.
436                (if (save-excursion
437                      (skip-chars-backward "\n \t")
438                      (not (bobp)))
439                    (concat
440                     (buffer-substring (progn
441                                         (skip-chars-backward "\n \t")
442                                         (beginning-of-line)
443                                         (point))
444                                       (progn (end-of-line)
445                                              (skip-chars-backward " \t")
446                                              (point)))
447                     ;; Replace the newline and other whitespace with `...'.
448                     "..."
449                     (buffer-substring blinkpos (1+ blinkpos)))
450                  ;; There is nothing to show except the char itself.
451                  (buffer-substring blinkpos (1+ blinkpos))))))))
452     (goto-char oldpos)))
453
454
455 (defun LilyPond-electric-close-paren ()
456   "Blink on the matching open paren when a >, ), } or ] is inserted"
457   (interactive)
458   (let ((oldpos (point)))
459     (self-insert-command 1)
460     (setq close-char (char-before (point)))
461     ;; Test if a ligature \] or expressional slur \) was encountered;
462     ;; the result is now in backslashed-close-char, BUT
463     ;; the result should also be used  -- match also \] or \) !
464     ;; Thus, update: LilyPond-parens-regexp-alist, LilyPond-blink-matching-open
465     (setq char-before-close-char nil)
466     (if (memq close-char '(?] ?\)))
467       (progn 
468         (setq np 0)
469         (while (eq (char-before (- (point) (setq np (+ np 1)))) ?\\)
470           (setq char-before-close-char (if char-before-close-char nil ?\\)))))
471     (if (and blink-matching-paren
472              (not (LilyPond-inside-string-or-comment-p))
473              (save-excursion (re-search-backward 
474                               (concat (mapconcat 'cdr (mapcar 'cdr LilyPond-parens-regexp-alist) "\\|") "\\|)") nil t)
475                              (eq oldpos (1- (match-end 0)))))
476         (progn (backward-char 1)
477                (LilyPond-blink-matching-open close-char char-before-close-char)
478                (forward-char 1)))))