]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/extending/scheme-tutorial.itely
Documentation improvements concerning Scheme programming.
[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.15.18"
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 receive 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 using the display function:
107
108 @lisp
109 guile> (display a)
110 2guile>
111 @end lisp
112
113 @noindent
114 Note that both the value @code{2} and the guile prompt @code{guile}
115 showed up on the same line.  This can be avoided by calling the
116 newline 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 @w{@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 @subheading 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 @subheading 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 @subheading 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 @subheading 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,
410 the first element of the list is treated as a procedure to be
411 evaluated with the arguments of the remainder of the list.  Therefore,
412 all operators in Scheme are prefix operators.
413
414 If the first element of a Scheme expression that is a list passed to
415 the interpreter is @emph{not} an operator or procedure, an error will
416 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
432 operator or procedure, and it couldn't.  Hence the error is "Wrong
433 type to apply: 1".
434
435 Therefore, to create a list we need to use the list operator, or to
436 quote the list so that the interpreter will not try to evaluate it.
437
438 @lisp
439 guile> (list 1 2 3)
440 (1 2 3)
441 guile> '(1 2 3)
442 (1 2 3)
443 guile>
444 @end lisp
445
446 This is an error that can appear as you are working with Scheme in LilyPond.
447
448 @ignore
449 The same assignment can be done in completely in Scheme as well,
450
451 @example
452 #(define twentyFour (* 2 twelve))
453 @end example
454
455 @c this next section is confusing -- need to rewrite
456
457 The @emph{name} of a variable is also an expression, similar to a
458 number or a string.  It is entered as
459
460 @example
461 #'twentyFour
462 @end example
463
464 @funindex #'symbol
465 @cindex quoting in Scheme
466
467 The quote mark @code{'} prevents the Scheme interpreter from substituting
468 @code{24} for the @code{twentyFour}.  Instead, we get the name
469 @code{twentyFour}.
470 @end ignore
471
472
473 @node Scheme procedures
474 @subsection Scheme procedures
475
476 Scheme procedures are executable scheme expressions that return a
477 value resulting from their execution.  They can also manipulate
478 variables defined outside of the procedure.
479
480 @subheading Defining procedures
481
482 Procedures are defined in Scheme with define
483
484 @example
485 (define (function-name arg1 arg2 ... argn)
486  scheme-expression-that-gives-a-return-value)
487 @end example
488
489 For example, we could define a procedure to calculate the average:
490
491 @lisp
492 guile> (define (average x y) (/ (+ x y) 2))
493 guile> average
494 #<procedure average (x y)>
495 @end lisp
496
497 Once a procedure is defined, it is called by putting the procedure
498 name and the arguments in a list.  For example, we can calculate
499 the average of 3 and 12:
500
501 @lisp
502 guile> (average 3 12)
503 15/2
504 @end lisp
505
506 @subheading Predicates
507
508 Scheme procedures that return boolean values are often called
509 @emph{predicates}.  By convention (but not necessity), predicate names
510 typically end in a question mark:
511
512 @lisp
513 guile> (define (less-than-ten? x) (< x 10))
514 guile> (less-than-ten? 9)
515 #t
516 guile> (less-than-ten? 15)
517 #f
518 @end lisp
519
520 @subheading Return values
521
522 Scheme procedures always return a return value, which is the value
523 of the last expression executed in the procedure.  The return
524 value can be any valid Scheme value, including a complex data
525 structure or a procedure.
526
527 Sometimes the user would like to have multiple Scheme expressions in
528 a procedure.  There are two ways that multiple expressions can be
529 combined.  The first is the @code{begin} procedure, which allows
530 multiple expressions to be evaluated, and returns the value of
531 the last expression.
532
533 @lisp
534 guile> (begin (+ 1 2) (- 5 8) (* 2 2))
535 4
536 @end lisp
537
538 The second way to combine multiple expressions is in a @code{let} block.
539 In a let block, a series of bindings are created, and then a sequence
540 of expressions that can include those bindings is evaluated.  The
541 return value of the let block is the return value of the last
542 statement in the let block:
543
544 @lisp
545 guile> (let ((x 2) (y 3) (z 4)) (display (+ x y)) (display (- z 4))
546 ... (+ (* x y) (/ z x)))
547 508
548 @end lisp
549
550 @node Scheme conditionals
551 @subsection Scheme conditionals
552
553 @subheading if
554
555 Scheme has an @code{if} procedure:
556
557 @example
558 (if test-expression true-expression false-expression)
559 @end example
560
561 @var{test-expression} is an expression that returns a boolean
562 value.  If @var{test-expression} returns @code{#t}, the if
563 procedure returns the value of @var{true-expression}, otherwise
564 it returns the value of @var{false-expression}.
565
566 @lisp
567 guile> (define a 3)
568 guile> (define b 5)
569 guile> (if (> a b) "a is greater than b" "a is not greater than b")
570 "a is not greater than b"
571 @end lisp
572
573 @subheading cond
574
575 Another conditional procedure in scheme is @code{cond}:
576
577 @example
578 (cond (test-expression-1 result-expression-sequence-1)
579       (test-expression-2 result-expression-sequence-2)
580       ...
581       (test-expression-n result-expression-sequence-n))
582 @end example
583
584 For example:
585
586 @lisp
587 guile> (define a 6)
588 guile> (define b 8)
589 guile> (cond ((< a b) "a is less than b")
590 ...          ((= a b) "a equals b")
591 ...          ((> a b) "a is greater than b"))
592 "a is less than b"
593 @end lisp
594
595 @node Scheme in LilyPond
596 @section Scheme in LilyPond
597
598
599 @menu
600 * LilyPond Scheme syntax::
601 * LilyPond variables::
602 * Input variables and Scheme::
603 * Object properties::
604 * LilyPond compound variables::
605 * Internal music representation::
606 @end menu
607
608 @node LilyPond Scheme syntax
609 @subsection LilyPond Scheme syntax
610
611 The Guile interpreter is part of LilyPond, which means that
612 Scheme can be included in LilyPond input files.  The hash mark@tie{}@code{#}
613 is used to tell the LilyPond parser that the next value is a Scheme
614 value.
615
616 Once the parser sees a hash mark, input is passed to the Guile
617 interpreter to evaluate the Scheme expression.  The interpreter
618 continues to process input until the end of a Scheme expression is seen.
619 The resulting value can be used wherever @code{SCM_TOKEN} is explicitly
620 accepted by the @ruser{LilyPond grammar}.
621
622 There is another way to execute Scheme expressions by using a
623 dollar@tie{}@code{$} instead of a hash mark for introducing Scheme
624 expressions.  In this case, Lilypond evaluates the code immediately,
625 checks the resulting type, and reinserts a syntactical entity of that
626 type (like a number, string, music expression, pitch, duration@dots{})
627 into the input, making a copy of the value.  This process bypasses the
628 grammar, and the result appears in the grammar as one of several
629 @code{xxx_IDENTIFIER} tokens.
630
631 Scheme procedures can be defined in LilyPond input files:
632
633 @example
634 #(define (average a b c) (/ (+ a b c) 3))
635 @end example
636
637 Note that LilyPond comments (@code{%} and @code{%@{ %@}}) cannot
638 be used within Scheme code, even in a LilyPond input file, because
639 the Guile interpreter, not the LilyPond parser, is interpreting
640 the Scheme expression.  Comments in Guile Scheme are entered
641 as follows:
642
643 @example
644 ; this is a single-line comment
645
646 #!
647   This a (non-nestable) Guile-style block comment
648   But these are rarely used by Schemers and never in
649   LilyPond source code
650 !#
651 @end example
652
653 For the rest of this section, we will assume that the data is entered
654 in a music file, so we add@tie{}@code{#}s at the beginning of each Scheme
655 expression.
656
657 All of the top-level Scheme expressions in a LilyPond input file can
658 be combined into a single Scheme expression by the use of the
659 @code{begin} statement:
660
661 @example
662 #(begin
663   (define foo 0)
664   (define bar 1))
665 @end example
666
667
668 @node LilyPond variables
669 @subsection LilyPond variables
670
671 LilyPond variables are stored internally in the form of Scheme
672 variables.  Thus,
673
674 @example
675 twelve = 12
676 @end example
677
678 @noindent
679 is equivalent to
680
681 @example
682 #(define twelve 12)
683 @end example
684
685 This means that LilyPond variables are available
686 for use in Scheme expressions.  For example, we could use
687
688 @example
689 twentyFour = #(* 2 twelve)
690 @end example
691
692 @noindent
693 which would result in the number 24 being stored in the
694 LilyPond (and Scheme) variable @code{twentyFour}.
695
696 @node Input variables and Scheme
697 @subsection Input variables and Scheme
698
699 The input format supports the notion of variables: in the following
700 example, a music expression is assigned to a variable with the name
701 @code{traLaLa}.
702
703 @example
704 traLaLa = @{ c'4 d'4 @}
705 @end example
706
707 @noindent
708
709 There is also a form of scoping: in the following example, the
710 @code{\layout} block also contains a @code{traLaLa} variable, which is
711 independent of the outer @code{\traLaLa}.
712
713 @example
714 traLaLa = @{ c'4 d'4 @}
715 \layout @{ traLaLa = 1.0 @}
716 @end example
717
718 @c
719 In effect, each input file is a scope, and all @code{\header},
720 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
721 toplevel scope.
722
723 Both variables and scoping are implemented in the GUILE module system.
724 An anonymous Scheme module is attached to each scope.  An assignment of
725 the form:
726
727 @example
728 traLaLa = @{ c'4 d'4 @}
729 @end example
730
731 @noindent
732 is internally converted to a Scheme definition:
733
734 @example
735 (define traLaLa @var{Scheme value of `@code{... }'})
736 @end example
737
738 This means that LilyPond variables and Scheme variables may be freely
739 mixed.  In the following example, a music fragment is stored in the
740 variable @code{traLaLa}, and duplicated using Scheme.  The result is
741 imported in a @code{\score} block by means of a second variable
742 @code{twice}:
743
744 @lilypond[verbatim]
745 traLaLa = { c'4 d'4 }
746
747 #(define newLa (map ly:music-deep-copy
748   (list traLaLa traLaLa)))
749 #(define twice
750   (make-sequential-music newLa))
751
752 { \twice }
753 @end lilypond
754
755 @c Due to parser lookahead
756
757 This is actually a rather interesting example.  The assignment will only
758 take place after the parser has ascertained that nothing akin to
759 @code{\addlyrics} follows, so it needs to check what comes next.  It
760 reads @code{#} and the following Scheme expression @emph{without}
761 evaluating it, so it can go ahead with the assignment, and
762 @emph{afterwards} execute the Scheme code without problem.
763
764 The above example shows how to @q{export} music expressions from the
765 input to the Scheme interpreter.  The opposite is also possible.  By
766 placing it after @code{$}, a Scheme
767 value is interpreted as if it were entered in LilyPond syntax.
768 Instead of defining @code{\twice}, the example above could also have
769 been written as
770
771 @example
772 ...
773 @{ $(make-sequential-music (list newLa)) @}
774 @end example
775
776 You can use @code{$} with a Scheme expression anywhere you could use
777 @code{\@var{name}} after having assigned the Scheme expression to a
778 variable @var{name}.  This replacement happens in the @q{Lexer}, so
779 Lilypond is not even aware of the difference.
780
781 One drawback, however, is that of timing.  If we had been using @code{$}
782 instead of @code{#} for defining @code{newLa} in the above example, the
783 Lexer would have evaluated the Scheme code right away in order to figure
784 out the kind of the next token before Lilypond would have had a chance
785 for executing the assignment.  Consequently, the Scheme definition would
786 have failed because @code{traLaLa} would not yet have been defined.  As
787 a rule, using @code{#} rather than @code{$} whenever it is allowed will
788 cause fewer surprises.
789
790 Scheme code is evaluated as soon as the parser encounters it.  To
791 define some Scheme code in a macro (to be called later), use
792 @ref{Void scheme functions}, or
793
794 @example
795 #(define (nopc)
796   (ly:set-option 'point-and-click #f))
797
798 ...
799 #(nopc)
800 @{ c'4 @}
801 @end example
802
803 @knownissues
804
805 Mixing Scheme and LilyPond variables is not possible with the
806 @option{--safe} option.
807
808
809 @node Object properties
810 @subsection Object properties
811
812 Object properties are stored in LilyPond in the form of alist-chains,
813 which are lists of alists.  Properties are set by adding values at
814 the beginning of the property list.  Properties are read by retrieving
815 values from the alists.
816
817 Setting a new value for a property requires assigning a value to
818 the alist with both a key and a value.  The LilyPond syntax for doing
819 this is:
820
821 @example
822 \override Stem #'thickness = #2.6
823 @end example
824
825 This instruction adjusts the appearance of stems.  An alist entry
826 @code{'(thickness . 2.6)} is added to the property list of the
827 @code{Stem}
828 object.  @code{thickness} is measured relative to the thickness of
829 staff lines, so these stem lines will be @code{2.6} times the
830 width of staff lines.  This makes stems almost twice as thick as their
831 normal size.  To distinguish between variables defined in input files (like
832 @code{twentyFour} in the example above) and variables of internal
833 objects, we will call the latter @q{properties} and the former
834 @q{variables.}  So, the stem object has a @code{thickness} property,
835 while @code{twentyFour} is a variable.
836
837 @cindex properties vs. variables
838 @cindex variables vs. properties
839
840 @c  todo -- here we're getting interesting.  We're now introducing
841 @c  LilyPond variable types.  I think this deserves a section all
842 @c  its own
843
844 @node LilyPond compound variables
845 @subsection LilyPond compound variables
846
847 @subheading Offsets
848
849 Two-dimensional offsets (X and Y coordinates) are stored as @code{pairs}.
850 The @code{car} of the offset is the X coordinate, and the @code{cdr} is
851 the Y coordinate.
852
853 @example
854 \override TextScript #'extra-offset = #'(1 . 2)
855 @end example
856
857 This assigns the pair @code{(1 . 2)} to the @code{extra-offset}
858 property of the
859 TextScript object.  These numbers are measured in staff-spaces, so
860 this command moves the object 1 staff space to the right, and 2 spaces up.
861
862 Procedures for working with offsets are found in @file{scm/lily-library.scm}.
863
864 @subheading Extents
865
866 Pairs are also used to store intervals, which represent a range of numbers
867 from the minimum (the @code{car}) to the maximum (the @code{cdr}).
868 Intervals are used to store the X- and Y- extents of printable objects.
869 For X extents, the @code{car} is the left hand X coordinate, and the
870 @code{cdr} is the right hand X coordinate.  For Y extents, the @code{car}
871 is the bottom coordinate, and the @code{cdr} is the top coordinate.
872
873 Procedures for working with intervals are found in
874 @file{scm/lily-library.scm}.  These procedures should be used when possible
875 to ensure consistency of code.
876
877 @subheading Property alists
878
879 A property alist is a LilyPond data structure that is an alist whose
880 keys are properties and whose values are Scheme expressions that give
881 the desired value for the property.
882
883 LilyPond properties are Scheme symbols, such as @code{'thickness}.
884
885 @subheading Alist chains
886
887 An alist chain is a list containing property alists.
888
889 The set of all properties that will apply to a grob is typically
890 stored as an alist chain.  In order to find the value for a particular
891 property that a grob should have, each alist in the chain is searched in
892 order, looking for an entry containing the property key.  The first alist
893 entry found is returned, and the value is the property value.
894
895 The Scheme procedure @code{chain-assoc-get} is normally used to get
896 grob property values.
897
898 @node Internal music representation
899 @subsection Internal music representation
900
901 Internally, music is represented as a Scheme list.  The list contains
902 various elements that affect the printed output.  Parsing is the process
903 of converting music from the LilyPond input representation to the
904 internal Scheme representation.
905
906 When a music expression is parsed, it is converted into a set of
907 Scheme music objects.  The defining property of a music object is that
908 it takes up time.  The time it takes up is called its @emph{duration}.
909 Durations are expressed as a rational number that measures the length
910 of the music object in whole notes.
911
912 A music object has three kinds of types:
913 @itemize
914 @item
915 music name: Each music expression has a name.  For example, a note
916 leads to a @rinternals{NoteEvent}, and @code{\simultaneous} leads to
917 a @rinternals{SimultaneousMusic}.  A list of all expressions
918 available is in the Internals Reference manual, under
919 @rinternals{Music expressions}.
920
921 @item
922 @q{type} or interface: Each music name has several @q{types} or
923 interfaces, for example, a note is an @code{event}, but it is also a
924 @code{note-event}, a @code{rhythmic-event}, and a
925 @code{melodic-event}.  All classes of music are listed in the
926 Internals Reference, under
927 @rinternals{Music classes}.
928
929 @item
930 C++ object: Each music object is represented by an object of the C++
931 class @code{Music}.
932 @end itemize
933
934 The actual information of a music expression is stored in properties.
935 For example, a @rinternals{NoteEvent} has @code{pitch} and
936 @code{duration} properties that store the pitch and duration of that
937 note.  A list of all properties available can be found in the
938 Internals Reference, under @rinternals{Music properties}.
939
940 A compound music expression is a music object that contains other
941 music objects in its properties.  A list of objects can be stored in
942 the @code{elements} property of a music object, or a single @q{child}
943 music object in the @code{element} property.  For example,
944 @rinternals{SequentialMusic} has its children in @code{elements},
945 and @rinternals{GraceMusic} has its single argument in
946 @code{element}.  The body of a repeat is stored in the @code{element}
947 property of @rinternals{RepeatedMusic}, and the alternatives in
948 @code{elements}.
949
950 @node Building complicated functions
951 @section Building complicated functions
952
953 This section explains how to gather the information necessary
954 to create complicated music functions.
955
956 @menu
957 * Displaying music expressions::
958 * Music properties::
959 * Doubling a note with slurs (example)::
960 * Adding articulation to notes (example)::
961 @end menu
962
963 @node Displaying music expressions
964 @subsection Displaying music expressions
965
966 @cindex internal storage
967 @cindex displaying music expressions
968 @cindex internal representation, displaying
969 @cindex displayMusic
970 @funindex \displayMusic
971
972 When writing a music function it is often instructive to inspect how
973 a music expression is stored internally.  This can be done with the
974 music function @code{\displayMusic}
975
976 @example
977 @{
978   \displayMusic @{ c'4\f @}
979 @}
980 @end example
981
982 @noindent
983 will display
984
985 @example
986 (make-music
987   'SequentialMusic
988   'elements
989   (list (make-music
990           'EventChord
991           'elements
992           (list (make-music
993                   'NoteEvent
994                   'duration
995                   (ly:make-duration 2 0 1 1)
996                   'pitch
997                   (ly:make-pitch 0 0 0))
998                 (make-music
999                   'AbsoluteDynamicEvent
1000                   'text
1001                   "f")))))
1002 @end example
1003
1004 By default, LilyPond will print these messages to the console along
1005 with all the other messages.  To split up these messages and save
1006 the results of @code{\display@{STUFF@}}, redirect the output to
1007 a file.
1008
1009 @example
1010 lilypond file.ly >display.txt
1011 @end example
1012
1013 With a combined bit of Lilypond and Scheme magick, you can actually
1014 let Lilypond direct just this output to a file of its own:
1015
1016 @example
1017 @{
1018   $(with-output-to-file "display.txt"
1019       (lambda () #@{ \displayMusic @{ c'4\f @} #@}))
1020 @}
1021 @end example
1022
1023
1024 A bit of reformatting makes the above information easier to read:
1025
1026 @example
1027 (make-music 'SequentialMusic
1028   'elements (list (make-music 'EventChord
1029                     'elements (list (make-music 'NoteEvent
1030                                       'duration (ly:make-duration 2 0 1 1)
1031                                       'pitch (ly:make-pitch 0 0 0))
1032                                     (make-music 'AbsoluteDynamicEvent
1033                                       'text "f")))))
1034 @end example
1035
1036 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
1037 and its inner expressions are stored as a list in its @code{'elements}
1038 property.  A note is represented as an @code{EventChord} expression,
1039 containing a @code{NoteEvent} object (storing the duration and
1040 pitch properties) and any extra information (in this case, an
1041 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
1042
1043 @funindex{\void}
1044 @code{\displayMusic} returns the music it displays, so it will get
1045 interpreted as well as displayed.  To avoid interpretation, write
1046 @code{\void} before @code{\displayMusic}.
1047
1048 @node Music properties
1049 @subsection Music properties
1050
1051 TODO -- make sure we delineate between @emph{music} properties,
1052 @emph{context} properties, and @emph{layout} properties.  These
1053 are potentially confusing.
1054
1055 The @code{NoteEvent} object is the first object of the
1056 @code{'elements} property of @code{someNote}.
1057
1058 @example
1059 someNote = c'
1060 \displayMusic \someNote
1061 ===>
1062 (make-music
1063   'EventChord
1064   'elements
1065   (list (make-music
1066           'NoteEvent
1067           'duration
1068           (ly:make-duration 2 0 1 1)
1069           'pitch
1070           (ly:make-pitch 0 0 0))))
1071 @end example
1072
1073 The @code{display-scheme-music} function is the function used by
1074 @code{\displayMusic} to display the Scheme representation of a music
1075 expression.
1076
1077 @example
1078 #(display-scheme-music (first (ly:music-property someNote 'elements)))
1079 ===>
1080 (make-music
1081   'NoteEvent
1082   'duration
1083   (ly:make-duration 2 0 1 1)
1084   'pitch
1085   (ly:make-pitch 0 0 0))
1086 @end example
1087
1088 Then the note pitch is accessed through the @code{'pitch} property
1089 of the @code{NoteEvent} object,
1090
1091 @example
1092 #(display-scheme-music
1093    (ly:music-property (first (ly:music-property someNote 'elements))
1094                       'pitch))
1095 ===>
1096 (ly:make-pitch 0 0 0)
1097 @end example
1098
1099 The note pitch can be changed by setting this @code{'pitch} property,
1100
1101 @funindex \displayLilyMusic
1102
1103 @example
1104 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
1105                           'pitch)
1106        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
1107 \displayLilyMusic \someNote
1108 ===>
1109 d'
1110 @end example
1111
1112
1113 @node Doubling a note with slurs (example)
1114 @subsection Doubling a note with slurs (example)
1115
1116 Suppose we want to create a function that translates input like
1117 @code{a} into @code{a( a)}.  We begin by examining the internal
1118 representation of the desired result.
1119
1120 @example
1121 \displayMusic@{ a'( a') @}
1122 ===>
1123 (make-music
1124   'SequentialMusic
1125   'elements
1126   (list (make-music
1127           'EventChord
1128           'elements
1129           (list (make-music
1130                   'NoteEvent
1131                   'duration
1132                   (ly:make-duration 2 0 1 1)
1133                   'pitch
1134                   (ly:make-pitch 0 5 0))
1135                 (make-music
1136                   'SlurEvent
1137                   'span-direction
1138                   -1)))
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 0 5 0))
1148                 (make-music
1149                   'SlurEvent
1150                   'span-direction
1151                   1)))))
1152 @end example
1153
1154 The bad news is that the @code{SlurEvent} expressions
1155 must be added @q{inside} the note (or more precisely,
1156 inside the @code{EventChord} expression).
1157
1158 Now we examine the input,
1159
1160 @example
1161 (make-music
1162   'SequentialMusic
1163   'elements
1164   (list (make-music
1165           'EventChord
1166           'elements
1167           (list (make-music
1168                   'NoteEvent
1169                   'duration
1170                   (ly:make-duration 2 0 1 1)
1171                   'pitch
1172                   (ly:make-pitch 0 5 0))))))
1173 @end example
1174
1175 So in our function, we need to clone this expression (so that we
1176 have two notes to build the sequence), add a @code{SlurEvent} to the
1177 @code{'elements} property of each one, and finally make a
1178 @code{SequentialMusic} with the two @code{EventChords}.
1179
1180 @example
1181 doubleSlur = #(define-music-function (parser location note) (ly:music?)
1182          "Return: @{ note ( note ) @}.
1183          `note' is supposed to be an EventChord."
1184          (let ((note2 (ly:music-deep-copy note)))
1185            (set! (ly:music-property note 'elements)
1186                  (cons (make-music 'SlurEvent 'span-direction -1)
1187                        (ly:music-property note 'elements)))
1188            (set! (ly:music-property note2 'elements)
1189                  (cons (make-music 'SlurEvent 'span-direction 1)
1190                        (ly:music-property note2 'elements)))
1191            (make-music 'SequentialMusic 'elements (list note note2))))
1192 @end example
1193
1194
1195 @node Adding articulation to notes (example)
1196 @subsection Adding articulation to notes (example)
1197
1198 The easy way to add articulation to notes is to merge two music
1199 expressions into one context, as explained in
1200 @ruser{Creating contexts}.  However, suppose that we want to write
1201 a music function that does this.
1202
1203 A @code{$variable} inside the @code{#@{...#@}} notation is like
1204 a regular @code{\variable} in classical LilyPond notation.  We
1205 know that
1206
1207 @example
1208 @{ \music -. -> @}
1209 @end example
1210
1211 @noindent
1212 will not work in LilyPond.  We could avoid this problem by attaching
1213 the articulation to a fake note,
1214
1215 @example
1216 @{ << \music s1*0-.-> @}
1217 @end example
1218
1219 @noindent
1220 but for the sake of this example, we will learn how to do this in
1221 Scheme.  We begin by examining our input and desired output,
1222
1223 @example
1224 %  input
1225 \displayMusic c4
1226 ===>
1227 (make-music
1228   'EventChord
1229   'elements
1230   (list (make-music
1231           'NoteEvent
1232           'duration
1233           (ly:make-duration 2 0 1 1)
1234           'pitch
1235           (ly:make-pitch -1 0 0))))
1236 =====
1237 %  desired output
1238 \displayMusic c4->
1239 ===>
1240 (make-music
1241   'EventChord
1242   'elements
1243   (list (make-music
1244           'NoteEvent
1245           'duration
1246           (ly:make-duration 2 0 1 1)
1247           'pitch
1248           (ly:make-pitch -1 0 0))
1249         (make-music
1250           'ArticulationEvent
1251           'articulation-type
1252           "marcato")))
1253 @end example
1254
1255 We see that a note (@code{c4}) is represented as an @code{EventChord}
1256 expression, with a @code{NoteEvent} expression in its elements list.  To
1257 add a marcato articulation, an @code{ArticulationEvent} expression must
1258 be added to the elements property of the @code{EventChord}
1259 expression.
1260
1261 To build this function, we begin with
1262
1263 @example
1264 (define (add-marcato event-chord)
1265   "Add a marcato ArticulationEvent to the elements of `event-chord',
1266   which is supposed to be an EventChord expression."
1267   (let ((result-event-chord (ly:music-deep-copy event-chord)))
1268     (set! (ly:music-property result-event-chord 'elements)
1269           (cons (make-music 'ArticulationEvent
1270                   'articulation-type "marcato")
1271                 (ly:music-property result-event-chord 'elements)))
1272     result-event-chord))
1273 @end example
1274
1275 The first line is the way to define a function in Scheme: the function
1276 name is @code{add-marcato}, and has one variable called
1277 @code{event-chord}.  In Scheme, the type of variable is often clear
1278 from its name.  (this is good practice in other programming languages,
1279 too!)
1280
1281 @example
1282 "Add a marcato..."
1283 @end example
1284
1285 @noindent
1286 is a description of what the function does.  This is not strictly
1287 necessary, but just like clear variable names, it is good practice.
1288
1289 @example
1290 (let ((result-event-chord (ly:music-deep-copy event-chord)))
1291 @end example
1292
1293 @code{let} is used to declare local variables.  Here we use one local
1294 variable, named @code{result-event-chord}, to which we give the value
1295 @code{(ly:music-deep-copy event-chord)}.  @code{ly:music-deep-copy} is
1296 a function specific to LilyPond, like all functions prefixed by
1297 @code{ly:}.  It is use to make a copy of a music
1298 expression.  Here we copy @code{event-chord} (the parameter of the
1299 function).  Recall that our purpose is to add a marcato to an
1300 @code{EventChord} expression.  It is better to not modify the
1301 @code{EventChord} which was given as an argument, because it may be
1302 used elsewhere.
1303
1304 Now we have a @code{result-event-chord}, which is a
1305 @code{NoteEventChord} expression and is a copy of
1306 @code{event-chord}.  We add the marcato to its @code{'elements}
1307 list property.
1308
1309 @example
1310 (set! place new-value)
1311 @end example
1312
1313 Here, what we want to set (the @q{place}) is the @code{'elements}
1314 property of @code{result-event-chord} expression.
1315
1316 @example
1317 (ly:music-property result-event-chord 'elements)
1318 @end example
1319
1320 @code{ly:music-property} is the function used to access music properties
1321 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
1322 see in the @code{\displayMusic} output above).  The new value is the
1323 former @code{'elements} property, with an extra item: the
1324 @code{ArticulationEvent} expression, which we copy from the
1325 @code{\displayMusic} output,
1326
1327 @example
1328 (cons (make-music 'ArticulationEvent
1329         'articulation-type "marcato")
1330       (ly:music-property result-event-chord 'elements))
1331 @end example
1332
1333 @code{cons} is used to add an element to a list without modifying
1334 the original list.  This is what we want: the same list as before,
1335 plus the new @code{ArticulationEvent} expression.  The order
1336 inside the @code{'elements} property is not important here.
1337
1338 Finally, once we have added the marcato articulation to its @code{elements}
1339 property, we can return @code{result-event-chord}, hence the last line of
1340 the function.
1341
1342 Now we transform the @code{add-marcato} function into a music
1343 function,
1344
1345 @example
1346 addMarcato = #(define-music-function (parser location event-chord)
1347                                      (ly:music?)
1348     "Add a marcato ArticulationEvent to the elements of `event-chord',
1349     which is supposed to be an EventChord expression."
1350     (let ((result-event-chord (ly:music-deep-copy event-chord)))
1351       (set! (ly:music-property result-event-chord 'elements)
1352             (cons (make-music 'ArticulationEvent
1353                     'articulation-type "marcato")
1354                   (ly:music-property result-event-chord 'elements)))
1355       result-event-chord))
1356 @end example
1357
1358 We may verify that this music function works correctly,
1359
1360 @example
1361 \displayMusic \addMarcato c4
1362 @end example
1363
1364
1365
1366
1367
1368 @ignore
1369 @menu
1370 * Tweaking with Scheme::
1371 @end menu
1372
1373 @c @nod e Tweaking with Scheme
1374 @c @sectio n Tweaking with Scheme
1375
1376 We have seen how LilyPond output can be heavily modified using
1377 commands like
1378 @code{\override TextScript #'extra-offset = ( 1 . -1)}.  But
1379 we have even more power if we use Scheme.  For a full explanation
1380 of this, see the @ref{Scheme tutorial}, and
1381 @ref{Interfaces for programmers}.
1382
1383 We can use Scheme to simply @code{\override} commands,
1384
1385 TODO Find a simple example
1386 @c This isn't a valid example with skylining
1387 @c It works fine without padText  -td
1388 @end ignore
1389
1390 @ignore
1391 @lilypond[quote,verbatim,ragged-right]
1392 padText = #(define-music-function (parser location padding) (number?)
1393 #{
1394   \once \override TextScript #'padding = #padding
1395 #})
1396
1397 \relative c''' {
1398   c4^"piu mosso" b a b
1399   \padText #1.8
1400   c4^"piu mosso" d e f
1401   \padText #2.6
1402   c4^"piu mosso" fis a g
1403 }
1404 @end lilypond
1405 @end ignore
1406
1407 @ignore
1408 We can use it to create new commands:
1409
1410 @c Check this is a valid example with skylining
1411 @c It is - 'padding still works
1412
1413
1414 @lilypond[quote,verbatim,ragged-right]
1415 tempoPadded = #(define-music-function (parser location padding tempotext)
1416   (number? string?)
1417 #{
1418   \once \override Score.MetronomeMark #'padding = $padding
1419   \tempo \markup { \bold $tempotext }
1420 #})
1421
1422 \relative c'' {
1423   \tempo \markup { "Low tempo" }
1424   c4 d e f g1
1425   \tempoPadded #4.0 #"High tempo"
1426   g4 f e d c1
1427 }
1428 @end lilypond
1429
1430
1431 Even music expressions can be passed in:
1432
1433 @lilypond[quote,verbatim,ragged-right]
1434 pattern = #(define-music-function (parser location x y) (ly:music? ly:music?)
1435 #{
1436   $x e8 a b $y b a e
1437 #})
1438
1439 \relative c''{
1440   \pattern c8 c8\f
1441   \pattern {d16 dis} { ais16-> b\p }
1442 }
1443 @end lilypond
1444 @end ignore