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