]> git.donarmstrong.com Git - lilypond.git/blob - elisp/lilypond-mode.el
80a3f298ebbcb5dc3ea6bcdb86215e325fb320d0
[lilypond.git] / elisp / lilypond-mode.el
1 ;;;;
2 ;;;; lilypond-mode.el --- Major mode for editing GNU LilyPond music scores
3 ;;;;
4 ;;;; source file of the GNU LilyPond music typesetter
5 ;;;;  
6 ;;;; (c) 1999--2007 Jan Nieuwenhuizen <janneke@gnu.org>
7 ;;;; 
8 ;;;; Changed 2001--2003 Heikki Junes <heikki.junes@hut.fi>
9 ;;;;    * Add PS-compilation, PS-viewing and MIDI-play (29th Aug 2001)
10 ;;;;    * Keyboard shortcuts (12th Sep 2001)
11 ;;;;    * Inserting tags, inspired on sgml-mode (11th Oct 2001)
12 ;;;;    * Autocompletion & Info (23rd Nov 2002)
13
14 ;;; Inspired on auctex
15
16 ;;; Look lilypond-init.el or Documentation/topdocs/INSTALL.texi
17 ;;; for installing instructions.
18
19 (require 'easymenu)
20 (require 'compile)
21
22 (defconst LilyPond-version "2.5.20"
23   "`LilyPond-mode' version number.")
24
25 (defconst LilyPond-help-address "bug-lilypond@gnu.org"
26   "Address accepting submission of bug reports.")
27
28 (defvar LilyPond-mode-hook nil
29   "*Hook called by `LilyPond-mode'.")
30
31 (defvar LilyPond-region-file-prefix "emacs-lily"
32   "File prefix for commands on buffer or region.")
33
34 (defvar LilyPond-master-file nil
35   "Master file that Lilypond will be run on.")
36
37 ;; FIXME: find ``\score'' in buffers / make settable?
38 (defun LilyPond-get-master-file ()
39   (or LilyPond-master-file
40       (buffer-file-name)))
41
42 (defvar LilyPond-kick-xdvi nil
43   "If true, no simultaneous xdvi's are started, but reload signal is sent.")
44
45 (defvar LilyPond-command-history nil
46   "Command history list.")
47         
48 (defvar LilyPond-regexp-alist
49   '(("\\([a-zA-Z]?:?[^:( \t\n]+\\)[:( \t]+\\([0-9]+\\)[:) \t]" 1 2))
50   "Regexp used to match LilyPond errors.  See `compilation-error-regexp-alist'.")
51
52 (defvar LilyPond-imenu nil
53   "A flag to tell whether LilyPond-imenu is turned on.")
54 (make-variable-buffer-local 'LilyPond-imenu)
55
56 (defcustom LilyPond-include-path ".:/tmp"
57   "* LilyPond include path."
58   :type 'string
59   :group 'LilyPond)
60
61 (defun LilyPond-words-filename ()
62   "The file containing LilyPond \keywords \Identifiers and ReservedWords.
63 Finds file lilypond-words.el from load-path."
64   (let ((fn nil)
65         (lp load-path)
66         (words-file "lilypond-words.el"))
67     (while (and (> (length lp) 0) (not fn))
68       (setq fn (concat (car lp) "/" words-file))
69       (if (not (file-readable-p fn)) 
70           (progn (setq fn nil) (setq lp (cdr lp)))))
71     (if (not fn)
72         (progn (message "Warning: `lilypond-words.el' not found in `load-path'. See `lilypond-init.el'.")
73                (sit-for 5 0)))
74     fn))
75
76 (defun LilyPond-add-dictionary-word (x)
77   "Contains all words: \keywords \Identifiers and ReservedWords."
78   (nconc '(("" . 1)) x))
79
80 (if (> emacs-major-version 20)
81     (defun get-buffer-size (b) (buffer-size b))
82   (defun get-buffer-size (b)
83     (let (size (current-buffer (current-buffer)))
84       (set-buffer b)
85       (setq size (buffer-size))
86       (set-buffer current-buffer)
87       size
88     )))
89
90 ;; creates dictionary if empty
91 (if (and (eq (length (LilyPond-add-dictionary-word ())) 1)
92          (not (eq (LilyPond-words-filename) nil)))
93     (progn
94       (setq b (find-file-noselect (LilyPond-words-filename) t t))
95       (setq m (set-marker (make-marker) 1 (get-buffer b)))
96       (setq i 1)
97       (while (> (get-buffer-size b) (marker-position m))
98         (setq i (+ i 1))
99         (setq copy (copy-alist (list (eval (symbol-name (read m))))))
100         (setcdr copy i)
101         (LilyPond-add-dictionary-word (list copy)))
102       (kill-buffer b)))
103
104 (defvar LilyPond-insert-tag-current ""
105   "The last command selected from the LilyPond-Insert -menu.")
106
107 (defconst LilyPond-menu-keywords 
108   (let ((wordlist '())
109         (co (all-completions "" (LilyPond-add-dictionary-word ())))
110         (currword ""))
111     (progn
112       (while (> (length co) 0)
113         (setq currword (car co))
114         (if (string-equal "-" (car (setq co (cdr co))))
115             (progn
116               (add-to-list 'wordlist currword)
117               (while (and (> (length co) 0)
118                           (not (string-equal "-" (car (setq co (cdr co))))))))))
119       (reverse wordlist)))
120   "Keywords inserted from LilyPond-Insert-menu.")
121
122 (defconst LilyPond-keywords
123   (let ((wordlist '("\\score"))
124         (co (all-completions "" (LilyPond-add-dictionary-word ())))
125         (currword ""))
126     (progn
127       (while (> (length co) 0)
128         (setq currword (car co))
129         (if (> (length currword) 1)
130             (if (and (string-equal "\\" (substring currword 0 1))
131                      (string-match "[a-z-]+" currword)
132                      (= (match-beginning 0) 1)
133                      (= (match-end 0) (length currword))
134                      (not (string-equal "\\longa" currword))
135                      (not (string-equal "\\breve" currword))
136                      (not (string-equal "\\maxima" currword))
137                      (string-equal (downcase currword) currword))
138                 (add-to-list 'wordlist currword)))
139         (if (string-equal "-" (car (setq co (cdr co))))
140             (while (and (> (length co) 0)
141                         (not (string-equal "-" (car (setq co (cdr co)))))))))
142       (reverse wordlist)))
143   "LilyPond \\keywords")
144
145 (defconst LilyPond-identifiers 
146   (let ((wordlist '("\\voiceOne"))
147         (co (all-completions "" (LilyPond-add-dictionary-word ()))))
148     (progn
149       (while (> (length co) 0)
150         (setq currword (car co))
151         (if (> (length currword) 1)
152             (if (and (string-equal "\\" (substring currword 0 1))
153                      (string-match "[a-zA-Z-]+" currword)
154                      (= (match-beginning 0) 1)
155                      (= (match-end 0) (length currword))
156                      (not (string-equal (downcase currword) currword)))
157                 (add-to-list 'wordlist currword)))
158         (if (string-equal "-" (car (setq co (cdr co))))
159             (while (and (> (length co) 0)
160                         (not (string-equal "-" (car (setq co (cdr co)))))))))
161       (reverse wordlist)))
162   "LilyPond \\Identifiers")
163
164 (defconst LilyPond-Capitalized-Reserved-Words 
165   (let ((wordlist '("StaffContext"))
166         (co (all-completions "" (LilyPond-add-dictionary-word ()))))
167     (progn
168       (while (> (length co) 0)
169         (setq currword (car co))
170         (if (> (length currword) 0)
171             (if (and (string-match "[a-zA-Z_]+" currword)
172                      (= (match-beginning 0) 0)
173                      (= (match-end 0) (length currword))
174                      (not (string-equal (downcase currword) currword)))
175                 (add-to-list 'wordlist currword)))
176         (if (string-equal "-" (car (setq co (cdr co))))
177             (while (and (> (length co) 0)
178                         (not (string-equal "-" (car (setq co (cdr co)))))))))
179       (reverse wordlist)))
180   "LilyPond ReservedWords")
181
182 (defconst LilyPond-non-capitalized-reserved-words
183   (let ((wordlist '("cessess"))
184         (co (all-completions "" (LilyPond-add-dictionary-word ()))))
185     (progn
186       (while (> (length co) 0)
187         (setq currword (car co))
188         (if (> (length currword) 0)
189             (if (and (string-match "[a-z]+" currword)
190                      (= (match-beginning 0) 0)
191                      (= (match-end 0) (length currword))
192                      (string-equal (downcase currword) currword))
193                 (add-to-list 'wordlist currword)))
194         (if (string-equal "-" (car (setq co (cdr co))))
195             (while (and (> (length co) 0)
196                         (not (string-equal "-" (car (setq co (cdr co)))))))))
197       (reverse wordlist)))
198   "LilyPond notenames")
199
200 (defun LilyPond-check-files (derived originals extensions)
201   "Check that DERIVED is newer than any of the ORIGINALS.
202 Try each original with each member of EXTENSIONS, in all directories
203 in LilyPond-include-path."
204   (let ((found nil)
205         (regexp (concat "\\`\\("
206                         (mapconcat (function (lambda (dir)
207                                       (regexp-quote (expand-file-name dir))))
208                                    LilyPond-include-path "\\|")
209                         "\\).*\\("
210                         (mapconcat 'regexp-quote originals "\\|")
211                         "\\)\\.\\("
212                         (mapconcat 'regexp-quote extensions "\\|")
213                         "\\)\\'"))
214         (buffers (buffer-list)))
215     (while buffers
216       (let* ((buffer (car buffers))
217              (name (buffer-file-name buffer)))
218         (setq buffers (cdr buffers))
219         (if (and name (string-match regexp name))
220             (progn
221               (and (buffer-modified-p buffer)
222                    (or (not LilyPond-save-query)
223                        (y-or-n-p (concat "Save file "
224                                          (buffer-file-name buffer)
225                                          "? ")))
226                    (save-excursion (set-buffer buffer) (save-buffer)))
227               (if (file-newer-than-file-p name derived)
228                   (setq found t))))))
229     found))
230
231 (defun LilyPond-running ()
232   "Check the currently running LilyPond compiling jobs."
233   (let ((process-names (list "lilypond" "tex" "2dvi" "2ps" "2midi" 
234                              "book" "latex"))
235         (running nil))
236     (while (setq process-name (pop process-names))
237       (setq process (get-process process-name))
238       (if (and process 
239                (eq (process-status process) 'run))
240           (push process-name running)))
241     running)) ; return the running jobs
242
243 (defun LilyPond-midi-running ()
244   "Check the currently running Midi processes."
245   (let ((process-names (list "midi" "midiall"))
246         (running nil))
247     (while (setq process-name (pop process-names))
248       (setq process (get-process process-name))
249       (if (and process 
250                (eq (process-status process) 'run))
251           (push process-name running)))
252     running)) ; return the running jobs
253
254 (defun LilyPond-kill-jobs ()
255   "Kill the currently running LilyPond compiling jobs."
256   (interactive)
257   (let ((process-names (LilyPond-running))
258         (killed nil))
259     (while (setq process-name (pop process-names))
260       (quit-process (get-process process-name) t)
261       (push process-name killed))
262     killed)) ; return the killed jobs
263
264 (defun LilyPond-kill-midi ()
265   "Kill the currently running midi processes."
266   (let ((process-names (LilyPond-midi-running))
267         (killed nil))
268     (while (setq process-name (pop process-names))
269       (quit-process (get-process process-name) t)
270       (push process-name killed))
271     killed)) ; return the killed jobs
272
273 ;; URG, should only run LilyPond-compile for LilyPond
274 ;; not for tex,xdvi (lilypond?)
275 (defun LilyPond-compile-file (command name)
276   ;; We maybe should know what we run here (Lily, lilypond, tex)
277   ;; and adjust our error-matching regex ?
278   (compile-internal
279    (if (eq LilyPond-command-current 'LilyPond-command-master)
280        command
281      ;; use temporary directory for Commands on Buffer/Region
282      ;; hm.. the directory is set twice, first to default-dir
283      (concat "cd " (LilyPond-temp-directory) "; " command))
284    "No more errors" name))
285
286 ;; do we still need this, now that we're using compile-internal?
287 (defun LilyPond-save-buffer ()
288   "Save buffer and set default command for compiling."
289   (interactive)
290   (if (buffer-modified-p)
291       (progn (save-buffer)
292              (setq LilyPond-command-next LilyPond-command-default))))
293
294 ;;; return (dir base ext)
295 (defun split-file-name (name)
296   (let* ((i (string-match "[^/]*$" name))
297          (dir (if (> i 0) (substring name 0 i) "./"))
298          (file (substring name i (length name)))
299          (i (string-match "[^.]*$" file)))
300     (if (and
301          (> i 0)
302          (< i (length file)))
303         (list dir (substring file 0 (- i 1)) (substring file i (length file)))
304       (list dir file ""))))
305
306
307 ;; Should check whether in command-alist?
308 (defcustom LilyPond-command-default "LilyPond"
309   "Default command. Must identify a member of LilyPond-command-alist."
310
311   :group 'LilyPond
312   :type 'string)
313 ;;;(make-variable-buffer-local 'LilyPond-command-last)
314
315 (defvar LilyPond-command-next LilyPond-command-default)
316
317 (defvar LilyPond-command-current 'LilyPond-command-master)
318 ;;;(make-variable-buffer-local 'LilyPond-command-master)
319
320
321 ;; If non-nil, LilyPond-command-query will return the value of this
322 ;; variable instead of quering the user. 
323 (defvar LilyPond-command-force nil)
324
325 (defcustom LilyPond-lilypond-command "lilypond"
326   "Command used to compile LY files."
327   :group 'LilyPond
328   :type 'string)
329
330 (defcustom LilyPond-dvi-command "xdvi"
331   "Command used to display DVI files."
332
333   :group 'LilyPond
334   :type 'string)
335
336 (defcustom LilyPond-ps-command "gv --watch"
337   "Command used to display PS files."
338
339   :group 'LilyPond
340   :type 'string)
341
342 (defcustom LilyPond-pdf-command "xpdf"
343   "Command used to display PDF files."
344
345   :group 'LilyPond
346   :type 'string)
347
348 (defcustom LilyPond-midi-command "timidity"
349   "Command used to play MIDI files."
350
351   :group 'LilyPond
352   :type 'string)
353
354 (defcustom LilyPond-all-midi-command "timidity -ia"
355   "Command used to play MIDI files."
356
357   :group 'LilyPond
358   :type 'string)
359
360 (defun LilyPond-command-current-midi ()
361   "Play midi corresponding to the current document."
362   (interactive)
363   (LilyPond-command (LilyPond-command-menu "Midi") 'LilyPond-get-master-file))
364
365 (defun LilyPond-command-all-midi ()
366   "Play midi corresponding to the current document."
367   (interactive)
368   (LilyPond-command (LilyPond-command-menu "MidiAll") 'LilyPond-get-master-file))
369
370 (defun count-matches-as-number (re)
371   "Count-matches in emacs 22 backwards-incompatibly returns a number"
372   (let ((result (count-matches re)))
373     (if (stringp result)
374         (string-to-number result)
375       result)))
376     
377 (defun count-rexp (start end rexp)
378   "Print number of found regular expressions in the region."
379   (interactive "r")
380   (save-excursion
381     (save-restriction
382       (narrow-to-region start end)
383       (goto-char (point-min))
384       (count-matches-as-number rexp))))
385
386 (defun count-midi-words ()
387   "Check number of midi-scores before the curser."
388   (if (eq LilyPond-command-current 'LilyPond-command-region)
389       (count-rexp (mark t) (point) "\\\\midi")
390     (count-rexp (point-min) (point-max) "\\\\midi")))
391  
392 (defun count-midi-words-backwards ()
393   "Check number of midi-scores before the curser."
394   (if (eq LilyPond-command-current 'LilyPond-command-region)
395       (count-rexp (mark t) (point) "\\\\midi")
396     (count-rexp (point-min) (point) "\\\\midi")))
397  
398 (defun LilyPond-string-current-midi ()
399   "Check the midi file of the following midi-score in the current document."
400   (let ((fnameprefix (if (eq LilyPond-command-current 'LilyPond-command-master)
401                          (substring (LilyPond-get-master-file) 0 -3); suppose ".ly"
402                        LilyPond-region-file-prefix))
403         (allcount (count-midi-words))
404         (count (count-midi-words-backwards)))
405     (concat  fnameprefix
406              (if (and (> allcount 1) (> count 0)) ; not first score
407                  (if (eq count allcount)          ; last score
408                      (concat "-" (number-to-string (+ count -1)))
409                    (concat "-" (number-to-string count))))
410              ".midi")))
411
412 (defun LilyPond-string-all-midi ()
413   "Return the midi files of the current document in ascending order."
414   (let ((fnameprefix (if (eq LilyPond-command-current 'LilyPond-command-master)
415                          (substring (LilyPond-get-master-file) 0 -3); suppose ".ly"
416                        LilyPond-region-file-prefix))
417         (allcount (count-midi-words)))
418     (concat (if (> allcount 0)  ; at least one midi-score
419                 (concat fnameprefix ".midi "))
420             (if (> allcount 1)  ; more than one midi-score
421                 (concat fnameprefix "-[1-9].midi "))
422             (if (> allcount 9)  ; etc.
423                 (concat fnameprefix "-[1-9][0-9].midi"))
424             (if (> allcount 99) ; not first score
425                 (concat fnameprefix "-[1-9][0-9][0-9].midi")))))
426
427 ;; This is the major configuration variable.
428 (defcustom LilyPond-command-alist
429   ;; Should expand this to include possible keyboard shortcuts which
430   ;; could then be mapped to define-key and menu.
431   `(
432     ("LilyPond" . (,(concat LilyPond-lilypond-command " %s") "%s" "%l" "View"))
433     ("TeX" . ("tex '\\nonstopmode\\input %t'" "%t" "%d" "ViewDVI"))
434     ("2Dvi" . (,(concat LilyPond-lilypond-command " -b tex %s") "%s" "%d" "LaTeX"))
435     ("2PS" . (,(concat LilyPond-lilypond-command " -f ps %s") "%s" "%p" "ViewPS"))
436     ("2Gnome" . (,(concat LilyPond-lilypond-command " -b gnome %s")))
437
438     ("Book" . ("lilypond-book %x" "%x" "%l" "LaTeX"))
439     ("LaTeX" . ("latex '\\nonstopmode\\input %l'" "%l" "%d" "ViewDVI"))
440
441     ;; refreshes when kicked USR1
442     ("View" . (,(concat LilyPond-pdf-command " %f")))
443     ("ViewPDF" . (,(concat LilyPond-pdf-command " %f")))
444     ("ViewDVI" . (,(concat LilyPond-dvi-command " %d")))
445     ("ViewPS" . (,(concat LilyPond-ps-command " %p")))
446
447     ;; The following are refreshed in LilyPond-command:
448     ;; - current-midi depends on cursor position and
449     ("Midi" . ("")) ; 
450     ;; - all-midi depends on number of midi-score.
451     ("MidiAll" . (""))
452     )
453
454   "AList of commands to execute on the current document.
455
456 The key is the name of the command as it will be presented to the
457 user, the value is a cons of the command string handed to the shell
458 after being expanded, and the next command to be executed upon
459 success.  The expansion is done using the information found in
460 LilyPond-expand-list.
461 "
462   :group 'LilyPond
463   :type '(repeat (cons :tag "Command Item"
464                        (string :tag "Key")
465                        (cons :tag "How"
466                         (string :tag "Command")
467                         (string :tag "Next Key")))))
468
469 ;; drop this?
470 (defcustom LilyPond-file-extension ".ly"
471   "*File extension used in LilyPond sources."
472   :group 'LilyPond
473   :type 'string)
474
475
476 (defcustom LilyPond-expand-alist 
477   '(
478     ("%s" . ".ly")
479     ("%t" . ".tex")
480     ("%d" . ".dvi")
481     ("%f" . ".pdf")
482     ("%p" . ".ps")
483     ("%l" . ".tex")
484     ("%x" . ".tely")
485     ("%m" . ".midi")
486     )
487     
488   "Alist of expansion strings for LilyPond command names."
489   :group 'LilyPond
490   :type '(repeat (cons :tag "Alist item"
491                   (string :tag "Symbol")
492                   (string :tag "Expansion")))) 
493
494
495 (defcustom LilyPond-command-Show "View"
496   "*The default command to show (view or print) a LilyPond file.
497 Must be the car of an entry in `LilyPond-command-alist'."
498   :group 'LilyPond
499   :type 'string)
500   (make-variable-buffer-local 'LilyPond-command-Show)
501
502 (defcustom LilyPond-command-Print "Print"
503   "The name of the Print entry in LilyPond-command-Print."
504   :group 'LilyPond
505   :type 'string)
506
507 (defun LilyPond-find-required-command (command file)
508   "Find the first command in the chain that is needed to run
509  (input file is newer than the output file)"
510   (let* ((entry (cdr (assoc command LilyPond-command-alist)))
511         (next-command (nth 3 entry)))
512     (if (null next-command)
513         command
514       (let* ((src-string (nth 1 entry))
515             (input (LilyPond-command-expand src-string file))
516             (output (LilyPond-command-expand (nth 2 entry) file)))
517         (if (or (file-newer-than-file-p input output)
518                 (and (equal "%s" src-string)
519                      (not (equal (buffer-name) file))
520                      (file-newer-than-file-p (buffer-name)
521                                              output)))
522             command
523           (LilyPond-find-required-command next-command file))))))
524
525 (defun LilyPond-command-query (name)
526   "Query the user for what LilyPond command to use."
527   (cond ((string-equal name LilyPond-region-file-prefix)
528          (LilyPond-check-files (concat name ".tex")
529                                (list name)
530                                (list LilyPond-file-extension)))
531         ((verify-visited-file-modtime (current-buffer))
532          (and (buffer-modified-p)
533               (y-or-n-p "Save buffer before next command? ")
534               (LilyPond-save-buffer)))
535         ((y-or-n-p "The command will be invoked to an already saved buffer. Revert it? ")
536          (revert-buffer t t)))
537     
538   (let* ((default (LilyPond-find-required-command LilyPond-command-next name))
539          (completion-ignore-case t)
540          (answer (or LilyPond-command-force
541                      (completing-read
542                       (concat "Command: (default " default ") ")
543                       LilyPond-command-alist nil t nil 'LilyPond-command-history))))
544
545     ;; If the answer is "LilyPond" it will not be expanded to "LilyPond"
546     (let ((answer (car-safe (assoc answer LilyPond-command-alist))))
547       (if (and answer
548                (not (string-equal answer "")))
549           answer
550         default))))
551
552 (defun LilyPond-command-master ()
553   "Run command on the current document."
554   (interactive)
555   (LilyPond-command-select-master)
556   (LilyPond-command (LilyPond-command-query (LilyPond-get-master-file))
557                     'LilyPond-get-master-file))
558
559 (defun LilyPond-command-lilypond ()
560   "Run lilypond for the current document."
561   (interactive)
562   (LilyPond-command (LilyPond-command-menu "LilyPond") 'LilyPond-get-master-file)
563 )
564
565 (defun LilyPond-command-formatdvi ()
566   "Format the dvi output of the current document."
567   (interactive)
568   (LilyPond-command (LilyPond-command-menu "2Dvi") 'LilyPond-get-master-file)
569 )
570
571 (defun LilyPond-command-formatps ()
572   "Format the ps output of the current document."
573   (interactive)
574   (LilyPond-command (LilyPond-command-menu "2PS") 'LilyPond-get-master-file)
575 )
576
577 (defun LilyPond-command-formatgnome ()
578   "Format the gnome output of the current document."
579   (interactive)
580   (LilyPond-command (LilyPond-command-menu "2Gnome") 'LilyPond-get-master-file))
581
582 (defun LilyPond-command-formatmidi ()
583   "Format the midi output of the current document."
584   (interactive)
585   (LilyPond-command (LilyPond-command-menu "2Midi") 'LilyPond-get-master-file))
586
587 (defun LilyPond-command-view ()
588   "View the output of current document."
589   (interactive)
590   (LilyPond-command-viewpdf))
591
592 (defun LilyPond-command-viewpdf ()
593   "View the ps output of current document."
594   (interactive)
595   (LilyPond-command (LilyPond-command-menu "ViewPDF") 'LilyPond-get-master-file))
596
597 (defun LilyPond-command-viewps ()
598   "View the ps output of current document."
599   (interactive)
600   (LilyPond-command (LilyPond-command-menu "ViewPS") 'LilyPond-get-master-file))
601
602 ;; FIXME, this is broken
603 (defun LilyPond-region-file (begin end)
604   (let (
605         ;; (dir "./")
606         (dir (LilyPond-temp-directory))
607         (base LilyPond-region-file-prefix)
608         (ext LilyPond-file-extension))
609     (concat dir base ext)))
610
611 ;;; Commands on Region work if there is an appropriate '\score'.
612 (defun LilyPond-command-region (begin end)
613   "Run LilyPond on the current region."
614   (interactive "r")
615   (if (or (> begin (point-min)) (< end (point-max)))
616       (LilyPond-command-select-region))
617   (write-region begin end (LilyPond-region-file begin end) nil 'nomsg)
618   (LilyPond-command (LilyPond-command-query
619                      (LilyPond-region-file begin end))
620                     '(lambda () (LilyPond-region-file begin end)))
621   ;; Region may deactivate even if buffer was intact, reactivate?
622   ;; Currently, also deactived regions are used.
623   )
624
625 (defun LilyPond-command-buffer ()
626   "Run LilyPond on buffer."
627   (interactive)
628   (LilyPond-command-select-buffer)
629   (LilyPond-command-region (point-min) (point-max)))
630
631 (defun LilyPond-command-expand (string file)
632   (let ((case-fold-search nil))
633     (if (string-match "%" string)
634         (let* ((b (match-beginning 0))
635                (e (+ b 2))
636                (l (split-file-name file))
637                (dir (car l))
638                (base (cadr l)))
639           (LilyPond-command-expand
640            (concat (substring string 0 b)
641                    (shell-quote-argument (concat dir base))
642                    (let ((entry (assoc (substring string b e)
643                                        LilyPond-expand-alist)))
644                      (if entry (cdr entry) ""))
645                    (substring string e))
646            file))
647       string)))
648
649 (defun LilyPond-shell-process (name buffer command)
650   (let ((old (current-buffer)))
651     (switch-to-buffer-other-window buffer)
652     ;; If we empty the buffer don't see messages scroll by.
653     ;; (erase-buffer)
654     
655     (start-process-shell-command name buffer command)
656     (switch-to-buffer-other-window old)))
657   
658
659 (defun LilyPond-command (name file)
660   "Run command NAME on the file you get by calling FILE.
661
662 FILE is a function return a file name.  It has one optional argument,
663 the extension to use on the file.
664
665 Use the information in LilyPond-command-alist to determine how to run the
666 command."
667
668   (let ((entry (assoc name LilyPond-command-alist)))
669     (if entry
670         (let ((command (LilyPond-command-expand (cadr entry)
671                                                 (apply file nil)))
672               (jobs nil)
673               (job-string "no jobs"))
674           (if (member name (list "View" "ViewPS"))
675               ;; is USR1 a right signal for viewps?
676               (let ((buffer-xdvi (get-buffer-create (concat "*" name "*"))))
677                 ;; what if XEDITOR is set to gedit or so, should we steal it?
678                 (if (not (getenv "XEDITOR"))
679                     (setenv "XEDITOR" "emacsclient --no-wait +%l:%c %f"))
680                 (if LilyPond-kick-xdvi
681                   (let ((process-xdvi (get-buffer-process buffer-xdvi)))
682                     (if process-xdvi
683                         (signal-process (process-id process-xdvi) 'SIGUSR1)
684                       (LilyPond-shell-process name buffer-xdvi command)))
685                   (LilyPond-shell-process name buffer-xdvi command)))
686             (progn
687               (if (string-equal name "Midi")
688                   (progn
689                     (setq command (concat LilyPond-midi-command " " (LilyPond-string-current-midi)))
690                     (if (LilyPond-kill-midi)
691                         (setq job-string nil)))) ; either stop or start playing
692               (if (string-equal name "MidiAll")
693                   (progn
694                     (setq command (concat LilyPond-all-midi-command " " (LilyPond-string-all-midi)))
695                     (LilyPond-kill-midi))) ; stop and start playing
696               (if (and (member name (list "Midi" "MidiAll")) job-string)
697                   (if (file-newer-than-file-p
698                        (LilyPond-get-master-file)
699                        (concat (substring (LilyPond-get-master-file) 0 -3) ".midi"))
700                       (if (y-or-n-p "Midi older than source. Reformat midi?")
701                           (progn
702                             (LilyPond-command-formatmidi)
703                             (while (LilyPond-running)
704                               (message "Starts playing midi once it is built.")
705                               (sit-for 0 100))))))
706               (if (member name (list "LilyPond" "TeX" "2Midi" "2PS" "2Dvi" 
707                                      "Book" "LaTeX"))
708                   (if (setq jobs (LilyPond-running))
709                       (progn
710                         (setq job-string "Process") ; could also suggest compiling after process has ended
711                         (while jobs
712                           (setq job-string (concat job-string " \"" (pop jobs) "\"")))
713                         (setq job-string (concat job-string " is already running; kill it to proceed "))
714                         (if (y-or-n-p job-string)
715                             (progn
716                               (setq job-string "no jobs")
717                               (LilyPond-kill-jobs)
718                               (while (LilyPond-running)
719                                 (sit-for 0 100)))
720                           (setq job-string nil)))))
721
722               (setq LilyPond-command-next
723                     (let* ((entry (assoc name LilyPond-command-alist))
724                            (next-command (nth 3 (cdr entry))))
725                       (or next-command
726                           LilyPond-command-default)))
727               
728               (if (string-equal job-string "no jobs")
729                   (LilyPond-compile-file command name))))))))
730           
731 (defun LilyPond-mark-active ()
732   "Check if there is an active mark."
733   (and transient-mark-mode
734        (if (string-match "XEmacs\\|Lucid" emacs-version) (mark) mark-active)))
735
736 (defun LilyPond-temp-directory ()
737   "Temporary file directory for Commands on Region."
738   (interactive)
739   (if (string-match "XEmacs\\|Lucid" emacs-version)
740       (concat (temp-directory) "/")
741     temporary-file-directory))
742
743 ;;; Keymap
744
745 (defvar LilyPond-mode-map ()
746   "Keymap used in `LilyPond-mode' buffers.")
747
748 ;; Note:  if you make changes to the map, you must do
749 ;;    M-x set-variable LilyPond-mode-map nil
750 ;;    M-x eval-buffer
751 ;;    M-x LilyPond-mode
752 ;; to let the changest take effect
753
754 (if LilyPond-mode-map
755     ()
756   (setq LilyPond-mode-map (make-sparse-keymap))
757   ;; Put keys to LilyPond-command-alist and fetch them from there somehow.
758   (define-key LilyPond-mode-map "\C-c\C-l" 'LilyPond-command-lilypond)
759   (define-key LilyPond-mode-map "\C-c\C-r" 'LilyPond-command-region)
760   (define-key LilyPond-mode-map "\C-c\C-b" 'LilyPond-command-buffer)
761   (define-key LilyPond-mode-map "\C-c\C-k" 'LilyPond-kill-jobs)
762   (define-key LilyPond-mode-map "\C-c\C-c" 'LilyPond-command-master)
763   (define-key LilyPond-mode-map "\C-cm" 'LilyPond-command-formatmidi)
764   (define-key LilyPond-mode-map "\C-c\C-d" 'LilyPond-command-formatdvi)
765   (define-key LilyPond-mode-map "\C-c\C-f" 'LilyPond-command-formatps)
766   (define-key LilyPond-mode-map "\C-c\C-g" 'LilyPond-command-formatgnome)
767   (define-key LilyPond-mode-map "\C-c\C-s" 'LilyPond-command-view)
768   (define-key LilyPond-mode-map "\C-c\C-p" 'LilyPond-command-viewps)
769   (define-key LilyPond-mode-map [(control c) return] 'LilyPond-command-current-midi)
770   (define-key LilyPond-mode-map [(control c) (control return)] 'LilyPond-command-all-midi)
771   (define-key LilyPond-mode-map "\C-x\C-s" 'LilyPond-save-buffer)
772   (define-key LilyPond-mode-map "\C-cb" 'LilyPond-what-beat)
773   (define-key LilyPond-mode-map "\C-cf" 'font-lock-fontify-buffer)
774   (define-key LilyPond-mode-map "\C-ci" 'LilyPond-insert-tag-current)
775   ;; the following will should be overriden by Lilypond Quick Insert Mode
776   (define-key LilyPond-mode-map "\C-cq" 'LilyPond-quick-insert-mode)
777   (define-key LilyPond-mode-map "\C-c;" 'LilyPond-comment-region)
778   (define-key LilyPond-mode-map ")" 'LilyPond-electric-close-paren)
779   (define-key LilyPond-mode-map ">" 'LilyPond-electric-close-paren)
780   (define-key LilyPond-mode-map "}" 'LilyPond-electric-close-paren)
781   (define-key LilyPond-mode-map "]" 'LilyPond-electric-close-paren)
782   (define-key LilyPond-mode-map "|" 'LilyPond-electric-bar)
783   (if (string-match "XEmacs\\|Lucid" emacs-version)
784       (define-key LilyPond-mode-map [iso-left-tab] 'LilyPond-autocompletion)
785     (define-key LilyPond-mode-map [iso-lefttab] 'LilyPond-autocompletion))
786   (define-key LilyPond-mode-map "\C-c\t" 'LilyPond-info-index-search)
787   )
788
789 ;;; Menu Support
790
791 ;;; This mode was originally LilyPond-quick-note-insert by Heikki Junes.
792 ;;; The original version has been junked since CVS-1.97,
793 ;;; in order to merge the efforts done by Nicolas Sceaux.
794 ;;; LilyPond Quick Insert Mode is a major mode, toggled by C-c q.
795 (defun LilyPond-quick-insert-mode ()
796   "Insert notes with fewer key strokes by using a simple keyboard piano."
797   (interactive)
798   (progn 
799     (message "Invoke (C-c q) from keyboard. If you still see this message,") (sit-for 5 0)
800     (message "then you have not installed LilyPond Quick Insert Mode (lyqi).") (sit-for 5 0)
801     (message "Download lyqi from http://nicolas.sceaux.free.fr/lilypond/lyqi.html,") (sit-for 5 0)
802     (message "see installation instructions from lyqi's README -file.") (sit-for 5 0)
803     (message "You need also eieio (Enhanced Integration of Emacs Interpreted Objects).") (sit-for 5 0)
804     (message "Download eieio from http://cedet.sourceforge.net/eieio.shtml,") (sit-for 5 0)
805     (message "see installation instructions from eieio's INSTALL -file.") (sit-for 5 0)
806     (message "")
807     ))    
808
809 (defun LilyPond-pre-word-search ()
810   "Fetch the alphabetic characters and \\ in front of the cursor."
811   (let ((pre "")
812         (prelen 0)
813         (ch (char-before (- (point) 0))))
814     (while (and ch (or (and (>= ch 65) (<= ch 90))  ; not bolp, A-Z
815                        (and (>= ch 97) (<= ch 122)) ; a-z
816                        (= ch 92)))                  ; \\
817       (setq pre (concat (char-to-string ch) pre))
818       (setq prelen (+ prelen 1))
819       (setq ch (char-before (- (point) prelen))))
820     pre))
821
822 (defun LilyPond-post-word-search ()
823   "Fetch the alphabetic characters behind the cursor."
824   (let ((post "")
825         (postlen 0)
826         (ch (char-after (+ (point) 0))))
827     (while (and ch (or (and (>= ch 65) (<= ch 90))    ; not eolp, A-Z
828                        (and (>= ch 97) (<= ch 122)))) ; a-z
829       (setq post (concat post (char-to-string ch)))
830       (setq postlen (+ postlen 1))
831       (setq ch (char-after (+ (point) postlen))))
832     post))
833
834 (defun LilyPond-autocompletion ()
835   "Show completions in mini-buffer for the given word."
836   (interactive)
837   (let ((pre (LilyPond-pre-word-search))
838         (post (LilyPond-post-word-search))
839         (compsstr ""))
840     ;; insert try-completion and show all-completions
841     (if (> (length pre) 0)
842         (progn
843           (setq trycomp (try-completion pre (LilyPond-add-dictionary-word ())))
844           (if (char-or-string-p trycomp)
845               (if (string-equal (concat pre post) trycomp)
846                   (goto-char (+ (point) (length post)))
847                 (progn
848                   (delete-region (point) (+ (point) (length post)))
849                   (insert (substring trycomp (length pre) nil))))
850             (progn
851               (delete-region (point) (+ (point) (length post)))
852               (font-lock-fontify-buffer))) ; only inserting fontifies
853         
854         (setq complist (all-completions pre (LilyPond-add-dictionary-word ())))
855         (while (> (length complist) 0)
856           (setq compsstr (concat compsstr "\"" (car complist) "\" "))
857           (setq complist (cdr complist)))
858         (message compsstr) 
859         (sit-for 0 100)))))
860
861 (defun LilyPond-info ()
862   "Launch Info for lilypond."
863   (interactive)
864   (info "lilypond"))
865   
866 (defun LilyPond-music-glossary-info ()
867   "Launch Info for music-glossary."
868   (interactive)
869   (info "music-glossary"))
870
871 (defun LilyPond-internals-info ()
872   "Launch Info for lilypond-internals."
873   (interactive)
874   (info "lilypond-internals"))
875   
876 (defun LilyPond-info-index-search ()
877   "In `*info*'-buffer, launch `info lilypond --index-search word-under-cursor'"
878   (interactive)
879   (let ((str (concat (LilyPond-pre-word-search) (LilyPond-post-word-search))))
880     (if (and (> (length str) 0) 
881              (string-equal (substring str 0 1) "\\"))
882         (setq str (substring str 1 nil)))
883     (LilyPond-info)
884     (Info-index str)))
885
886 (defun LilyPond-insert-tag-current (&optional word)
887   "Set the current tag to be inserted."
888   (interactive)
889   (if word
890       (setq LilyPond-insert-tag-current word))
891   (if (memq LilyPond-insert-tag-current LilyPond-menu-keywords)
892       (LilyPond-insert-tag)
893     (message "No tag was selected from LilyPond->Insert tag-menu.")))
894
895 (defun LilyPond-insert-tag ()
896   "Insert syntax for given tag. The definitions are in LilyPond-words-filename."
897   (interactive)
898   (setq b (find-file-noselect (LilyPond-words-filename) t t))
899   (let ((word LilyPond-insert-tag-current)
900         (found nil)
901         (p nil)
902         (query nil)
903         (m (set-marker (make-marker) 1 (get-buffer b)))
904         (distance (if (LilyPond-mark-active)
905                       (abs (- (mark-marker) (point-marker))) 0))
906        )
907    ;; find the place first
908    (if (LilyPond-mark-active)
909        (goto-char (min (mark-marker) (point-marker))))
910    (while (and (not found) (> (get-buffer-size b) (marker-position m)))
911     (setq copy (car (copy-alist (list (eval (symbol-name (read m)))))))
912     (if (string-equal word copy) (setq found t)))
913    (if found (insert word))
914    (if (> (get-buffer-size b) (marker-position m))
915        (setq copy (car (copy-alist (list (eval (symbol-name (read m))))))))
916    (if (not (string-equal "-" copy)) 
917        (setq found nil))
918    (while (and found (> (get-buffer-size b) (marker-position m)))
919     ;; find next symbol
920     (setq copy (car (copy-alist (list (eval (symbol-name (read m)))))))
921     ;; check whether it is the word, or the word has been found
922     (cond 
923      ((string-equal "-" copy) (setq found nil))
924      ((string-equal "%" copy) (insert " " (read-string "Give Arguments: ")))
925      ((string-equal "_" copy) 
926       (progn 
927        (setq p (point))
928        (goto-char (+ p distance))))
929      ((string-equal "\?" copy) (setq query t))
930      ((string-equal "\!" copy) (setq query nil))
931      ((string-equal "\\n" copy) 
932       (if (not query)
933        (progn (LilyPond-indent-line) (insert "\n") (LilyPond-indent-line))))
934      ((string-equal "{" copy) 
935       (if (not query) 
936           (progn (insert " { "))))
937      ((string-equal "}" copy)
938       (if (not query)
939        (progn (insert " } ") (setq query nil) )))
940      ((not query)
941       (insert copy))
942      (query
943       (if (y-or-n-p (concat "Proceed with `" copy "'? "))
944        (progn (insert copy) (setq query nil))))
945    ))
946    (if p (goto-char p))
947    (kill-buffer b))
948 )
949
950 (defun LilyPond-command-menu-entry (entry)
951   ;; Return LilyPond-command-alist ENTRY as a menu item.
952   (let ((name (car entry)))
953     (cond ((and (string-equal name LilyPond-command-Print)
954                 LilyPond-printer-list)
955            (let ((command LilyPond-print-command)
956                  (lookup 1))
957              (append (list LilyPond-command-Print)
958                      (mapcar 'LilyPond-command-menu-printer-entry
959                              LilyPond-printer-list))))
960           (t
961            (vector name (list 'LilyPond-command-menu name) t)))))
962
963
964 (easy-menu-define LilyPond-command-menu
965   LilyPond-mode-map
966   "Menu used in LilyPond mode."
967   (append '("Command")
968           '(("Command on"
969              [ "Master File" LilyPond-command-select-master
970                :keys "C-c C-c" :style radio
971                :selected (eq LilyPond-command-current 'LilyPond-command-master) ]
972              [ "Buffer" LilyPond-command-select-buffer
973                :keys "C-c C-b" :style radio
974                :selected (eq LilyPond-command-current 'LilyPond-command-buffer) ]
975              [ "Region" LilyPond-command-select-region
976                :keys "C-c C-r" :style radio
977                :selected (eq LilyPond-command-current 'LilyPond-command-region) ]))
978 ;;;       (let ((file 'LilyPond-command-on-current))
979 ;;;         (mapcar 'LilyPond-command-menu-entry LilyPond-command-alist))
980 ;;; Some kind of mapping which includes :keys might be more elegant
981 ;;; Put keys to LilyPond-command-alist and fetch them from there somehow.
982           '([ "LilyPond" LilyPond-command-lilypond t])
983           '([ "TeX" (LilyPond-command (LilyPond-command-menu "TeX") 'LilyPond-get-master-file) ])
984           '([ "2Dvi" LilyPond-command-formatdvi t])
985           '([ "2PS" LilyPond-command-formatps t])
986           '([ "2Midi" LilyPond-command-formatmidi t])
987           '([ "Book" (LilyPond-command (LilyPond-command-menu "Book") 'LilyPond-get-master-file) ])
988           '([ "LaTeX" (LilyPond-command (LilyPond-command-menu "LaTeX") 'LilyPond-get-master-file) ])
989           '([ "Kill jobs" LilyPond-kill-jobs t])
990           '("-----")
991           '([ "View" LilyPond-command-view t])
992           '([ "ViewPS" LilyPond-command-viewps t])
993           '("-----")
994           '([ "Midi (toggle)" LilyPond-command-current-midi t])
995           '([ "Midi all" LilyPond-command-all-midi t])
996           ))
997
998 (defun LilyPond-menu-keywords-item (arg)
999   "Make vector for LilyPond-mode-keywords."
1000   (vector arg (list 'LilyPond-insert-tag-current arg) :style 'radio :selected (list 'eq 'LilyPond-insert-tag-current arg)))
1001
1002 (defun LilyPond-menu-keywords ()
1003   "Make Insert Tag menu. 
1004
1005 The Insert Tag -menu is splitted into parts if it is long enough."
1006
1007   (let ((li (mapcar 'LilyPond-menu-keywords-item LilyPond-menu-keywords))
1008         (w (round (sqrt (length LilyPond-menu-keywords))))
1009         (splitted '())
1010         (imin 0) imax lw rw)
1011     (while (< imin (length LilyPond-menu-keywords))
1012       (setq imax (- (min (+ imin w) (length LilyPond-menu-keywords)) 1))
1013       (setq lw (nth imin LilyPond-menu-keywords)) 
1014       (setq rw (nth imax LilyPond-menu-keywords))
1015       (add-to-list 'splitted
1016          (let ((l (list (concat (substring lw 0 (min 7 (length lw))) 
1017                                 " ... " 
1018                                 (substring rw 0 (min 7 (length rw)))))))
1019            (while (<= imin imax)
1020              (add-to-list 'l (nth imin li))
1021              (setq imin (1+ imin)))
1022            (reverse l))))
1023     (if (> (length LilyPond-menu-keywords) 12) (reverse splitted) li)))
1024
1025 ;;; LilyPond-mode-menu should not be interactive, via "M-x LilyPond-<Tab>"
1026 (easy-menu-define LilyPond-mode-menu
1027   LilyPond-mode-map
1028   "Menu used in LilyPond mode."
1029   (append '("LilyPond")
1030           '(["Add index menu" LilyPond-add-imenu-menu])
1031           (list (cons "Insert tag" 
1032                 (cons ["Previously selected" LilyPond-insert-tag-current t] 
1033                 (cons "-----"
1034                       (LilyPond-menu-keywords)))))
1035           '(("Miscellaneous"
1036              ["Autocompletion"   LilyPond-autocompletion t]
1037              ["(Un)comment Region" LilyPond-comment-region t]
1038              ["Refontify buffer" font-lock-fontify-buffer t]
1039              "-----"
1040              ["Quick Insert Mode"  LilyPond-quick-insert-mode :keys "C-c q"]
1041              ))
1042           '(("Info"
1043              ["LilyPond" LilyPond-info t]
1044              ["LilyPond index-search" LilyPond-info-index-search t]
1045              ["Music Glossary" LilyPond-music-glossary-info t]
1046              ["LilyPond internals" LilyPond-internals-info t]
1047              ))
1048           ))
1049
1050 (defconst LilyPond-imenu-generic-re "^\\([a-zA-Z]+\\) *="
1051   "Regexp matching Identifier definitions.")
1052
1053 (defvar LilyPond-imenu-generic-expression
1054   (list (list nil LilyPond-imenu-generic-re 1))
1055   "Expression for imenu")
1056
1057 (defun LilyPond-command-select-master ()
1058   (interactive)
1059   (message "Next command will be on the master file")
1060   (setq LilyPond-command-current 'LilyPond-command-master))
1061
1062 (defun LilyPond-command-select-buffer ()
1063   (interactive)
1064   (message "Next command will be on the buffer")
1065   (setq LilyPond-command-current 'LilyPond-command-buffer))
1066
1067 (defun LilyPond-command-select-region ()
1068   (interactive)
1069   (message "Next command will be on the region")
1070   (setq LilyPond-command-current 'LilyPond-command-region))
1071
1072 (defun LilyPond-command-menu (name)
1073   ;; Execute LilyPond-command-alist NAME from a menu.
1074   (let ((LilyPond-command-force name))
1075     (if (eq LilyPond-command-current 'LilyPond-command-region)
1076         (if (eq (mark t) nil)
1077             (progn (message "The mark is not set now") (sit-for 0 500))
1078           (progn (if (not (not (LilyPond-mark-active)))
1079                      (progn (message "Region is not active, using region between inactive mark and current point.") (sit-for 0 500)))
1080                  (LilyPond-command-region (mark t) (point))))
1081       (funcall LilyPond-command-current))))
1082
1083 (defun LilyPond-add-imenu-menu ()
1084   (interactive)
1085   "Add an imenu menu to the menubar."
1086   (if (not LilyPond-imenu)
1087       (progn
1088         (imenu-add-to-menubar "Index")
1089         (redraw-frame (selected-frame))
1090         (setq LilyPond-imenu t))
1091     (message "%s" "LilyPond-imenu already exists.")))
1092 (put 'LilyPond-add-imenu-menu 'menu-enable '(not LilyPond-imenu))
1093
1094 (defun LilyPond-mode ()
1095   "Major mode for editing LilyPond music files.
1096
1097 This mode knows about LilyPond keywords and line comments, not about
1098 indentation or block comments.  It features easy compilation, error
1099 finding and viewing of a LilyPond source buffer or region.
1100
1101 COMMANDS
1102 \\{LilyPond-mode-map}
1103 VARIABLES
1104
1105 LilyPond-command-alist\t\talist from name to command
1106 LilyPond-dvi-command\t\tcommand to display dvi files -- bit superfluous"
1107   (interactive)
1108   ;; set up local variables
1109   (kill-all-local-variables)
1110
1111   (make-local-variable 'font-lock-defaults)
1112   (setq font-lock-defaults '(LilyPond-font-lock-keywords))
1113
1114   ;; string and comments are fontified explicitly
1115   (make-local-variable 'font-lock-keywords-only)
1116   (setq font-lock-keywords-only t)
1117
1118   ;; Multi-line font-locking needs Emacs 21.1 or newer.
1119   ;; For older versions there is hotkey "C-c f".
1120   (make-local-variable 'font-lock-multiline) 
1121   (setq font-lock-multiline t) 
1122
1123   (make-local-variable 'paragraph-separate)
1124   (setq paragraph-separate "^[ \t]*$")
1125
1126   (make-local-variable 'paragraph-start)
1127   (setq paragraph-start "^[ \t]*$")
1128
1129   (make-local-variable 'comment-start)
1130   (setq comment-start "%")
1131
1132   (make-local-variable 'comment-start-skip)
1133   (setq comment-start-skip "%{? *")
1134
1135   (make-local-variable 'comment-end)
1136   (setq comment-end "")
1137
1138   (make-local-variable 'block-comment-start)
1139   (setq block-comment-start "%{")
1140
1141   (make-local-variable 'block-comment-end)  
1142   (setq block-comment-end   "%}")
1143
1144   (make-local-variable 'indent-line-function)
1145   (setq indent-line-function 'LilyPond-indent-line)
1146
1147   (LilyPond-mode-set-syntax-table '(?\< ?\> ?\{ ?\}))
1148   (setq major-mode 'LilyPond-mode)
1149   (setq mode-name "LilyPond")
1150   (setq local-abbrev-table LilyPond-mode-abbrev-table)
1151   (use-local-map LilyPond-mode-map)
1152
1153   ;; In XEmacs imenu was synched up with: FSF 20.4
1154   (make-local-variable 'imenu-generic-expression)
1155   (setq imenu-generic-expression LilyPond-imenu-generic-expression)
1156   ;; (imenu-add-to-menubar "Index") ; see LilyPond-add-imenu-menu
1157
1158   ;; In XEmacs one needs to use 'easy-menu-add'.
1159   (if (string-match "XEmacs\\|Lucid" emacs-version)
1160       (progn
1161         (easy-menu-add LilyPond-mode-menu)
1162         (easy-menu-add LilyPond-command-menu)))
1163
1164   ;; Use Command on Region even for inactive mark (region).
1165   (if (string-match "XEmacs\\|Lucid" emacs-version)
1166       (setq zmacs-regions nil)
1167     (setq mark-even-if-inactive t))
1168
1169   ;; Context dependent syntax tables in LilyPond-mode
1170   (make-local-hook 'post-command-hook) ; XEmacs requires
1171   (add-hook 'post-command-hook 'LilyPond-mode-context-set-syntax-table nil t)
1172
1173   ;; Turn on paren-mode buffer-locally, i.e., in LilyPond-mode
1174   (if (string-match "XEmacs\\|Lucid" emacs-version)
1175       (progn
1176         (make-local-variable 'paren-mode)
1177         (paren-set-mode 'paren)
1178         (make-local-variable 'blink-matching-paren)
1179         (setq blink-matching-paren t)
1180         )
1181     (progn
1182       (make-local-variable 'blink-matching-paren-on-screen)
1183       (setq blink-matching-paren-on-screen t)
1184      ))
1185
1186   ;; run the mode hook. LilyPond-mode-hook use is deprecated
1187   (run-hooks 'LilyPond-mode-hook))
1188
1189 (defun LilyPond-version ()
1190   "Echo the current version of `LilyPond-mode' in the minibuffer."
1191   (interactive)
1192   (message "Using `LilyPond-mode' version %s" LilyPond-version))
1193
1194 (load-library "lilypond-font-lock")
1195 (load-library "lilypond-indent")
1196 (load-library "lilypond-what-beat")
1197
1198 (defun LilyPond-guile ()
1199   (interactive)
1200   (require 'ilisp)
1201   (guile "lilyguile" (LilyPond-command-expand (cadr (assoc "2Dvi" LilyPond-command-alist))
1202                                               (funcall 'LilyPond-get-master-file)))
1203   (comint-default-send (ilisp-process) "(define-module (*anonymous-ly-0*))")
1204   (comint-default-send (ilisp-process) "(set! %load-path (cons \"/usr/share/ilisp/\" %load-path))")
1205   (comint-default-send (ilisp-process) "(use-modules (guile-user) (guile-ilisp))")
1206   (comint-default-send (ilisp-process) "(newline)"))
1207
1208 (provide 'lilypond-mode)
1209 ;;; lilypond-mode.el ends here
1210