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