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