[emacs] Start switching to M-Emacs.

This commit is contained in:
Mikaël Capelle
2019-12-29 22:22:51 +01:00
committed by Mikaël Capelle
parent 67141d8dc5
commit f3a1c670d9
78 changed files with 9306 additions and 445 deletions

View File

@@ -0,0 +1,190 @@
;;; lilypond-font-lock.el --- syntax coloring for LilyPond mode
;; Author: 2001-2006: Heikki Junes
;; * Emacs-mode: new keywords, reserved words, identifiers, notenames,
;; some dynamics and brackets are font-lock-keywords
;; * context-dependent syntax-tables
;; Author: 1997: Han-Wen Nienhuys
;; Author: 1995-1996 Barry A. Warsaw
;; 1992-1994 Tim Peters
;; Created: Feb 1992
;; Version: 2.9.29
;; Last Modified: 11NOV2006
;; Keywords: lilypond languages music notation
;; This started out as a cannabalised version of python-mode.el, by hwn
;; For changes see the LilyPond ChangeLog
;;
;; TODO:
;; - handle lexer modes (\header, \melodic) etc.
(defconst LilyPond-font-lock-keywords
(let* ((kwregex (mapconcat (lambda (x) (concat "\\" x)) LilyPond-keywords "\\|"))
(iregex (mapconcat (lambda (x) (concat "\\" x)) LilyPond-identifiers "\\|"))
(ncrwregex (mapconcat (lambda (x) (concat "" x)) LilyPond-non-capitalized-reserved-words "\\|"))
(rwregex (mapconcat (lambda (x) (concat "" x)) LilyPond-Capitalized-Reserved-Words "\\|"))
(duration "\\([ \t]*\\(128\\|6?4\\|3?2\\|16?\\|8\\)[.]*\\([ \t]*[*][ \t]*[0-9]+\\(/[1-9][0-9]*\\)?\\)?\\)")
(longduration "\\([ \t]*\\(\\\\\\(longa\\|breve\\|maxima\\)\\)[.]*\\([ \t]*[*][ \t]*[0-9]+\\(/[1-9][0-9]*\\)?\\)?\\)")
)
(list
;; Fonts in use (from GNU Emacs Lisp Reference Manual, elisp.ps):
;; font-lock- (c)omment / (s)tring / (k)eyword / (b)uiltin / (f)unction-name /
;; (v)ariable-name / (t)ype / co(n)stant / (w)arning -face
;; The order below is designed so that proofreading would be possible.
;; Fontify...
;; ... (f) identifiers and (k) keywords.
;; ... (n) user defined indetifiers
;; ... (v) the right and the left side of '='-marks.
;; ... (v) reserved words, e.g., FiguredBass.
;; ... (t) notes and rests
;; "on top", ... (s) lyrics-mode
;; "on top", ... (w) horizontal grouping
;; "on top", ... (f) vertical grouping
;; "on top", ... (b) expressional grouping
;; "on top", ... (s) (multiline-)scheme; urgh. one should count the slurs
;; "on top", ... (s) strings
;; "on top", ... (c) (multiline-)comments
;; One should note 'font-lock-multiline' has been possible since Emacs 21.1.
;; See, e.g., text in "http://emacs.kldp.org/emacs-21.1/etc/NEWS".
;; ... identifiers (defined above, see iregex)
(cons (concat "\\(\\([_^-]?\\(" iregex "\\)\\)+\\)\\($\\|[] \t(~{}>\\\\_()^*-]\\)") '(1 font-lock-function-name-face))
;; ... keywords (defined above, see kwregex)
(cons (concat "\\(\\([_^-]?\\(" kwregex "\\)\\)+\\)\\($\\|[] \t(~{}>\\\\_()^*-]\\)") '(1 font-lock-keyword-face))
;; ... user defined identifiers, roughly \[a-zA-Z]+ with single - or _ in between.
'("\\([_^-]?\\\\\\([a-zA-Z[:nonascii:]]\\(?:[-_]?[a-zA-Z[:nonascii:]]\\)*\\)\\)" 1 font-lock-constant-face)
;; ... the left side of '=' -mark
'("\\([_a-zA-Z.0-9-]+\\)[ \t]*=[ \t]*" 1 font-lock-variable-name-face)
;; ... the right side of '=' -mark
'("[ \t]*=[ \t]*\\([_a-zA-Z.0-9-]+\\)" 1 font-lock-variable-name-face)
;; ... reserved words (defined above, see rwregex)
(cons (concat "\\(" rwregex "\\)") 'font-lock-variable-name-face)
;; ... note or rest with (an accidental and) a duration, e.g., b,?16.*3/4
(cons (concat "\\(^\\|[ <\{[/~(!)\t\\\|]\\)\\(\\(\\(" ncrwregex "\\)[,']*[?!]?\\|[srR]\\)" duration "?\\)") '(2 font-lock-type-face))
;; "on top", ... notes and rests with a long duration
(cons (concat "\\(^\\|[ <\{[/~(!)\t\\\|]\\)\\(\\(\\(" ncrwregex "\\)[,']*[?!]?\\|[srR]\\)" longduration "\\)") '(2 font-lock-type-face t))
;; "on top", ... lyrics-mode: fontify everything between '<'...'>' or '{'...'}'
; URGH, does not know anything about inner brackets.
; Multiple lines may need refontifying (C-c f).
'("\\(\\\\lyrics[^{<]*\\)\\({[^}]*\\|<[^>]*\\)" 2 font-lock-string-face t)
;; "on top", ... horizontal grouping, also as postfix syntax '-*':
;; - brackets '{[]}'
;; - ties '~'
;; - ligatures \[, \]
'("\\(-?[][~}{]\\|\\\\[][]\\)" 0 font-lock-reference-face t)
;; "on top", ... vertical grouping:
;; - '<>'-chord brackets with '\\'-voice sep., not marcato '->'
;; - '<< a b >>8' -chords
(cons (concat "\\(\\(-.\\)+\\|[^-^_]\\)\\([<>]+\\(" duration "\\|" longduration "\\)?\\|\\\\\\\\\\)") '(3 font-lock-function-name-face t))
;; "on top", ... expressional grouping, also as postfix syntax '-*':
;; - slurs ( ), \( \), [-^_][()]
;; - hairpins \<, \>, \!
'("\\(-?\\\\[(<!>)]\\|[-^_]?[()]\\)" 0 font-lock-builtin-face t)
;; "on top", ... (multiline-)scheme: try find slurs up to 7th
'("[_^-]?#\\(#[ft]\\|-?[0-9.]+\\|\"[^\"]*\"\\|['`]?[a-zA-Z:-]+\\|['`]?([^()]*\\(([^()]*\\(([^()]*\\(([^()]*\\(([^()]*\\(([^()]*\\(([^)]*)[^()]*\\)*)[^()]*\\)*)[^()]*\\)*)[^()]*\\)*)[^()]*\\)*)[^()]*\\)*[^)]*)\\)" 0 font-lock-string-face t)
;; "on top", ... strings, match also unending strings at eof:
;; if '\n' was not found, it must be '$' which is eof (?).
'("\\([_^-]?\"\\([^\"\\\\]\\|\\\\.\\|\\\\\n\\)*\\(\"\\|$\\)\\)" 0 font-lock-string-face t)
;; "on top", ... (multiline-)comments
'("\\(%\\({[^%]*%\\(}\\|\\([^}][^%]*%\\)+}\\)\\|.*\\)\\)" 0 font-lock-comment-face t)
)
)
"Additional expressions to fontify in LilyPond mode.")
;; define a mode-specific abbrev table for those who use such things
(defvar LilyPond-mode-abbrev-table nil
"Abbrev table in use in `LilyPond-mode' buffers.")
(define-abbrev-table 'LilyPond-mode-abbrev-table nil)
(defvar LilyPond-mode-syntax-table nil
"Syntax table used in `LilyPond-mode' buffers.")
(defun LilyPond-mode-set-syntax-table (&optional not-punct)
"Change syntax table according to the argument `not-punct' which contains characters which are given a context dependent non-punctuation syntax: parentheses may be set to parenthesis syntax and characters `-', `^' and `_' may be set to escape syntax."
(if (not not-punct) (setq not-punct '()))
(setq LilyPond-mode-syntax-table (make-syntax-table))
(let ((defaults
'(
;; NOTE: Emacs knows only "13"-style (used), XEmacs knows also "1b3b", etc.
( ?\% . "< 13" ) ; comment starter, 1st char in block-comments
( ?\n . ">") ; newline: comment ender
( ?\r . ">") ; formfeed: comment ender
( ?\\ . "\\" ) ; escape characters (as '\n' in strings)
( ?\" . "\"" ) ; string quote characters
;; word constituents (e.g., belonging to a note)
( ?\' . "w") ( ?\, . "w") ; transposing octaves
;; punctuation characters (separate symbols from another)
( ?\$ . "." ) ( ?\& . "." )
( ?\* . "." ) ( ?\+ . "." ) ( ?\/ . "." ) ( ?\= . "." )
( ?\| . "." ) ; bar line
)))
;; all the paren characters are now handled by lily-specific indenting/matching code in lilypond-indent.el
(if (or (memq ?\{ not-punct) (memq ?\} not-punct))
(setq defaults (cons '( ?\{ . "(} 2" ) (cons '( ?\} . "){ 4" ) defaults))) ; begin and end of a block-comment
(setq defaults (cons '( ?\{ . ". 2" ) (cons '( ?\} . ". 4" ) defaults)))) ; begin and end of a block-comment
(if (or (memq ?\[ not-punct) (memq ?\] not-punct))
(setq defaults (cons '( ?\[ . "(]" ) (cons '( ?\] . ")[" ) defaults)))
(setq defaults (cons '( ?\[ . "." ) (cons '( ?\] . "." ) defaults))))
(if (or (memq ?\< not-punct) (memq ?\> not-punct))
(setq defaults (cons '( ?\< . "(>" ) (cons '( ?\> . ")<" ) defaults)))
(setq defaults (cons '( ?\< . "." ) (cons '( ?\> . "." ) defaults))))
(if (or (memq ?\( not-punct) (memq ?\) not-punct))
(setq defaults (cons '( ?\( . "()" ) (cons '( ?\) . ")(" ) defaults)))
(setq defaults (cons '( ?\( . "." ) (cons '( ?\) . "." ) defaults))))
;; In LilyPond the following chars serve as escape chars, e.g., c^> d-) e_( ,
;; but they may be set to punctuation chars, since inside strings they should not act as escape chars
(setq defaults (cons (if (memq ?- not-punct) '( ?\- . "\\" ) '( ?\- . "." ) ) defaults))
(setq defaults (cons (if (memq ?^ not-punct) '( ?^ . "\\" ) '( ?^ . "." ) ) defaults))
(setq defaults (cons (if (memq ?\_ not-punct) '( ?\_ . "\\" ) '( ?\_ . "." ) ) defaults))
(mapcar (function
(lambda (x) (modify-syntax-entry
(car x) (cdr x) LilyPond-mode-syntax-table)))
defaults)
(set-syntax-table LilyPond-mode-syntax-table)))
(defun LilyPond-mode-context-set-syntax-table ()
"Change syntax table according to current context."
(interactive)
;; default syntax table sets parentheses to punctuation characters
(LilyPond-mode-set-syntax-table)
;; find current context
(setq context (parse-partial-sexp (point-min) (point)))
(cond ((nth 3 context)) ; inside string
((nth 4 context)) ; inside a comment
((eq (char-syntax (or (char-before (point)) 0)) ?\\)) ; found escape-char
((and (eq (char-syntax (or (char-before (- (point) 1)) 0)) ?\\)
(memq (char-before (point)) '( ?\) ?\] )))) ; found escape-char
((memq (char-before (point)) '( ?\) ))
(LilyPond-mode-set-syntax-table '( ?\( ?\) )))
((memq (char-before (point)) '( ?\] ))
(LilyPond-mode-set-syntax-table '( ?\[ ?\] )))
((memq (char-before (point)) '( ?\> ?\} ))
(LilyPond-mode-set-syntax-table '( ?\< ?\> ?\{ ?\} ?\^ ?\- ?\_ )))
((memq (char-after (point)) '( ?\( ))
(LilyPond-mode-set-syntax-table '( ?\( ?\) )))
((memq (char-after (point)) '( ?\[ ))
(LilyPond-mode-set-syntax-table '( ?\[ ?\] )))
((memq (char-after (point)) '( ?\< ?\{ ))
(LilyPond-mode-set-syntax-table '( ?\< ?\> ?\{ ?\} ?\^ ?\- ?\_ )))
))

View File

@@ -0,0 +1,587 @@
;;; lilypond-indent.el --- Auto-indentation for lilypond code
;;;
;;; Heikki Junes <hjunes@cc.hut.fi>
;;; * ond-char paren matching is handled by context dependent syntax tables
;;; * match two-char slurs '\( ... \)' and '\[ ... \]' separately.
;;; * adopt Emacs' f90-comment-region
;;; Chris Jackson <chris@fluffhouse.org.uk>
;;; some code is taken from ESS (Emacs Speaks Statistics) S-mode by A.J.Rossini <rossini@biostat.washington.edu>
;;; Variables for customising indentation style
;;; TODO:
;;; * currently, in bracket matching one may need a non-bracket
;;; chararacter between the bracket characters, like ( ( ) )
(defcustom LilyPond-indent-level 2
"*Indentation of lilypond statements with respect to containing block."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-brace-offset 0
"*Extra indentation for open braces.
Compares with other text in same context."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-angle-offset 0
"*Extra indentation for open angled brackets.
Compares with other text in same context."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-square-offset 0
"*Extra indentation for open square brackets.
Compares with other text in same context."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-scheme-paren-offset 0
"*Extra indentation for open scheme parens.
Compares with other text in same context."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-close-brace-offset 0
"*Extra indentation for closing braces."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-close-angle-offset 0
"*Extra indentation for closing angle brackets."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-close-square-offset 0
"*Extra indentation for closing square brackets."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-close-scheme-paren-offset 0
"*Extra indentation for closing scheme parens."
:group 'LilyPond
:type 'integer)
(defcustom LilyPond-fancy-comments t
"*Non-nil means distiguish between %, %%, and %%% for indentation."
:group 'LilyPond
:type 'boolean)
(defcustom LilyPond-comment-region "%%%"
"*String inserted by \\[LilyPond-comment-region]\
at start of each line in region."
:group 'LilyPond
:type 'string)
(defun LilyPond-comment-region (beg-region end-region)
"Comment/uncomment every line in the region.
Insert LilyPond-comment-region at the beginning of every line in the region
or, if already present, remove it."
(interactive "*r")
(let ((end (make-marker)))
(set-marker end end-region)
(goto-char beg-region)
(beginning-of-line)
(if (looking-at (regexp-quote LilyPond-comment-region))
(delete-region (point) (match-end 0))
(insert LilyPond-comment-region))
(while (and (zerop (forward-line 1))
(< (point) (marker-position end)))
(if (looking-at (regexp-quote LilyPond-comment-region))
(delete-region (point) (match-end 0))
(insert LilyPond-comment-region)))
(set-marker end nil)))
(defun LilyPond-calculate-indent ()
"Return appropriate indentation for current line as lilypond code.
In usual case returns an integer: the column to indent to.
Returns nil if line starts inside a string"
(save-excursion
(beginning-of-line)
(let ((indent-point (point))
(case-fold-search nil)
state)
(setq containing-sexp (save-excursion (LilyPond-scan-containing-sexp)))
(beginning-of-defun)
(while (< (point) indent-point)
(setq state (parse-partial-sexp (point) indent-point 0)))
;; (setq containing-sexp (car (cdr state))) is the traditional way for languages
;; with simpler parenthesis delimiters
(cond ((nth 3 state)
;; point is in the middle of a string
nil)
((nth 4 state)
;; point is in the middle of a block comment
(LilyPond-calculate-indent-within-blockcomment))
((null containing-sexp)
;; Line is at top level - no indent
(beginning-of-line)
0)
(t
;; Find previous non-comment character.
(goto-char indent-point)
(LilyPond-backward-to-noncomment containing-sexp)
;; Now we get the answer.
;; Position following last unclosed open.
(goto-char containing-sexp)
(or
;; Is line first statement after an open brace or bracket?
;; If no, find that first statement and indent like it.
(save-excursion
(forward-char 1)
;; Skip over comments following open brace.
(skip-chars-forward " \t\n")
(cond ((looking-at "%{")
(while (progn
(and (not (looking-at "%}"))
(< (point) (point-max))))
(forward-line 1)
(skip-chars-forward " \t\n"))
(forward-line 1)
(skip-chars-forward " \t\n"))
((looking-at "%")
(while (progn (skip-chars-forward " \t\n")
(looking-at "%"))
(forward-line 1))))
;; The first following code counts
;; if it is before the line we want to indent.
(and (< (point) indent-point)
(current-column)))
;; If no previous statement,
;; indent it relative to line brace is on.
;; For open brace in column zero, don't let statement
;; start there too. If LilyPond-indent-level is zero, use
;; LilyPond-brace-offset instead
(+ (if (and (bolp) (zerop LilyPond-indent-level))
(cond ((= (following-char) ?{)
LilyPond-brace-offset)
((= (following-char) ?<)
LilyPond-angle-offset)
((= (following-char) ?\[)
LilyPond-square-offset)
((= (following-char) ?\))
LilyPond-scheme-paren-offset)
(t
0))
LilyPond-indent-level)
(progn
(skip-chars-backward " \t")
(current-indentation)))))))))
(defun LilyPond-indent-line ()
"Indent current line as lilypond code.
Return the amount the indentation changed by."
(let ((indent (LilyPond-calculate-indent))
beg shift-amt
(case-fold-search nil)
(pos (- (point-max) (point))))
(beginning-of-line)
(setq beg (point))
(cond ((eq indent nil)
(setq indent (current-indentation)))
(t
(skip-chars-forward " \t")
(if (and LilyPond-fancy-comments (looking-at "%%%\\|%{\\|%}"))
(setq indent 0))
(if (and LilyPond-fancy-comments
(looking-at "%")
(not (looking-at "%%\\|%{\\|%}")))
(setq indent comment-column)
(if (eq indent t) (setq indent 0))
(if (listp indent) (setq indent (car indent)))
(cond
((= (following-char) ?})
(setq indent (+ indent (- LilyPond-close-brace-offset LilyPond-indent-level))))
((= (following-char) ?>)
(setq indent (+ indent (- LilyPond-close-angle-offset LilyPond-indent-level))))
((= (following-char) ?\])
(setq indent (+ indent (- LilyPond-close-square-offset LilyPond-indent-level))))
((and (= (following-char) ?\)) (LilyPond-inside-scheme-p))
(setq indent (+ indent (- LilyPond-close-scheme-paren-offset LilyPond-indent-level))))
((= (following-char) ?{)
(setq indent (+ indent LilyPond-brace-offset)))
((= (following-char) ?<)
(setq indent (+ indent LilyPond-angle-offset)))
((= (following-char) ?\[)
(setq indent (+ indent LilyPond-square-offset)))
((and (= (following-char) ?\() (LilyPond-inside-scheme-p))
(setq indent (+ indent LilyPond-scheme-paren-offset)))
))))
(skip-chars-forward " \t")
(setq shift-amt (- indent (current-column)))
(if (zerop shift-amt)
(if (> (- (point-max) pos) (point))
(goto-char (- (point-max) pos)))
(delete-region beg (point))
(indent-to indent)
;; If initial point was within line's indentation,
;; position after the indentation.
;; Else stay at same point in text.
(if (> (- (point-max) pos) (point))
(goto-char (- (point-max) pos))))
shift-amt))
(defun LilyPond-inside-comment-p ()
"Return non-nil if point is inside a line or block comment"
(setq this-point (point))
(or (save-excursion (beginning-of-line)
(skip-chars-forward " \t")
(looking-at "%"))
(save-excursion
;; point is in the middle of a block comment
(setq lastopen (save-excursion (re-search-backward "%{[ \\t]*" (point-min) t)))
(setq lastclose (save-excursion (re-search-backward "%}[ \\t]*" (point-min) t)))
(if (or (and (= (char-before) ?%) (= (char-after) ?{))
(and (= (char-after) ?%) (= (char-after (1+ (point))) ?{)))
(setq lastopen (save-excursion (backward-char) (point))))
(and
lastopen
(or (not lastclose)
(<= lastclose lastopen))))
))
(defun LilyPond-inside-string-or-comment-p ()
"Test if point is inside a string or a comment"
(setq this-point (point))
(or (save-excursion (beginning-of-line)
(skip-chars-forward " \t")
(looking-at "%"))
(save-excursion
(beginning-of-defun)
(while (< (point) this-point)
(setq state (parse-partial-sexp (point) this-point 0)))
(cond ((nth 3 state)
;; point is in the middle of a string
t )
((nth 4 state)
;; point is in the middle of a block comment
t )
(t
nil)))))
(defun LilyPond-backward-over-blockcomments (lim)
"Move point back to closest non-whitespace character not part of a block comment"
(setq lastopen (save-excursion (re-search-backward "%{[ \\t]*" lim t)))
(setq lastclose (save-excursion (re-search-backward "%}[ \\t]*" lim t)))
(if lastopen
(if lastclose
(if (<= lastclose lastopen)
(goto-char lastopen))
(goto-char lastopen)))
(skip-chars-backward " %\t\n\f"))
(defun LilyPond-backward-over-linecomments (lim)
"Move point back to the closest non-whitespace character not part of a line comment.
Argument LIM limit."
(let (opoint stop)
(while (not stop)
(skip-chars-backward " \t\n\f" lim)
(setq opoint (point))
(beginning-of-line)
(search-forward "%" opoint 'move)
(skip-chars-backward " \t%")
(setq stop (or (/= (preceding-char) ?\n) (<= (point) lim)))
(if stop (point)
(beginning-of-line)))))
(defun LilyPond-backward-to-noncomment (lim)
"Move point back to closest non-whitespace character not part of a comment"
(LilyPond-backward-over-linecomments lim)
(LilyPond-backward-over-blockcomments lim))
(defun LilyPond-calculate-indent-within-blockcomment ()
"Return the indentation amount for line inside a block comment."
(let (end percent-start)
(save-excursion
(beginning-of-line)
(skip-chars-forward " \t")
(skip-chars-backward " \t\n")
(setq end (point))
(beginning-of-line)
(skip-chars-forward " \t")
(and (re-search-forward "%{[ \t]*" end t)
(goto-char (1+ (match-beginning 0))))
(if (and (looking-at "[ \t]*$") (= (preceding-char) ?\%))
(1+ (current-column))
(current-column)))))
;; Key: Type of bracket (character).
;; Value: Pair of regexps representing the corresponding open and close bracket
;; () are treated specially (need to indent in Scheme but not in music)
(defconst LilyPond-parens-regexp-alist
`( ( ?> . ("\\([^\\]\\|^\\)<" . "\\([^ \\n\\t_^-]\\|[_^-][-^]\\|\\s-\\)\\s-*>"))
;; a b c->, a b c^> and a b c_> are not close-angle-brackets, they're accents
;; but a b c^-> and a b c^^> are close brackets with tenuto/marcato before them
;; also \> and \< are hairpins
;; duh .. a single '>', as in chords '<< ... >>', was not matched here
( ?} . ("{" . "}"))
;; ligatures '\[ ... \]' are skipped in the following expression
( ?\] . ("\\([^\\]\\([\\][\\]\\)*\\|^\\)[[]" . "\\([^\\]\\([\\][\\]\\)*\\|^\\)[]]"))
( "\\]" . ("\\([^\\]\\|^\\)\\([\\][\\]\\)*[\\][[]" . "\\([^\\]\\|^\\)\\([\\][\\]\\)*[\\][]]"))
( "\\)" . ("\\([^\\]\\|^\\)\\([\\][\\]\\)*[\\][(]" . "\\([^\\]\\|^\\)\\([\\][\\]\\)*[\\][)]"))
))
(defconst LilyPond-parens-alist
`( ( ?< . ?> )
( ?{ . ?} )
( ?\[ . ?\] )
( "\\[" . "\\]" )
( ?\( . ?\) )
( "\\(" . "\\)" )
))
(defun LilyPond-matching-paren (bracket-type)
"Returns the open corresponding to the close specified by bracket-type, or vice versa"
(cond ( (member bracket-type (mapcar 'car LilyPond-parens-alist))
(cdr (assoc bracket-type LilyPond-parens-alist)) )
( (member bracket-type (mapcar 'cdr LilyPond-parens-alist))
(car (rassoc bracket-type LilyPond-parens-alist)) )
nil))
(defun LilyPond-scan-containing-sexp (&optional bracket-type slur-paren-p dir)
"Move point to the beginning of the deepest parenthesis pair enclosing point.
If the optional argument bracket-type, a character representing a
close bracket such as ) or }, is specified, then the parenthesis pairs
searched are limited to this type.
If the optional argument slur-paren-p is non-nil, then slur
parentheses () are considered as matching pairs. Otherwise Scheme
parentheses are considered to be matching pairs, but slurs are not.
slur-paren-p defaults to nil.
"
;;; An user does not call this function directly, or by a key sequence.
;; (interactive)
(let ( (level (if (not (eq dir 1)) 1 -1))
(regexp-alist LilyPond-parens-regexp-alist)
(oldpos (point))
(assoc-bracket-type (if (not (eq dir 1)) bracket-type (LilyPond-matching-paren bracket-type))))
(if (LilyPond-inside-scheme-p)
(setq paren-regexp "(\\|)")
(if slur-paren-p
;; expressional slurs '\( ... \)' are not taken into account
(setq regexp-alist (cons '( ?\) . ("\\([^\\]\\([\\][\\]\\)*\\|^\\)(" . "\\([^\\]\\([\\][\\]\\)*\\|^\\))")) regexp-alist)))
(if (member assoc-bracket-type (mapcar 'car regexp-alist))
(progn (setq paren-regexp (cdr (assoc assoc-bracket-type regexp-alist)))
(setq paren-regexp (concat (car paren-regexp) "\\|" (cdr paren-regexp))))
(setq paren-regexp (concat (mapconcat 'car (mapcar 'cdr regexp-alist) "\\|") "\\|"
(mapconcat 'cdr (mapcar 'cdr regexp-alist) "\\|")))))
;; match concurrent one-char opening and closing slurs
(if (and (eq dir 1)
(not (sequencep bracket-type))
(eq (char-syntax (or (char-after oldpos) 0)) ?\()
(not (eq (char-after oldpos) ?<)))
;; anyway do not count open slur, since already level = -1
(progn (forward-char 1)
(if (eq (following-char)
(LilyPond-matching-paren (char-after oldpos)))
;; matching char found, go after it and set level = 0
(progn (forward-char 1)
(setq level 0)))))
;; browse the code until matching slur is found, or report mismatch
(while (and (if (not (eq dir 1))
(> level 0)
(< level 0))
;; dir tells whether to search backward or forward
(if (not (eq dir 1))
(re-search-backward paren-regexp nil t)
(re-search-forward paren-regexp nil t))
;; note: in case of two-char bracket only latter is compared
(setq match (char-before (match-end 0))))
;;; (message "%d" level) (sit-for 0 300)
(if (not (save-excursion (goto-char (match-end 0))
;; skip over strings and comments
(LilyPond-inside-string-or-comment-p)))
(if (memq match '(?} ?> ?\] ?\)))
;; count closing brackets
(progn (setq level (1+ level))
;; slurs may be close to each other, e.g.,
;; a single '>' was not matched .. need to be corrected
(if (and (eq dir 1) (eq (char-after (match-end 0)) match))
(if (/= level 0)
(progn
(setq level (1+ level))
(forward-char 1))))
;;; (message "%d %c" level match) (sit-for 0 300)
;; hmm..
(if (and (= match ?>)
(looking-at ".\\s-+>\\|\\({\\|}\\|<\\|>\\|(\\|)\\|[][]\\)>"))
(forward-char 1)))
;; count opening brackets
(progn (setq level (1- level))
;;; (message "%d %c" level match) (sit-for 0 300)
;; hmm..
(if (and (= match ?<)
(looking-at ".\\s-+<\\|\\({\\|}\\|<\\|>\\|(\\|)\\|[][]\\)<"))
(forward-char 1))))))
;; jump to the matching slur
(if (not (eq dir 1))
(progn
(if (sequencep bracket-type)
;; match the latter char in two-char brackets
(if (looking-at "..[][)(]") (forward-char 1)))
;; if the following char is not already a slur
(if (and (not (looking-at "[)(]"))
;; match the slur which follows
(looking-at ".[][><)(]")) (forward-char 1)))
(backward-char 1))
(if (= level 0)
(point)
(progn (goto-char oldpos)
nil))))
(defun LilyPond-inside-scheme-p ()
"Tests if point is inside embedded Scheme code"
;;; An user does not call this function directly, or by a key sequence.
;; (interactive)
(let ( (test-point (point))
(level 0) )
(save-excursion
(if (or (and (eq (char-after (point)) ?\()
(save-excursion
(skip-chars-backward "'`")
(memq (char-before) '(?# ?$))))
(and (re-search-backward "[#$][`']?(" nil t)
(progn
(search-forward "(")
(setq level 1)
(while (and (> level 0)
(re-search-forward "[()]" test-point t)
(setq match (char-after (match-beginning 0)))
(<= (point) test-point))
(if (= match ?\()
(setq level (1+ level))
(setq level (1- level))))
(> level 0))))
t
nil))))
;;; Largely taken from the 'blink-matching-open' in lisp/simple.el in
;;; the Emacs distribution.
(defun LilyPond-blink-matching-paren (&optional dir)
"Move cursor momentarily to the beginning of the sexp before
point. In lilypond files this is used for closing ), ], } and >, whereas the
builtin 'blink-matching-open' is not used. In syntax table, see
`lilypond-font-lock.el', all brackets are punctuation characters."
;;; An user does not call this function directly, or by a key sequence.
;; (interactive)
(let ( (oldpos (point))
(level 0)
(mismatch) )
(if (not (or (equal this-command 'LilyPond-electric-close-paren)
(eq dir 1)))
(goto-char (setq oldpos (- oldpos 1))))
;; Test if a ligature \] or expressional slur \) was encountered
(setq bracket-type (char-after (point)))
(setq char-before-bracket-type nil)
(if (memq bracket-type '(?\] ?\) ?\[ ?\())
(progn
(setq np -1)
(while (eq (char-before (- (point) (setq np (+ np 1)))) ?\\)
(setq char-before-bracket-type (if char-before-bracket-type nil ?\\)))
(if (eq char-before-bracket-type ?\\)
(setq bracket-type (string char-before-bracket-type bracket-type)))))
(when blink-matching-paren-distance
(narrow-to-region
(max (point-min) (- (point) blink-matching-paren-distance))
(min (point-max) (+ (point) blink-matching-paren-distance))))
(if (and (equal this-command 'LilyPond-electric-close-paren)
(memq bracket-type '(?> ?} ?< ?{)))
;; < { need to be mutually balanced and nested, so search backwards for both of these bracket types
(LilyPond-scan-containing-sexp nil nil dir)
;; whereas ( ) slurs within music don't, so only need to search for ( )
;; use same mechanism for [ ] slurs
(LilyPond-scan-containing-sexp bracket-type t dir))
(setq blinkpos (point))
(setq mismatch
(or (null (LilyPond-matching-paren (char-after blinkpos)))
(/= (char-after oldpos)
(LilyPond-matching-paren (char-after blinkpos)))))
(if mismatch (progn (setq blinkpos nil)
(message "Mismatched parentheses")))
(if (and blinkpos
(equal this-command 'LilyPond-electric-close-paren))
(if (pos-visible-in-window-p)
(and blink-matching-paren-on-screen
(sit-for blink-matching-delay))
(message
"Matches %s"
;; Show what precedes the open in its line, if anything.
(if (save-excursion
(skip-chars-backward " \t")
(not (bolp)))
(buffer-substring (progn (beginning-of-line) (point))
(1+ blinkpos))
;; Show what follows the open in its line, if anything.
(if (save-excursion
(forward-char 1)
(skip-chars-forward " \t")
(not (eolp)))
(buffer-substring blinkpos
(progn (end-of-line) (point)))
;; Otherwise show the previous nonblank line,
;; if there is one.
(if (save-excursion
(skip-chars-backward "\n \t")
(not (bobp)))
(concat
(buffer-substring (progn
(skip-chars-backward "\n \t")
(beginning-of-line)
(point))
(progn (end-of-line)
(skip-chars-backward " \t")
(point)))
;; Replace the newline and other whitespace with `...'.
"..."
(buffer-substring blinkpos (1+ blinkpos)))
;; There is nothing to show except the char itself.
(buffer-substring blinkpos (1+ blinkpos))))))))
(if (not (equal this-command 'LilyPond-electric-close-paren))
(goto-char (setq oldpos (+ oldpos 1)))
(goto-char oldpos))
(if (not (eq dir 1))
blinkpos
(+ blinkpos 1))))
(defun LilyPond-electric-close-paren ()
"Blink on the matching open paren when a >, ), } or ] is inserted"
(interactive)
(let ((oldpos (point)))
(self-insert-command 1)
;; Refontify buffer if a block-comment-ender '%}' is inserted
(if (and (eq (char-before (point)) ?})
(eq (char-before (- (point) 1)) ?%))
(font-lock-fontify-buffer)
;; Match paren if the cursor is not inside string or comment.
(if (and blink-matching-paren
(not (LilyPond-inside-string-or-comment-p))
(save-excursion (re-search-backward
(concat (mapconcat 'cdr (mapcar 'cdr LilyPond-parens-regexp-alist) "\\|") "\\|)") nil t)
(eq oldpos (1- (match-end 0)))))
(progn (backward-char 1)
(LilyPond-blink-matching-paren)
(forward-char 1))))))
(defun LilyPond-scan-sexps (pos dir)
"This function is redefined to be used in Emacs' show-paren-function and
in XEmacs' paren-highlight."
(LilyPond-blink-matching-paren dir))

View File

@@ -0,0 +1,21 @@
;;; lilypond-init.el --- Startup code for LilyPond mode
;;
;; Instructions, extracted from Documentation/topdocs/INSTALL.texi:
;; Emacs mode for entering music and running LilyPond is contained in
;; the source archive as `lilypond-mode.el', `lilypond-indent.el',
;; `lilypond-font-lock.el' and `lilypond-words.el'. You should install
;; these files to a directory included in your `load-path'.
;; File `lilypond-init.el' should be placed to `load-path/site-start.d/'
;; or appended to your `~/.emacs' or `~/.emacs.el'.
;; As a user, you may want add your source path or, e.g., `~/site-lisp/' to
;; your `load-path'. Append the following line (modified) to your `~/.emacs':
;(setq load-path (append (list (expand-file-name "~/site-lisp")) load-path))
(autoload 'LilyPond-mode "lilypond-mode" "LilyPond Editing Mode" t)
(add-to-list 'auto-mode-alist '("\\.ly$" . LilyPond-mode))
(add-to-list 'auto-mode-alist '("\\.ily$" . LilyPond-mode))
(add-hook 'LilyPond-mode-hook (lambda () (turn-on-font-lock)))

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,556 @@
;;;; lilypond-song.el --- Emacs support for LilyPond singing
;;;;
;;;; This file is part of LilyPond, the GNU music typesetter.
;;;;
;;;; Copyright (C) 2006 Brailcom, o.p.s.
;;;; Author: Milan Zamazal <pdm@brailcom.org>
;;;;
;;;; LilyPond is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; LilyPond is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public License
;;;; along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This file adds Emacs support for singing lyrics of LilyPond files.
;; It extends lilypond-mode with the following commands (see their
;; documentation for more information):
;;
;; - M-x LilyPond-command-sing (C-c C-a)
;; - M-x LilyPond-command-sing-and-play (C-c C-q)
;; - M-x LilyPond-command-sing-last (C-c C-z)
;;
;; Note these commands are not available from the standard LilyPond mode
;; command menus.
;;; Code:
(require 'cl)
(require 'lilypond-mode)
(ignore-errors (require 'ecasound))
;;; User options
(defcustom LilyPond-synthesize-command "lilysong"
"Command used to sing LilyPond files."
:group 'LilyPond
:type 'string)
(defcustom LilyPond-play-command (or (executable-find "ecaplay") "play")
"Command used to play WAV files."
:group 'LilyPond
:type 'string)
;; In case you would like to use fluidsynth (not recommended as fluidsynth
;; can perform wave file synthesis only in real time), you can use the
;; following setting:
;; (setq LilyPond-midi->wav-command "fluidsynth -nil -a file soundfont.sf2 '%s' && sox -t raw -s -r 44100 -w -c 2 fluidsynth.raw '%t'")
(defcustom LilyPond-midi->wav-command "timidity -Ow %m -s %r -o '%t' '%s'"
"Command used to make a WAV file from a MIDI file.
%s in the string is replaced with the source MIDI file name,
%t is replaced with the target WAV file name.
%r is replaced with rate.
%m is replaced with lilymidi call."
:group 'LilyPond
:type 'string)
(defcustom LilyPond-voice-rates
'((".*czech.*" . 44100)
(".*\\<fi\\(\\>\\|nnish\\).*" . 22050)
(".*" . 16000))
"Alist of regexps matching voices and the corresponding voice rates.
It may be necessary to define proper voice rates here in order to
avoid ecasound resampling problems."
:group 'LilyPond
:type '(alist :key-type regexp :value-type integer))
(defcustom LilyPond-use-ecasound (and (featurep 'ecasound)
(executable-find "ecasound")
t)
"If non-nil, use ecasound for mixing and playing songs."
:group 'LilyPond
:type 'boolean)
(defcustom LilyPond-voice-track-regexp "voice"
"Perl regexp matching names of MIDI tracks to be ignored on sing&play."
:group 'LilyPond
:type 'string)
(defcustom LilyPond-lilymidi-command "\"`lilymidi --prefix-tracks -Q --filter-tracks '%s' '%f'`\""
"Command to insert into LilyPond-midi->wav-command calls.
%f is replaced with the corresponding MIDI file name.
%s is replaced with `LilyPond-voice-track-regexp'."
:group 'LilyPond
:type 'string)
;;; Lyrics language handling
(defvar lilysong-language nil)
(make-variable-buffer-local 'lilysong-language)
(defvar lilysong-last-language nil)
(make-variable-buffer-local 'lilysong-last-language)
(defvar lilysong-languages '("cs" "en"))
(defvar lilysong-voices nil)
(defun lilysong-voices ()
(or lilysong-voices
(with-temp-buffer
(call-process "lilysong" nil t nil "--list-voices")
(call-process "lilysong" nil t nil "--list-languages")
(goto-char (point-min))
(while (not (eobp))
(push (buffer-substring-no-properties
(line-beginning-position) (line-end-position))
lilysong-voices)
(forward-line))
lilysong-voices)))
(defun lilysong-change-language ()
"Change synthesis language or voice of the current document."
(interactive)
(setq lilysong-language
(completing-read "Lyrics language or voice: "
(mapcar 'list (lilysong-voices)))))
(defun lilysong-update-language ()
(unless lilysong-language
(lilysong-change-language)))
;;; Looking for \festival* and \midi commands
(defun lilysong-document-files ()
(let ((resulting-files ())
(stack (list (LilyPond-get-master-file))))
(while (not (null stack))
(let ((file (expand-file-name (pop stack))))
(when (and (file-exists-p file)
(not (member file resulting-files)))
(push file resulting-files)
(save-excursion
(save-restriction
(set-buffer (find-file-noselect file nil))
(widen)
(goto-char (point-min))
(while (re-search-forward "^[^%\n]*\\\\include +\"\\([^\"]+\\)\"" nil t)
(push (match-string 1) stack)))))))
(nreverse resulting-files)))
(defvar lilysong-festival-command-regexp
"^[^%\n]*\\\\festival\\(syl\\)? +#\"\\([^\"]+\\)\"")
(defun lilysong-find-song (direction)
"Find XML file name of the nearest Festival command in the given DIRECTION.
DIRECTION is one of the symbols `forward' or `backward'.
If no Festival command is found in the current buffer, return nil.
The point is left at the position where the command occurrence was found."
(save-match-data
(when (funcall (if (eq direction 'backward)
're-search-backward
're-search-forward)
lilysong-festival-command-regexp nil t)
(match-string-no-properties 2))))
(defun lilysong-current-song ()
"Return the XML file name corresponding to the song around current point.
If there is none, return nil."
(save-excursion
(or (progn (end-of-line) (lilysong-find-song 'backward))
(progn (beginning-of-line) (lilysong-find-song 'forward)))))
(defun lilysong-all-songs (&optional limit-to-region)
"Return list of XML file names of the song commands in the current buffer.
If there are none, return an empty list.
If LIMIT-TO-REGION is non-nil, look for the commands in the current region
only."
(let ((result '())
(current nil))
(save-excursion
(save-restriction
(when limit-to-region
(narrow-to-region (or (mark) (point)) (point)))
(goto-char (point-min))
(while (setq current (lilysong-find-song 'forward))
(push current result))))
(nreverse result)))
(defun lilysong-walk-files (collector)
(save-excursion
(mapcar (lambda (f)
(set-buffer (find-file-noselect f))
(funcall collector))
(lilysong-document-files))))
(defun lilysong-all-songs* ()
"Return list of XML file names of the song commands in the current document."
(remove-duplicates (apply #'append (lilysong-walk-files #'lilysong-all-songs))
:test #'equal))
(defvar lilysong-song-history nil)
(make-variable-buffer-local 'lilysong-song-history)
(defvar lilysong-last-song-list nil)
(make-variable-buffer-local 'lilysong-last-song-list)
(defvar lilysong-last-command-args nil)
(make-variable-buffer-local 'lilysong-last-command-args)
(defun lilysong-song-list (multi)
(cond
((eq multi 'all)
(lilysong-all-songs*))
(multi
(lilysong-select-songs))
(t
(lilysong-select-single-song))))
(defun lilysong-select-single-song ()
(let ((song (lilysong-current-song)))
(if song
(list song)
(error "No song found"))))
(defun lilysong-select-songs ()
(let* ((all-songs (lilysong-all-songs*))
(available-songs all-songs)
(initial-songs (if (or (not lilysong-last-song-list)
(eq LilyPond-command-current
'LilyPond-command-region))
(lilysong-all-songs t)
lilysong-last-song-list))
(last-input (completing-read
(format "Sing file%s: "
(if initial-songs
(format " (default `%s')"
(mapconcat 'identity initial-songs
", "))
""))
(mapcar 'list all-songs)
nil t nil
'lilysong-song-history)))
(if (equal last-input "")
initial-songs
(let ((song-list '())
default-input)
(while (not (equal last-input ""))
(push last-input song-list)
(setq default-input (second (member last-input available-songs)))
(setq available-songs (remove last-input available-songs))
(setq last-input (completing-read "Sing file: "
(mapcar #'list available-songs)
nil t default-input
'lilysong-song-history)))
(setq lilysong-last-song-list (nreverse song-list))))))
(defun lilysong-count-midi-words ()
(count-rexp (point-min) (point-max) "^[^%]*\\\\midi"))
(defun lilysong-midi-list (multi)
(if multi
(let ((basename (file-name-sans-extension (buffer-file-name)))
(count (apply #'+ (save-match-data
(lilysong-walk-files #'lilysong-count-midi-words))))
(midi-files '()))
(while (> count 0)
(setq count (1- count))
(if (= count 0)
(push (concat basename ".midi") midi-files)
(push (format "%s-%d.midi" basename count) midi-files)))
midi-files)
(list (LilyPond-string-current-midi))))
;;; Compilation
(defun lilysong-file->wav (filename &optional extension)
(format "%s.%s" (save-match-data
(if (string-match "\\.midi$" filename)
filename
(file-name-sans-extension filename)))
(or extension "wav")))
(defun lilysong-file->ewf (filename)
(lilysong-file->wav filename "ewf"))
(defstruct lilysong-compilation-data
command
makefile
buffer
songs
midi
in-parallel)
(defvar lilysong-compilation-data nil)
(defun lilysong-sing (songs &optional midi-files in-parallel)
(setq lilysong-last-command-args (list songs midi-files in-parallel))
(lilysong-update-language)
(add-to-list 'compilation-finish-functions 'lilysong-after-compilation)
(setq songs (mapcar #'expand-file-name songs))
(let* ((makefile (lilysong-makefile (current-buffer) songs midi-files))
(command (format "make -f %s" makefile)))
(setq lilysong-compilation-data
(make-lilysong-compilation-data
:command command
:makefile makefile
:buffer (current-buffer)
:songs songs
:midi midi-files
:in-parallel in-parallel))
(save-some-buffers (not compilation-ask-about-save))
(unless (equal lilysong-language lilysong-last-language)
(mapc #'(lambda (f) (when (file-exists-p f) (delete-file f)))
(append songs (mapcar 'lilysong-file->wav midi-files))))
(if (lilysong-up-to-date-p makefile)
(lilysong-process-generated-files lilysong-compilation-data)
(compile command))))
(defun lilysong-up-to-date-p (makefile)
(equal (call-process "make" nil nil nil "-f" makefile "-q") 0))
(defun lilysong-makefile (buffer songs midi-files)
(let ((temp-file (make-temp-file "Makefile.lilysong-el"))
(language lilysong-language))
(with-temp-file temp-file
(let ((source-files (save-excursion
(set-buffer buffer)
(lilysong-document-files)))
(master-file (save-excursion
(set-buffer buffer)
(LilyPond-get-master-file)))
(lilyfiles (append songs midi-files)))
(insert "all:")
(dolist (f (mapcar 'lilysong-file->wav (append songs midi-files)))
(insert " " f))
(insert "\n")
(when lilyfiles
(dolist (f songs)
(insert f " "))
(when midi-files
(dolist (f midi-files)
(insert f " ")))
(insert ": " master-file "\n")
(insert "\t" LilyPond-lilypond-command " " master-file "\n")
(dolist (f songs)
(insert (lilysong-file->wav f) ": " f "\n")
(insert "\t" LilyPond-synthesize-command " $< " (or language "") "\n"))
;; We can't use midi files in ecasound directly, because setpos
;; doesn't work on them.
(let ((lilymidi LilyPond-lilymidi-command)
(voice-rate (format "%d" (or (cdr (assoc-if (lambda (key) (string-match key language))
LilyPond-voice-rates))
16000))))
(when (string-match "%s" lilymidi)
(setq lilymidi (replace-match LilyPond-voice-track-regexp nil nil lilymidi)))
(dolist (f midi-files)
(insert (lilysong-file->wav f) ": " f "\n")
(let ((command LilyPond-midi->wav-command)
(lilymidi* lilymidi))
(when (string-match "%s" command)
(setq command (replace-match f nil nil command)))
(when (string-match "%t" command)
(setq command (replace-match (lilysong-file->wav f) nil nil command)))
(when (string-match "%r" command)
(setq command (replace-match voice-rate nil nil command)))
(when (string-match "%f" lilymidi*)
(setq lilymidi (replace-match f nil nil lilymidi*)))
(when (string-match "%m" command)
(setq command (replace-match lilymidi nil nil command)))
(insert "\t" command "\n")))
))))
temp-file))
(defun lilysong-after-compilation (buffer message)
(let ((data lilysong-compilation-data))
(when (and data
(equal compile-command
(lilysong-compilation-data-command data)))
(unwind-protect
(when (lilysong-up-to-date-p (lilysong-compilation-data-makefile data))
(lilysong-process-generated-files data))
(delete-file (lilysong-compilation-data-makefile data))))))
(defun lilysong-process-generated-files (data)
(with-current-buffer (lilysong-compilation-data-buffer data)
(setq lilysong-last-language lilysong-language))
(lilysong-play-files (lilysong-compilation-data-in-parallel data)
(lilysong-compilation-data-songs data)
(lilysong-compilation-data-midi data)))
;;; Playing files
(defun lilysong-play-files (in-parallel songs midi-files)
(funcall (if LilyPond-use-ecasound
'lilysong-play-with-ecasound
'lilysong-play-with-play)
in-parallel songs midi-files))
(defun lilysong-call-play (files)
(apply 'start-process "lilysong-el" nil LilyPond-play-command files))
(defun lilysong-play-with-play (in-parallel songs midi-files)
(let ((files (mapcar 'lilysong-file->wav (append songs midi-files))))
(if in-parallel
(dolist (f files)
(lilysong-call-play (list f)))
(lilysong-call-play files))))
(defun lilysong-make-ewf-files (files)
(let ((offset 0.0))
(dolist (f files)
(let* ((wav-file (lilysong-file->wav f))
(length (with-temp-buffer
(call-process "ecalength" nil t nil "-s" wav-file)
(goto-char (point-max))
(forward-line -1)
(read (current-buffer)))))
(with-temp-file (lilysong-file->ewf f)
(insert "source = " wav-file "\n")
(insert (format "offset = %s\n" offset))
(insert "start-position = 0.0\n")
(insert (format "length = %s\n" length))
(insert "looping = false\n"))
(setq offset (+ offset length))))))
(when (and (featurep 'ecasound)
(not (fboundp 'eci-cs-set-param)))
(defeci cs-set-param ((parameter "sChainsetup option: " "%s"))))
(defun lilysong-play-with-ecasound (in-parallel songs midi-files)
(ecasound)
(eci-cs-add "lilysong-el")
(eci-cs-select "lilysong-el")
(eci-cs-remove)
(eci-cs-add "lilysong-el")
(eci-cs-select "lilysong-el")
(eci-cs-set-param "-z:mixmode,sum")
(unless in-parallel
(lilysong-make-ewf-files songs)
;; MIDI files should actually start with each of the songs
(mapc 'lilysong-make-ewf-files (mapcar 'list midi-files)))
(let* ((file->wav (if in-parallel 'lilysong-file->wav 'lilysong-file->ewf))
(files (mapcar file->wav (append songs midi-files))))
(dolist (f files)
(eci-c-add f)
(eci-c-select f)
(eci-ai-add f))
(eci-c-select-all)
(eci-ao-add-default)
(let* ((n (length songs))
(right (if (<= n 1) 50 0))
(step (if (<= n 1) 0 (/ 100.0 (1- n)))))
(dolist (f songs)
(let ((chain (funcall file->wav f)))
(eci-c-select chain)
(eci-cop-add "-erc:1,2")
(eci-cop-add (format "-epp:%f" (min right 100)))
(incf right step))))
(eci-start)))
;;; User commands
(defun lilysong-arg->multi (arg)
(cond
((not arg)
nil)
((or
(numberp arg)
(equal arg '(4)))
t)
(t
'all)))
(defun lilysong-command (arg play-midi?)
(let* ((multi (lilysong-arg->multi arg))
(song-list (lilysong-song-list multi))
(midi-list (if play-midi? (lilysong-midi-list multi))))
(message "Singing %s" (mapconcat 'identity song-list ", "))
(lilysong-sing song-list midi-list (if play-midi? t (listp arg)))))
(defun LilyPond-command-sing (&optional arg)
"Sing lyrics of the current LilyPond buffer.
Without any prefix argument, sing current \\festival* command.
With the universal prefix argument, ask which parts to sing.
With a double universal prefix argument, sing all the parts.
With a numeric prefix argument, ask which parts to sing and sing them
sequentially rather than in parallel."
(interactive "P")
(lilysong-command arg nil))
(defun LilyPond-command-sing-and-play (&optional arg)
"Sing lyrics and play midi of the current LilyPond buffer.
Without any prefix argument, sing and play current \\festival* and \\midi
commands.
With the universal prefix argument, ask which parts to sing and play.
With a double universal prefix argument, sing and play all the parts."
(interactive "P")
(lilysong-command arg t))
(defun LilyPond-command-sing-last ()
"Repeat last LilyPond singing command."
(interactive)
(if lilysong-last-command-args
(apply 'lilysong-sing lilysong-last-command-args)
(error "No previous singing command")))
(defun LilyPond-command-clean ()
"Remove generated *.xml and *.wav files used for singing."
(interactive)
(flet ((delete-file* (file)
(when (file-exists-p file)
(delete-file file))))
(dolist (xml-file (lilysong-song-list 'all))
(delete-file* xml-file)
(delete-file* (lilysong-file->wav xml-file)))
(mapc 'delete-file* (mapcar 'lilysong-file->wav (lilysong-midi-list 'all)))))
(define-key LilyPond-mode-map "\C-c\C-a" 'LilyPond-command-sing)
(define-key LilyPond-mode-map "\C-c\C-q" 'LilyPond-command-sing-and-play)
(define-key LilyPond-mode-map "\C-c\C-x" 'LilyPond-command-clean)
(define-key LilyPond-mode-map "\C-c\C-z" 'LilyPond-command-sing-last)
(easy-menu-add-item LilyPond-command-menu nil
["Sing Current" LilyPond-command-sing t])
(easy-menu-add-item LilyPond-command-menu nil
["Sing Selected" (LilyPond-command-sing '(4)) t])
(easy-menu-add-item LilyPond-command-menu nil
["Sing All" (LilyPond-command-sing '(16)) t])
(easy-menu-add-item LilyPond-command-menu nil
["Sing Selected Sequentially" (LilyPond-command-sing 1) t])
(easy-menu-add-item LilyPond-command-menu nil
["Sing and Play Current" LilyPond-command-sing-and-play t])
(easy-menu-add-item LilyPond-command-menu nil
["Sing and Play Selected" (LilyPond-command-sing-and-play '(4)) t])
(easy-menu-add-item LilyPond-command-menu nil
["Sing and Play All" (LilyPond-command-sing-and-play '(16)) t])
(easy-menu-add-item LilyPond-command-menu nil
["Sing Last" LilyPond-command-sing-last t])
;;; Announce
(provide 'lilypond-song)
;;; lilypond-song.el ends here

View File

@@ -0,0 +1,260 @@
; Features:
;
; -> Counts number of notes between last | and point. Adds durations of
; each note up, and returns result.
;
; -> Works well on notes and chords.
;
; -> Ignores most keywords, like \override
;
; -> Is aware of certain keywords which often contain parameters that
; look like notes, but should not be counted.
; | a \key b \minor c % b is not counted, but a and c are.
;
; -> Ignores Scheme expressions, which start with #
;
; -> Doesn't ignore the \times keyword. Intelligently handles triplets.
;
;
; Caveats:
;
; -> Doesn't work on regions that aren't preceded by a |. This is because such
; notes are only delimited by a {, and what-beat can't distinguish a { that
; opens a set of notes from an internal { (say from a triplet)
;
; -> Doesn't work with << >> expressions or nested {} expressions (unless
; {} is part of a keyword like \times)
;
; -> Keywords abutted against a note are not visible to what-beat, and
; can therefore surreptitiosly sneak fake notes into what-beat.
; | c\glissando f <- BAD: the f gets counted, but shouldn't
; | c \glissando f <- GOOD: the f gets ignored
;
; -> Does not look outside notes context. Derivation rules don't work:
; str = \notes { a8 b c d }
; \score { \notes { | e4 %{ gets counted }% \str %{gets ignored}%
;
; -> Does not handle repeats.
;
; -> Ignores \bar commands (and does not get confused by a | inside a \bar)
;
; Recognizes pitch & octave
(setq pitch-regex "\\([a-z]+[,']*\\|<[^>]*>\\)\\(=[,']*\\)?")
; Recognizes duration
(setq duration-regex "[ \t\n]*\\(\\(\\(128\\|6?4\\|3?2\\|16?\\|8\\)\\([.]*\\)\\)\\([ \t]*[*][ \t]*\\([0-9]+\\)\\(/\\([1-9][0-9]*\\)\\)?\\)?\\)")
; These keywords precede notes that should not be counted during beats
(setq Parm-Keywords '("key" "clef" "appoggiatura" "acciaccatura" "grace"
"override" "revert" "glissando"))
(defun extract-match (string match-num)
(if (null (match-beginning match-num))
nil
(substring string (match-beginning match-num) (match-end match-num))))
(defun add-fractions (f1 f2)
"Adds two fractions, both are (numerator denominator)"
(setq result (list (+ (* (car f1) (cadr f2)) (* (car f2) (cadr f1)))
(* (cadr f1) (cadr f2))))
(setq result (reduce-fraction result 2))
(setq result (reduce-fraction result 3))
(setq result (reduce-fraction result 5))
(setq result (reduce-fraction result 7))
)
(defun reduce-fraction (f divisor)
"Eliminates divisor from fraction if present"
(while (and (= 0 (% (car result) divisor))
(= 0 (% (cadr result) divisor))
(< 1 (cadr result))
(< 0 (car result)))
(setq result (list (/ (car result) divisor) (/ (cadr result) divisor))))
result
)
(defun parse-duration (duration)
"Returns a duration string parsed as '(numerator denominator)"
(string-match duration-regex duration)
(let ((result (list 1 (string-to-number (extract-match duration 2))))
(dots (extract-match duration 4))
(numerator (or (extract-match duration 6) "1"))
(denominator (or (extract-match duration 8) "1")))
(if (and (not (null dots)) (< 0 (string-width dots)))
(dotimes (dummy (string-width dots))
(setq result (list (1+ (* 2 (car result))) (* 2 (cadr result))))))
(list (* (string-to-number numerator) (car result))
(* (string-to-number denominator) (cadr result)))
))
(defun walk-note-duration ()
"Returns duration of next note, moving point past note.
If point is not before a note, returns nil
If next note has no duration, returns t"
(let ((have-pitch (looking-at pitch-regex)))
(if have-pitch (goto-char (match-end 0)))
(if (not (looking-at duration-regex))
have-pitch
(goto-char (match-end 0))
(parse-duration (match-string 0)))))
; returns nil if not at a comment
(defun skip-comment ()
(if (not (char-equal ?\% (following-char)))
nil
(progn
(forward-char)
(if (char-equal ?\{ (following-char))
(re-search-forward "}%" nil t)
(progn
(skip-chars-forward "^\n")
(forward-char)))
t
)))
; returns nil if not at a quotation
(defun skip-quotation ()
(if (not (char-equal ?\" (following-char)))
nil
(progn
(forward-char)
(skip-chars-forward "^\"")
(forward-char)
t
)))
; returns nil if not at a sexp
(defun skip-sexp ()
(interactive)
(if (not (char-equal ?\# (following-char)))
nil
(progn
(forward-char)
(if (char-equal ?\' (following-char))
(forward-char))
(if (not (char-equal ?\( (following-char)))
(skip-chars-forward "^ \t\n")
(progn
(let ((paren 1))
(while (< 0 paren)
(forward-char)
(cond ((char-equal ?\( (following-char))
(setq paren (1+ paren)))
((char-equal ?\) (following-char))
(setq paren (1- paren)))))
(forward-char)
t
))))))
(defun goto-note-begin ()
(interactive)
; skip anything that is not ws. And skip any comments or quotations
(while (or (< 0 (skip-chars-forward "^ \t\n~%#\""))
(skip-comment)
(skip-quotation)
(skip-sexp)))
; Now skip anything that isn't alphanum or \. And skip comments or quotations
(while (or (< 0 (skip-chars-forward "^A-Za-z1-9<%}#=\""))
(skip-comment)
(skip-quotation)
(skip-sexp)))
; (skip-chars-forward "^\\") Why doesn't this work?!!
(if (char-equal ?\\ (preceding-char))
(backward-char))
)
(defun skip-good-keywords ()
(if (looking-at "\\\\\\([a-z]*\\)")
(progn
(goto-char (match-end 0))
(if (member (match-string 1) Parm-Keywords)
(progn
(if (looking-at "[ \t\n]*?\\([a-z0-9_]+\\|{[^}]*}\\|\"[^\"]*\"\\)")
(goto-char (match-end 0))
(error "Improper regex match:")
(error "Unknown text: %s")
))))))
(defun find-measure-start ()
(let ((start (re-search-backward "\|" 0 t)))
(if (null start)
-1
(if (looking-at "[^ \n\t]*\"")
(find-measure-start)
(point)
))))
(defun get-beat ()
(save-excursion
(save-restriction
(let* ((end (point))
(measure-start (find-measure-start))
(last-dur (or (re-search-backward duration-regex 0 t) -1))
(duration (if (= -1 last-dur) 0 (parse-duration (match-string 0))))
(result '(0 1))) ; 0 in fraction form
(if (= measure-start -1)
(message "No | before point")
(goto-char (1+ measure-start))
(goto-note-begin)
(while (< (point) end)
(let ((new-duration (walk-note-duration)))
(if (null new-duration)
(if (not (looking-at
(concat "\\\\t\\(?:\\(imes\\)\\|uplet\\)[ \t]*\\([0-9]+\\)/\\([0-9]+\\)\\(?:[ \t\n]"
duration-regex "\\)?[ \t\n]*{")))
(skip-good-keywords)
; handle \times/\tuplet specially
(let* ((times-p (match-beginning 1))
(numerator (string-to-number (match-string (if times-p 2 3))))
(denominator (string-to-number (match-string (if times-p 3 2)))))
(goto-char (match-end 0))
(goto-note-begin)
(while (and (not (looking-at "}"))
(< (point) end))
(setq new-duration (walk-note-duration))
(if (null new-duration)
(if (looking-at "\\\\[a-z]*[ \t]*[a-z]*")
(goto-char (match-end 0))
(error "Unknown text: %S %s" result(buffer-substring (point) end))))
(if (not (eq new-duration t))
(setq duration new-duration))
(setq result (add-fractions result
(list (* numerator (car duration))
(* denominator (cadr duration)))))
(goto-note-begin))
(if (< (point) end)
(forward-char 1)))) ; skip }
(if (not (eq new-duration t))
(setq duration new-duration))
(setq result (add-fractions result duration)))
(goto-note-begin)))
result)))))
(defun LilyPond-what-beat ()
"Returns how much of a measure lies between last measaure '|' and point.
Recognizes chords, and triples."
(interactive)
(let ((beat (get-beat)))
(message "Beat: %d/%d" (car beat) (cadr beat)))
)
(defun LilyPond-electric-bar ()
"Indicate the number of beats in last measure when a | is inserted"
(interactive)
(self-insert-command 1)
(save-excursion
(save-restriction
(backward-char)
(LilyPond-what-beat)
(forward-char)
)))

File diff suppressed because it is too large Load Diff