]> git.donarmstrong.com Git - lilypond.git/blob - lilypond-indent.el
* scm/music-functions.scm (make-ottava-set):
[lilypond.git] / lilypond-indent.el
1 ;;; lilypond-indent.el --- Auto-indentation for lilypond code
2 ;;;
3 ;;; Heikki Junes <hjunes@cc.hut.fi>
4 ;;; * redefine Emacs' show-paren-function and XEmacs' paren-highlight
5 ;;; * match two-char slurs '\( ... \)' and '\[ ... \]' separately.
6 ;;; * adopt Emacs' f90-comment-region
7
8 ;;; Chris Jackson <chris@fluffhouse.org.uk>
9 ;;; some code is taken from ESS (Emacs Speaks Statistics) S-mode by A.J.Rossini <rossini@biostat.washington.edu>
10
11 ;;; Variables for customising indentation style
12
13 ;;; TODO:
14 ;;;    * currently, in bracket matching one may need a non-bracket 
15 ;;;      chararacter between the bracket characters, like ( ( ) )
16 ;;;    * in syntax-highlighting slurs are not always highlighted the right way
17 ;;;      e.g. opening slurs are found found better in "#( ( ) ( ) )" than
18 ;;;      opening slurs
19 ;;;    * is locality of show-paren-function and paren-highlight possible?
20
21 (defcustom LilyPond-indent-level 4
22   "*Indentation of lilypond statements with respect to containing block.")
23
24 (defcustom LilyPond-brace-offset 0
25   "*Extra indentation for open braces.
26 Compares with other text in same context.")
27
28 (defcustom LilyPond-angle-offset 0
29   "*Extra indentation for open angled brackets.
30 Compares with other text in same context.")
31
32 (defcustom LilyPond-square-offset 0
33   "*Extra indentation for open square brackets.
34 Compares with other text in same context.")
35
36 (defcustom LilyPond-scheme-paren-offset 0
37   "*Extra indentation for open scheme parens.
38 Compares with other text in same context.")
39
40 (defcustom LilyPond-close-brace-offset 0
41   "*Extra indentation for closing braces.")
42
43 (defcustom LilyPond-close-angle-offset 0
44   "*Extra indentation for closing angle brackets.")
45
46 (defcustom LilyPond-close-square-offset 0
47   "*Extra indentation for closing square brackets.")
48
49 (defcustom LilyPond-close-scheme-paren-offset 0
50   "*Extra indentation for closing scheme parens.")
51
52 (defcustom LilyPond-fancy-comments t
53   "*Non-nil means distiguish between %, %%, and %%% for indentation.")
54
55 (defcustom LilyPond-comment-region "%%$"
56   "*String inserted by \\[LilyPond-comment-region]\
57  at start of each line in region.")
58
59 (defun LilyPond-comment-region (beg-region end-region)
60   "Comment/uncomment every line in the region.
61 Insert LilyPond-comment-region at the beginning of every line in the region
62 or, if already present, remove it."
63   (interactive "*r")
64   (let ((end (make-marker)))
65     (set-marker end end-region)
66     (goto-char beg-region)
67     (beginning-of-line)
68     (if (looking-at (regexp-quote LilyPond-comment-region))
69         (delete-region (point) (match-end 0))
70       (insert LilyPond-comment-region))
71     (while (and  (zerop (forward-line 1))
72                  (< (point) (marker-position end)))
73       (if (looking-at (regexp-quote LilyPond-comment-region))
74           (delete-region (point) (match-end 0))
75         (insert LilyPond-comment-region)))
76     (set-marker end nil)))
77
78 (defun LilyPond-calculate-indent ()
79   "Return appropriate indentation for current line as lilypond code.
80 In usual case returns an integer: the column to indent to.
81 Returns nil if line starts inside a string"
82   (save-excursion
83     (beginning-of-line)
84     (let ((indent-point (point))
85           (case-fold-search nil)
86           state)
87       (setq containing-sexp (save-excursion (LilyPond-scan-containing-sexp)))
88       (beginning-of-defun)
89       (while (< (point) indent-point)
90         (setq state (parse-partial-sexp (point) indent-point 0)))
91       ;; (setq containing-sexp (car (cdr state))) is the traditional way for languages
92       ;; with simpler parenthesis delimiters
93       (cond ((nth 3 state) 
94              ;; point is in the middle of a string 
95              nil)
96             ((nth 4 state)
97              ;; point is in the middle of a block comment
98              (LilyPond-calculate-indent-within-blockcomment))
99             ((null containing-sexp)
100              ;; Line is at top level - no indent
101              (beginning-of-line)
102              0)
103             (t
104              ;; Find previous non-comment character.
105              (goto-char indent-point)
106              (LilyPond-backward-to-noncomment containing-sexp)
107              ;; Now we get the answer.
108              ;; Position following last unclosed open.
109              (goto-char containing-sexp)
110              (or
111               ;; Is line first statement after an open brace or bracket?
112               ;; If no, find that first statement and indent like it.
113               (save-excursion
114                 (forward-char 1)
115                 ;; Skip over comments following open brace.
116                 (skip-chars-forward " \t\n")
117                 (cond ((looking-at "%{")
118                        (while  (progn 
119                                  (and (not (looking-at "%}"))
120                                       (< (point) (point-max))))
121                          (forward-line 1)
122                          (skip-chars-forward " \t\n"))
123                        (forward-line 1)
124                        (skip-chars-forward " \t\n"))
125                       ((looking-at "%")
126                        (while (progn (skip-chars-forward " \t\n")
127                                      (looking-at "%"))
128                          (forward-line 1))))
129                 ;; The first following code counts
130                 ;; if it is before the line we want to indent.
131                 (and (< (point) indent-point)
132                      (current-column)))
133               ;; If no previous statement,
134               ;; indent it relative to line brace is on.
135               ;; For open brace in column zero, don't let statement
136               ;; start there too.  If LilyPond-indent-level is zero, use
137               ;; LilyPond-brace-offset instead
138               (+ (if (and (bolp) (zerop LilyPond-indent-level))
139                      (cond ((= (following-char) ?{) 
140                             LilyPond-brace-offset)
141                            ((= (following-char) ?<) 
142                             LilyPond-angle-offset)
143                            ((= (following-char) ?[) 
144                             LilyPond-square-offset)
145                            ((= (following-char) ?\))
146                             LilyPond-scheme-paren-offset)
147                            (t
148                             0))
149                    LilyPond-indent-level)
150                  (progn
151                    (skip-chars-backward " \t")
152                    (current-indentation)))))))))
153
154
155 (defun LilyPond-indent-line ()
156   "Indent current line as lilypond code.
157 Return the amount the indentation changed by."
158   (let ((indent (LilyPond-calculate-indent))
159         beg shift-amt
160         (case-fold-search nil)
161         (pos (- (point-max) (point))))
162     (beginning-of-line)
163     (setq beg (point))
164     (cond ((eq indent nil)
165            (setq indent (current-indentation)))
166           (t
167            (skip-chars-forward " \t")
168            (if (and LilyPond-fancy-comments (looking-at "%%%\\|%{\\|%}"))
169                (setq indent 0))
170            (if (and LilyPond-fancy-comments
171                     (looking-at "%")
172                     (not (looking-at "%%\\|%{\\|%}")))
173                (setq indent comment-column)
174              (if (eq indent t) (setq indent 0))
175              (if (listp indent) (setq indent (car indent)))
176              (cond
177               ((= (following-char) ?})
178                (setq indent  (+ indent (- LilyPond-close-brace-offset LilyPond-indent-level))))
179               ((= (following-char) ?>)
180                (setq indent  (+ indent (- LilyPond-close-angle-offset LilyPond-indent-level))))
181               ((= (following-char) ?])
182                (setq indent  (+ indent (- LilyPond-close-square-offset LilyPond-indent-level))))
183               ((and (= (following-char) ?\)) (LilyPond-inside-scheme-p))
184                (setq indent  (+ indent (- LilyPond-close-scheme-paren-offset LilyPond-indent-level))))
185               ((= (following-char) ?{)
186                (setq indent  (+ indent LilyPond-brace-offset)))
187               ((= (following-char) ?<)
188                (setq indent  (+ indent LilyPond-angle-offset)))
189               ((= (following-char) ?[)
190                (setq indent  (+ indent LilyPond-square-offset)))
191               ((and (= (following-char) ?\() (LilyPond-inside-scheme-p))
192                (setq indent  (+ indent LilyPond-scheme-paren-offset)))
193               ))))
194     (skip-chars-forward " \t")
195     (setq shift-amt (- indent (current-column)))
196     (if (zerop shift-amt)
197         (if (> (- (point-max) pos) (point))
198             (goto-char (- (point-max) pos)))
199       (delete-region beg (point))
200       (indent-to indent)
201       ;; If initial point was within line's indentation,
202       ;; position after the indentation.
203       ;; Else stay at same point in text.
204       (if (> (- (point-max) pos) (point))
205           (goto-char (- (point-max) pos))))
206     shift-amt))
207
208
209 (defun LilyPond-inside-comment-p ()
210   "Return non-nil if point is inside a line or block comment"
211   (setq this-point (point))
212   (or (save-excursion (beginning-of-line)
213                       (skip-chars-forward " \t")
214                       (looking-at "%"))
215       (save-excursion 
216         ;; point is in the middle of a block comment
217         (setq lastopen  (save-excursion (re-search-backward "%{[ \\t]*" (point-min) t)))
218         (setq lastclose (save-excursion (re-search-backward "%}[ \\t]*" (point-min) t)))
219         (if (or (and (= (char-before) ?%) (= (char-after) ?{))
220                 (and (= (char-after)  ?%) (= (char-after (1+ (point))) ?{)))
221             (setq lastopen (save-excursion (backward-char) (point))))
222         (and 
223          lastopen
224          (or (not lastclose)
225              (<= lastclose lastopen))))
226       ))
227
228
229 (defun LilyPond-inside-string-or-comment-p ()
230   "Test if point is inside a string or a comment"
231   (setq this-point (point))
232   (or (save-excursion (beginning-of-line)
233                       (skip-chars-forward " \t")
234                       (looking-at "%"))
235       (save-excursion 
236         (beginning-of-defun)
237         (while (< (point) this-point)
238           (setq state (parse-partial-sexp (point) this-point 0)))
239         (cond ((nth 3 state) 
240                ;; point is in the middle of a string 
241                t )
242               ((nth 4 state)
243                ;; point is in the middle of a block comment
244                t ) 
245               (t
246                nil)))))
247
248
249 (defun LilyPond-backward-over-blockcomments (lim)
250   "Move point back to closest non-whitespace character not part of a block comment"
251   (setq lastopen  (save-excursion (re-search-backward "%{[ \\t]*" lim t)))
252   (setq lastclose (save-excursion (re-search-backward "%}[ \\t]*" lim t)))
253   (if lastopen
254       (if lastclose
255           (if (<= lastclose lastopen)
256               (goto-char lastopen))
257         (goto-char lastopen)))
258   (skip-chars-backward " %\t\n\f"))
259
260
261 (defun LilyPond-backward-over-linecomments (lim)
262   "Move point back to the closest non-whitespace character not part of a line comment.
263 Argument LIM limit."
264   (let (opoint stop)
265     (while (not stop)
266       (skip-chars-backward " \t\n\f" lim)
267       (setq opoint (point))
268       (beginning-of-line)
269       (search-forward "%" opoint 'move)
270       (skip-chars-backward " \t%")
271       (setq stop (or (/= (preceding-char) ?\n) (<= (point) lim)))
272       (if stop (point)
273         (beginning-of-line)))))
274
275
276 (defun LilyPond-backward-to-noncomment (lim)
277   "Move point back to closest non-whitespace character not part of a comment"
278   (LilyPond-backward-over-linecomments lim)
279   (LilyPond-backward-over-blockcomments lim))
280
281
282 (defun LilyPond-calculate-indent-within-blockcomment ()
283   "Return the indentation amount for line inside a block comment."
284   (let (end percent-start)
285     (save-excursion
286       (beginning-of-line)
287       (skip-chars-forward " \t")
288       (skip-chars-backward " \t\n")
289       (setq end (point))
290       (beginning-of-line)
291       (skip-chars-forward " \t")
292       (and (re-search-forward "%{[ \t]*" end t)
293            (goto-char (1+ (match-beginning 0))))
294       (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\%))
295           (1+ (current-column))
296         (current-column)))))
297
298
299 ;; Key:   Type of bracket (character). 
300 ;; Value: Pair of regexps representing the corresponding open and close bracket
301 ;; () are treated specially (need to indent in Scheme but not in music)
302
303 (defconst LilyPond-parens-regexp-alist
304   `( ( ?>  .  ("\\([^\\]\\|^\\)<" . "\\([^ \\n\\t_^-]\\|[_^-][-^]\\|\\s-\\)\\s-*>"))
305      ;; a b c->, a b c^> and a b c_> are not close-angle-brackets, they're accents
306      ;; but a b c^-> and a b c^^> are close brackets with tenuto/marcato before them
307      ;; also \> and \< are hairpins
308      ;; duh .. a single '>', as in chords '<< ... >>', was not matched here
309      ( ?}  .  ("{" . "}"))
310      ;; ligatures  '\[ ... \]' are skipped in the following expression
311      ( ?]  .  ("\\([^\\]\\([\\][\\]\\)*\\|^\\)[[]" . "\\([^\\]\\([\\][\\]\\)*\\|^\\)[]]"))
312      ( "\\]" . ("\\([^\\]\\|^\\)\\([\\][\\]\\)*[\\][[]" . "\\([^\\]\\|^\\)\\([\\][\\]\\)*[\\][]]"))
313      ( "\\)" . ("\\([^\\]\\|^\\)\\([\\][\\]\\)*[\\][(]" . "\\([^\\]\\|^\\)\\([\\][\\]\\)*[\\][)]"))
314      ))
315
316
317 (defconst LilyPond-parens-alist
318   `( ( ?<  .  ?> )    
319      ( ?{  .  ?} )    
320      ( ?[  .  ?] )
321      ( "\\["  .  "\\]" )
322      ( ?\(  .  ?\) )
323      ( "\\("  .  "\\)" )
324      ))
325
326
327 (defun LilyPond-matching-paren (bracket-type)
328   "Returns the open corresponding to the close specified by bracket-type, or vice versa"
329   (cond ( (member bracket-type (mapcar 'car LilyPond-parens-alist))
330           (cdr (assoc bracket-type LilyPond-parens-alist)) )
331         ( (member bracket-type (mapcar 'cdr LilyPond-parens-alist))
332           (car (rassoc bracket-type LilyPond-parens-alist)) )
333         nil))
334
335
336 (defun LilyPond-scan-containing-sexp (&optional bracket-type slur-paren-p dir)
337   "Move point to the beginning of the deepest parenthesis pair enclosing point. 
338
339 If the optional argument bracket-type, a character representing a
340 close bracket such as ) or }, is specified, then the parenthesis pairs
341 searched are limited to this type.
342
343 If the optional argument slur-paren-p is non-nil, then slur
344 parentheses () are considered as matching pairs. Otherwise Scheme
345 parentheses are considered to be matching pairs, but slurs are not.
346 slur-paren-p defaults to nil.
347 "
348 ;;; An user does not call this function directly, or by a key sequence.
349   ;;  (interactive)
350   (let ( (level (if (not (eq dir 1)) 1 -1))
351          (regexp-alist LilyPond-parens-regexp-alist) 
352          (oldpos (point))
353          (assoc-bracket-type (if (not (eq dir 1)) bracket-type (LilyPond-matching-paren bracket-type))))
354     
355     (if (LilyPond-inside-scheme-p)
356         (setq paren-regexp "(\\|)")
357       (if slur-paren-p
358           ;; expressional slurs  '\( ... \)' are not taken into account
359           (setq regexp-alist (cons '( ?\) . ("\\([^\\]\\([\\][\\]\\)*\\|^\\)(" . "\\([^\\]\\([\\][\\]\\)*\\|^\\))")) regexp-alist)))
360       (if (member assoc-bracket-type (mapcar 'car regexp-alist))
361           (progn (setq paren-regexp (cdr (assoc assoc-bracket-type regexp-alist)))
362                  (setq paren-regexp (concat (car paren-regexp) "\\|" (cdr paren-regexp))))
363         (setq paren-regexp (concat (mapconcat 'car (mapcar 'cdr regexp-alist) "\\|") "\\|"
364                                    (mapconcat 'cdr (mapcar 'cdr regexp-alist) "\\|")))))
365     ;; match concurrent one-char opening and closing slurs
366     (if (and (eq dir 1)
367              (not (sequencep bracket-type))
368              (eq (char-syntax (char-after oldpos)) ?\()
369              (not (eq (char-after oldpos) ?<)))
370         ;; anyway do not count open slur, since already level = -1
371         (progn (forward-char 1)
372                (if (eq (following-char) 
373                        (LilyPond-matching-paren (char-after oldpos)))
374                    ;; matching char found, go after it and set level = 0
375                    (progn (forward-char 1)
376                           (setq level 0)))))
377     ;; browse the code until matching slur is found, or report mismatch
378     (while (and (if (not (eq dir 1)) 
379                     (> level 0) 
380                   (< level 0))
381                 ;; dir tells whether to search backward or forward
382                 (if (not (eq dir 1))
383                     (re-search-backward paren-regexp nil t)
384                   (re-search-forward paren-regexp nil t))
385                 ;; note: in case of two-char bracket only latter is compared
386                 (setq match (char-before (match-end 0))))
387 ;;;      (message "%d" level) (sit-for 0 300)
388       (if (not (save-excursion (goto-char (match-end 0))
389                                ;; skip over strings and comments
390                                (LilyPond-inside-string-or-comment-p)))
391           (if (memq match '(?} ?> ?] ?\)))
392               ;; count closing brackets
393               (progn (setq level (1+ level))
394                      ;; slurs may be close to each other, e.g.,
395                      ;; a single '>' was not matched .. need to be corrected
396                      (if (and (eq dir 1) (eq (char-after (match-end 0)) match))
397                          (if (/= level 0)
398                              (progn
399                                (setq level (1+ level))
400                                (forward-char 1))))
401 ;;;                  (message "%d %c" level match) (sit-for 0 300)
402                      ;; hmm..
403                      (if (and (= match ?>) 
404                               (looking-at ".\\s-+>\\|\\({\\|}\\|<\\|>\\|(\\|)\\|[][]\\)>"))
405                          (forward-char 1)))
406             ;; count opening brackets
407             (progn (setq level (1- level))
408 ;;;                (message "%d %c" level match) (sit-for 0 300)
409                    ;; hmm..
410                    (if (and (= match ?<)
411                             (looking-at ".\\s-+<\\|\\({\\|}\\|<\\|>\\|(\\|)\\|[][]\\)<"))
412                        (forward-char 1))))))
413     ;; jump to the matching slur
414     (if (not (eq dir 1))
415         (progn
416           (if (sequencep bracket-type)
417               ;; match the latter char in two-char brackets
418               (if (looking-at "..[][)(]") (forward-char 1)))
419           ;; if the following char is not already a slur
420           (if (and (not (looking-at "[)(]"))
421                    ;; match the slur which follows
422                    (looking-at ".[][><)(]")) (forward-char 1)))
423       (backward-char 1))
424     (if (= level 0) 
425         (point)
426       (progn (goto-char oldpos)
427              nil))))
428
429
430 (defun LilyPond-inside-scheme-p ()
431   "Tests if point is inside embedded Scheme code"
432 ;;; An user does not call this function directly, or by a key sequence.
433   ;;  (interactive)
434   (let ( (test-point (point))
435          (level 0) )
436     (save-excursion 
437       (if (or (and (/= (point) (point-max))
438                    (= (char-after (point)) ?\()
439                    (or (= (char-after (- (point) 1)) ?#)
440                        (and (= (char-after (- (point) 2)) ?#)
441                             (= (char-after (- (point) 1)) ?`))))
442               (and (re-search-backward "#(\\|#`(" nil t)
443                    (progn 
444                      (search-forward "(")
445                      (setq level 1)
446                      (while (and (> level 0)
447                                  (re-search-forward "(\\|)" test-point t)
448                                  (setq match (char-after (match-beginning 0)))
449                                  (<= (point) test-point))
450                        (if (= match ?\()
451                            (setq level (1+ level))
452                          (setq level (1- level))))
453                      (> level 0))))
454           t
455         nil))))
456
457
458 ;;; Largely taken from the 'blink-matching-open' in lisp/simple.el in
459 ;;; the Emacs distribution.
460
461 (defun LilyPond-blink-matching-paren (&optional dir)
462   "Move cursor momentarily to the beginning of the sexp before
463 point. In lilypond files this is used for closing ), ], } and >, whereas the
464 builtin 'blink-matching-open' is not used. In syntax table, see
465 `lilypond-font-lock.el', all brackets are punctuation characters."
466 ;;; An user does not call this function directly, or by a key sequence.
467   ;;  (interactive)
468   (let ( (oldpos (point))
469          (level 0) 
470          (mismatch) )
471     (if (not (or (equal this-command 'LilyPond-electric-close-paren)
472                  (eq dir 1)))
473         (goto-char (setq oldpos (- oldpos 1))))
474     ;; Test if a ligature \] or expressional slur \) was encountered
475     (setq bracket-type (char-after (point)))
476     (setq char-before-bracket-type nil)
477     (if (memq bracket-type '(?] ?\) ?[ ?\())
478       (progn 
479         (setq np -1)
480         (while (eq (char-before (- (point) (setq np (+ np 1)))) ?\\)
481           (setq char-before-bracket-type (if char-before-bracket-type nil ?\\)))
482         (if (eq char-before-bracket-type ?\\)
483             (setq bracket-type (string char-before-bracket-type bracket-type)))))
484     (when blink-matching-paren-distance
485       (narrow-to-region
486        (max (point-min) (- (point) blink-matching-paren-distance))
487        (min (point-max) (+ (point) blink-matching-paren-distance))))
488     (if (and (equal this-command 'LilyPond-electric-close-paren)
489              (memq bracket-type '(?> ?} ?< ?{)))
490         ;; < { need to be mutually balanced and nested, so search backwards for both of these bracket types 
491         (LilyPond-scan-containing-sexp nil nil dir)  
492       ;; whereas ( ) slurs within music don't, so only need to search for ( )
493       ;; use same mechanism for [ ] slurs
494       (LilyPond-scan-containing-sexp bracket-type t dir))
495     (setq blinkpos (point))
496     (setq mismatch
497           (or (null (LilyPond-matching-paren (char-after blinkpos)))
498               (/= (char-after oldpos)
499                   (LilyPond-matching-paren (char-after blinkpos)))))
500     (if mismatch (progn (setq blinkpos nil)
501                         (message "Mismatched parentheses")))
502     (if (and blinkpos
503              (equal this-command 'LilyPond-electric-close-paren))
504         (if (pos-visible-in-window-p)
505             (and blink-matching-paren-on-screen
506                  (sit-for blink-matching-delay))
507           (message
508            "Matches %s"
509            ;; Show what precedes the open in its line, if anything.
510            (if (save-excursion
511                  (skip-chars-backward " \t")
512                  (not (bolp)))
513                (buffer-substring (progn (beginning-of-line) (point))
514                                  (1+ blinkpos))
515              ;; Show what follows the open in its line, if anything.
516              (if (save-excursion
517                    (forward-char 1)
518                    (skip-chars-forward " \t")
519                    (not (eolp)))
520                  (buffer-substring blinkpos
521                                    (progn (end-of-line) (point)))
522                ;; Otherwise show the previous nonblank line,
523                ;; if there is one.
524                (if (save-excursion
525                      (skip-chars-backward "\n \t")
526                      (not (bobp)))
527                    (concat
528                     (buffer-substring (progn
529                                         (skip-chars-backward "\n \t")
530                                         (beginning-of-line)
531                                         (point))
532                                       (progn (end-of-line)
533                                              (skip-chars-backward " \t")
534                                              (point)))
535                     ;; Replace the newline and other whitespace with `...'.
536                     "..."
537                     (buffer-substring blinkpos (1+ blinkpos)))
538                  ;; There is nothing to show except the char itself.
539                  (buffer-substring blinkpos (1+ blinkpos))))))))
540     (if (not (equal this-command 'LilyPond-electric-close-paren))
541         (goto-char (setq oldpos (+ oldpos 1)))
542       (goto-char oldpos))
543     (if (not (eq dir 1))
544         blinkpos
545       (+ blinkpos 1))))
546
547
548 (defun LilyPond-electric-close-paren ()
549   "Blink on the matching open paren when a >, ), } or ] is inserted"
550   (interactive)
551   (let ((oldpos (point)))
552     (self-insert-command 1)
553     ;; Refontify buffer if a block-comment-ender '%}' is inserted
554     (if (and (eq (char-before (point)) ?})
555              (eq (char-before (- (point) 1)) ?%))
556         (font-lock-fontify-buffer)
557       ;; Match paren if the cursor is not inside string or comment.
558       (if (and blink-matching-paren
559                (not (LilyPond-inside-string-or-comment-p))
560                (save-excursion (re-search-backward 
561                                 (concat (mapconcat 'cdr (mapcar 'cdr LilyPond-parens-regexp-alist) "\\|") "\\|)") nil t)
562                                (eq oldpos (1- (match-end 0)))))
563           (progn (backward-char 1)
564                  (LilyPond-blink-matching-paren)
565                  (forward-char 1))))))
566
567 (defun LilyPond-scan-sexps (pos dir) 
568   "This function is redefined to be used in Emacs' show-paren-function and
569 in XEmacs' paren-highlight."
570   (LilyPond-blink-matching-paren dir))
571
572 ;;; REDEFINITIONS: in future make show-paren-mode and paren-highlight local?
573
574 ;;; From Emacs' paren.el, with minimal changes (see "LilyPond"-lines)
575 ;; Find the place to show, if there is one,
576 ;; and show it until input arrives.
577 (defun show-paren-function ()
578 ;;(defun LilyPond-show-paren-function () ; make show-paren-function local ??
579   (if show-paren-mode
580       (let (pos dir mismatch face (oldpos (point)))
581         (cond ((eq (char-syntax (preceding-char)) ?\))
582                (setq dir -1))
583               ((eq (char-syntax (following-char)) ?\()
584                (setq dir 1)))
585         ;;
586         ;; Find the other end of the sexp.
587         (when (and dir
588                    (not (LilyPond-inside-string-or-comment-p)))
589           (save-excursion
590             (save-restriction
591               ;; Determine the range within which to look for a match.
592               (when blink-matching-paren-distance
593                 (narrow-to-region
594                  (max (point-min) (- (point) blink-matching-paren-distance))
595                  (min (point-max) (+ (point) blink-matching-paren-distance))))
596               ;; Scan across one sexp within that range.
597               ;; Errors or nil mean there is a mismatch.
598               (condition-case ()
599                   (setq pos (LilyPond-scan-sexps (point) dir))
600                 (error (setq pos t mismatch t)))
601               ;; If found a "matching" paren, see if it is the right
602               ;; kind of paren to match the one we started at.
603               (when (integerp pos)
604                 (let ((beg (min pos oldpos)) (end (max pos oldpos)))
605                   (when (/= (char-syntax (char-after beg)) ?\$)
606                     (setq mismatch
607                           (not (eq (char-before end)
608                                    ;; This can give nil.
609                                    (matching-paren (char-after beg)))))))))))
610         ;;
611         ;; Highlight the other end of the sexp, or unhighlight if none.
612         (if (not pos)
613             (progn
614               ;; If not at a paren that has a match,
615               ;; turn off any previous paren highlighting.
616               (and show-paren-overlay (overlay-buffer show-paren-overlay)
617                    (delete-overlay show-paren-overlay))
618               (and show-paren-overlay-1 (overlay-buffer show-paren-overlay-1)
619                    (delete-overlay show-paren-overlay-1)))
620           ;;
621           ;; Use the correct face.
622           (if mismatch
623               (progn
624                 (if show-paren-ring-bell-on-mismatch
625                     (beep))
626                 (setq face 'show-paren-mismatch-face))
627             (setq face 'show-paren-match-face))
628           ;;
629           ;; If matching backwards, highlight the closeparen
630           ;; before point as well as its matching open.
631           ;; If matching forward, and the openparen is unbalanced,
632           ;; highlight the paren at point to indicate misbalance.
633           ;; Otherwise, turn off any such highlighting.
634           (if (and (= dir 1) (integerp pos))
635               (when (and show-paren-overlay-1
636                          (overlay-buffer show-paren-overlay-1))
637                 (delete-overlay show-paren-overlay-1))
638             (let ((from (if (= dir 1)
639                             (point)
640                           (forward-point -1)))
641                   (to (if (= dir 1)
642                           (forward-point 1)
643                         (point))))
644               (if show-paren-overlay-1
645                   (move-overlay show-paren-overlay-1 from to (current-buffer))
646                 (setq show-paren-overlay-1 (make-overlay from to)))
647               ;; Always set the overlay face, since it varies.
648               (overlay-put show-paren-overlay-1 'priority show-paren-priority)
649               (overlay-put show-paren-overlay-1 'face face)))
650           ;;
651           ;; Turn on highlighting for the matching paren, if found.
652           ;; If it's an unmatched paren, turn off any such highlighting.
653           (unless (integerp pos)
654             (delete-overlay show-paren-overlay))
655           (let ((to (if (or (eq show-paren-style 'expression)
656                             (and (eq show-paren-style 'mixed)
657                                  (not (pos-visible-in-window-p pos))))
658                         (point)
659                       pos))
660                 (from (if (or (eq show-paren-style 'expression)
661                               (and (eq show-paren-style 'mixed)
662                                    (not (pos-visible-in-window-p pos))))
663                           pos
664                         (save-excursion
665                           (goto-char pos)
666                           (forward-point (- dir))))))
667             (if show-paren-overlay
668                 (move-overlay show-paren-overlay from to (current-buffer))
669               (setq show-paren-overlay (make-overlay from to))))
670           ;;
671           ;; Always set the overlay face, since it varies.
672           (overlay-put show-paren-overlay 'priority show-paren-priority)
673           (overlay-put show-paren-overlay 'face face)))
674     ;; show-paren-mode is nil in this buffer.
675     (and show-paren-overlay
676          (delete-overlay show-paren-overlay))
677     (and show-paren-overlay-1
678          (delete-overlay show-paren-overlay-1))))
679
680 ;;; From XEmacs' paren.el, with minimal changes (see "LilyPond"-lines)
681 ;; Find the place to show, if there is one,
682 ;; and show it until input arrives.
683 (if (string-match "XEmacs\\|Lucid" emacs-version)
684     (paren-set-mode 'paren)) ; works if this is set here (, right place?)
685 (defun paren-highlight ()
686 ;;(defun LilyPond-paren-highlight () ; make paren-highlight local ??
687   "This highlights matching parentheses.
688
689 See the variables:
690   paren-message-offscreen   use modeline when matching paren is offscreen?
691   paren-ding-unmatched      make noise when passing over mismatched parens?
692   paren-mode                'blink-paren, 'paren, or 'sexp
693   blink-matching-paren-distance  maximum distance to search for parens.
694
695 and the following faces:
696   paren-match, paren-mismatch, paren-blink-off"
697
698   ;; I suppose I could check here to see if a keyboard macro is executing,
699   ;; but I did a quick empirical check and couldn't tell that there was any
700   ;; difference in performance
701
702   (let ((oldpos (point))
703         (pface nil)                     ; face for paren...nil kills the overlay
704         (dir (and paren-mode
705                   (not (input-pending-p))
706                   (not executing-kbd-macro)
707                   (cond ((eq (char-syntax (preceding-char)) ?\))
708                          -1)
709                         ((eq (char-syntax (following-char)) ?\()
710                          1))))
711         pos mismatch)
712
713     (save-excursion
714       (if (or (not dir)
715               (LilyPond-inside-string-or-comment-p)
716               (not (save-restriction
717                      ;; Determine the range within which to look for a match.
718                      (if blink-matching-paren-distance
719                          (narrow-to-region
720                           (max (point-min)
721                                (- (point) blink-matching-paren-distance))
722                           (min (point-max)
723                                (+ (point) blink-matching-paren-distance))))
724
725                      ;; Scan across one sexp within that range.
726                      (condition-case nil
727                          (setq pos (LilyPond-scan-sexps (point) dir))
728                        ;; NOTE - if blink-matching-paren-distance is set,
729                        ;; then we can have spurious unmatched parens.
730                        (error (paren-maybe-ding)
731                               nil)))))
732
733           ;; do nothing if we didn't find a matching paren...
734           nil
735
736         ;; See if the "matching" paren is the right kind of paren
737         ;; to match the one we started at.
738         (let ((beg (min pos oldpos)) (end (max pos oldpos)))
739           (setq mismatch
740                 (and (/= (char-syntax (char-after beg)) ?\\)
741                      (/= (char-syntax (char-after beg)) ?\$)
742                      ;; XEmacs change
743                      (matching-paren (char-after beg))
744                      (/= (char-after (1- end))
745                          (matching-paren (char-after beg)))))
746           (if (eq paren-mode 'sexp)
747               (setq paren-extent (make-extent beg end))))
748         (and mismatch
749              (paren-maybe-ding))
750         (setq pface (if mismatch
751                         'paren-mismatch
752                       'paren-match))
753         (and (memq paren-mode '(blink-paren paren))
754              (setq paren-extent (make-extent (- pos dir) pos)))
755
756         (if (and paren-message-offscreen
757                  (eq dir -1)
758                  (not (current-message))
759                  (not (window-minibuffer-p (selected-window)))
760                  (not (pos-visible-in-window-safe pos)))
761             (paren-describe-match pos mismatch))
762                  
763         ;; put the right face on the extent
764         (cond (pface
765                (set-extent-face paren-extent pface) 
766                (set-extent-priority paren-extent 100) ; want this to be high
767                (and (eq paren-mode 'blink-paren)
768                     (setq paren-blink-on-face pface
769                           paren-n-blinks 0
770                           paren-timeout-id
771                           (and paren-blink-interval
772                                (add-timeout paren-blink-interval
773                                             'paren-blink-timeout
774                                             nil
775                                             paren-blink-interval))))))
776         ))))