]> git.donarmstrong.com Git - lilypond.git/blob - lilypond-mode.el
drum fixes
[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-smartview ()
476   "View the dvi output of current document."
477   (interactive)
478   (LilyPond-command (LilyPond-command-menu "SmartView") 'LilyPond-master-file)
479 )
480
481 (defun LilyPond-command-view ()
482   "View the dvi output of current document."
483   (interactive)
484   (LilyPond-command (LilyPond-command-menu "View") 'LilyPond-master-file)
485 )
486
487 (defun LilyPond-command-viewps ()
488   "View the ps output of current document."
489   (interactive)
490   (LilyPond-command (LilyPond-command-menu "ViewPS") 'LilyPond-master-file)
491 )
492
493 ;; FIXME, does not find commend ender
494 (defun LilyPond-un-comment-region (start end level)
495   "Remove up to LEVEL comment characters from each line in the region."
496   (interactive "*r\np") 
497   (comment-region start end (- level)))
498
499 ;; FIXME, this is broken
500 (defun LilyPond-region-file (begin end)
501   (let (
502         ;; (dir "/tmp/")
503         ;; urg
504         (dir "./")
505         (base "emacs-lily")
506         ;; Hmm
507         (ext (if (string-match "^[\\]score" (buffer-substring begin end))
508                  ".ly"
509                (if (< 50 (abs (- begin end)))
510                    ".fly"
511                  ".sly"))))
512     (concat dir base ext)))
513
514 (defun LilyPond-command-region (begin end)
515   "Run LilyPond on the current region."
516   (interactive "r")
517   (write-region begin end (LilyPond-region-file begin end) nil 'nomsg)
518   (LilyPond-command (LilyPond-command-query
519                      (LilyPond-region-file begin end))
520                     '(lambda () (LilyPond-region-file begin end))))
521
522 (defun LilyPond-command-buffer ()
523   "Run LilyPond on buffer."
524   (interactive)
525   (LilyPond-command-region (point-min) (point-max)))
526
527 (defun LilyPond-command-expand (string file)
528   (let ((case-fold-search nil))
529     (if (string-match "%" string)
530         (let* ((b (match-beginning 0))
531                (e (+ b 2))
532                (l (split-file-name file))
533                (dir (car l))
534                (base (cadr l)))
535           (LilyPond-command-expand
536            (concat (substring string 0 b)
537                    dir
538                    base
539                    (let ((entry (assoc (substring string b e)
540                                        LilyPond-expand-alist)))
541                      (if entry (cdr entry) ""))
542                    (substring string e))
543            file))
544       string)))
545
546 (defun LilyPond-shell-process (name buffer command)
547   (let ((old (current-buffer)))
548     (switch-to-buffer-other-window buffer)
549     ;; If we empty the buffer don't see messages scroll by.
550     ;; (erase-buffer)
551     
552     (start-process-shell-command name buffer command)
553     (switch-to-buffer-other-window old)))
554   
555
556 (defun LilyPond-command (name file)
557   "Run command NAME on the file you get by calling FILE.
558
559 FILE is a function return a file name.  It has one optional argument,
560 the extension to use on the file.
561
562 Use the information in LilyPond-command-alist to determine how to run the
563 command."
564   
565   (let ((entry (assoc name LilyPond-command-alist)))
566     (if entry
567         (let ((command (LilyPond-command-expand (cadr entry)
568                                                 (apply file nil)))
569               (jobs nil)
570               (job-string "no jobs"))
571           (if (string-equal name "View")
572               (let ((buffer-xdvi (get-buffer-create "*view*")))
573                 (if LilyPond-kick-xdvi
574                   (let ((process-xdvi (get-buffer-process buffer-xdvi)))
575                     (if process-xdvi
576                         (signal-process (process-id process-xdvi) 'SIGUSR1)
577                       (LilyPond-shell-process name buffer-xdvi command)))
578                   (LilyPond-shell-process name buffer-xdvi command)))
579             (progn
580               (if (string-equal name "Midi")
581                   (progn
582                     (setq command (concat LilyPond-midi-command " " (LilyPond-string-current-midi)))
583                     (if (LilyPond-kill-midi)
584                         (setq job-string nil)))) ; either stop or start playing
585               (if (string-equal name "MidiAll")
586                   (progn
587                     (setq command (concat LilyPond-all-midi-command " " (LilyPond-string-all-midi)))
588                     (LilyPond-kill-midi))) ; stop and start playing
589               (if (member name (list "LilyPond" "TeX" "2Midi" "2PS" "2Dvi" 
590                                      "Book" "LaTeX"))
591                   (if (setq jobs (LilyPond-running))
592                       (progn
593                         (setq job-string "Process") ; could also suggest compiling after process has ended
594                         (while jobs
595                           (setq job-string (concat job-string " \"" (pop jobs) "\"")))
596                         (setq job-string (concat job-string " is already running; kill it to proceed "))
597                         (if (y-or-n-p job-string)
598                             (progn
599                               (setq job-string "no jobs")
600                               (LilyPond-kill-jobs)
601                               (sit-for 0 500 nil)) ; should wait killing
602                           (setq job-string nil)))))
603
604               (setq LilyPond-command-default name)
605               (if (string-equal job-string "no jobs")
606                   (LilyPond-compile-file command name))))))))
607           
608 ;; XEmacs stuff
609 ;; Sadly we need this for a macro in Emacs 19.
610 (eval-when-compile
611   ;; Imenu isn't used in XEmacs, so just ignore load errors.
612   (condition-case ()
613       (require 'imenu)
614     (error nil)))
615
616
617 ;;; Keymap
618
619 (defvar LilyPond-mode-map ()
620   "Keymap used in `LilyPond-mode' buffers.")
621
622 ;; Note:  if you make changes to the map, you must do
623 ;;    M-x set-variable LilyPond-mode-map nil
624 ;;    M-x eval-buffer
625 ;;    M-x LilyPond-mode
626 ;; to let the changest take effect
627
628 (if LilyPond-mode-map
629     ()
630   (setq LilyPond-mode-map (make-sparse-keymap))
631   ;; Put keys to Lilypond-command-alist and fetch them from there somehow.
632   (define-key LilyPond-mode-map "\C-c\C-l" 'LilyPond-command-lilypond)
633   (define-key LilyPond-mode-map "\C-c\C-r" 'LilyPond-command-region)
634   (define-key LilyPond-mode-map "\C-c\C-b" 'LilyPond-command-buffer)
635   (define-key LilyPond-mode-map "\C-c\C-k" 'LilyPond-kill-jobs)
636   (define-key LilyPond-mode-map "\C-c\C-c" 'LilyPond-command-master)
637   (define-key LilyPond-mode-map "\C-c\C-d" 'LilyPond-command-formatdvi)
638   (define-key LilyPond-mode-map "\C-c\C-f" 'LilyPond-command-formatps)
639   (define-key LilyPond-mode-map "\C-c\C-s" 'LilyPond-command-smartview)
640   (define-key LilyPond-mode-map "\C-c\C-v" 'LilyPond-command-view)
641   (define-key LilyPond-mode-map "\C-c\C-p" 'LilyPond-command-viewps)
642   (define-key LilyPond-mode-map [(control c) return] 'LilyPond-command-current-midi)
643   (define-key LilyPond-mode-map [(control c) (control return)] 'LilyPond-command-all-midi)
644   (define-key LilyPond-mode-map "\C-x\C-s" 'LilyPond-save-buffer)
645   (define-key LilyPond-mode-map "\C-cf" 'font-lock-fontify-buffer)
646   (define-key LilyPond-mode-map "\C-ci" 'LilyPond-quick-note-insert)
647   (define-key LilyPond-mode-map "\C-cn" 'LilyPond-insert-tag-notes)
648   (define-key LilyPond-mode-map "\C-cs" 'LilyPond-insert-tag-score)
649   (define-key LilyPond-mode-map "\C-c:" 'LilyPond-un-comment-region)
650   (define-key LilyPond-mode-map "\C-c;" 'comment-region)
651   (define-key LilyPond-mode-map ")" 'LilyPond-electric-close-paren) ; urgh
652   (define-key LilyPond-mode-map ">" 'LilyPond-electric-close-paren) ; argh
653   (define-key LilyPond-mode-map "}" 'LilyPond-electric-close-paren) ; ..rgh
654   (define-key LilyPond-mode-map [S-iso-lefttab] 'LilyPond-autocompletion)
655   (define-key LilyPond-mode-map "\C-c\t" 'LilyPond-info-index-search)
656   )
657
658 ;;; Menu Support
659
660 (defun LilyPond-quick-note-insert()
661   "Insert notes with fewer key strokes by using a simple keyboard piano."
662   (interactive)
663   (setq dutch-notes
664         '(("k" "a") ("l" "b") ("a" "c") ("s" "d") 
665           ("d" "e") ("f" "f") ("j" "g") ("r" "r")))
666   (setq dutch-note-ends '("eses" "es" "" "is" "isis"))
667   (setq dutch-note-replacements '("" ""))
668   (setq finnish-note-replacements
669         '(("eeses" "eses") ("ees" "es") ("aeses" "asas") ("aes" "as") ("b" "h")
670           ("beses" "heses") ("bes" "b") ("bis" "his") ("bisis" "hisis")))
671                               ; add more translations of the note names
672   (setq spanish-note-replacements
673         '(("c" "do") ("d" "re") ("e" "mi") ("f" "fa") ("g" "sol") ("a" "la") ("b" "si")
674       ("cis" "dos") ("cisis" "doss") ("ces" "dob") ("ceses" "dobb")
675       ("dis" "res") ("disis" "ress") ("des" "reb") ("deses" "rebb")
676       ("eis" "mis") ("eisis" "miss") ("ees" "mib") ("eeses" "mibb")
677       ("fis" "fas") ("fisis" "fass") ("fes" "fab") ("feses" "fabb")
678       ("gis" "sols") ("gisis" "solss") ("ges" "solb") ("geses" "solbb")
679       ("ais" "las") ("aisis" "lass") ("aes" "lab") ("aeses" "labb")
680       ("bis" "sis") ("bisis" "siss") ("bes" "sib") ("beses" "sibb")))
681   (setq other-keys "()<>~}")
682   (setq accid 0) (setq octav 0) (setq durat "") (setq dots 0)
683
684   (message "Press h for help.") (sit-for 0 750 1)
685
686   (setq note-replacements dutch-note-replacements)
687   (while (not (= 27 ; esc to quit
688     (setq x (read-char-exclusive 
689              (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"
690                      (if (string= (car(cdr(assoc "b" note-replacements))) "h")
691                          "h" "b")
692                      (nth (+ accid 2) dutch-note-ends)
693                      (make-string (abs octav) (if (> octav 0) ?' ?,)) 
694                      durat 
695                      (if (string= durat "") "" (make-string dots ?.)))))))
696     ;; (insert (number-to-string x)) ; test numbers for characters
697     (setq note (cdr (assoc (char-to-string x) dutch-notes)))
698     (cond
699      ((= x 127) (backward-kill-word 1)) ; backspace
700      ((= x 13) (progn (insert "\n") (LilyPond-indent-line)))) ; return
701     (setq x (char-to-string x))
702     (cond
703      ((and (string< x "9") (string< "0" x))
704       (progn (setq durat (int-to-string (expt 2 (- (string-to-int x) 1))))
705              (setq dots 0)))
706      ((string= x " ") (insert " "))
707      ((string= x "/") (progn (insert "\\times ")
708                              (while (not (and (string< x "9") (string< "0" x)))
709                                (setq x (char-to-string (read-char-exclusive "Insert a number for the denominator (\"x/\")"))))
710                              (insert (format "%s/" x)) (setq x "/")
711                              (while (not (and (string< x "9") (string< "0" x)))
712                                (setq x (char-to-string (read-char-exclusive "Insert a number for the numerator (\"/y\")"))))
713                              (insert (format "%s { " x))))
714      ((string= x "0") (progn (setq accid 0) (setq octav 0) 
715                              (setq durat "") (setq dots 0)))
716      ((string= x "i") (setq accid (if (= accid 2) 0 (max (+ accid 1) 1))))
717      ((string= x "e") (setq accid (if (= accid -2) 0 (min (+ accid -1) -1))))
718      ((string= x "'") (setq octav (if (= octav 4) 0 (max (+ octav 1) 1))))
719      ((string= x ",") (setq octav (if (= octav -4) 0 (min (+ octav -1) -1))))
720      ((string= x ".") (setq dots (if (= dots 4) 0 (+ dots 1))))
721      ((not (null (member x (split-string other-keys ""))))
722       (insert (format "%s " x)))
723      ((not (null note))
724       (progn
725         (setq note 
726               (format "%s%s" (car note) (if (string= "r" (car note)) "" 
727                                           (nth (+ accid 2) dutch-note-ends))))
728         (setq notetwo (car (cdr (assoc note note-replacements))))
729         (if (not (null notetwo)) (setq note notetwo))
730         (insert
731          (format "%s%s%s%s " 
732                  note
733                  (if (string= "r" note) ""
734                      (make-string (abs octav) (if (> octav 0) ?' ?,)))
735                  durat
736                  (if (string= durat "") "" (make-string dots ?.))))
737         (setq accid 0) (setq octav 0) (setq durat "") (setq dots 0)))
738      ((string= x "t") (progn (setq note-replacements dutch-note-replacements)
739                              (message "Selected Dutch notes") 
740                              (sit-for 0 750 1))) ; t
741      ((string= x "n") (progn (setq note-replacements finnish-note-replacements)
742                              (message "Selected Finnish/Deutsch notes") 
743                              (sit-for 0 750 1))) ; n
744                               ; add more translations of the note names
745      ((string= x "p") (progn (setq note-replacements spanish-note-replacements)
746                              (message "Selected Spanish notes") 
747                              (sit-for 0 750 1))) ; p
748      ((string= x "h") 
749       (progn (message "Insert notes with fewer key strokes. For example \"i,5.f\" produces \"fis,32. \".") (sit-for 5 0 1) 
750              (message "Add also \"a ~ a\"-ties, \"a ( ) b\"-slurs and \"< a b >\"-chords.") (sit-for 5 0 1) 
751              (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) 
752              (message "Backspace deletes last note, return starts a new indented line and Esc quits.") (sit-for 5 0 1) 
753              (message "Insert note triplets \"\\times 2/3 { a b } \" by typing \"/23ab}\".") (sit-for 5 0 1) 
754              (message "Remember to add all other details as well.") (sit-for 5 0 1)))
755     )))
756
757 (defun LilyPond-pre-word-search ()
758   "Fetch the alphabetic characters and \\ in front of the cursor."
759   (interactive)
760   (let ((pre "")
761         (prelen 0)
762         (ch (char-before (- (point) 0))))
763     (while (and ch (or (and (>= ch 65) (<= ch 90))  ; not bolp, A-Z
764                        (and (>= ch 97) (<= ch 122)) ; a-z
765                        (= ch 92)))                  ; \\
766       (setq pre (concat (char-to-string ch) pre))
767       (setq prelen (+ prelen 1))
768       (setq ch (char-before (- (point) prelen))))
769     pre))
770
771 (defun LilyPond-post-word-search ()
772   "Fetch the alphabetic characters behind the cursor."
773   (interactive)
774   (let ((post "")
775         (postlen 0)
776         (ch (char-after (+ (point) 0))))
777     (while (and ch (or (and (>= ch 65) (<= ch 90))    ; not eolp, A-Z
778                        (and (>= ch 97) (<= ch 122)))) ; a-z
779       (setq post (concat post (char-to-string ch)))
780       (setq postlen (+ postlen 1))
781       (setq ch (char-after (+ (point) postlen))))
782     post))
783
784 (defun LilyPond-autocompletion ()
785   "Show completions in mini-buffer for the given word."
786   (interactive)
787   (let ((pre (LilyPond-pre-word-search))
788         (post (LilyPond-post-word-search))
789         (compsstr ""))
790     ;; insert try-completion and show all-completions
791     (if (> (length pre) 0)
792         (progn
793           (setq trycomp (try-completion pre (LilyPond-add-dictionary-word ())))
794           (if (char-or-string-p trycomp)
795               (if (string-equal (concat pre post) trycomp)
796                   (goto-char (+ (point) (length post)))
797                 (progn
798                   (delete-region (point) (+ (point) (length post)))
799                   (insert (substring trycomp (length pre) nil))))
800             (progn
801               (delete-region (point) (+ (point) (length post)))
802               (font-lock-fontify-buffer))) ; only inserting fontifies
803         
804         (setq complist (all-completions pre (LilyPond-add-dictionary-word ())))
805         (while (> (length complist) 0)
806           (setq compsstr (concat compsstr "\"" (car complist) "\" "))
807           (setq complist (cdr complist)))
808         (message compsstr) 
809         (sit-for 0 100 1)))))
810
811 (defun LilyPond-info ()
812   "Launch Info for lilypond."
813   (interactive)
814   (info "lilypond"))
815   
816 (defun LilyPond-music-glossary-info ()
817   "Launch Info for music-glossary."
818   (interactive)
819   (info "music-glossary"))
820
821 (defun LilyPond-internals-info ()
822   "Launch Info for lilypond-internals."
823   (interactive)
824   (info "lilypond-internals"))
825   
826 (defun LilyPond-info-index-search ()
827   "Inside Emacs, launch `info lilypond --index-search word-under-cursor'"
828   (interactive)
829   (let ((str (concat (LilyPond-pre-word-search) (LilyPond-post-word-search))))
830     (if (and (> (length str) 0) 
831              (string-equal (substring str 0 1) "\\"))
832         (setq str (substring str 1 nil)))
833     (LilyPond-info)
834     (Info-index str)))
835
836 (defun LilyPond-insert-string (pre)
837   "Insert text to the buffer."
838   (interactive)
839   (insert pre)
840   (length pre))
841
842 (defun LilyPond-insert-between (text pre post)
843   "Insert text to the buffer if non-empty string is given."
844   (interactive)
845   (let ((str (read-string text)))
846     (if (string-equal str "")
847         0
848       (progn (setq pre_str_post (concat pre str post))
849              (insert pre_str_post)
850              (length pre_str_post)))))
851
852 (defun LilyPond-insert-tag-notes ()
853   "LilyPond notes tag."
854   (interactive)
855   (setq begin (if (and transient-mark-mode mark-active) 
856                   (mark-marker) (point-marker)))
857   (setq end (point-marker))
858   (goto-char begin)
859   (setq l1 (LilyPond-insert-string "\\notes "))
860   (setq l2 (LilyPond-insert-between "Relative (e.g. c'): " "\\relative " " "))
861   (if (eq l2 0)
862       (setq l2 (LilyPond-insert-between "Transpose (e.g. c c'): " "\\transpose " " ")))
863   (setq l3 (LilyPond-insert-string "{ "))
864   (goto-char (+ end l1 l2 l3))
865   (LilyPond-insert-string " }")
866   (goto-char (+ end l1 l2 l3)))
867
868 (defun LilyPond-insert-tag-score ()
869   "LilyPond score tag."
870   (interactive)
871   (setq begin (if (and transient-mark-mode mark-active) 
872                   (mark-marker) (point-marker)))
873   (setq end (point-marker))
874   (goto-char begin)
875   (setq l1 (LilyPond-insert-string "\\score {\n    ")) ; keep track of lengths
876   (goto-char (+ end l1))
877   (LilyPond-insert-string "\n    \\paper { }\n")
878   (setq l2 (if (y-or-n-p "Insert \"\\header\" field? ")
879                (+ (LilyPond-insert-string "    \\header {")
880                   (LilyPond-insert-between "Title: " "\n      title = \"" "\"")
881                   (LilyPond-insert-between "Subtitle: " "\n      subtitle = \"" "\"")
882                   (LilyPond-insert-between "Piece: " "\n      piece = \"" "\"")
883                   (LilyPond-insert-between "Opus: "  "\n      opus = \"" "\"")
884                   (LilyPond-insert-string "\n    }\n"))
885              0))
886   (setq l3 (if (y-or-n-p "Insert \"\\midi\" field? ")
887                (+ (LilyPond-insert-string "    \\midi {")
888                   (LilyPond-insert-between "Tempo: " " \\tempo (e.g. 4 = 60)" "")
889                   (LilyPond-insert-string " }\n"))
890              0))
891   (setq l4 (LilyPond-insert-string "}\n"))
892   (goto-char (+ end l1)))
893
894 (defun LilyPond-command-menu-entry (entry)
895   ;; Return LilyPond-command-alist ENTRY as a menu item.
896   (let ((name (car entry)))
897     (cond ((and (string-equal name LilyPond-command-Print)
898                 LilyPond-printer-list)
899            (let ((command LilyPond-print-command)
900                  (lookup 1))
901              (append (list LilyPond-command-Print)
902                      (mapcar 'LilyPond-command-menu-printer-entry
903                              LilyPond-printer-list))))
904           (t
905            (vector name (list 'LilyPond-command-menu name) t)))))
906
907
908 (easy-menu-define LilyPond-command-menu
909   LilyPond-mode-map
910   "Menu used in LilyPond mode."
911   (append '("Command")
912           '(("Command on"
913              [ "Master File" LilyPond-command-select-master
914                :keys "C-c C-c" :style radio
915                :selected (eq LilyPond-command-current 'LilyPond-command-master) ]
916              [ "Buffer" LilyPond-command-select-buffer
917                :keys "C-c C-b" :style radio
918                :selected (eq LilyPond-command-current 'LilyPond-command-buffer) ]
919              [ "Region" LilyPond-command-select-region
920                :keys "C-c C-r" :style radio
921                :selected (eq LilyPond-command-current 'LilyPond-command-region) ]))
922 ;;;       (let ((file 'LilyPond-command-on-current))
923 ;;;         (mapcar 'LilyPond-command-menu-entry LilyPond-command-alist))
924 ;;; Some kind of mapping which includes :keys might be more elegant
925 ;;; Put keys to Lilypond-command-alist and fetch them from there somehow.
926           '([ "LilyPond" LilyPond-command-lilypond t])
927           '([ "TeX" (LilyPond-command (LilyPond-command-menu "TeX") 'LilyPond-master-file) ])
928           '([ "2Dvi" LilyPond-command-formatdvi t])
929           '([ "2PS" LilyPond-command-formatps t])
930           '([ "2Midi" (LilyPond-command (LilyPond-command-menu "2Midi") 'LilyPond-master-file)])
931           '([ "Book" (LilyPond-command (LilyPond-command-menu "Book") 'LilyPond-master-file) ])
932           '([ "LaTeX" (LilyPond-command (LilyPond-command-menu "LaTeX") 'LilyPond-master-file) ])
933           '([ "Kill jobs" LilyPond-kill-jobs t])
934           '("-----")
935           '([ "SmartView" LilyPond-command-smartview t])
936           '([ "View" LilyPond-command-view t])
937           '([ "ViewPS" LilyPond-command-viewps t])
938           '("-----")
939           '([ "Midi (toggle)" LilyPond-command-current-midi t])
940           '([ "Midi all" LilyPond-command-all-midi t])
941           ))
942
943 (easy-menu-define LilyPond-mode-menu
944   LilyPond-mode-map
945   "Menu used in LilyPond mode."
946   (append '("LilyPond")
947           '(("Insert"
948              [ "\\notes..."  LilyPond-insert-tag-notes t]
949              [ "\\score..."  LilyPond-insert-tag-score t]
950              ["Quick Notes"  LilyPond-quick-note-insert t]
951              ["Autocompletion"   LilyPond-autocompletion t]
952              ))
953           '(("Miscellaneous"
954              ["Uncomment Region" LilyPond-un-comment-region t]
955              ["Comment Region" comment-region t]
956              ["Refontify buffer" font-lock-fontify-buffer t]
957              ))
958           '(("Info"
959              ["LilyPond" LilyPond-info t]
960              ["LilyPond index-search" LilyPond-info-index-search t]
961              ["Music Glossary" LilyPond-music-glossary-info t]
962              ["LilyPond internals" LilyPond-internals-info t]
963              ))
964           ))
965
966 (defconst LilyPond-imenu-generic-re "^\\([a-zA-Z]+\\) *="
967   "Regexp matching Identifier definitions.")
968
969 (defvar LilyPond-imenu-generic-expression
970   (list (list nil LilyPond-imenu-generic-re 1))
971   "Expression for imenu")
972
973 (defun LilyPond-command-select-master ()
974   (interactive)
975   (message "Next command will be on the master file")
976   (setq LilyPond-command-current 'LilyPond-command-master))
977
978 (defun LilyPond-command-select-buffer ()
979   (interactive)
980   (message "Next command will be on the buffer")
981   (setq LilyPond-command-current 'LilyPond-command-buffer))
982
983 (defun LilyPond-command-select-region ()
984   (interactive)
985   (message "Next command will be on the region")
986   (setq LilyPond-command-current 'LilyPond-command-region))
987
988 (defun LilyPond-command-menu (name)
989   ;; Execute LilyPond-command-alist NAME from a menu.
990   (let ((LilyPond-command-force name))
991     (funcall LilyPond-command-current)))
992
993 (defun LilyPond-mode ()
994   "Major mode for editing LilyPond music files.
995
996 This mode knows about LilyPond keywords and line comments, not about
997 indentation or block comments.  It features easy compilation, error
998 finding and viewing of a LilyPond source buffer or region.
999
1000 COMMANDS
1001 \\{LilyPond-mode-map}
1002 VARIABLES
1003
1004 LilyPond-command-alist\t\talist from name to command
1005 LilyPond-xdvi-command\t\tcommand to display dvi files -- bit superfluous"
1006   (interactive)
1007   ;; set up local variables
1008   (kill-all-local-variables)
1009
1010   (make-local-variable 'font-lock-defaults)
1011   (setq font-lock-defaults '(LilyPond-font-lock-keywords))
1012
1013   ;; string and comments are fontified explicitly
1014   (make-local-variable 'font-lock-keywords-only)
1015   (setq font-lock-keywords-only t)
1016
1017   ;; Multi-line font-locking needs Emacs 21.1 or newer.
1018   ;; For older versions there is hotkey "C-c f".
1019   (make-local-variable 'font-lock-multiline) 
1020   (setq font-lock-multiline t) 
1021
1022   (make-local-variable 'paragraph-separate)
1023   (setq paragraph-separate "^[ \t]*$")
1024
1025   (make-local-variable 'paragraph-start)
1026   (setq paragraph-start "^[ \t]*$")
1027
1028   (make-local-variable 'comment-start)
1029   (setq comment-start "%")
1030
1031   (make-local-variable 'comment-start-skip)
1032   (setq comment-start-skip "%{? *")
1033
1034   (make-local-variable 'comment-end)
1035   (setq comment-end "")
1036
1037   (make-local-variable 'block-comment-start)
1038   (setq block-comment-start "%{")
1039
1040   (make-local-variable 'block-comment-end)  
1041   (setq block-comment-end   "%}")
1042
1043   (make-local-variable 'indent-line-function)
1044   (setq indent-line-function 'LilyPond-indent-line)
1045
1046   (set-syntax-table LilyPond-mode-syntax-table)
1047   (setq major-mode 'LilyPond-mode)
1048   (setq mode-name "LilyPond")
1049   (setq local-abbrev-table LilyPond-mode-abbrev-table)
1050   (use-local-map LilyPond-mode-map)
1051
1052   (make-local-variable 'imenu-generic-expression)
1053   (setq imenu-generic-expression LilyPond-imenu-generic-expression)
1054   (imenu-add-to-menubar "Index")
1055
1056   ;; run the mode hook. LilyPond-mode-hook use is deprecated
1057   (run-hooks 'LilyPond-mode-hook))
1058
1059 (defun LilyPond-version ()
1060   "Echo the current version of `LilyPond-mode' in the minibuffer."
1061   (interactive)
1062   (message "Using `LilyPond-mode' version %s" LilyPond-version))
1063
1064 (load-library "lilypond-font-lock")
1065 (load-library "lilypond-indent")
1066
1067 (provide 'lilypond-mode)
1068 ;;; lilypond-mode.el ends here
1069