1 @c -*- coding: utf-8; mode: texinfo; -*-
4 Translation of GIT committish: FILL-IN-HEAD-COMMITTISH
6 When revising a translation, copy the HEAD committish of the
7 version that you are working on. For details, see the Contributors'
8 Guide, node Updating translation committishes..
14 @chapter Scheme tutorial
18 @cindex Scheme, in-line code
19 @cindex accessing Scheme
20 @cindex evaluating Scheme
23 LilyPond uses the Scheme programming language, both as part of the
24 input syntax, and as internal mechanism to glue modules of the program
25 together. This section is a very brief overview of entering data in
26 Scheme. If you want to know more about Scheme, see
27 @uref{http://@/www@/.schemers@/.org}.
29 LilyPond uses the GNU Guile implementation of Scheme, which is
30 based on the Scheme @qq{R5RS} standard. If you are learning Scheme
31 to use with LilyPond, working with a different implementation (or
32 referring to a different standard) is not recommended. Information
33 on guile can be found at @uref{http://www.gnu.org/software/guile/}.
34 The @qq{R5RS} Scheme standard is located at
35 @uref{http://www.schemers.org/Documents/Standards/R5RS/}.
38 * Introduction to Scheme::
39 * Scheme in LilyPond::
40 * Building complicated functions::
43 @node Introduction to Scheme
44 @section Introduction to Scheme
46 We begin with an introduction to Scheme. For this brief introduction,
47 we will use the GUILE interpreter to explore how the language works.
48 Once we are familiar with Scheme, we will show how the language can
49 be integrated in LilyPond files.
55 * Scheme simple data types::
56 * Scheme compound data types::
57 * Calculations in Scheme::
59 * Scheme conditionals::
63 @subsection Scheme sandbox
65 The LilyPond installation includes the Guile implementation of
66 Scheme. On most systems you can experiment in a Scheme sandbox by
67 opening a terminal window and typing @q{guile}. On some systems,
68 notably Windows, you may need to set the environment variable
69 @code{GUILE_LOAD_PATH} to the directory @code{../usr/share/guile/1.8}
70 in the LilyPond installation. For the full path to this directory
71 see @rlearning{Other sources of information}. Alternatively, Windows
72 users may simply choose @q{Run} from the Start menu and enter
75 However, a hands-on Scheme sandbox with all of Lilypond loaded is
76 available with this command line:
78 lilypond scheme-sandbox
82 Once the sandbox is running, you will receive a guile prompt:
88 You can enter Scheme expressions at this prompt to experiment with
89 Scheme. If you want to be able to use the GNU readline library for
90 nicer editing of the Scheme command line, check the file
91 @file{ly/scheme-sandbox.ly} for more information. If you already have
92 enabled the readline library for your interactive Guile sessions outside
93 of LilyPond, this should work in the sandbox as well.
95 @node Scheme variables
96 @subsection Scheme variables
98 Scheme variables can have any valid scheme value, including a Scheme
101 Scheme variables are created with @code{define}:
108 Scheme variables can be evaluated at the guile prompt simply by
109 typing the variable name:
117 Scheme variables can be printed on the display by using the display function:
125 Note that both the value @code{2} and the guile prompt @code{guile}
126 showed up on the same line. This can be avoided by calling the
127 newline procedure or displaying a newline character.
130 guile> (display a)(newline)
132 guile> (display a)(display "\n")
137 Once a variable has been created, its value can be changed with @code{set!}:
140 guile> (set! a 12345)
146 @node Scheme simple data types
147 @subsection Scheme simple data types
149 The most basic concept in a language is data typing: numbers, character
150 strings, lists, etc. Here is a list of simple Scheme data types that are
151 often used with LilyPond.
155 Boolean values are True or False. The Scheme for True is @code{#t}
156 and False is @code{#f}.
161 Numbers are entered in the standard fashion,
162 @code{1} is the (integer) number one, while @w{@code{-1.5}} is a
163 floating point number (a non-integer number).
166 Strings are enclosed in double quotes:
172 Strings may span several lines:
181 and the newline characters at the end of each line will be included
184 Newline characters can also be added by including @code{\n} in the
188 "this\nis a\nmultiline string"
192 Quotation marks and backslashes are added to strings
193 by preceding them with a backslash.
194 The string @code{\a said "b"} is entered as
202 There are additional Scheme data types that are not discussed here.
203 For a complete listing see the Guile reference guide,
204 @uref{http://www.gnu.org/software/guile/manual/html_node/Simple-Data-Types.html}.
206 @node Scheme compound data types
207 @subsection Scheme compound data types
209 There are also compound data types in Scheme. The types commonly used in
210 LilyPond programming include pairs, lists, alists, and hash tables.
214 The foundational compound data type of Scheme is the @code{pair}. As
215 might be expected from its name, a pair is two values glued together.
216 The operator used to form a pair is called @code{cons}.
224 Note that the pair is displayed as two items surrounded by
225 parentheses and separated by whitespace, a period (@code{.}), and
226 more whitespace. The period is @emph{not} a decimal point, but
227 rather an indicator of the pair.
229 Pairs can also be entered as literal values by preceding them with
230 a single quote character.
238 The two elements of a pair may be any valid Scheme value:
243 guile> '("blah-blah" . 3.1415926535)
244 ("blah-blah" . 3.1415926535)
248 The first and second elements of the pair can be accessed by the
249 Scheme procedures @code{car} and @code{cdr}, respectively.
252 guile> (define mypair (cons 123 "hello there")
263 Note: @code{cdr} is pronounced "could-er", according Sussman and
265 @uref{http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html#footnote_Temp_133}
269 A very common Scheme data structure is the @emph{list}. Formally, a
270 list is defined as either the empty list (represented as @code{'()},
271 or a pair whose @code{cdr} is a list.
273 There are many ways of creating lists. Perhaps the most common is
274 with the @code{list} procedure:
277 guile> (list 1 2 3 "abc" 17.5)
281 As can be seen, a list is displayed in the form of individual elements
282 separated by whitespace and enclosed in parentheses. Unlike a pair,
283 there is no period between the elements.
285 A list can also be entered as a literal list by enclosing its
286 elements in parentheses, and adding a quote:
289 guile> '(17 23 "foo" "bar" "bazzle")
290 (17 23 "foo" "bar" "bazzle")
293 Lists are a central part of Scheme. In, fact, Scheme is considered
294 a dialect of lisp, where @q{lisp} is an abbreviation for
295 @q{List Processing}. Scheme expressions are all lists.
297 @subheading Association lists (alists)
299 A special type of list is an @emph{association list} or @emph{alist}.
300 An alist is used to store data for easy retrieval.
302 Alists are lists whose elements are pairs. The @code{car} of each
303 element is called the @emph{key}, and the @code{cdr} of each element
304 is called the @emph{value}. The Scheme procedure @code{assoc} is
305 used to retrieve an entry from the alist, and @code{cdr} is used to
309 guile> (define my-alist '((1 . "A") (2 . "B") (3 . "C")))
311 ((1 . "A") (2 . "B") (3 . "C"))
312 guile> (assoc 2 my-alist)
314 guile> (cdr (assoc 2 my-alist))
319 Alists are widely used in LilyPond to store properties and other data.
321 @subheading Hash tables
323 A data structure that is used occasionally in LilyPond. A hash table
324 is similar to an array, but the indexes to the array can be any type
325 of Scheme value, not just integers.
327 Hash tables are more efficient than alists if there is a lot of data
328 to store and the data changes very infrequently.
330 The syntax to create hash tables is a bit complex, but you
331 can see examples of it in the LilyPond source.
334 guile> (define h (make-hash-table 10))
337 guile> (hashq-set! h 'key1 "val1")
339 guile> (hashq-set! h 'key2 "val2")
341 guile> (hashq-set! h 3 "val3")
345 Values are retrieved from hash tables with @code{hashq-ref}.
348 guile> (hashq-ref h 3)
350 guile> (hashq-ref h 'key2)
355 Keys and values are retrieved as a pair with @code{hashq-get-handle}.
356 This is a preferred way, because it will return @code{#f} if a key is
360 guile> (hashq-get-handle h 'key1)
362 guile> (hashq-get-handle h 'frob)
367 @node Calculations in Scheme
368 @subsection Calculations in Scheme
371 We have been using lists all along. A calculation, like @code{(+ 1 2)}
372 is also a list (containing the symbol @code{+} and the numbers 1
373 and@tie{}2). Normally lists are interpreted as calculations, and the
374 Scheme interpreter substitutes the outcome of the calculation. To enter a
375 list, we stop the evaluation. This is done by quoting the list with a
376 quote @code{'} symbol. So, for calculations do not use a quote.
378 Inside a quoted list or pair, there is no need to quote anymore. The
379 following is a pair of symbols, a list of symbols and a list of lists
384 #'(staff clef key-signature)
389 Scheme can be used to do calculations. It uses @emph{prefix}
390 syntax. Adding 1 and@tie{}2 is written as @code{(+ 1 2)} rather than the
391 traditional @math{1+2}.
398 Calculations may be nested; the result of a function may
399 be used for another calculation.
406 These calculations are examples of evaluations; an expression like
407 @code{(* 3 4)} is replaced by its value @code{12}.
409 Scheme calculations are sensitive to the differences between integers
410 and non-integers. Integer calculations are exact, while non-integers
411 are calculated to the appropriate limits of precision:
420 When the scheme interpreter encounters an expression that is a list,
421 the first element of the list is treated as a procedure to be
422 evaluated with the arguments of the remainder of the list. Therefore,
423 all operators in Scheme are prefix operators.
425 If the first element of a Scheme expression that is a list passed to
426 the interpreter is @emph{not} an operator or procedure, an error will
436 <unnamed port>:52:1: In expression (1 2 3):
437 <unnamed port>:52:1: Wrong type to apply: 1
442 Here you can see that the interpreter was trying to treat 1 as an
443 operator or procedure, and it couldn't. Hence the error is "Wrong
446 Therefore, to create a list we need to use the list operator, or to
447 quote the list so that the interpreter will not try to evaluate it.
457 This is an error that can appear as you are working with Scheme in LilyPond.
460 The same assignment can be done in completely in Scheme as well,
463 #(define twentyFour (* 2 twelve))
466 @c this next section is confusing -- need to rewrite
468 The @emph{name} of a variable is also an expression, similar to a
469 number or a string. It is entered as
476 @cindex quoting in Scheme
478 The quote mark @code{'} prevents the Scheme interpreter from substituting
479 @code{24} for the @code{twentyFour}. Instead, we get the name
484 @node Scheme procedures
485 @subsection Scheme procedures
487 Scheme procedures are executable scheme expressions that return a
488 value resulting from their execution. They can also manipulate
489 variables defined outside of the procedure.
491 @subheading Defining procedures
493 Procedures are defined in Scheme with define
496 (define (function-name arg1 arg2 ... argn)
497 scheme-expression-that-gives-a-return-value)
500 For example, we could define a procedure to calculate the average:
503 guile> (define (average x y) (/ (+ x y) 2))
505 #<procedure average (x y)>
508 Once a procedure is defined, it is called by putting the procedure
509 name and the arguments in a list. For example, we can calculate
510 the average of 3 and 12:
513 guile> (average 3 12)
517 @subheading Predicates
519 Scheme procedures that return boolean values are often called
520 @emph{predicates}. By convention (but not necessity), predicate names
521 typically end in a question mark:
524 guile> (define (less-than-ten? x) (< x 10))
525 guile> (less-than-ten? 9)
527 guile> (less-than-ten? 15)
531 @subheading Return values
533 Scheme procedures always return a return value, which is the value
534 of the last expression executed in the procedure. The return
535 value can be any valid Scheme value, including a complex data
536 structure or a procedure.
538 Sometimes the user would like to have multiple Scheme expressions in
539 a procedure. There are two ways that multiple expressions can be
540 combined. The first is the @code{begin} procedure, which allows
541 multiple expressions to be evaluated, and returns the value of
545 guile> (begin (+ 1 2) (- 5 8) (* 2 2))
549 The second way to combine multiple expressions is in a @code{let} block.
550 In a let block, a series of bindings are created, and then a sequence
551 of expressions that can include those bindings is evaluated. The
552 return value of the let block is the return value of the last
553 statement in the let block:
556 guile> (let ((x 2) (y 3) (z 4)) (display (+ x y)) (display (- z 4))
557 ... (+ (* x y) (/ z x)))
561 @node Scheme conditionals
562 @subsection Scheme conditionals
566 Scheme has an @code{if} procedure:
569 (if test-expression true-expression false-expression)
572 @var{test-expression} is an expression that returns a boolean
573 value. If @var{test-expression} returns @code{#t}, the if
574 procedure returns the value of @var{true-expression}, otherwise
575 it returns the value of @var{false-expression}.
580 guile> (if (> a b) "a is greater than b" "a is not greater than b")
581 "a is not greater than b"
586 Another conditional procedure in scheme is @code{cond}:
589 (cond (test-expression-1 result-expression-sequence-1)
590 (test-expression-2 result-expression-sequence-2)
592 (test-expression-n result-expression-sequence-n))
600 guile> (cond ((< a b) "a is less than b")
601 ... ((= a b) "a equals b")
602 ... ((> a b) "a is greater than b"))
606 @node Scheme in LilyPond
607 @section Scheme in LilyPond
611 * LilyPond Scheme syntax::
612 * LilyPond variables::
613 * Input variables and Scheme::
614 * Object properties::
615 * LilyPond compound variables::
616 * Internal music representation::
619 @node LilyPond Scheme syntax
620 @subsection LilyPond Scheme syntax
624 The Guile interpreter is part of LilyPond, which means that
625 Scheme can be included in LilyPond input files. There are several
626 methods for including Scheme in LilyPond.
628 The simplest way is to use a hash mark@tie{}@code{#} before a Scheme
631 Now LilyPond's input is structured into tokens and expressions, much
632 like human language is structured into words and sentences. LilyPond
633 has a lexer that recognizes tokens (literal numbers, strings, Scheme
634 elements, pitches and so on), and a parser that understands the syntax,
635 @ruser{LilyPond grammar}. Once it knows that a particular syntax rule
636 applies, it executes actions associated with it.
638 The hash mark@tie{}@code{#} method of embedding Scheme is a natural fit
639 for this system. Once the lexer sees a hash mark, it calls the Scheme
640 reader to read one full Scheme expression (this can be an identifier, an
641 expression enclosed in parentheses, or several other things). After the
642 Scheme expression is read, it is stored away as the value for an
643 @code{SCM_TOKEN} in the grammar. Once the parser knows how to make use
644 of this token, it calls Guile for evaluating the Scheme expression.
645 Since the parser usually requires a bit of lookahead from the lexer to
646 make its parsing decisions, this separation of reading and evaluation
647 between lexer and parser is exactly what is needed to keep the execution
648 of LilyPond and Scheme expressions in sync. For this reason, you should
649 use the hash mark@tie{}@code{#} for calling Scheme whenever this is
652 Another way to call the Scheme interpreter from LilyPond is the use of
653 dollar@tie{}@code{$} instead of a hash mark for introducing Scheme
654 expressions. In this case, Lilypond evaluates the code right after the
655 lexer has read it. It checks the resulting type of the Scheme
656 expression and then picks a token type (one of several
657 @code{xxx_IDENTIFIER} in the syntax) for it. It creates a @emph{copy}
658 of the value and uses that for the value of the token. If the value of
659 the expression is void (Guile's value of @code{*unspecified*}), nothing
660 at all is passed to the parser.
662 This is, in fact, exactly the same mechanism that Lilypond employs when
663 you call any variable or music function by name, as @code{\name}, with
664 the only difference that its end is determined by the Lilypond lexer
665 without consulting the Scheme reader, and thus only variable names
666 consistent with the current Lilypond mode are accepted.
668 The immediate action of @code{$} can lead to surprises, @ref{Input
669 variables and Scheme}. Using @code{#} where the parser supports it is
672 Now let's take a look at some actual Scheme code. Scheme procedures can
673 be defined in LilyPond input files:
676 #(define (average a b c) (/ (+ a b c) 3))
679 Note that LilyPond comments (@code{%} and @code{%@{ %@}}) cannot
680 be used within Scheme code, even in a LilyPond input file, because
681 the Guile interpreter, not the LilyPond lexer, is reading
682 the Scheme expression. Comments in Guile Scheme are entered
686 ; this is a single-line comment
689 This a (non-nestable) Guile-style block comment
690 But these are rarely used by Schemers and never in
695 For the rest of this section, we will assume that the data is entered
696 in a music file, so we add@tie{}@code{#}s at the beginning of each Scheme
699 All of the top-level Scheme expressions in a LilyPond input file can
700 be combined into a single Scheme expression by the use of the
701 @code{begin} statement:
710 @node LilyPond variables
711 @subsection LilyPond variables
713 LilyPond variables are stored internally in the form of Scheme
727 This means that LilyPond variables are available
728 for use in Scheme expressions. For example, we could use
731 twentyFour = #(* 2 twelve)
735 which would result in the number 24 being stored in the
736 LilyPond (and Scheme) variable @code{twentyFour}.
738 The usual way to refer to Lilypond variables, @ref{LilyPond Scheme
739 syntax}, is to call them using a backslash, i.e., @code{\twentyFour}.
740 Since this creates a copy of the value for most of LilyPond's internal
741 types, in particular music expressions, music functions don't usually
742 create copies of material they change. For this reason, music
743 expressions given with @code{#} should usually not contain material that
744 is not either created from scratch or explicitly copied rather than
747 @node Input variables and Scheme
748 @subsection Input variables and Scheme
750 The input format supports the notion of variables: in the following
751 example, a music expression is assigned to a variable with the name
755 traLaLa = @{ c'4 d'4 @}
760 There is also a form of scoping: in the following example, the
761 @code{\layout} block also contains a @code{traLaLa} variable, which is
762 independent of the outer @code{\traLaLa}.
765 traLaLa = @{ c'4 d'4 @}
766 \layout @{ traLaLa = 1.0 @}
770 In effect, each input file is a scope, and all @code{\header},
771 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
774 Both variables and scoping are implemented in the GUILE module system.
775 An anonymous Scheme module is attached to each scope. An assignment of
779 traLaLa = @{ c'4 d'4 @}
783 is internally converted to a Scheme definition:
786 (define traLaLa @var{Scheme value of `@code{... }'})
789 This means that LilyPond variables and Scheme variables may be freely
790 mixed. In the following example, a music fragment is stored in the
791 variable @code{traLaLa}, and duplicated using Scheme. The result is
792 imported in a @code{\score} block by means of a second variable
796 traLaLa = { c'4 d'4 }
798 #(define newLa (map ly:music-deep-copy
799 (list traLaLa traLaLa)))
801 (make-sequential-music newLa))
806 @c Due to parser lookahead
808 This is actually a rather interesting example. The assignment will only
809 take place after the parser has ascertained that nothing akin to
810 @code{\addlyrics} follows, so it needs to check what comes next. It
811 reads @code{#} and the following Scheme expression @emph{without}
812 evaluating it, so it can go ahead with the assignment, and
813 @emph{afterwards} execute the Scheme code without problem.
815 The above example shows how to @q{export} music expressions from the
816 input to the Scheme interpreter. The opposite is also possible. By
817 placing it after @code{$}, a Scheme
818 value is interpreted as if it were entered in LilyPond syntax.
819 Instead of defining @code{\twice}, the example above could also have
824 @{ $(make-sequential-music (list newLa)) @}
827 You can use @code{$} with a Scheme expression anywhere you could use
828 @code{\@var{name}} after having assigned the Scheme expression to a
829 variable @var{name}. This replacement happens in the @q{lexer}, so
830 Lilypond is not even aware of the difference.
832 One drawback, however, is that of timing. If we had been using @code{$}
833 instead of @code{#} for defining @code{newLa} in the above example, the
834 following Scheme definition would have failed because @code{traLaLa}
835 would not yet have been defined. For an explanation of this timing
836 problem, @ref{LilyPond Scheme syntax}.
838 In any case, evaluation of Scheme code happens in the parser at latest.
839 If you need it to be executed at a later point of time, @ref{Void scheme
840 functions}, or store it in a macro:
844 (ly:set-option 'point-and-click #f))
853 Mixing Scheme and LilyPond variables is not possible with the
854 @option{--safe} option.
857 @node Object properties
858 @subsection Object properties
860 Object properties are stored in LilyPond in the form of alist-chains,
861 which are lists of alists. Properties are set by adding values at
862 the beginning of the property list. Properties are read by retrieving
863 values from the alists.
865 Setting a new value for a property requires assigning a value to
866 the alist with both a key and a value. The LilyPond syntax for doing
870 \override Stem #'thickness = #2.6
873 This instruction adjusts the appearance of stems. An alist entry
874 @code{'(thickness . 2.6)} is added to the property list of the
876 object. @code{thickness} is measured relative to the thickness of
877 staff lines, so these stem lines will be @code{2.6} times the
878 width of staff lines. This makes stems almost twice as thick as their
879 normal size. To distinguish between variables defined in input files (like
880 @code{twentyFour} in the example above) and variables of internal
881 objects, we will call the latter @q{properties} and the former
882 @q{variables.} So, the stem object has a @code{thickness} property,
883 while @code{twentyFour} is a variable.
885 @cindex properties vs. variables
886 @cindex variables vs. properties
888 @c todo -- here we're getting interesting. We're now introducing
889 @c LilyPond variable types. I think this deserves a section all
892 @node LilyPond compound variables
893 @subsection LilyPond compound variables
897 Two-dimensional offsets (X and Y coordinates) are stored as @emph{pairs}.
898 The @code{car} of the offset is the X coordinate, and the @code{cdr} is
902 \override TextScript #'extra-offset = #'(1 . 2)
905 This assigns the pair @code{(1 . 2)} to the @code{extra-offset}
907 TextScript object. These numbers are measured in staff-spaces, so
908 this command moves the object 1 staff space to the right, and 2 spaces up.
910 Procedures for working with offsets are found in @file{scm/lily-library.scm}.
912 @subheading Fractions
914 Fractions as used by LilyPond are again stored as @emph{pairs}, this
915 time of unsigned integers. While Scheme can represent rational numbers
916 as a native type, musically @samp{2/4} and @samp{1/2} are not the same,
917 and we need to be able to distinguish between them. Similarly there are
918 no negative @q{fractions} in LilyPond's mind. So @code{2/4} in LilyPond
919 means @code{(2 . 4)} in Scheme, and @code{#2/4} in LilyPond means
920 @code{1/2} in Scheme.
924 Pairs are also used to store intervals, which represent a range of numbers
925 from the minimum (the @code{car}) to the maximum (the @code{cdr}).
926 Intervals are used to store the X- and Y- extents of printable objects.
927 For X extents, the @code{car} is the left hand X coordinate, and the
928 @code{cdr} is the right hand X coordinate. For Y extents, the @code{car}
929 is the bottom coordinate, and the @code{cdr} is the top coordinate.
931 Procedures for working with intervals are found in
932 @file{scm/lily-library.scm}. These procedures should be used when possible
933 to ensure consistency of code.
935 @subheading Property alists
937 A property alist is a LilyPond data structure that is an alist whose
938 keys are properties and whose values are Scheme expressions that give
939 the desired value for the property.
941 LilyPond properties are Scheme symbols, such as @code{'thickness}.
943 @subheading Alist chains
945 An alist chain is a list containing property alists.
947 The set of all properties that will apply to a grob is typically
948 stored as an alist chain. In order to find the value for a particular
949 property that a grob should have, each alist in the chain is searched in
950 order, looking for an entry containing the property key. The first alist
951 entry found is returned, and the value is the property value.
953 The Scheme procedure @code{chain-assoc-get} is normally used to get
954 grob property values.
956 @node Internal music representation
957 @subsection Internal music representation
959 Internally, music is represented as a Scheme list. The list contains
960 various elements that affect the printed output. Parsing is the process
961 of converting music from the LilyPond input representation to the
962 internal Scheme representation.
964 When a music expression is parsed, it is converted into a set of
965 Scheme music objects. The defining property of a music object is that
966 it takes up time. The time it takes up is called its @emph{duration}.
967 Durations are expressed as a rational number that measures the length
968 of the music object in whole notes.
970 A music object has three kinds of types:
973 music name: Each music expression has a name. For example, a note
974 leads to a @rinternals{NoteEvent}, and @code{\simultaneous} leads to
975 a @rinternals{SimultaneousMusic}. A list of all expressions
976 available is in the Internals Reference manual, under
977 @rinternals{Music expressions}.
980 @q{type} or interface: Each music name has several @q{types} or
981 interfaces, for example, a note is an @code{event}, but it is also a
982 @code{note-event}, a @code{rhythmic-event}, and a
983 @code{melodic-event}. All classes of music are listed in the
984 Internals Reference, under
985 @rinternals{Music classes}.
988 C++ object: Each music object is represented by an object of the C++
992 The actual information of a music expression is stored in properties.
993 For example, a @rinternals{NoteEvent} has @code{pitch} and
994 @code{duration} properties that store the pitch and duration of that
995 note. A list of all properties available can be found in the
996 Internals Reference, under @rinternals{Music properties}.
998 A compound music expression is a music object that contains other
999 music objects in its properties. A list of objects can be stored in
1000 the @code{elements} property of a music object, or a single @q{child}
1001 music object in the @code{element} property. For example,
1002 @rinternals{SequentialMusic} has its children in @code{elements},
1003 and @rinternals{GraceMusic} has its single argument in
1004 @code{element}. The body of a repeat is stored in the @code{element}
1005 property of @rinternals{RepeatedMusic}, and the alternatives in
1008 @node Building complicated functions
1009 @section Building complicated functions
1011 This section explains how to gather the information necessary
1012 to create complicated music functions.
1015 * Displaying music expressions::
1016 * Music properties::
1017 * Doubling a note with slurs (example)::
1018 * Adding articulation to notes (example)::
1021 @node Displaying music expressions
1022 @subsection Displaying music expressions
1024 @cindex internal storage
1025 @cindex displaying music expressions
1026 @cindex internal representation, displaying
1027 @cindex displayMusic
1028 @funindex \displayMusic
1030 When writing a music function it is often instructive to inspect how
1031 a music expression is stored internally. This can be done with the
1032 music function @code{\displayMusic}
1036 \displayMusic @{ c'4\f @}
1051 'AbsoluteDynamicEvent
1055 (ly:make-duration 2 0 1 1)
1057 (ly:make-pitch 0 0 0))))
1060 By default, LilyPond will print these messages to the console along
1061 with all the other messages. To split up these messages and save
1062 the results of @code{\display@{STUFF@}}, redirect the output to
1066 lilypond file.ly >display.txt
1069 With a combined bit of Lilypond and Scheme magic, you can actually
1070 let Lilypond direct just this output to a file of its own:
1074 $(with-output-to-file "display.txt"
1075 (lambda () #@{ \displayMusic @{ c'4\f @} #@}))
1080 A bit of reformatting makes the above information easier to read:
1083 (make-music 'SequentialMusic
1085 (make-music 'NoteEvent
1086 'articulations (list
1087 (make-music 'AbsoluteDynamicEvent
1090 'duration (ly:make-duration 2 0 1 1)
1091 'pitch (ly:make-pitch 0 0 0))))
1094 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
1095 and its inner expressions are stored as a list in its @code{'elements}
1096 property. A note is represented as a @code{NoteEvent} object (storing
1097 the duration and pitch properties) with attached information (in this
1098 case, an @code{AbsoluteDynamicEvent} with a @code{"f"} text property)
1099 stored in its @code{articulations} property.
1102 @code{\displayMusic} returns the music it displays, so it will get
1103 interpreted as well as displayed. To avoid interpretation, write
1104 @code{\void} before @code{\displayMusic}.
1106 @node Music properties
1107 @subsection Music properties
1109 TODO -- make sure we delineate between @emph{music} properties,
1110 @emph{context} properties, and @emph{layout} properties. These
1111 are potentially confusing.
1113 Let's look at an example:
1117 \displayMusic \someNote
1122 (ly:make-duration 2 0 1 1)
1124 (ly:make-pitch 0 0 0))
1127 The @code{NoteEvent} object is the representation of @code{someNote}.
1128 Straightforward. How about putting c' in a chord?
1132 \displayMusic \someNote
1140 (ly:make-duration 2 0 1 1)
1142 (ly:make-pitch 0 0 0))))
1145 Now the @code{NoteEvent} object is the first object of the
1146 @code{'elements} property of @code{someNote}.
1148 The @code{display-scheme-music} function is the function used by
1149 @code{\displayMusic} to display the Scheme representation of a music
1153 #(display-scheme-music (first (ly:music-property someNote 'elements)))
1158 (ly:make-duration 2 0 1 1)
1160 (ly:make-pitch 0 0 0))
1163 Then the note pitch is accessed through the @code{'pitch} property
1164 of the @code{NoteEvent} object,
1167 #(display-scheme-music
1168 (ly:music-property (first (ly:music-property someNote 'elements))
1171 (ly:make-pitch 0 0 0)
1174 The note pitch can be changed by setting this @code{'pitch} property,
1176 @funindex \displayLilyMusic
1179 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
1181 (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
1182 \displayLilyMusic \someNote
1188 @node Doubling a note with slurs (example)
1189 @subsection Doubling a note with slurs (example)
1191 Suppose we want to create a function that translates input like
1192 @code{a} into @code{@{ a( a) @}}. We begin by examining the internal
1193 representation of the desired result.
1196 \displayMusic@{ a'( a') @}
1209 (ly:make-duration 2 0 1 1)
1211 (ly:make-pitch 0 5 0))
1220 (ly:make-duration 2 0 1 1)
1222 (ly:make-pitch 0 5 0))))
1225 The bad news is that the @code{SlurEvent} expressions
1226 must be added @q{inside} the note (in its @code{articulations}
1229 Now we examine the input,
1237 (ly:make-duration 2 0 1 1)
1239 (ly:make-pitch 0 5 0))))
1242 So in our function, we need to clone this expression (so that we have
1243 two notes to build the sequence), add a @code{SlurEvent} to the
1244 @code{'articulations} property of each one, and finally make a
1245 @code{SequentialMusic} with the two @code{EventChords}. For adding to a
1246 property, it is useful to know that an unset property is read out as
1247 @code{'()}, the empty list, so no special checks are required before we
1248 put another element at the front of the @code{articulations} property.
1251 doubleSlur = #(define-music-function (parser location note) (ly:music?)
1252 "Return: @{ note ( note ) @}.
1253 `note' is supposed to be a single note."
1254 (let ((note2 (ly:music-deep-copy note)))
1255 (set! (ly:music-property note 'articulations)
1256 (cons (make-music 'SlurEvent 'span-direction -1)
1257 (ly:music-property note 'articulations)))
1258 (set! (ly:music-property note2 'articulations)
1259 (cons (make-music 'SlurEvent 'span-direction 1)
1260 (ly:music-property note2 'articulations)))
1261 (make-music 'SequentialMusic 'elements (list note note2))))
1265 @node Adding articulation to notes (example)
1266 @subsection Adding articulation to notes (example)
1268 The easy way to add articulation to notes is to merge two music
1269 expressions into one context, as explained in @ruser{Creating contexts}.
1270 However, suppose that we want to write a music function that does this.
1271 This will have the additional advantage that we can use that music
1272 function to add an articulation (like a fingering instruction) to a
1273 single note inside of a chord which is not possible if we just merge
1276 A @code{$variable} inside the @code{#@{...#@}} notation is like
1277 a regular @code{\variable} in classical LilyPond notation. We
1285 will not work in LilyPond. We could avoid this problem by attaching
1286 the articulation to a fake note,
1289 @{ << \music s1*0-.-> @}
1293 but for the sake of this example, we will learn how to do this in
1294 Scheme. We begin by examining our input and desired output,
1303 (ly:make-duration 2 0 1 1)
1305 (ly:make-pitch -1 0 0))))
1318 (ly:make-duration 2 0 1 1)
1320 (ly:make-pitch -1 0 0))
1323 We see that a note (@code{c4}) is represented as an @code{NoteEvent}
1324 expression. To add an accent articulation, an @code{ArticulationEvent}
1325 expression must be added to the @code{articulations} property of the
1326 @code{NoteEvent} expression.
1328 To build this function, we begin with
1331 (define (add-accent note-event)
1332 "Add an accent ArticulationEvent to the articulations of `note-event',
1333 which is supposed to be a NoteEvent expression."
1334 (set! (ly:music-property note-event 'articulations)
1335 (cons (make-music 'ArticulationEvent
1336 'articulation-type "accent")
1337 (ly:music-property note-event 'articulations)))
1341 The first line is the way to define a function in Scheme: the function
1342 name is @code{add-accent}, and has one variable called
1343 @code{note-event}. In Scheme, the type of variable is often clear
1344 from its name. (this is good practice in other programming languages,
1352 is a description of what the function does. This is not strictly
1353 necessary, but just like clear variable names, it is good practice.
1355 You may wonder why we modify the note event directly instead of working
1356 on a copy (@code{ly:music-deep-copy} can be used for that). The reason
1357 is a silent contract: music functions are allowed to modify their
1358 arguments: they are either generated from scratch (like user input) or
1359 are already copied (referencing a music variable with @samp{\name} or
1360 music from immediate Scheme expressions @samp{$(@dots{})} provides a
1361 copy). Since it would be inefficient to create unnecessary copies, the
1362 return value from a music function is @emph{not} copied. So to heed
1363 that contract, you must not use any arguments more than once, and
1364 returning it counts as one use.
1366 In an earlier example, we constructed music by repeating a given music
1367 argument. In that case, at least one repetition had to be a copy of its
1368 own. If it weren't, strange things may happen. For example, if you use
1369 @code{\relative} or @code{\transpose} on the resulting music containing
1370 the same elements multiple times, those will be subjected to
1371 relativation or transposition multiple times. If you assign them to a
1372 music variable, the curse is broken since referencing @samp{\name} will
1373 again create a copy which does not retain the identity of the repeated
1376 Now while the above function is not a music function, it will normally
1377 be used within music functions. So it makes sense to heed the same
1378 contract we use for music functions: the input may be modified for
1379 producing the output, and the caller is responsible for creating copies
1380 if it still needs the unchanged argument itself. If you take a look at
1381 LilyPond's own functions like @code{music-map}, you'll find that they
1382 stick with the same principles.
1384 Where were we? Now we have a @code{note-event} we may modify, not
1385 because of using @code{ly:music-deep-copy} but because of a long-winded
1386 explanation. We add the accent to its @code{'articulations} list
1390 (set! place new-value)
1393 Here, what we want to set (the @q{place}) is the @code{'articulations}
1394 property of @code{note-event} expression.
1397 (ly:music-property note-event 'articulations)
1400 @code{ly:music-property} is the function used to access music properties
1401 (the @code{'articulations}, @code{'duration}, @code{'pitch}, etc, that we
1402 see in the @code{\displayMusic} output above). The new value is the
1403 former @code{'articulations} property, with an extra item: the
1404 @code{ArticulationEvent} expression, which we copy from the
1405 @code{\displayMusic} output,
1408 (cons (make-music 'ArticulationEvent
1409 'articulation-type "accent")
1410 (ly:music-property result-event-chord 'articulations))
1413 @code{cons} is used to add an element to the front of a list without
1414 modifying the original list. This is what we want: the same list as
1415 before, plus the new @code{ArticulationEvent} expression. The order
1416 inside the @code{'articulations} property is not important here.
1418 Finally, once we have added the accent articulation to its
1419 @code{articulations} property, we can return @code{note-event}, hence
1420 the last line of the function.
1422 Now we transform the @code{add-accent} function into a music
1423 function (a matter of some syntactic sugar and a declaration of the type
1424 of its sole @q{real} argument).
1427 addAccent = #(define-music-function (parser location note-event)
1429 "Add an accent ArticulationEvent to the articulations of `note-event',
1430 which is supposed to be a NoteEvent expression."
1431 (set! (ly:music-property note-event 'articulations)
1432 (cons (make-music 'ArticulationEvent
1433 'articulation-type "accent")
1434 (ly:music-property note-event 'articulations)))
1438 We may verify that this music function works correctly,
1441 \displayMusic \addAccent c4
1450 * Tweaking with Scheme::
1453 @c @nod e Tweaking with Scheme
1454 @c @sectio n Tweaking with Scheme
1456 We have seen how LilyPond output can be heavily modified using
1458 @code{\override TextScript #'extra-offset = ( 1 . -1)}. But
1459 we have even more power if we use Scheme. For a full explanation
1460 of this, see the @ref{Scheme tutorial}, and
1461 @ref{Interfaces for programmers}.
1463 We can use Scheme to simply @code{\override} commands,
1465 TODO Find a simple example
1466 @c This isn't a valid example with skylining
1467 @c It works fine without padText -td
1471 @lilypond[quote,verbatim,ragged-right]
1472 padText = #(define-music-function (parser location padding) (number?)
1474 \once \override TextScript #'padding = #padding
1478 c4^"piu mosso" b a b
1480 c4^"piu mosso" d e f
1482 c4^"piu mosso" fis a g
1488 We can use it to create new commands:
1490 @c Check this is a valid example with skylining
1491 @c It is - 'padding still works
1494 @lilypond[quote,verbatim,ragged-right]
1495 tempoPadded = #(define-music-function (parser location padding tempotext)
1498 \once \override Score.MetronomeMark #'padding = $padding
1499 \tempo \markup { \bold #tempotext }
1503 \tempo \markup { "Low tempo" }
1505 \tempoPadded #4.0 #"High tempo"
1511 Even music expressions can be passed in:
1513 @lilypond[quote,verbatim,ragged-right]
1514 pattern = #(define-music-function (parser location x y) (ly:music? ly:music?)
1521 \pattern {d16 dis} { ais16-> b\p }