]> git.donarmstrong.com Git - lilypond.git/blob - lilypond-mode.el
* lily/source-file.cc (Source_file): Add warning for possibly
[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--2001 Jan Nieuwenhuizen <janneke@gnu.org>
7 ;;; 
8 ;;; Changed 2001--2002 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 ;;; Changed 2002 Carlos Betancourt <carlos.betancourt@chello.be>
15 ;;;    * Added spanish-note-replacements
16
17 ;;; Inspired on auctex
18
19 ;;; Look lilypond-init.el or Documentation/topdocs/INSTALL.texi
20 ;;; for installing instructions.
21
22 ;;; TODO:
23 ;;;    * XEmacs, broken ?
24 ;;;    * parenthesis matching
25
26 (require 'easymenu)
27 (require 'compile)
28
29 (defconst LilyPond-version "1.7.9"
30   "`LilyPond-mode' version number.")
31
32 (defconst LilyPond-help-address "bug-lilypond@gnu.org"
33   "Address accepting submission of bug reports.")
34
35 (defvar LilyPond-mode-hook nil
36   "*Hook called by `LilyPond-mode'.")
37
38 ;; FIXME: find ``\score'' in buffers / make settable?
39 (defun LilyPond-master-file ()
40   ;; duh
41   (buffer-file-name))
42
43 (defvar LilyPond-kick-xdvi nil
44   "If true, no simultaneous xdvi's are started, but reload signal is sent.")
45
46 (defvar LilyPond-command-history nil
47   "Command history list.")
48         
49 (defvar LilyPond-regexp-alist
50   '(("\\([a-zA-Z]?:?[^:( \t\n]+\\)[:( \t]+\\([0-9]+\\)[:) \t]" 1 2))
51   "Regexp used to match LilyPond errors.  See `compilation-error-regexp-alist'.")
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     fn))
69
70 (defun LilyPond-add-dictionary-word (x)
71   "Contains all words: keywords, identifiers, reserved words."
72   (nconc '(("" . 1)) x))
73
74 ;; creates dictionary if empty
75 (if (eq (length (LilyPond-add-dictionary-word ())) 1)
76     (progn
77       (setq fn (LilyPond-words-filename))
78       (setq b (find-file-noselect fn t t))
79       (setq m (set-marker (make-marker) 1 (get-buffer b)))
80       (setq i 1)
81       (while (> (buffer-size b) (marker-position m))
82         (setq i (+ i 1))
83         (setq copy (copy-alist (list (eval (symbol-name (read m))))))
84         (setcdr copy i)
85         (LilyPond-add-dictionary-word (list copy)))
86       (kill-buffer b)))
87
88 (defconst LilyPond-keywords 
89   (let ((wordlist ())
90         (co (all-completions "" (LilyPond-add-dictionary-word ()))))
91     (progn
92       (while (> (length co) 0)
93         (if (> (length (car co)) 1)
94             (if (and (string-equal "\\" (substring (car co) 0 1))
95                      (string-equal (downcase (car co)) (car co)))
96                 (add-to-list 'wordlist (car co))))
97         (setq co (cdr co)))
98       wordlist))
99   "LilyPond \\keywords")
100
101 (defconst LilyPond-identifiers 
102   (let ((wordlist ())
103         (co (all-completions "" (LilyPond-add-dictionary-word ()))))
104     (progn
105       (while (> (length co) 0)
106         (if (> (length (car co)) 1)
107             (if (and (string-equal "\\" (substring (car co) 0 1))
108                      (not (string-equal (downcase (car co)) (car co))))
109                 (add-to-list 'wordlist (car co))))
110         (setq co (cdr co)))
111       wordlist))
112   "LilyPond \\Identifiers")
113
114 (defconst LilyPond-reserved-words 
115   (let ((wordlist ())
116         (co (all-completions "" (LilyPond-add-dictionary-word ()))))
117     (progn
118       (while (> (length co) 0)
119         (if (> (length (car co)) 0)
120             (if (not (string-equal "\\" (substring (car co) 0 1)))
121                 (add-to-list 'wordlist (car co))))
122         (setq co (cdr co)))
123       wordlist))
124   "LilyPond ReservedWords")
125
126 (defun LilyPond-check-files (derived originals extensions)
127   "Check that DERIVED is newer than any of the ORIGINALS.
128 Try each original with each member of EXTENSIONS, in all directories
129 in LilyPond-include-path."
130   (let ((found nil)
131         (regexp (concat "\\`\\("
132                         (mapconcat (function (lambda (dir)
133                                       (regexp-quote (expand-file-name dir))))
134                                    LilyPond-include-path "\\|")
135                         "\\).*\\("
136                         (mapconcat 'regexp-quote originals "\\|")
137                         "\\)\\.\\("
138                         (mapconcat 'regexp-quote extensions "\\|")
139                         "\\)\\'"))
140         (buffers (buffer-list)))
141     (while buffers
142       (let* ((buffer (car buffers))
143              (name (buffer-file-name buffer)))
144         (setq buffers (cdr buffers))
145         (if (and name (string-match regexp name))
146             (progn
147               (and (buffer-modified-p buffer)
148                    (or (not LilyPond-save-query)
149                        (y-or-n-p (concat "Save file "
150                                          (buffer-file-name buffer)
151                                          "? ")))
152                    (save-excursion (set-buffer buffer) (save-buffer)))
153               (if (file-newer-than-file-p name derived)
154                   (setq found t))))))
155     found))
156
157 (defun LilyPond-running ()
158   "Check the currently running LilyPond compiling jobs."
159   (interactive)
160   (let ((process-names (list "lilypond" "tex" "2dvi" "2ps" "2midi" 
161                              "book" "latex"))
162         (running nil))
163     (while (setq process-name (pop process-names))
164       (setq process (get-process process-name))
165       (if (and process 
166                (eq (process-status process) 'run))
167           (push process-name running)))
168     running)) ; return the running jobs
169
170 (defun LilyPond-midi-running ()
171   "Check the currently running Midi processes."
172   (interactive)
173   (let ((process-names (list "midi" "midiall"))
174         (running nil))
175     (while (setq process-name (pop process-names))
176       (setq process (get-process process-name))
177       (if (and process 
178                (eq (process-status process) 'run))
179           (push process-name running)))
180     running)) ; return the running jobs
181
182 (defun LilyPond-kill-jobs ()
183   "Kill the currently running LilyPond compiling jobs."
184   (interactive)
185   (let ((process-names (LilyPond-running))
186         (killed nil))
187     (while (setq process-name (pop process-names))
188       (quit-process (get-process process-name) t)
189       (push process-name killed))
190     killed)) ; return the killed jobs
191
192 (defun LilyPond-kill-midi ()
193   "Kill the currently running midi processes."
194   (let ((process-names (LilyPond-midi-running))
195         (killed nil))
196     (while (setq process-name (pop process-names))
197       (quit-process (get-process process-name) t)
198       (push process-name killed))
199     killed)) ; return the killed jobs
200
201 ;; URG, should only run LilyPond-compile for LilyPond
202 ;; not for tex,xdvi (ly2dvi?)
203 (defun LilyPond-compile-file (command name)
204   ;; We maybe should know what we run here (Lily, ly2dvi, tex)
205   ;; and adjust our error-matching regex ?
206   (compile-internal command "No more errors" name ))
207
208 ;; do we still need this, now that we're using compile-internal?
209 (defun LilyPond-save-buffer ()
210   "Save buffer and set default command for compiling."
211   (interactive)
212   (if (buffer-modified-p)
213       (progn (save-buffer)
214              (setq LilyPond-command-default "LilyPond"))))
215
216 ;;; return (dir base ext)
217 (defun split-file-name (name)
218   (let* ((i (string-match "[^/]*$" name))
219          (dir (if (> i 0) (substring name 0 i) "./"))
220          (file (substring name i (length name)))
221          (i (string-match "[^.]*$" file)))
222     (if (and
223          (> i 0)
224          (< i (length file)))
225         (list dir (substring file 0 (- i 1)) (substring file i (length file)))
226       (list dir file ""))))
227
228
229 ;; Should check whether in command-alist?
230 (defcustom LilyPond-command-default "LilyPond"
231   "Default command. Must identify a member of LilyPond-command-alist."
232
233   :group 'LilyPond
234   :type 'string)
235 ;;;(make-variable-buffer-local 'LilyPond-command-last)
236
237 (defvar LilyPond-command-current 'LilyPond-command-master)
238 ;;;(make-variable-buffer-local 'LilyPond-command-master)
239
240
241 ;; If non-nil, LilyPond-command-query will return the value of this
242 ;; variable instead of quering the user. 
243 (defvar LilyPond-command-force nil)
244
245 (defcustom LilyPond-xdvi-command "xdvi"
246   "Command used to display DVI files."
247
248   :group 'LilyPond
249   :type 'string)
250
251 (defcustom LilyPond-gv-command "gv -watch"
252   "Command used to display PS files."
253
254   :group 'LilyPond
255   :type 'string)
256
257 (defcustom LilyPond-midi-command "timidity"
258   "Command used to play MIDI files."
259
260   :group 'LilyPond
261   :type 'string)
262
263 (defcustom LilyPond-all-midi-command "timidity -ia"
264   "Command used to play MIDI files."
265
266   :group 'LilyPond
267   :type 'string)
268
269 (defun LilyPond-command-current-midi ()
270   "Play midi corresponding to the current document."
271   (interactive)
272   (LilyPond-command (LilyPond-command-menu "Midi") 'LilyPond-master-file))
273
274 (defun LilyPond-command-all-midi ()
275   "Play midi corresponding to the current document."
276   (interactive)
277   (LilyPond-command (LilyPond-command-menu "MidiAll") 'LilyPond-master-file))
278
279 (defun count-rexp (start end rexp)
280   "Print number of found regular expressions in the region."
281   (interactive "r")
282   (save-excursion
283     (save-restriction
284       (narrow-to-region start end)
285       (goto-char (point-min))
286       (count-matches rexp))))
287
288 (defun count-midi-words ()
289   "Check number of midi-scores before the curser."
290   (interactive)
291   (count-rexp (point-min) (point-max) "\\\\midi"))
292  
293 (defun count-midi-words-backwards ()
294   "Check number of midi-scores before the curser."
295   (interactive)
296   (count-rexp (point-min) (point) "\\\\midi"))
297  
298 (defun LilyPond-string-current-midi ()
299   "Check the midi file of the following midi-score in the current document."
300   (interactive)
301   (let ((fnameprefix (substring (LilyPond-master-file) 0 -3)) ; suppose ".ly"
302         (allcount (string-to-number (substring (count-midi-words) 0 -12)))
303         (count (string-to-number (substring (count-midi-words-backwards) 0 -12))))
304     (concat  fnameprefix
305              (if (and (> allcount 1) (> count 0)) ; not first score
306                  (if (eq count allcount)          ; last score
307                      (concat "-" (number-to-string (+ count -1)))
308                    (concat "-" (number-to-string count))))
309              ".midi")))
310
311 (defun LilyPond-string-all-midi ()
312   "Return the midi files of the current document in ascending order."
313   (interactive)
314   (let ((fnameprefix (substring (LilyPond-master-file) 0 -3))
315         (allcount (string-to-number (substring (count-midi-words) 0 -12))))
316     (concat (if (> allcount 0)  ; at least one midi-score
317                 (concat fnameprefix ".midi "))
318             (if (> allcount 1)  ; more than one midi-score
319                 (concat fnameprefix "-[1-9].midi "))
320             (if (> allcount 9)  ; etc.
321                 (concat fnameprefix "-[1-9][0-9].midi"))
322             (if (> allcount 99) ; not first score
323                 (concat fnameprefix "-[1-9][0-9][0-9].midi")))))
324
325 ;; This is the major configuration variable.
326 (defcustom LilyPond-command-alist
327   ;; Should expand this to include possible keyboard shortcuts which
328   ;; could then be mapped to define-key and menu.
329   `(
330     ("LilyPond" . ("lilypond %s" . "LaTeX"))
331     ("TeX" . ("tex '\\nonstopmode\\input %t'" . "View"))
332
333     ("2Dvi" . ("ly2dvi %s" . "View"))
334     ("2PS" . ("ly2dvi -P %s" . "ViewPS"))
335     ("2Midi" . ("lilypond -m %s" . "View"))
336
337     ("Book" . ("lilypond-book %x" . "LaTeX"))
338     ("LaTeX" . ("latex '\\nonstopmode\\input %l'" . "View"))
339
340     ;; point-n-click (arg: exits upop USR1)
341     ("SmartView" . ("xdvi %d" . "LilyPond"))
342
343     ;; refreshes when kicked USR1
344     ("View" . (,(concat LilyPond-xdvi-command " %d") . "LilyPond"))
345     ("ViewPS" . (,(concat LilyPond-gv-command " %p") . "LilyPond"))
346
347     ;; The following are refreshed in LilyPond-command:
348     ;; - current-midi depends on cursor position and
349     ("Midi" . (,(concat LilyPond-midi-command " " (LilyPond-string-current-midi)) . "LilyPond" )) ; 
350     ;; - all-midi depends on number of midi-score.
351     ("MidiAll" . (,(concat LilyPond-all-midi-command " " (LilyPond-string-all-midi)) . "LilyPond"))
352     )
353
354   "AList of commands to execute on the current document.
355
356 The key is the name of the command as it will be presented to the
357 user, the value is a cons of the command string handed to the shell
358 after being expanded, and the next command to be executed upon
359 success.  The expansion is done using the information found in
360 LilyPond-expand-list.
361 "
362   :group 'LilyPond
363   :type '(repeat (cons :tag "Command Item"
364                        (string :tag "Key")
365                        (cons :tag "How"
366                         (string :tag "Command")
367                         (string :tag "Next Key")))))
368
369 ;; drop this?
370 (defcustom LilyPond-file-extensions '(".ly" ".sly" ".fly")
371   "*File extensions used by manually generated TeX files."
372   :group 'LilyPond
373   :type '(repeat (string :format "%v")))
374
375
376 (defcustom LilyPond-expand-alist 
377   '(
378     ("%s" . ".ly")
379     ("%t" . ".tex")
380     ("%d" . ".dvi")
381     ("%p" . ".ps")
382     ("%l" . ".tex")
383     ("%x" . ".tely")
384     ("%m" . ".midi")
385     )
386     
387   "Alist of expansion strings for LilyPond command names."
388   :group 'LilyPond
389   :type '(repeat (cons :tag "Alist item"
390                   (string :tag "Symbol")
391                   (string :tag "Expansion")))) 
392
393
394 (defcustom LilyPond-command-Show "View"
395   "*The default command to show (view or print) a LilyPond file.
396 Must be the car of an entry in `LilyPond-command-alist'."
397   :group 'LilyPond
398   :type 'string)
399   (make-variable-buffer-local 'LilyPond-command-Show)
400
401 (defcustom LilyPond-command-Print "Print"
402   "The name of the Print entry in LilyPond-command-Print."
403   :group 'LilyPond
404   :type 'string)
405
406 (defun xLilyPond-compile-sentinel (process msg)
407   (if (and process
408            (= 0 (process-exit-status process)))
409       (setq LilyPond-command-default
410               (cddr (assoc LilyPond-command-default LilyPond-command-alist)))))
411
412 ;; FIXME: shouldn't do this for stray View/xdvi
413 (defun LilyPond-compile-sentinel (buffer msg)
414   (if (string-match "^finished" msg)
415       (setq LilyPond-command-default
416             (cddr (assoc LilyPond-command-default LilyPond-command-alist)))))
417
418 ;;(make-variable-buffer-local 'compilation-finish-function)
419 (setq compilation-finish-function 'LilyPond-compile-sentinel)
420
421 (defun LilyPond-command-query (name)
422   "Query the user for what LilyPond command to use."
423   (let* ((default (cond ((if (string-equal name "emacs-lily")
424                              (LilyPond-check-files (concat name ".tex")
425                                                    (list name)
426                                                    LilyPond-file-extensions)
427                            (if (verify-visited-file-modtime (current-buffer))
428                                (if (buffer-modified-p)
429                                    (if (y-or-n-p "Save buffer before next command? ")
430                                        (LilyPond-save-buffer)))
431                              (if (y-or-n-p "The command will be invoked to an already saved buffer. Revert it? ")
432                                  (revert-buffer t t)))
433                            ;;"LilyPond"
434                            LilyPond-command-default))
435                         (t LilyPond-command-default)))
436
437          (completion-ignore-case t)
438          
439          (answer (or LilyPond-command-force
440                      (completing-read
441                       (concat "Command: (default " default ") ")
442                       LilyPond-command-alist nil t nil 'LilyPond-command-history))))
443
444     ;; If the answer is "LilyPond" it will not be expanded to "LilyPond"
445     (let ((answer (car-safe (assoc answer LilyPond-command-alist))))
446       (if (and answer
447                (not (string-equal answer "")))
448           answer
449         default))))
450
451 (defun LilyPond-command-master ()
452   "Run command on the current document."
453   (interactive)
454   (LilyPond-command (LilyPond-command-query (LilyPond-master-file))
455                     'LilyPond-master-file))
456
457 (defun LilyPond-command-lilypond ()
458   "Run lilypond for the current document."
459   (interactive)
460   (LilyPond-command (LilyPond-command-menu "LilyPond") 'LilyPond-master-file)
461 )
462
463 (defun LilyPond-command-formatdvi ()
464   "Format the dvi output of the current document."
465   (interactive)
466   (LilyPond-command (LilyPond-command-menu "2Dvi") 'LilyPond-master-file)
467 )
468
469 (defun LilyPond-command-formatps ()
470   "Format the ps output of the current document."
471   (interactive)
472   (LilyPond-command (LilyPond-command-menu "2PS") 'LilyPond-master-file)
473 )
474
475 (defun LilyPond-command-formatmidi ()
476   "Format the midi output of the current document."
477   (interactive)
478   (LilyPond-command (LilyPond-command-menu "2Midi") 'LilyPond-master-file)
479 )
480
481 (defun LilyPond-command-smartview ()
482   "View the dvi output of current document."
483   (interactive)
484   (LilyPond-command (LilyPond-command-menu "SmartView") 'LilyPond-master-file)
485 )
486
487 (defun LilyPond-command-view ()
488   "View the dvi output of current document."
489   (interactive)
490   (LilyPond-command (LilyPond-command-menu "View") 'LilyPond-master-file)
491 )
492
493 (defun LilyPond-command-viewps ()
494   "View the ps output of current document."
495   (interactive)
496   (LilyPond-command (LilyPond-command-menu "ViewPS") 'LilyPond-master-file)
497 )
498
499 ;; FIXME, does not find commend ender
500 (defun LilyPond-un-comment-region (start end level)
501   "Remove up to LEVEL comment characters from each line in the region."
502   (interactive "*r\np") 
503   (comment-region start end (- level)))
504
505 ;; FIXME, this is broken
506 (defun LilyPond-region-file (begin end)
507   (let (
508         ;; (dir "/tmp/")
509         ;; urg
510         (dir "./")
511         (base "emacs-lily")
512         ;; Hmm
513         (ext (if (string-match "^[\\]score" (buffer-substring begin end))
514                  ".ly"
515                (if (< 50 (abs (- begin end)))
516                    ".fly"
517                  ".sly"))))
518     (concat dir base ext)))
519
520 (defun LilyPond-command-region (begin end)
521   "Run LilyPond on the current region."
522   (interactive "r")
523   (write-region begin end (LilyPond-region-file begin end) nil 'nomsg)
524   (LilyPond-command (LilyPond-command-query
525                      (LilyPond-region-file begin end))
526                     '(lambda () (LilyPond-region-file begin end))))
527
528 (defun LilyPond-command-buffer ()
529   "Run LilyPond on buffer."
530   (interactive)
531   (LilyPond-command-region (point-min) (point-max)))
532
533 (defun LilyPond-command-expand (string file)
534   (let ((case-fold-search nil))
535     (if (string-match "%" string)
536         (let* ((b (match-beginning 0))
537                (e (+ b 2))
538                (l (split-file-name file))
539                (dir (car l))
540                (base (cadr l)))
541           (LilyPond-command-expand
542            (concat (substring string 0 b)
543                    dir
544                    base
545                    (let ((entry (assoc (substring string b e)
546                                        LilyPond-expand-alist)))
547                      (if entry (cdr entry) ""))
548                    (substring string e))
549            file))
550       string)))
551
552 (defun LilyPond-shell-process (name buffer command)
553   (let ((old (current-buffer)))
554     (switch-to-buffer-other-window buffer)
555     ;; If we empty the buffer don't see messages scroll by.
556     ;; (erase-buffer)
557     
558     (start-process-shell-command name buffer command)
559     (switch-to-buffer-other-window old)))
560   
561
562 (defun LilyPond-command (name file)
563   "Run command NAME on the file you get by calling FILE.
564
565 FILE is a function return a file name.  It has one optional argument,
566 the extension to use on the file.
567
568 Use the information in LilyPond-command-alist to determine how to run the
569 command."
570   
571   (let ((entry (assoc name LilyPond-command-alist)))
572     (if entry
573         (let ((command (LilyPond-command-expand (cadr entry)
574                                                 (apply file nil)))
575               (jobs nil)
576               (job-string "no jobs"))
577           (if (string-equal name "View")
578               (let ((buffer-xdvi (get-buffer-create "*view*")))
579                 (if LilyPond-kick-xdvi
580                   (let ((process-xdvi (get-buffer-process buffer-xdvi)))
581                     (if process-xdvi
582                         (signal-process (process-id process-xdvi) 'SIGUSR1)
583                       (LilyPond-shell-process name buffer-xdvi command)))
584                   (LilyPond-shell-process name buffer-xdvi command)))
585             (progn
586               (if (member name (list "Midi" "MidiAll"))
587                   (if (file-newer-than-file-p
588                        (LilyPond-master-file)
589                        (concat (substring (LilyPond-master-file) 0 -3) ".midi"))
590                       (if (y-or-n-p "Midi older than source. Reformat midi?")
591                           (progn
592                             (LilyPond-command-formatmidi)
593                             (while (LilyPond-running)
594                               (message "Starts playing midi once it is built.")
595                               (sit-for 0 100))))))
596               (if (string-equal name "Midi")
597                   (progn
598                     (setq command (concat LilyPond-midi-command " " (LilyPond-string-current-midi)))
599                     (if (LilyPond-kill-midi)
600                         (setq job-string nil)))) ; either stop or start playing
601               (if (string-equal name "MidiAll")
602                   (progn
603                     (setq command (concat LilyPond-all-midi-command " " (LilyPond-string-all-midi)))
604                     (LilyPond-kill-midi))) ; stop and start playing
605               (if (member name (list "LilyPond" "TeX" "2Midi" "2PS" "2Dvi" 
606                                      "Book" "LaTeX"))
607                   (if (setq jobs (LilyPond-running))
608                       (progn
609                         (setq job-string "Process") ; could also suggest compiling after process has ended
610                         (while jobs
611                           (setq job-string (concat job-string " \"" (pop jobs) "\"")))
612                         (setq job-string (concat job-string " is already running; kill it to proceed "))
613                         (if (y-or-n-p job-string)
614                             (progn
615                               (setq job-string "no jobs")
616                               (LilyPond-kill-jobs)
617                               (while (LilyPond-running)
618                                 (sit-for 0 100)))
619                           (setq job-string nil)))))
620
621               (setq LilyPond-command-default name)
622               (if (string-equal job-string "no jobs")
623                   (LilyPond-compile-file command name))))))))
624           
625 ;; XEmacs stuff
626 ;; Sadly we need this for a macro in Emacs 19.
627 (eval-when-compile
628   ;; Imenu isn't used in XEmacs, so just ignore load errors.
629   (condition-case ()
630       (require 'imenu)
631     (error nil)))
632
633
634 ;;; Keymap
635
636 (defvar LilyPond-mode-map ()
637   "Keymap used in `LilyPond-mode' buffers.")
638
639 ;; Note:  if you make changes to the map, you must do
640 ;;    M-x set-variable LilyPond-mode-map nil
641 ;;    M-x eval-buffer
642 ;;    M-x LilyPond-mode
643 ;; to let the changest take effect
644
645 (if LilyPond-mode-map
646     ()
647   (setq LilyPond-mode-map (make-sparse-keymap))
648   ;; Put keys to Lilypond-command-alist and fetch them from there somehow.
649   (define-key LilyPond-mode-map "\C-c\C-l" 'LilyPond-command-lilypond)
650   (define-key LilyPond-mode-map "\C-c\C-r" 'LilyPond-command-region)
651   (define-key LilyPond-mode-map "\C-c\C-b" 'LilyPond-command-buffer)
652   (define-key LilyPond-mode-map "\C-c\C-k" 'LilyPond-kill-jobs)
653   (define-key LilyPond-mode-map "\C-c\C-c" 'LilyPond-command-master)
654   (define-key LilyPond-mode-map "\C-cm" 'LilyPond-command-formatmidi)
655   (define-key LilyPond-mode-map "\C-c\C-d" 'LilyPond-command-formatdvi)
656   (define-key LilyPond-mode-map "\C-c\C-f" 'LilyPond-command-formatps)
657   (define-key LilyPond-mode-map "\C-c\C-s" 'LilyPond-command-smartview)
658   (define-key LilyPond-mode-map "\C-c\C-v" 'LilyPond-command-view)
659   (define-key LilyPond-mode-map "\C-c\C-p" 'LilyPond-command-viewps)
660   (define-key LilyPond-mode-map [(control c) return] 'LilyPond-command-current-midi)
661   (define-key LilyPond-mode-map [(control c) (control return)] 'LilyPond-command-all-midi)
662   (define-key LilyPond-mode-map "\C-x\C-s" 'LilyPond-save-buffer)
663   (define-key LilyPond-mode-map "\C-cf" 'font-lock-fontify-buffer)
664   (define-key LilyPond-mode-map "\C-ci" 'LilyPond-quick-note-insert)
665   (define-key LilyPond-mode-map "\C-cn" 'LilyPond-insert-tag-notes)
666   (define-key LilyPond-mode-map "\C-cs" 'LilyPond-insert-tag-score)
667   (define-key LilyPond-mode-map "\C-c:" 'LilyPond-un-comment-region)
668   (define-key LilyPond-mode-map "\C-c;" 'comment-region)
669   (define-key LilyPond-mode-map ")" 'LilyPond-electric-close-paren) ; urgh
670   (define-key LilyPond-mode-map ">" 'LilyPond-electric-close-paren) ; argh
671   (define-key LilyPond-mode-map "}" 'LilyPond-electric-close-paren) ; ..rgh
672   (define-key LilyPond-mode-map [S-iso-lefttab] 'LilyPond-autocompletion)
673   (define-key LilyPond-mode-map "\C-c\t" 'LilyPond-info-index-search)
674   )
675
676 ;;; Menu Support
677
678 (defun LilyPond-quick-note-insert()
679   "Insert notes with fewer key strokes by using a simple keyboard piano."
680   (interactive)
681   (setq dutch-notes
682         '(("k" "a") ("l" "b") ("a" "c") ("s" "d") 
683           ("d" "e") ("f" "f") ("j" "g") ("r" "r")))
684   (setq dutch-note-ends '("eses" "es" "" "is" "isis"))
685   (setq dutch-note-replacements '("" ""))
686   (setq finnish-note-replacements
687         '(("eeses" "eses") ("ees" "es") ("aeses" "asas") ("aes" "as") ("b" "h")
688           ("beses" "heses") ("bes" "b") ("bis" "his") ("bisis" "hisis")))
689                               ; add more translations of the note names
690   (setq spanish-note-replacements
691         '(("c" "do") ("d" "re") ("e" "mi") ("f" "fa") ("g" "sol") ("a" "la") ("b" "si")
692       ("cis" "dos") ("cisis" "doss") ("ces" "dob") ("ceses" "dobb")
693       ("dis" "res") ("disis" "ress") ("des" "reb") ("deses" "rebb")
694       ("eis" "mis") ("eisis" "miss") ("ees" "mib") ("eeses" "mibb")
695       ("fis" "fas") ("fisis" "fass") ("fes" "fab") ("feses" "fabb")
696       ("gis" "sols") ("gisis" "solss") ("ges" "solb") ("geses" "solbb")
697       ("ais" "las") ("aisis" "lass") ("aes" "lab") ("aeses" "labb")
698       ("bis" "sis") ("bisis" "siss") ("bes" "sib") ("beses" "sibb")))
699   (setq other-keys "()<>~}")
700   (setq accid 0) (setq octav 0) (setq durat "") (setq dots 0)
701
702   (message "Press h for help.") (sit-for 0 750 1)
703
704   (setq note-replacements dutch-note-replacements)
705   (while (not (= 27 ; esc to quit
706     (setq x (read-char-exclusive 
707              (format " | a[_]s[_]d | f[_]j[_]k[_]l | r with ie ,' 12345678 . 0 (<~>)/}\\b\\n Esc \n | c | d | e | f | g | a | %s | r with %s%s%s%s"
708                      (if (string= (car(cdr(assoc "b" note-replacements))) "h")
709                          "h" "b")
710                      (nth (+ accid 2) dutch-note-ends)
711                      (make-string (abs octav) (if (> octav 0) ?' ?,)) 
712                      durat 
713                      (if (string= durat "") "" (make-string dots ?.)))))))
714     ;; (insert (number-to-string x)) ; test numbers for characters
715     (setq note (cdr (assoc (char-to-string x) dutch-notes)))
716     (cond
717      ((= x 127) (backward-kill-word 1)) ; backspace
718      ((= x 13) (progn (insert "\n") (LilyPond-indent-line)))) ; return
719     (setq x (char-to-string x))
720     (cond
721      ((and (string< x "9") (string< "0" x))
722       (progn (setq durat (int-to-string (expt 2 (- (string-to-int x) 1))))
723              (setq dots 0)))
724      ((string= x " ") (insert " "))
725      ((string= x "/") (progn (insert "\\times ")
726                              (while (not (and (string< x "9") (string< "0" x)))
727                                (setq x (char-to-string (read-char-exclusive "Insert a number for the denominator (\"x/\")"))))
728                              (insert (format "%s/" x)) (setq x "/")
729                              (while (not (and (string< x "9") (string< "0" x)))
730                                (setq x (char-to-string (read-char-exclusive "Insert a number for the numerator (\"/y\")"))))
731                              (insert (format "%s { " x))))
732      ((string= x "0") (progn (setq accid 0) (setq octav 0) 
733                              (setq durat "") (setq dots 0)))
734      ((string= x "i") (setq accid (if (= accid 2) 0 (max (+ accid 1) 1))))
735      ((string= x "e") (setq accid (if (= accid -2) 0 (min (+ accid -1) -1))))
736      ((string= x "'") (setq octav (if (= octav 4) 0 (max (+ octav 1) 1))))
737      ((string= x ",") (setq octav (if (= octav -4) 0 (min (+ octav -1) -1))))
738      ((string= x ".") (setq dots (if (= dots 4) 0 (+ dots 1))))
739      ((not (null (member x (split-string other-keys ""))))
740       (insert (format "%s " x)))
741      ((not (null note))
742       (progn
743         (setq note 
744               (format "%s%s" (car note) (if (string= "r" (car note)) "" 
745                                           (nth (+ accid 2) dutch-note-ends))))
746         (setq notetwo (car (cdr (assoc note note-replacements))))
747         (if (not (null notetwo)) (setq note notetwo))
748         (insert
749          (format "%s%s%s%s " 
750                  note
751                  (if (string= "r" note) ""
752                      (make-string (abs octav) (if (> octav 0) ?' ?,)))
753                  durat
754                  (if (string= durat "") "" (make-string dots ?.))))
755         (setq accid 0) (setq octav 0) (setq durat "") (setq dots 0)))
756      ((string= x "t") (progn (setq note-replacements dutch-note-replacements)
757                              (message "Selected Dutch notes") 
758                              (sit-for 0 750 1))) ; t
759      ((string= x "n") (progn (setq note-replacements finnish-note-replacements)
760                              (message "Selected Finnish/Deutsch notes") 
761                              (sit-for 0 750 1))) ; n
762                               ; add more translations of the note names
763      ((string= x "p") (progn (setq note-replacements spanish-note-replacements)
764                              (message "Selected Spanish notes") 
765                              (sit-for 0 750 1))) ; p
766      ((string= x "h") 
767       (progn (message "Insert notes with fewer key strokes. For example \"i,5.f\" produces \"fis,32. \".") (sit-for 5 0 1) 
768              (message "Add also \"a ~ a\"-ties, \"a ( ) b\"-slurs and \"< a b >\"-chords.") (sit-for 5 0 1) 
769              (message "Note names are in Du(t)ch by default. Hit 'n' for Fin(n)ish/Deutsch note names. Hit 'p' for S(p)anish note names") (sit-for 5 0 1) 
770              (message "Backspace deletes last note, return starts a new indented line and Esc quits.") (sit-for 5 0 1) 
771              (message "Insert note triplets \"\\times 2/3 { a b } \" by typing \"/23ab}\".") (sit-for 5 0 1) 
772              (message "Remember to add all other details as well.") (sit-for 5 0 1)))
773     )))
774
775 (defun LilyPond-pre-word-search ()
776   "Fetch the alphabetic characters and \\ in front of the cursor."
777   (interactive)
778   (let ((pre "")
779         (prelen 0)
780         (ch (char-before (- (point) 0))))
781     (while (and ch (or (and (>= ch 65) (<= ch 90))  ; not bolp, A-Z
782                        (and (>= ch 97) (<= ch 122)) ; a-z
783                        (= ch 92)))                  ; \\
784       (setq pre (concat (char-to-string ch) pre))
785       (setq prelen (+ prelen 1))
786       (setq ch (char-before (- (point) prelen))))
787     pre))
788
789 (defun LilyPond-post-word-search ()
790   "Fetch the alphabetic characters behind the cursor."
791   (interactive)
792   (let ((post "")
793         (postlen 0)
794         (ch (char-after (+ (point) 0))))
795     (while (and ch (or (and (>= ch 65) (<= ch 90))    ; not eolp, A-Z
796                        (and (>= ch 97) (<= ch 122)))) ; a-z
797       (setq post (concat post (char-to-string ch)))
798       (setq postlen (+ postlen 1))
799       (setq ch (char-after (+ (point) postlen))))
800     post))
801
802 (defun LilyPond-autocompletion ()
803   "Show completions in mini-buffer for the given word."
804   (interactive)
805   (let ((pre (LilyPond-pre-word-search))
806         (post (LilyPond-post-word-search))
807         (compsstr ""))
808     ;; insert try-completion and show all-completions
809     (if (> (length pre) 0)
810         (progn
811           (setq trycomp (try-completion pre (LilyPond-add-dictionary-word ())))
812           (if (char-or-string-p trycomp)
813               (if (string-equal (concat pre post) trycomp)
814                   (goto-char (+ (point) (length post)))
815                 (progn
816                   (delete-region (point) (+ (point) (length post)))
817                   (insert (substring trycomp (length pre) nil))))
818             (progn
819               (delete-region (point) (+ (point) (length post)))
820               (font-lock-fontify-buffer))) ; only inserting fontifies
821         
822         (setq complist (all-completions pre (LilyPond-add-dictionary-word ())))
823         (while (> (length complist) 0)
824           (setq compsstr (concat compsstr "\"" (car complist) "\" "))
825           (setq complist (cdr complist)))
826         (message compsstr) 
827         (sit-for 0 100 1)))))
828
829 (defun LilyPond-info ()
830   "Launch Info for lilypond."
831   (interactive)
832   (info "lilypond"))
833   
834 (defun LilyPond-music-glossary-info ()
835   "Launch Info for music-glossary."
836   (interactive)
837   (info "music-glossary"))
838
839 (defun LilyPond-internals-info ()
840   "Launch Info for lilypond-internals."
841   (interactive)
842   (info "lilypond-internals"))
843   
844 (defun LilyPond-info-index-search ()
845   "Inside Emacs, launch `info lilypond --index-search word-under-cursor'"
846   (interactive)
847   (let ((str (concat (LilyPond-pre-word-search) (LilyPond-post-word-search))))
848     (if (and (> (length str) 0) 
849              (string-equal (substring str 0 1) "\\"))
850         (setq str (substring str 1 nil)))
851     (LilyPond-info)
852     (Info-index str)))
853
854 (defun LilyPond-insert-string (pre)
855   "Insert text to the buffer."
856   (interactive)
857   (insert pre)
858   (length pre))
859
860 (defun LilyPond-insert-between (text pre post)
861   "Insert text to the buffer if non-empty string is given."
862   (interactive)
863   (let ((str (read-string text)))
864     (if (string-equal str "")
865         0
866       (progn (setq pre_str_post (concat pre str post))
867              (insert pre_str_post)
868              (length pre_str_post)))))
869
870 (defun LilyPond-insert-tag-notes ()
871   "LilyPond notes tag."
872   (interactive)
873   (setq begin (if (and transient-mark-mode mark-active) 
874                   (mark-marker) (point-marker)))
875   (setq end (point-marker))
876   (goto-char begin)
877   (setq l1 (LilyPond-insert-string "\\notes "))
878   (setq l2 (LilyPond-insert-between "Relative (e.g. c'): " "\\relative " " "))
879   (if (eq l2 0)
880       (setq l2 (LilyPond-insert-between "Transpose (e.g. c c'): " "\\transpose " " ")))
881   (setq l3 (LilyPond-insert-string "{ "))
882   (goto-char (+ end l1 l2 l3))
883   (LilyPond-insert-string " }")
884   (goto-char (+ end l1 l2 l3)))
885
886 (defun LilyPond-insert-tag-score ()
887   "LilyPond score tag."
888   (interactive)
889   (setq begin (if (and transient-mark-mode mark-active) 
890                   (mark-marker) (point-marker)))
891   (setq end (point-marker))
892   (goto-char begin)
893   (setq l1 (LilyPond-insert-string "\\score {\n    ")) ; keep track of lengths
894   (goto-char (+ end l1))
895   (LilyPond-insert-string "\n    \\paper { }\n")
896   (setq l2 (if (y-or-n-p "Insert \"\\header\" field? ")
897                (+ (LilyPond-insert-string "    \\header {")
898                   (LilyPond-insert-between "Title: " "\n      title = \"" "\"")
899                   (LilyPond-insert-between "Subtitle: " "\n      subtitle = \"" "\"")
900                   (LilyPond-insert-between "Piece: " "\n      piece = \"" "\"")
901                   (LilyPond-insert-between "Opus: "  "\n      opus = \"" "\"")
902                   (LilyPond-insert-string "\n    }\n"))
903              0))
904   (setq l3 (if (y-or-n-p "Insert \"\\midi\" field? ")
905                (+ (LilyPond-insert-string "    \\midi {")
906                   (LilyPond-insert-between "Tempo: " " \\tempo (e.g. 4 = 60)" "")
907                   (LilyPond-insert-string " }\n"))
908              0))
909   (setq l4 (LilyPond-insert-string "}\n"))
910   (goto-char (+ end l1)))
911
912 (defun LilyPond-command-menu-entry (entry)
913   ;; Return LilyPond-command-alist ENTRY as a menu item.
914   (let ((name (car entry)))
915     (cond ((and (string-equal name LilyPond-command-Print)
916                 LilyPond-printer-list)
917            (let ((command LilyPond-print-command)
918                  (lookup 1))
919              (append (list LilyPond-command-Print)
920                      (mapcar 'LilyPond-command-menu-printer-entry
921                              LilyPond-printer-list))))
922           (t
923            (vector name (list 'LilyPond-command-menu name) t)))))
924
925
926 (easy-menu-define LilyPond-command-menu
927   LilyPond-mode-map
928   "Menu used in LilyPond mode."
929   (append '("Command")
930           '(("Command on"
931              [ "Master File" LilyPond-command-select-master
932                :keys "C-c C-c" :style radio
933                :selected (eq LilyPond-command-current 'LilyPond-command-master) ]
934              [ "Buffer" LilyPond-command-select-buffer
935                :keys "C-c C-b" :style radio
936                :selected (eq LilyPond-command-current 'LilyPond-command-buffer) ]
937              [ "Region" LilyPond-command-select-region
938                :keys "C-c C-r" :style radio
939                :selected (eq LilyPond-command-current 'LilyPond-command-region) ]))
940 ;;;       (let ((file 'LilyPond-command-on-current))
941 ;;;         (mapcar 'LilyPond-command-menu-entry LilyPond-command-alist))
942 ;;; Some kind of mapping which includes :keys might be more elegant
943 ;;; Put keys to Lilypond-command-alist and fetch them from there somehow.
944           '([ "LilyPond" LilyPond-command-lilypond t])
945           '([ "TeX" (LilyPond-command (LilyPond-command-menu "TeX") 'LilyPond-master-file) ])
946           '([ "2Dvi" LilyPond-command-formatdvi t])
947           '([ "2PS" LilyPond-command-formatps t])
948           '([ "2Midi" LilyPond-command-formatmidi t])
949           '([ "Book" (LilyPond-command (LilyPond-command-menu "Book") 'LilyPond-master-file) ])
950           '([ "LaTeX" (LilyPond-command (LilyPond-command-menu "LaTeX") 'LilyPond-master-file) ])
951           '([ "Kill jobs" LilyPond-kill-jobs t])
952           '("-----")
953           '([ "SmartView" LilyPond-command-smartview t])
954           '([ "View" LilyPond-command-view t])
955           '([ "ViewPS" LilyPond-command-viewps t])
956           '("-----")
957           '([ "Midi (toggle)" LilyPond-command-current-midi t])
958           '([ "Midi all" LilyPond-command-all-midi t])
959           ))
960
961 (easy-menu-define LilyPond-mode-menu
962   LilyPond-mode-map
963   "Menu used in LilyPond mode."
964   (append '("LilyPond")
965           '(("Insert"
966              [ "\\notes..."  LilyPond-insert-tag-notes t]
967              [ "\\score..."  LilyPond-insert-tag-score t]
968              ["Quick Notes"  LilyPond-quick-note-insert t]
969              ["Autocompletion"   LilyPond-autocompletion t]
970              ))
971           '(("Miscellaneous"
972              ["Uncomment Region" LilyPond-un-comment-region t]
973              ["Comment Region" comment-region t]
974              ["Refontify buffer" font-lock-fontify-buffer t]
975              ))
976           '(("Info"
977              ["LilyPond" LilyPond-info t]
978              ["LilyPond index-search" LilyPond-info-index-search t]
979              ["Music Glossary" LilyPond-music-glossary-info t]
980              ["LilyPond internals" LilyPond-internals-info t]
981              ))
982           ))
983
984 (defconst LilyPond-imenu-generic-re "^\\([a-zA-Z]+\\) *="
985   "Regexp matching Identifier definitions.")
986
987 (defvar LilyPond-imenu-generic-expression
988   (list (list nil LilyPond-imenu-generic-re 1))
989   "Expression for imenu")
990
991 (defun LilyPond-command-select-master ()
992   (interactive)
993   (message "Next command will be on the master file")
994   (setq LilyPond-command-current 'LilyPond-command-master))
995
996 (defun LilyPond-command-select-buffer ()
997   (interactive)
998   (message "Next command will be on the buffer")
999   (setq LilyPond-command-current 'LilyPond-command-buffer))
1000
1001 (defun LilyPond-command-select-region ()
1002   (interactive)
1003   (message "Next command will be on the region")
1004   (setq LilyPond-command-current 'LilyPond-command-region))
1005
1006 (defun LilyPond-command-menu (name)
1007   ;; Execute LilyPond-command-alist NAME from a menu.
1008   (let ((LilyPond-command-force name))
1009     (funcall LilyPond-command-current)))
1010
1011 (defun LilyPond-mode ()
1012   "Major mode for editing LilyPond music files.
1013
1014 This mode knows about LilyPond keywords and line comments, not about
1015 indentation or block comments.  It features easy compilation, error
1016 finding and viewing of a LilyPond source buffer or region.
1017
1018 COMMANDS
1019 \\{LilyPond-mode-map}
1020 VARIABLES
1021
1022 LilyPond-command-alist\t\talist from name to command
1023 LilyPond-xdvi-command\t\tcommand to display dvi files -- bit superfluous"
1024   (interactive)
1025   ;; set up local variables
1026   (kill-all-local-variables)
1027
1028   (make-local-variable 'font-lock-defaults)
1029   (setq font-lock-defaults '(LilyPond-font-lock-keywords))
1030
1031   ;; string and comments are fontified explicitly
1032   (make-local-variable 'font-lock-keywords-only)
1033   (setq font-lock-keywords-only t)
1034
1035   ;; Multi-line font-locking needs Emacs 21.1 or newer.
1036   ;; For older versions there is hotkey "C-c f".
1037   (make-local-variable 'font-lock-multiline) 
1038   (setq font-lock-multiline t) 
1039
1040   (make-local-variable 'paragraph-separate)
1041   (setq paragraph-separate "^[ \t]*$")
1042
1043   (make-local-variable 'paragraph-start)
1044   (setq paragraph-start "^[ \t]*$")
1045
1046   (make-local-variable 'comment-start)
1047   (setq comment-start "%")
1048
1049   (make-local-variable 'comment-start-skip)
1050   (setq comment-start-skip "%{? *")
1051
1052   (make-local-variable 'comment-end)
1053   (setq comment-end "")
1054
1055   (make-local-variable 'block-comment-start)
1056   (setq block-comment-start "%{")
1057
1058   (make-local-variable 'block-comment-end)  
1059   (setq block-comment-end   "%}")
1060
1061   (make-local-variable 'indent-line-function)
1062   (setq indent-line-function 'LilyPond-indent-line)
1063
1064   (set-syntax-table LilyPond-mode-syntax-table)
1065   (setq major-mode 'LilyPond-mode)
1066   (setq mode-name "LilyPond")
1067   (setq local-abbrev-table LilyPond-mode-abbrev-table)
1068   (use-local-map LilyPond-mode-map)
1069
1070   (make-local-variable 'imenu-generic-expression)
1071   (setq imenu-generic-expression LilyPond-imenu-generic-expression)
1072   (imenu-add-to-menubar "Index")
1073
1074   ;; run the mode hook. LilyPond-mode-hook use is deprecated
1075   (run-hooks 'LilyPond-mode-hook))
1076
1077 (defun LilyPond-version ()
1078   "Echo the current version of `LilyPond-mode' in the minibuffer."
1079   (interactive)
1080   (message "Using `LilyPond-mode' version %s" LilyPond-version))
1081
1082 (load-library "lilypond-font-lock")
1083 (load-library "lilypond-indent")
1084
1085 (provide 'lilypond-mode)
1086 ;;; lilypond-mode.el ends here
1087