]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/extending/scheme-tutorial.itely
Fix compile.
[lilypond.git] / Documentation / extending / scheme-tutorial.itely
1 @c -*- coding: utf-8; mode: texinfo; -*-
2
3 @ignore
4     Translation of GIT committish: FILL-IN-HEAD-COMMITTISH
5
6     When revising a translation, copy the HEAD committish of the
7     version that you are working on.  See TRANSLATION for details.
8 @end ignore
9
10 @c \version "2.12.0"
11
12 @node Scheme tutorial
13 @chapter Scheme tutorial
14
15 @funindex #
16 @cindex Scheme
17 @cindex GUILE
18 @cindex Scheme, in-line code
19 @cindex accessing Scheme
20 @cindex evaluating Scheme
21 @cindex LISP
22
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}.
28
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/}.
36
37 @menu
38 * Introduction to Scheme::
39 * Scheme in LilyPond::
40 * Building complicated functions::
41 @end menu
42
43 @node Introduction to Scheme
44 @section Introduction to Scheme
45
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.
50
51
52 @menu
53 * Scheme sandbox::
54 * Scheme variables::
55 * Scheme simple data types::
56 * Scheme compound data types::
57 * Calculations in Scheme::
58 * Scheme procedures::
59 * Scheme conditionals::
60 @end menu
61
62 @node Scheme sandbox
63 @subsection Scheme sandbox
64
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/shr/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
73 @q{guile}.
74
75 Once the guile sandbox is running, you will received a guile prompt:
76
77 @lisp
78 guile>
79 @end lisp
80
81 You can enter Scheme expressions at this prompt to experiment with Scheme.
82
83 @node Scheme variables
84 @subsection Scheme variables
85
86 Scheme variables can have any valid scheme value, including a Scheme
87 procedure.
88
89 Scheme variables are created with @code{define}:
90
91 @lisp
92 guile> (define a 2)
93 guile>
94 @end lisp
95
96 Scheme variables can be evaluated at the guile prompt simply by
97 typing the variable name:
98
99 @lisp
100 guile> a
101 2
102 guile>
103 @end lisp
104
105 Scheme variables can be printed on the display by use of the display function:
106
107 @lisp
108 guile> (display a)
109 2guile>
110 @end lisp
111
112 @noindent
113 Note that the value @code{2} and the guile prompt @code{guile} both
114 showed up on the same line.  This can be avoided by calling the newline
115 procedure or displaying a newline character.
116
117 @lisp
118 guile> (display a)(newline)
119 2
120 guile> (display a)(display "\n")
121 2
122 guile>
123 @end lisp
124
125 Once a variable has been created, its value can be changed with @code{set!}:
126
127 @lisp
128 guile> (set! a 12345)
129 guile> a
130 12345
131 guile>
132 @end lisp
133
134 @node Scheme simple data types
135 @subsection Scheme simple data types
136
137 The most basic concept in a language is data typing: numbers, character
138 strings, lists, etc.  Here is a list of simple Scheme data types that are
139 often used with LilyPond.
140
141 @table @asis
142 @item Booleans
143 Boolean values are True or False.  The Scheme for True is @code{#t}
144 and False is @code{#f}.
145 @funindex ##t
146 @funindex ##f
147
148 @item Numbers
149 Numbers are entered in the standard fashion,
150 @code{1} is the (integer) number one, while @code{-1.5} is a
151 floating point number (a non-integer number).
152
153 @item Strings
154 Strings are enclosed in double quotes,
155
156 @example
157 "this is a string"
158 @end example
159
160 Strings may span several lines:
161
162 @example
163 "this
164 is
165 a string"
166 @end example
167
168 @noindent
169 and the newline characters at the end of each line will be included
170 in the string.
171
172 Newline characters can also be added by including @code{\n} in the
173 string.
174
175 @example
176 "this\nis a\nmultiline string"
177 @end example
178
179
180 Quotation marks and backslashes are added to strings
181 by preceding them with a backslash.
182 The string @code{\a said "b"} is entered as
183
184 @example
185 "\\a said \"b\""
186 @end example
187
188 @end table
189
190 There are additional Scheme data types that are not discussed here.
191 For a complete listing see the Guile reference guide,
192 @uref{http://www.gnu.org/software/guile/manual/html_node/Simple-Data-Types.html}.
193
194 @node Scheme compound data types
195 @subsection Scheme compound data types
196
197 There are also compound data types in Scheme.  The  types commonly used in
198 LilyPond programming include pairs, lists, alists, and hash tables.
199
200 @unnumberedsubsubsec Pairs
201
202 The foundational compound data type of Scheme is the @code{pair}.  As
203 might be expected from its name, a pair is two values glued together.
204 The operator used to form a pair is called @code{cons}.
205
206 @lisp
207 guile> (cons 4 5)
208 (4 . 5)
209 guile>
210 @end lisp
211
212 Note that the pair is displayed as two items surrounded by
213 parentheses and separated by whitespace, a period (@code{.}), and
214 more whitespace.  The period is @emph{not} a decimal point, but
215 rather an indicator of the pair.
216
217 Pairs can also be entered as literal values by preceding them with
218 a single quote character.
219
220 @lisp
221 guile> '(4 . 5)
222 (4 . 5)
223 guile>
224 @end lisp
225
226 The two elements of a pair may be any valid Scheme value:
227
228 @lisp
229 guile> (cons #t #f)
230 (#t . #f)
231 guile> '("blah-blah" . 3.1415926535)
232 ("blah-blah" . 3.1415926535)
233 guile>
234 @end lisp
235
236 The first and second elements of the pair can be accessed by the
237 Scheme procedures @code{car} and @code{cdr}, respectively.
238
239 @lisp
240 guile> (define mypair (cons 123 "hello there")
241 ... )
242 guile> (car mypair)
243 123
244 guile> (cdr mypair)
245 "hello there"
246 guile>
247 @end lisp
248
249 @noindent
250
251 Note:  @code{cdr} is pronounced "could-er", according Sussman and
252 Abelson, see
253 @uref{http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html#footnote_Temp_133}
254
255
256 @unnumberedsubsubsec Lists
257
258 A very common Scheme data structure is the @emph{list}.  Formally, a
259 list is defined as either the empty list (represented as @code{'()},
260 or a pair whose @code{cdr} is a list.
261
262 There are many ways of creating lists.  Perhaps the most common is
263 with the @code{list} procedure:
264
265 @lisp
266 guile> (list 1 2 3 "abc" 17.5)
267 (1 2 3 "abc" 17.5)
268 @end lisp
269
270 As can be seen, a list is displayed in the form of individual elements
271 separated by whitespace and enclosed in parentheses.  Unlike a pair,
272 there is no period between the elements.
273
274 A list can also be entered as a literal list by enclosing its
275 elements in parentheses, and adding a quote:
276
277 @lisp
278 guile> '(17 23 "foo" "bar" "bazzle")
279 (17 23 "foo" "bar" "bazzle")
280 @end lisp
281
282 Lists are a central part of Scheme.  In, fact, Scheme is considered
283 a dialect of lisp, where @q{lisp} is an abbreviation for
284 @q{List Processing}.  Scheme expressions are all lists.
285
286 @unnumberedsubsubsec Association lists (alists)
287
288 A special type of list is an @emph{association list} or @emph{alist}.
289 An alist is used to store data for easy retrieval.
290
291 Alists are lists whose elements are pairs.  The @code{car} of each
292 element is called the @emph{key}, and the @code{cdr} of each element
293 is called the @emph{value}.  The Scheme procedure @code{assoc} is
294 used to retrieve an entry from the alist, and @code{cdr} is used to
295 retrieve the value:
296
297 @lisp
298 guile> (define my-alist '((1  . "A") (2 . "B") (3 . "C")))
299 guile> my-alist
300 ((1 . "A") (2 . "B") (3 . "C"))
301 guile> (assoc 2 my-alist)
302 (2 . "B")
303 guile> (cdr (assoc 2 my-alist))
304 "B"
305 guile>
306 @end lisp
307
308 Alists are widely used in LilyPond to store properties and other data.
309
310 @unnumberedsubsubsec Hash tables
311
312 A data structure that is used occasionally in LilyPond.  A hash table
313 is similar to an array, but the indexes to the array can be any type
314 of Scheme value, not just integers.
315
316 Hash tables are more efficient than alists if there is a lot of data
317 to store and the data changes very infrequently.
318
319 The syntax to create hash tables is a bit complex, but you
320 can see examples of it in the LilyPond source.
321
322 @lisp
323 guile> (define h (make-hash-table 10))
324 guile> h
325 #<hash-table 0/31>
326 guile> (hashq-set! h 'key1 "val1")
327 "val1"
328 guile> (hashq-set! h 'key2 "val2")
329 "val2"
330 guile> (hashq-set! h 3 "val3")
331 "val3"
332 @end lisp
333
334 Values are retrieved from hash tables with @code{hashq-ref}.
335
336 @lisp
337 guile> (hashq-ref h 3)
338 "val3"
339 guile> (hashq-ref h 'key2)
340 "val2"
341 guile>
342 @end lisp
343
344 Keys and values are retrieved as a pair with @code{hashq-get-handle}.
345 This is a preferred way, because it will return @code{#f} if a key is
346 not found.
347
348 @lisp
349 guile> (hashq-get-handle h 'key1)
350 (key1 . "val1")
351 guile> (hashq-get-handle h 'frob)
352 #f
353 guile>
354 @end lisp
355
356 @node Calculations in Scheme
357 @subsection Calculations in Scheme
358
359 @ignore
360 We have been using lists all along.  A calculation, like @code{(+ 1 2)}
361 is also a list (containing the symbol @code{+} and the numbers 1
362 and@tie{}2).  Normally lists are interpreted as calculations, and the
363 Scheme interpreter substitutes the outcome of the calculation.  To enter a
364 list, we stop the evaluation.  This is done by quoting the list with a
365 quote @code{'} symbol.  So, for calculations do not use a quote.
366
367 Inside a quoted list or pair, there is no need to quote anymore.  The
368 following is a pair of symbols, a list of symbols and a list of lists
369 respectively,
370
371 @example
372 #'(stem . head)
373 #'(staff clef key-signature)
374 #'((1) (2))
375 @end example
376 @end ignore
377
378 Scheme can be used to do calculations.  It uses @emph{prefix}
379 syntax.  Adding 1 and@tie{}2 is written as @code{(+ 1 2)} rather than the
380 traditional @math{1+2}.
381
382 @lisp
383 guile> (+ 1 2)
384 3
385 @end lisp
386
387 Calculations may be nested; the result of a function may
388 be used for another calculation.
389
390 @lisp
391 guile> (+ 1 (* 3 4))
392 13
393 @end lisp
394
395 These calculations are examples of evaluations; an expression like
396 @code{(* 3 4)} is replaced by its value @code{12}.
397
398 Scheme calculations are sensitive to the differences between integers
399 and non-integers.  Integer calculations are exact, while non-integers
400 are calculated to the appropriate limits of precision:
401
402 @lisp
403 guile> (/ 7 3)
404 7/3
405 guile> (/ 7.0 3.0)
406 2.33333333333333
407 @end lisp
408
409 When the scheme interpreter encounters an expression that is a list, the
410 first element of the list is treated as a procedure to be evaluated
411 with the arguments of the remainder of the list.  Therefore, all operators
412 in Scheme are prefix operators.
413
414 If the first element of a Scheme expression that is a list passed to the
415 interpreter`is @emph{not} an operator or procedure, an error will occur:
416
417 @lisp
418 guile> (1 2 3)
419
420 Backtrace:
421 In current input:
422   52: 0* [1 2 3]
423
424 <unnamed port>:52:1: In expression (1 2 3):
425 <unnamed port>:52:1: Wrong type to apply: 1
426 ABORT: (misc-error)
427 guile>
428 @end lisp
429
430 Here you can see that the interpreter was trying to treat 1 as an operator
431 or procedure, and it couldn't.  Hence the error is "Wrong type to apply: 1".
432
433 To create a list, then , we need to use the list operator, or we need to
434 quote the list so that the interpreter will not try to evaluate it.
435
436 @lisp
437 guile> (list 1 2 3)
438 (1 2 3)
439 guile> '(1 2 3)
440 (1 2 3)
441 guile>
442 @end lisp
443
444 This is an error that can appear as you are working with Scheme in LilyPond.
445
446 @ignore
447 The same assignment can be done in completely in Scheme as well,
448
449 @example
450 #(define twentyFour (* 2 twelve))
451 @end example
452
453 @c this next section is confusing -- need to rewrite
454
455 The @emph{name} of a variable is also an expression, similar to a
456 number or a string.  It is entered as
457
458 @example
459 #'twentyFour
460 @end example
461
462 @funindex #'symbol
463 @cindex quoting in Scheme
464
465 The quote mark @code{'} prevents the Scheme interpreter from substituting
466 @code{24} for the @code{twentyFour}.  Instead, we get the name
467 @code{twentyFour}.
468 @end ignore
469
470
471 @node Scheme procedures
472 @subsection Scheme procedures
473
474 Scheme procedures are executable scheme expressions that return
475 a value resulting from their execution.,  They can also manipulate
476 variables defined outside of the procedure.
477
478 @unnumberedsubsubsec Defining procedures
479
480 Procedures are defined in Scheme with define
481
482 @example
483 (define (function-name arg1 arg2 ... argn)
484  scheme-expression-that-gives-a-return-value)
485 @end example
486
487 For example, we could define a procedure to calculate the average:
488
489 @lisp
490 guile> (define (average x y) (/ (+ x y) 2))
491 guile> average
492 #<procedure average (x y)>
493 @end lisp
494
495 Once a procedure is defined, it is called by putting the procedure
496 name and the arguments in a list.  For example, we can calculate
497 the average of 3 and 12:
498
499 @lisp
500 guile> (average 3 12)
501 15/2
502 @end lisp
503
504 @unnumberedsubsubsec Predicates
505
506 Scheme procedures that return boolean values are often called
507 @emph{predicates}.  By convention (but not necessity), predicate names
508 typically end in a question mark:
509
510 @lisp
511 guile> (define (less-than-ten? x) (< x 10))
512 guile> (less-than-ten? 9)
513 #t
514 guile> (less-than-ten? 15)
515 #f
516 @end lisp
517
518 @unnumberedsubsubsec Return values
519
520 Sometimes the user would like to have multiple Scheme expressions in
521 a procedure.  There are two ways that multiple expressions can be
522 combined.  The first is the @code{begin} procedure, which allows
523 multiple expressions to be evaluated, and returns the value of
524 the last expression.
525
526 @lisp
527 guile> (begin (+ 1 2) (- 5 8) (* 2 2))
528 4
529 @end lisp
530
531 The second way to combine multiple expressions is in a @code{let} block.
532 In a let block, a series of bindings are created, and then a sequence
533 of expressions that can include those bindings is evaluated.  The
534 return value of the let block is the return value of the last
535 statement in the let block:
536
537 @lisp
538 guile> (let ((x 2) (y 3) (z 4)) (display (+ x y)) (display (- z 4))
539 ... (+ (* x y) (/ z x)))
540 508
541 @end lisp
542
543 @node Scheme conditionals
544 @subsection Scheme conditionals
545
546 @unnumberedsubsubsec if
547
548 Scheme has an @code{if} procedure:
549
550 @example
551 (if test-expression true-expression false-expression)
552 @end example
553
554 @var{test-expression} is an expression that returns a boolean
555 value.  If @var{test-expression} returns @code{#t}, the if
556 procedure returns the value of @var{true-expression}, otherwise
557 it returns the value of @var{false-expression}.
558
559 @lisp
560 guile> (define a 3)
561 guile> (define b 5)
562 guile> (if (> a b) "a is greater than b" "a is not greater than b")
563 "a is not greater than b"
564 @end lisp
565
566 @unnumberedsubsubsec cond
567
568 Another conditional procedure in scheme is @code{cond}:
569
570 @example
571 (cond (test-expression-1 result-expression-sequence-1)
572       (test-expression-2 result-expression-sequence-2)
573       ...
574       (test-expression-n result-expression-sequence-n))
575 @end example
576
577 For example:
578
579 @lisp
580 guile> (define a 6)
581 guile> (define b 8)
582 guile> (cond ((< a b) "a is less than b")
583 ...          ((= a b) "a equals b")
584 ...          ((> a b) "a is greater than b"))
585 "a is less than b"
586 @end lisp
587
588 @node Scheme in LilyPond
589 @section Scheme in LilyPond
590
591
592 @menu
593 * LilyPond Scheme syntax::
594 * LilyPond variables::
595 * Input variables and Scheme::
596 * Object properties::
597 * LilyPond compound variables::
598 * Internal music representation::
599 @end menu
600
601 @node LilyPond Scheme syntax
602 @subsection LilyPond Scheme syntax
603
604 In a music file, snippets of Scheme code are introduced with the hash
605 mark @code{#}.  So, the previous examples translated to LilyPond are
606
607 @example
608 ##t ##f
609 #1 #-1.5
610 #"this is a string"
611 #"this
612 is
613 a string"
614 @end example
615
616 Note that LilyPond comments (@code{%} and @code{%@{ %@}}) cannot
617 be used within Scheme code.  Comments in Guile Scheme are entered
618 as follows:
619
620 @example
621 ; this is a single-line comment
622
623 #!
624   This a (non-nestable) Guile-style block comment
625   But these are rarely used by Schemers and never in
626   LilyPond source code
627 !#
628 @end example
629
630 Multiple consecutive scheme expressions in a music file can be
631 combined using the @code{begin} operator. This permits the number
632 of hash marks to be reduced to one.
633
634 @example
635 #(begin
636   (define foo 0)
637   (define bar 1))
638 @end example
639
640 @c todo -- # introduces a scheme *expression*
641 @c         need the concept of an expression
642
643 If @code{#} is followed by an opening parenthesis, @code{(}, as in
644 the example above, the parser will remain in Scheme mode until
645 a matching closing parenthesis, @code{)}, is found, so further
646 @code{#} symbols to introduce a Scheme section are not required.
647
648 For the rest of this section, we will assume that the data is entered
649 in a music file, so we add @code{#}s everywhere.
650
651 @node LilyPond variables
652 @subsection LilyPond variables
653
654
655 TODO -- make this read right
656
657 A similar thing
658 happens with variables.  After defining a variable
659
660 @example
661 twelve = 12
662 @end example
663
664 @noindent
665 variables can also be used in expressions, here
666
667 @example
668 twentyFour = (* 2 twelve)
669 @end example
670
671 @noindent
672 the number 24 is stored in the variable @code{twentyFour}.
673
674 @node Input variables and Scheme
675 @subsection Input variables and Scheme
676
677 The input format supports the notion of variables: in the following
678 example, a music expression is assigned to a variable with the name
679 @code{traLaLa}.
680
681 @example
682 traLaLa = @{ c'4 d'4 @}
683 @end example
684
685 @noindent
686
687 There is also a form of scoping: in the following example, the
688 @code{\layout} block also contains a @code{traLaLa} variable, which is
689 independent of the outer @code{\traLaLa}.
690 @example
691 traLaLa = @{ c'4 d'4 @}
692 \layout @{ traLaLa = 1.0 @}
693 @end example
694 @c
695 In effect, each input file is a scope, and all @code{\header},
696 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
697 toplevel scope.
698
699 Both variables and scoping are implemented in the GUILE module system.
700 An anonymous Scheme module is attached to each scope.  An assignment of
701 the form
702 @example
703 traLaLa = @{ c'4 d'4 @}
704 @end example
705
706 @noindent
707 is internally converted to a Scheme definition
708 @example
709 (define traLaLa @var{Scheme value of `@code{... }'})
710 @end example
711
712 This means that input variables and Scheme variables may be freely
713 mixed.  In the following example, a music fragment is stored in the
714 variable @code{traLaLa}, and duplicated using Scheme.  The result is
715 imported in a @code{\score} block by means of a second variable
716 @code{twice}:
717
718 @lilypond[verbatim]
719 traLaLa = { c'4 d'4 }
720
721 %% dummy action to deal with parser lookahead
722 #(display "this needs to be here, sorry!")
723
724 #(define newLa (map ly:music-deep-copy
725   (list traLaLa traLaLa)))
726 #(define twice
727   (make-sequential-music newLa))
728
729 { \twice }
730 @end lilypond
731
732 @c Due to parser lookahead
733
734 In this example, the assignment happens after the parser has
735 verified that nothing interesting happens after
736 @code{traLaLa = @{ ... @}}.  Without the dummy statement in the
737 above example, the @code{newLa} definition is executed before
738 @code{traLaLa} is defined, leading to a syntax error.
739
740 The above example shows how to @q{export} music expressions from the
741 input to the Scheme interpreter.  The opposite is also possible.  By
742 wrapping a Scheme value in the function @code{ly:export}, a Scheme
743 value is interpreted as if it were entered in LilyPond syntax.
744 Instead of defining @code{\twice}, the example above could also have
745 been written as
746
747 @example
748 ...
749 @{ #(ly:export (make-sequential-music (list newLa))) @}
750 @end example
751
752 Scheme code is evaluated as soon as the parser encounters it.  To
753 define some Scheme code in a macro (to be called later), use
754 @ref{Void functions}, or
755
756 @example
757 #(define (nopc)
758   (ly:set-option 'point-and-click #f))
759
760 ...
761 #(nopc)
762 @{ c'4 @}
763 @end example
764
765 @knownissues
766
767 Mixing Scheme and LilyPond variables is not possible with the
768 @code{--safe} option.
769
770
771
772
773 @node Object properties
774 @subsection Object properties
775
776 This syntax will be used very frequently, since many of the layout
777 tweaks involve assigning (Scheme) values to internal variables, for
778 example
779
780 @example
781 \override Stem #'thickness = #2.6
782 @end example
783
784 This instruction adjusts the appearance of stems.  The value @code{2.6}
785 is put into the @code{thickness} variable of a @code{Stem}
786 object.  @code{thickness} is measured relative to the thickness of
787 staff lines, so these stem lines will be @code{2.6} times the
788 width of staff lines.  This makes stems almost twice as thick as their
789 normal size.  To distinguish between variables defined in input files (like
790 @code{twentyFour} in the example above) and variables of internal
791 objects, we will call the latter @q{properties} and the former
792 @q{variables.}  So, the stem object has a @code{thickness} property,
793 while @code{twentyFour} is an variable.
794
795 @cindex properties vs. variables
796 @cindex variables vs. properties
797
798 @c  todo -- here we're getting interesting.  We're now introducing
799 @c  LilyPond variable types.  I think this deserves a section all
800 @c  its own
801
802 @node LilyPond compound variables
803 @subsection LilyPond compound variables
804
805 @unnumberedsubsubsec Offsets
806
807 Two-dimensional offsets (X and Y coordinates) as well as object sizes
808 (intervals with a left and right point) are entered as @code{pairs}.  A
809 pair@footnote{In Scheme terminology, the pair is called @code{cons},
810 and its two elements are called @code{car} and @code{cdr} respectively.}
811 is entered as @code{(first . second)} and, like symbols, they must be quoted,
812
813 @example
814 \override TextScript #'extra-offset = #'(1 . 2)
815 @end example
816
817 This assigns the pair (1, 2) to the @code{extra-offset} property of the
818 TextScript object.  These numbers are measured in staff-spaces, so
819 this command moves the object 1 staff space to the right, and 2 spaces up.
820
821 @unnumberedsubsubsec Extents
822
823 todo -- write something about extents
824
825 @unnumberedsubsubsec Property alists
826
827 todo -- write something about property alists
828
829 @unnumberedsubsubsec Alist chains
830
831 todo -- write something about alist chains
832
833 @node Internal music representation
834 @subsection Internal music representation
835
836 When a music expression is parsed, it is converted into a set of
837 Scheme music objects.  The defining property of a music object is that
838 it takes up time.  Time is a rational number that measures the length
839 of a piece of music in whole notes.
840
841 A music object has three kinds of types:
842 @itemize
843 @item
844 music name: Each music expression has a name.  For example, a note
845 leads to a @rinternals{NoteEvent}, and @code{\simultaneous} leads to
846 a @rinternals{SimultaneousMusic}.  A list of all expressions
847 available is in the Internals Reference manual, under
848 @rinternals{Music expressions}.
849
850 @item
851 @q{type} or interface: Each music name has several @q{types} or
852 interfaces, for example, a note is an @code{event}, but it is also a
853 @code{note-event}, a @code{rhythmic-event}, and a
854 @code{melodic-event}.  All classes of music are listed in the
855 Internals Reference, under
856 @rinternals{Music classes}.
857
858 @item
859 C++ object: Each music object is represented by an object of the C++
860 class @code{Music}.
861 @end itemize
862
863 The actual information of a music expression is stored in properties.
864 For example, a @rinternals{NoteEvent} has @code{pitch} and
865 @code{duration} properties that store the pitch and duration of that
866 note.  A list of all properties available can be found in the
867 Internals Reference, under @rinternals{Music properties}.
868
869 A compound music expression is a music object that contains other
870 music objects in its properties.  A list of objects can be stored in
871 the @code{elements} property of a music object, or a single @q{child}
872 music object in the @code{element} property.  For example,
873 @rinternals{SequentialMusic} has its children in @code{elements},
874 and @rinternals{GraceMusic} has its single argument in
875 @code{element}.  The body of a repeat is stored in the @code{element}
876 property of @rinternals{RepeatedMusic}, and the alternatives in
877 @code{elements}.
878
879 @node Building complicated functions
880 @section Building complicated functions
881
882 This section explains how to gather the information necessary
883 to create complicated music functions.
884
885 @menu
886 * Displaying music expressions::
887 * Music properties::
888 * Doubling a note with slurs (example)::
889 * Adding articulation to notes (example)::
890 @end menu
891
892
893 @node Displaying music expressions
894 @subsection Displaying music expressions
895
896 @cindex internal storage
897 @cindex displaying music expressions
898 @cindex internal representation, displaying
899 @cindex displayMusic
900 @funindex \displayMusic
901
902 When writing a music function it is often instructive to inspect how
903 a music expression is stored internally.  This can be done with the
904 music function @code{\displayMusic}
905
906 @example
907 @{
908   \displayMusic @{ c'4\f @}
909 @}
910 @end example
911
912 @noindent
913 will display
914
915 @example
916 (make-music
917   'SequentialMusic
918   'elements
919   (list (make-music
920           'EventChord
921           'elements
922           (list (make-music
923                   'NoteEvent
924                   'duration
925                   (ly:make-duration 2 0 1 1)
926                   'pitch
927                   (ly:make-pitch 0 0 0))
928                 (make-music
929                   'AbsoluteDynamicEvent
930                   'text
931                   "f")))))
932 @end example
933
934 By default, LilyPond will print these messages to the console along
935 with all the other messages.  To split up these messages and save
936 the results of @code{\display@{STUFF@}}, redirect the output to
937 a file.
938
939 @example
940 lilypond file.ly >display.txt
941 @end example
942
943 With a bit of reformatting, the above information is
944 easier to read,
945
946 @example
947 (make-music 'SequentialMusic
948   'elements (list (make-music 'EventChord
949                     'elements (list (make-music 'NoteEvent
950                                       'duration (ly:make-duration 2 0 1 1)
951                                       'pitch (ly:make-pitch 0 0 0))
952                                     (make-music 'AbsoluteDynamicEvent
953                                       'text "f")))))
954 @end example
955
956 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
957 and its inner expressions are stored as a list in its @code{'elements}
958 property.  A note is represented as an @code{EventChord} expression,
959 containing a @code{NoteEvent} object (storing the duration and
960 pitch properties) and any extra information (in this case, an
961 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
962
963
964 @node Music properties
965 @subsection Music properties
966
967 The @code{NoteEvent} object is the first object of the
968 @code{'elements} property of @code{someNote}.
969
970 @example
971 someNote = c'
972 \displayMusic \someNote
973 ===>
974 (make-music
975   'EventChord
976   'elements
977   (list (make-music
978           'NoteEvent
979           'duration
980           (ly:make-duration 2 0 1 1)
981           'pitch
982           (ly:make-pitch 0 0 0))))
983 @end example
984
985 The @code{display-scheme-music} function is the function used by
986 @code{\displayMusic} to display the Scheme representation of a music
987 expression.
988
989 @example
990 #(display-scheme-music (first (ly:music-property someNote 'elements)))
991 ===>
992 (make-music
993   'NoteEvent
994   'duration
995   (ly:make-duration 2 0 1 1)
996   'pitch
997   (ly:make-pitch 0 0 0))
998 @end example
999
1000 Then the note pitch is accessed through the @code{'pitch} property
1001 of the @code{NoteEvent} object,
1002
1003 @example
1004 #(display-scheme-music
1005    (ly:music-property (first (ly:music-property someNote 'elements))
1006                       'pitch))
1007 ===>
1008 (ly:make-pitch 0 0 0)
1009 @end example
1010
1011 The note pitch can be changed by setting this @code{'pitch} property,
1012
1013 @funindex \displayLilyMusic
1014
1015 @example
1016 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
1017                           'pitch)
1018        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
1019 \displayLilyMusic \someNote
1020 ===>
1021 d'
1022 @end example
1023
1024
1025 @node Doubling a note with slurs (example)
1026 @subsection Doubling a note with slurs (example)
1027
1028 Suppose we want to create a function that translates input like
1029 @code{a} into @code{a( a)}.  We begin by examining the internal
1030 representation of the desired result.
1031
1032 @example
1033 \displayMusic@{ a'( a') @}
1034 ===>
1035 (make-music
1036   'SequentialMusic
1037   'elements
1038   (list (make-music
1039           'EventChord
1040           'elements
1041           (list (make-music
1042                   'NoteEvent
1043                   'duration
1044                   (ly:make-duration 2 0 1 1)
1045                   'pitch
1046                   (ly:make-pitch 0 5 0))
1047                 (make-music
1048                   'SlurEvent
1049                   'span-direction
1050                   -1)))
1051         (make-music
1052           'EventChord
1053           'elements
1054           (list (make-music
1055                   'NoteEvent
1056                   'duration
1057                   (ly:make-duration 2 0 1 1)
1058                   'pitch
1059                   (ly:make-pitch 0 5 0))
1060                 (make-music
1061                   'SlurEvent
1062                   'span-direction
1063                   1)))))
1064 @end example
1065
1066 The bad news is that the @code{SlurEvent} expressions
1067 must be added @q{inside} the note (or more precisely,
1068 inside the @code{EventChord} expression).
1069
1070 Now we examine the input,
1071
1072 @example
1073 (make-music
1074   'SequentialMusic
1075   'elements
1076   (list (make-music
1077           'EventChord
1078           'elements
1079           (list (make-music
1080                   'NoteEvent
1081                   'duration
1082                   (ly:make-duration 2 0 1 1)
1083                   'pitch
1084                   (ly:make-pitch 0 5 0))))))
1085 @end example
1086
1087 So in our function, we need to clone this expression (so that we
1088 have two notes to build the sequence), add @code{SlurEvents} to the
1089 @code{'elements} property of each one, and finally make a
1090 @code{SequentialMusic} with the two @code{EventChords}.
1091
1092 @example
1093 doubleSlur = #(define-music-function (parser location note) (ly:music?)
1094          "Return: @{ note ( note ) @}.
1095          `note' is supposed to be an EventChord."
1096          (let ((note2 (ly:music-deep-copy note)))
1097            (set! (ly:music-property note 'elements)
1098                  (cons (make-music 'SlurEvent 'span-direction -1)
1099                        (ly:music-property note 'elements)))
1100            (set! (ly:music-property note2 'elements)
1101                  (cons (make-music 'SlurEvent 'span-direction 1)
1102                        (ly:music-property note2 'elements)))
1103            (make-music 'SequentialMusic 'elements (list note note2))))
1104 @end example
1105
1106
1107 @node Adding articulation to notes (example)
1108 @subsection Adding articulation to notes (example)
1109
1110 The easy way to add articulation to notes is to merge two music
1111 expressions into one context, as explained in
1112 @ruser{Creating contexts}.  However, suppose that we want to write
1113 a music function that does this.
1114
1115 A @code{$variable} inside the @code{#@{...#@}} notation is like
1116 a regular @code{\variable} in classical LilyPond notation.  We
1117 know that
1118
1119 @example
1120 @{ \music -. -> @}
1121 @end example
1122
1123 @noindent
1124 will not work in LilyPond.  We could avoid this problem by attaching
1125 the articulation to a fake note,
1126
1127 @example
1128 @{ << \music s1*0-.-> @}
1129 @end example
1130
1131 @noindent
1132 but for the sake of this example, we will learn how to do this in
1133 Scheme.  We begin by examining our input and desired output,
1134
1135 @example
1136 %  input
1137 \displayMusic c4
1138 ===>
1139 (make-music
1140   'EventChord
1141   'elements
1142   (list (make-music
1143           'NoteEvent
1144           'duration
1145           (ly:make-duration 2 0 1 1)
1146           'pitch
1147           (ly:make-pitch -1 0 0))))
1148 =====
1149 %  desired output
1150 \displayMusic c4->
1151 ===>
1152 (make-music
1153   'EventChord
1154   'elements
1155   (list (make-music
1156           'NoteEvent
1157           'duration
1158           (ly:make-duration 2 0 1 1)
1159           'pitch
1160           (ly:make-pitch -1 0 0))
1161         (make-music
1162           'ArticulationEvent
1163           'articulation-type
1164           "marcato")))
1165 @end example
1166
1167 We see that a note (@code{c4}) is represented as an @code{EventChord}
1168 expression, with a @code{NoteEvent} expression in its elements list.  To
1169 add a marcato articulation, an @code{ArticulationEvent} expression must
1170 be added to the elements property of the @code{EventChord}
1171 expression.
1172
1173 To build this function, we begin with
1174
1175 @example
1176 (define (add-marcato event-chord)
1177   "Add a marcato ArticulationEvent to the elements of `event-chord',
1178   which is supposed to be an EventChord expression."
1179   (let ((result-event-chord (ly:music-deep-copy event-chord)))
1180     (set! (ly:music-property result-event-chord 'elements)
1181           (cons (make-music 'ArticulationEvent
1182                   'articulation-type "marcato")
1183                 (ly:music-property result-event-chord 'elements)))
1184     result-event-chord))
1185 @end example
1186
1187 The first line is the way to define a function in Scheme: the function
1188 name is @code{add-marcato}, and has one variable called
1189 @code{event-chord}.  In Scheme, the type of variable is often clear
1190 from its name.  (this is good practice in other programming languages,
1191 too!)
1192
1193 @example
1194 "Add a marcato..."
1195 @end example
1196
1197 @noindent
1198 is a description of what the function does.  This is not strictly
1199 necessary, but just like clear variable names, it is good practice.
1200
1201 @example
1202 (let ((result-event-chord (ly:music-deep-copy event-chord)))
1203 @end example
1204
1205 @code{let} is used to declare local variables.  Here we use one local
1206 variable, named @code{result-event-chord}, to which we give the value
1207 @code{(ly:music-deep-copy event-chord)}.  @code{ly:music-deep-copy} is
1208 a function specific to LilyPond, like all functions prefixed by
1209 @code{ly:}.  It is use to make a copy of a music
1210 expression.  Here we copy @code{event-chord} (the parameter of the
1211 function).  Recall that our purpose is to add a marcato to an
1212 @code{EventChord} expression.  It is better to not modify the
1213 @code{EventChord} which was given as an argument, because it may be
1214 used elsewhere.
1215
1216 Now we have a @code{result-event-chord}, which is a
1217 @code{NoteEventChord} expression and is a copy of
1218 @code{event-chord}.  We add the marcato to its @code{'elements}
1219 list property.
1220
1221 @example
1222 (set! place new-value)
1223 @end example
1224
1225 Here, what we want to set (the @q{place}) is the @code{'elements}
1226 property of @code{result-event-chord} expression.
1227
1228 @example
1229 (ly:music-property result-event-chord 'elements)
1230 @end example
1231
1232 @code{ly:music-property} is the function used to access music properties
1233 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
1234 see in the @code{\displayMusic} output above).  The new value is the
1235 former @code{'elements} property, with an extra item: the
1236 @code{ArticulationEvent} expression, which we copy from the
1237 @code{\displayMusic} output,
1238
1239 @example
1240 (cons (make-music 'ArticulationEvent
1241         'articulation-type "marcato")
1242       (ly:music-property result-event-chord 'elements))
1243 @end example
1244
1245 @code{cons} is used to add an element to a list without modifying
1246 the original list.  This is what we want: the same list as before,
1247 plus the new @code{ArticulationEvent} expression.  The order
1248 inside the @code{'elements} property is not important here.
1249
1250 Finally, once we have added the marcato articulation to its @code{elements}
1251 property, we can return @code{result-event-chord}, hence the last line of
1252 the function.
1253
1254 Now we transform the @code{add-marcato} function into a music
1255 function,
1256
1257 @example
1258 addMarcato = #(define-music-function (parser location event-chord)
1259                                      (ly:music?)
1260     "Add a marcato ArticulationEvent to the elements of `event-chord',
1261     which is supposed to be an EventChord expression."
1262     (let ((result-event-chord (ly:music-deep-copy event-chord)))
1263       (set! (ly:music-property result-event-chord 'elements)
1264             (cons (make-music 'ArticulationEvent
1265                     'articulation-type "marcato")
1266                   (ly:music-property result-event-chord 'elements)))
1267       result-event-chord))
1268 @end example
1269
1270 We may verify that this music function works correctly,
1271
1272 @example
1273 \displayMusic \addMarcato c4
1274 @end example
1275
1276
1277
1278
1279
1280
1281 @ignore
1282 @menu
1283 * Tweaking with Scheme::
1284 @end menu
1285
1286 @c @node Tweaking with Scheme
1287 @c @section Tweaking with Scheme
1288
1289 We have seen how LilyPond output can be heavily modified using
1290 commands like
1291 @code{\override TextScript #'extra-offset = ( 1 . -1)}.  But
1292 we have even more power if we use Scheme.  For a full explanation
1293 of this, see the @ref{Scheme tutorial}, and
1294 @ref{Interfaces for programmers}.
1295
1296 We can use Scheme to simply @code{\override} commands,
1297
1298 TODO Find a simple example
1299 @c This isn't a valid example with skylining
1300 @c It works fine without padText  -td
1301 @end ignore
1302
1303 @ignore
1304 @lilypond[quote,verbatim,ragged-right]
1305 padText = #(define-music-function (parser location padding) (number?)
1306 #{
1307   \once \override TextScript #'padding = #$padding
1308 #})
1309
1310 \relative c''' {
1311   c4^"piu mosso" b a b
1312   \padText #1.8
1313   c4^"piu mosso" d e f
1314   \padText #2.6
1315   c4^"piu mosso" fis a g
1316 }
1317 @end lilypond
1318 @end ignore
1319
1320 @ignore
1321 We can use it to create new commands:
1322
1323 @c Check this is a valid example with skylining
1324 @c It is - 'padding still works
1325
1326
1327 @lilypond[quote,verbatim,ragged-right]
1328 tempoPadded = #(define-music-function (parser location padding tempotext)
1329   (number? string?)
1330 #{
1331   \once \override Score.MetronomeMark #'padding = $padding
1332   \tempo \markup { \bold $tempotext }
1333 #})
1334
1335 \relative c'' {
1336   \tempo \markup { "Low tempo" }
1337   c4 d e f g1
1338   \tempoPadded #4.0 #"High tempo"
1339   g4 f e d c1
1340 }
1341 @end lilypond
1342
1343
1344 Even music expressions can be passed in:
1345
1346 @lilypond[quote,verbatim,ragged-right]
1347 pattern = #(define-music-function (parser location x y) (ly:music? ly:music?)
1348 #{
1349   $x e8 a b $y b a e
1350 #})
1351
1352 \relative c''{
1353   \pattern c8 c8\f
1354   \pattern {d16 dis} { ais16-> b\p }
1355 }
1356 @end lilypond
1357 @end ignore