]> git.donarmstrong.com Git - lilypond.git/blob - lilypond-indent.el
add a warning about matching \] or \)
[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      ( ?]  .  ("[[]" . "[]]"))
283      ))
284
285
286 (defconst LilyPond-parens-alist
287   `( ( ?<  .  ?> )    
288      ( ?{  .  ?} )    
289      ( ?[  .  ?] )
290      ( ?\(  .  ?\) )
291      ))
292
293
294 (defun LilyPond-matching-paren (bracket-type)
295   "Returns the open corresponding to the close specified by bracket-type, or vice versa"
296   (cond ( (memq bracket-type (mapcar 'car LilyPond-parens-alist))
297           (cdr (assoc bracket-type LilyPond-parens-alist)) )
298         ( (memq bracket-type (mapcar 'cdr LilyPond-parens-alist))
299           (car (rassoc bracket-type LilyPond-parens-alist)) )
300         nil))
301
302
303 (defun LilyPond-beginning-of-containing-sexp (&optional bracket-type slur-paren-p)
304   "Move point to the beginning of the deepest parenthesis pair enclosing point. 
305
306 If the optional argument bracket-type, a character representing a
307 close bracket such as ) or }, is specified, then the parenthesis pairs
308 searched are limited to this type.
309
310 If the optional argument slur-paren-p is non-nil, then slur
311 parentheses () are considered as matching pairs. Otherwise Scheme
312 parentheses are considered to be matching pairs, but slurs are not.
313 slur-paren-p defaults to nil.
314 "
315 ;;; An user does not call this function directly, or by a key sequence.
316   ;;  (interactive)
317   (let ( (level 1) 
318          (regexp-alist LilyPond-parens-regexp-alist) 
319          (oldpos (point) ) )
320     (if (LilyPond-inside-scheme-p)
321         (setq paren-regexp "(\\|)")
322       (if slur-paren-p
323           (setq regexp-alist (cons '( ?\) . ("(" . ")")) regexp-alist)))
324       (if (memq bracket-type (mapcar 'car regexp-alist))
325           (progn (setq paren-regexp (cdr (assoc bracket-type regexp-alist)))
326                  (setq paren-regexp (concat (car paren-regexp) "\\|" (cdr paren-regexp))))
327         (setq paren-regexp (concat (mapconcat 'car (mapcar 'cdr regexp-alist) "\\|") "\\|"
328                                    (mapconcat 'cdr (mapcar 'cdr regexp-alist) "\\|")))))
329     (while (and (> level 0) 
330                 (re-search-backward paren-regexp nil t)
331                 (setq match (char-before (match-end 0))))
332       (if (not (save-excursion (goto-char (match-end 0)) 
333                                (LilyPond-inside-string-or-comment-p)))
334           (if (memq match '(?} ?> ?] ?\)))
335               (progn (setq level (1+ level))
336                      (if (and (= match ?>) 
337                               (looking-at ".\\s-+>\\|\\({\\|}\\|<\\|>\\|(\\|)\\|[][]\\)>"))
338                          (forward-char 1)))
339             (progn (setq level (1- level))
340                    (if (and (= match ?<)
341                             (looking-at ".\\s-+<\\|\\({\\|}\\|<\\|>\\|(\\|)\\|[][]\\)<"))
342                        (forward-char 1))))))
343     (if (looking-at ".<\\|.>") (forward-char 1))
344     (if (= level 0) 
345         (point)
346       (progn (goto-char oldpos)
347              nil))))
348
349
350 (defun LilyPond-inside-scheme-p ()
351   "Tests if point is inside embedded Scheme code"
352 ;;; An user does not call this function directly, or by a key sequence.
353   ;;  (interactive)
354   (let ( (test-point (point))
355          (level 0) )
356     (save-excursion 
357       (if (or (and (/= (point) (point-max))
358                    (= (char-after (point)) ?\()
359                    (or (= (char-after (- (point) 1)) ?#)
360                        (and (= (char-after (- (point) 2)) ?#)
361                             (= (char-after (- (point) 1)) ?`))))
362               (and (re-search-backward "#(\\|#`(" nil t)
363                    (progn 
364                      (search-forward "(")
365                      (setq level 1)
366                      (while (and (> level 0)
367                                  (re-search-forward "(\\|)" test-point t)
368                                  (setq match (char-after (match-beginning 0)))
369                                  (<= (point) test-point))
370                        (if (= match ?\()
371                            (setq level (1+ level))
372                          (setq level (1- level))))
373                      (> level 0))))
374           t
375         nil))))
376
377
378 ;;; Largely taken from the 'blink-matching-open' in lisp/simple.el in
379 ;;; the Emacs distribution.
380
381 (defun LilyPond-blink-matching-open (bracket-type char-before-bracket-type)
382   "Move cursor momentarily to the beginning of the sexp before
383 point. In lilypond files this is used for closing ), ], } and >, whereas the
384 builtin 'blink-matching-open' is not used. In syntax table, see
385 `lilypond-font-lock.el', all brackets are punctuation characters."
386 ;;; An user does not call this function directly, or by a key sequence.
387   ;;  (interactive)
388   (let ( (oldpos (point))
389          (level 0) 
390          (mismatch) )
391     (if (eq char-before-bracket-type ?\\)
392         (if (eq bracket-type ?])
393             (message "trying to match ligatures \\[ ... \\]")
394           (message "trying to match slurs \\( ... \\)")))
395     (save-restriction
396       (if blink-matching-paren-distance
397           (narrow-to-region (max (point-min)
398                                  (- (point) blink-matching-paren-distance))
399                             oldpos)))
400     (if (memq bracket-type '(?> ?} ?]))
401         ;; < { [ need to be mutually balanced and nested, so search backwards for both of these bracket types 
402         (LilyPond-beginning-of-containing-sexp nil nil)  
403       ;; whereas ( ) slurs within music don't, so only need to search for ( )
404       (LilyPond-beginning-of-containing-sexp bracket-type t))
405     (setq blinkpos (point))
406     (setq mismatch
407           (or (null (LilyPond-matching-paren (char-after blinkpos)))
408               (/= (char-after oldpos)
409                   (LilyPond-matching-paren (char-after blinkpos)))))
410     (if mismatch (progn (setq blinkpos nil)
411                         (message "Mismatched parentheses")))
412     (if blinkpos
413         (if (pos-visible-in-window-p)
414             (and blink-matching-paren-on-screen
415                  (sit-for blink-matching-delay))
416           (message
417            "Matches %s"
418            ;; Show what precedes the open in its line, if anything.
419            (if (save-excursion
420                  (skip-chars-backward " \t")
421                  (not (bolp)))
422                (buffer-substring (progn (beginning-of-line) (point))
423                                  (1+ blinkpos))
424              ;; Show what follows the open in its line, if anything.
425              (if (save-excursion
426                    (forward-char 1)
427                    (skip-chars-forward " \t")
428                    (not (eolp)))
429                  (buffer-substring blinkpos
430                                    (progn (end-of-line) (point)))
431                ;; Otherwise show the previous nonblank line,
432                ;; if there is one.
433                (if (save-excursion
434                      (skip-chars-backward "\n \t")
435                      (not (bobp)))
436                    (concat
437                     (buffer-substring (progn
438                                         (skip-chars-backward "\n \t")
439                                         (beginning-of-line)
440                                         (point))
441                                       (progn (end-of-line)
442                                              (skip-chars-backward " \t")
443                                              (point)))
444                     ;; Replace the newline and other whitespace with `...'.
445                     "..."
446                     (buffer-substring blinkpos (1+ blinkpos)))
447                  ;; There is nothing to show except the char itself.
448                  (buffer-substring blinkpos (1+ blinkpos))))))))
449     (goto-char oldpos)))
450
451
452 (defun LilyPond-electric-close-paren ()
453   "Blink on the matching open paren when a >, ), } or ] is inserted"
454   (interactive)
455   (let ((oldpos (point)))
456     (self-insert-command 1)
457     (setq close-char (char-before (point)))
458     ;; Test if a ligature \] or expressional slur \) was encountered;
459     ;; the result is now in backslashed-close-char, BUT
460     ;; the result should also be used  -- match also \] or \) !
461     ;; Thus, update: LilyPond-parens-regexp-alist, LilyPond-blink-matching-open
462     (setq char-before-close-char nil)
463     (if (memq close-char '(?] ?\)))
464       (progn 
465         (setq np 0)
466         (while (eq (char-before (- (point) (setq np (+ np 1)))) ?\\)
467           (setq char-before-close-char (if char-before-close-char nil ?\\)))))
468     (if (and blink-matching-paren
469              (not (LilyPond-inside-string-or-comment-p))
470              (save-excursion (re-search-backward 
471                               (concat (mapconcat 'cdr (mapcar 'cdr LilyPond-parens-regexp-alist) "\\|") "\\|)") nil t)
472                              (eq oldpos (1- (match-end 0)))))
473         (progn (backward-char 1)
474                (LilyPond-blink-matching-open close-char char-before-close-char)
475                (forward-char 1)))))