]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/extending/scheme-tutorial.itely
Documentation/extending: some improvements.
[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.20"
12
13 @node Scheme tutorial
14 @chapter Scheme tutorial
15
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 receive 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 using the display function:
106
107 @lisp
108 guile> (display a)
109 2guile>
110 @end lisp
111
112 @noindent
113 Note that both the value @code{2} and the guile prompt @code{guile}
114 showed up on the same line.  This can be avoided by calling the
115 newline 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 @w{@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 @subheading 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 @subheading Lists
256
257 A very common Scheme data structure is the @emph{list}.  Formally, a
258 list is defined as either the empty list (represented as @code{'()},
259 or a pair whose @code{cdr} is a list.
260
261 There are many ways of creating lists.  Perhaps the most common is
262 with the @code{list} procedure:
263
264 @lisp
265 guile> (list 1 2 3 "abc" 17.5)
266 (1 2 3 "abc" 17.5)
267 @end lisp
268
269 As can be seen, a list is displayed in the form of individual elements
270 separated by whitespace and enclosed in parentheses.  Unlike a pair,
271 there is no period between the elements.
272
273 A list can also be entered as a literal list by enclosing its
274 elements in parentheses, and adding a quote:
275
276 @lisp
277 guile> '(17 23 "foo" "bar" "bazzle")
278 (17 23 "foo" "bar" "bazzle")
279 @end lisp
280
281 Lists are a central part of Scheme.  In, fact, Scheme is considered
282 a dialect of lisp, where @q{lisp} is an abbreviation for
283 @q{List Processing}.  Scheme expressions are all lists.
284
285 @subheading Association lists (alists)
286
287 A special type of list is an @emph{association list} or @emph{alist}.
288 An alist is used to store data for easy retrieval.
289
290 Alists are lists whose elements are pairs.  The @code{car} of each
291 element is called the @emph{key}, and the @code{cdr} of each element
292 is called the @emph{value}.  The Scheme procedure @code{assoc} is
293 used to retrieve an entry from the alist, and @code{cdr} is used to
294 retrieve the value:
295
296 @lisp
297 guile> (define my-alist '((1  . "A") (2 . "B") (3 . "C")))
298 guile> my-alist
299 ((1 . "A") (2 . "B") (3 . "C"))
300 guile> (assoc 2 my-alist)
301 (2 . "B")
302 guile> (cdr (assoc 2 my-alist))
303 "B"
304 guile>
305 @end lisp
306
307 Alists are widely used in LilyPond to store properties and other data.
308
309 @subheading Hash tables
310
311 A data structure that is used occasionally in LilyPond.  A hash table
312 is similar to an array, but the indexes to the array can be any type
313 of Scheme value, not just integers.
314
315 Hash tables are more efficient than alists if there is a lot of data
316 to store and the data changes very infrequently.
317
318 The syntax to create hash tables is a bit complex, but you
319 can see examples of it in the LilyPond source.
320
321 @lisp
322 guile> (define h (make-hash-table 10))
323 guile> h
324 #<hash-table 0/31>
325 guile> (hashq-set! h 'key1 "val1")
326 "val1"
327 guile> (hashq-set! h 'key2 "val2")
328 "val2"
329 guile> (hashq-set! h 3 "val3")
330 "val3"
331 @end lisp
332
333 Values are retrieved from hash tables with @code{hashq-ref}.
334
335 @lisp
336 guile> (hashq-ref h 3)
337 "val3"
338 guile> (hashq-ref h 'key2)
339 "val2"
340 guile>
341 @end lisp
342
343 Keys and values are retrieved as a pair with @code{hashq-get-handle}.
344 This is a preferred way, because it will return @code{#f} if a key is
345 not found.
346
347 @lisp
348 guile> (hashq-get-handle h 'key1)
349 (key1 . "val1")
350 guile> (hashq-get-handle h 'frob)
351 #f
352 guile>
353 @end lisp
354
355 @node Calculations in Scheme
356 @subsection Calculations in Scheme
357
358 @ignore
359 We have been using lists all along.  A calculation, like @code{(+ 1 2)}
360 is also a list (containing the symbol @code{+} and the numbers 1
361 and@tie{}2).  Normally lists are interpreted as calculations, and the
362 Scheme interpreter substitutes the outcome of the calculation.  To enter a
363 list, we stop the evaluation.  This is done by quoting the list with a
364 quote @code{'} symbol.  So, for calculations do not use a quote.
365
366 Inside a quoted list or pair, there is no need to quote anymore.  The
367 following is a pair of symbols, a list of symbols and a list of lists
368 respectively,
369
370 @example
371 #'(stem . head)
372 #'(staff clef key-signature)
373 #'((1) (2))
374 @end example
375 @end ignore
376
377 Scheme can be used to do calculations.  It uses @emph{prefix}
378 syntax.  Adding 1 and@tie{}2 is written as @code{(+ 1 2)} rather than the
379 traditional @math{1+2}.
380
381 @lisp
382 guile> (+ 1 2)
383 3
384 @end lisp
385
386 Calculations may be nested; the result of a function may
387 be used for another calculation.
388
389 @lisp
390 guile> (+ 1 (* 3 4))
391 13
392 @end lisp
393
394 These calculations are examples of evaluations; an expression like
395 @code{(* 3 4)} is replaced by its value @code{12}.
396
397 Scheme calculations are sensitive to the differences between integers
398 and non-integers.  Integer calculations are exact, while non-integers
399 are calculated to the appropriate limits of precision:
400
401 @lisp
402 guile> (/ 7 3)
403 7/3
404 guile> (/ 7.0 3.0)
405 2.33333333333333
406 @end lisp
407
408 When the scheme interpreter encounters an expression that is a list,
409 the first element of the list is treated as a procedure to be
410 evaluated with the arguments of the remainder of the list.  Therefore,
411 all operators in Scheme are prefix operators.
412
413 If the first element of a Scheme expression that is a list passed to
414 the interpreter is @emph{not} an operator or procedure, an error will
415 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
431 operator or procedure, and it couldn't.  Hence the error is "Wrong
432 type to apply: 1".
433
434 Therefore, to create a list we need to use the list operator, or 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 a
476 value resulting from their execution.  They can also manipulate
477 variables defined outside of the procedure.
478
479 @subheading 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 @subheading 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 @subheading Return values
520
521 Scheme procedures always return a return value, which is the value
522 of the last expression executed in the procedure.  The return
523 value can be any valid Scheme value, including a complex data
524 structure or a procedure.
525
526 Sometimes the user would like to have multiple Scheme expressions in
527 a procedure.  There are two ways that multiple expressions can be
528 combined.  The first is the @code{begin} procedure, which allows
529 multiple expressions to be evaluated, and returns the value of
530 the last expression.
531
532 @lisp
533 guile> (begin (+ 1 2) (- 5 8) (* 2 2))
534 4
535 @end lisp
536
537 The second way to combine multiple expressions is in a @code{let} block.
538 In a let block, a series of bindings are created, and then a sequence
539 of expressions that can include those bindings is evaluated.  The
540 return value of the let block is the return value of the last
541 statement in the let block:
542
543 @lisp
544 guile> (let ((x 2) (y 3) (z 4)) (display (+ x y)) (display (- z 4))
545 ... (+ (* x y) (/ z x)))
546 508
547 @end lisp
548
549 @node Scheme conditionals
550 @subsection Scheme conditionals
551
552 @subheading if
553
554 Scheme has an @code{if} procedure:
555
556 @example
557 (if test-expression true-expression false-expression)
558 @end example
559
560 @var{test-expression} is an expression that returns a boolean
561 value.  If @var{test-expression} returns @code{#t}, the if
562 procedure returns the value of @var{true-expression}, otherwise
563 it returns the value of @var{false-expression}.
564
565 @lisp
566 guile> (define a 3)
567 guile> (define b 5)
568 guile> (if (> a b) "a is greater than b" "a is not greater than b")
569 "a is not greater than b"
570 @end lisp
571
572 @subheading cond
573
574 Another conditional procedure in scheme is @code{cond}:
575
576 @example
577 (cond (test-expression-1 result-expression-sequence-1)
578       (test-expression-2 result-expression-sequence-2)
579       ...
580       (test-expression-n result-expression-sequence-n))
581 @end example
582
583 For example:
584
585 @lisp
586 guile> (define a 6)
587 guile> (define b 8)
588 guile> (cond ((< a b) "a is less than b")
589 ...          ((= a b) "a equals b")
590 ...          ((> a b) "a is greater than b"))
591 "a is less than b"
592 @end lisp
593
594 @node Scheme in LilyPond
595 @section Scheme in LilyPond
596
597
598 @menu
599 * LilyPond Scheme syntax::
600 * LilyPond variables::
601 * Input variables and Scheme::
602 * Object properties::
603 * LilyPond compound variables::
604 * Internal music representation::
605 @end menu
606
607 @node LilyPond Scheme syntax
608 @subsection LilyPond Scheme syntax
609 @funindex $
610 @funindex #
611
612 The Guile interpreter is part of LilyPond, which means that
613 Scheme can be included in LilyPond input files.  There are several
614 methods for including Scheme in LilyPond.
615
616 The simplest way is to use a hash mark@tie{}@code{#} before a Scheme
617 expression.
618
619 Now LilyPond's input is structured into tokens and expressions, much
620 like human language is structured into words and sentences.  LilyPond
621 has a lexer that recognizes tokens (literal numbers, strings, Scheme
622 elements, pitches and so on), and a parser that understands the syntax,
623 @ruser{LilyPond grammar}.  Once it knows that a particular syntax rule
624 applies, it executes actions associated with it.
625
626 The hash mark@tie{}@code{#} method of embedding Scheme is a natural fit
627 for this system.  Once the lexer sees a hash mark, it calls the Scheme
628 reader to read one full Scheme expression (this can be an identifier, an
629 expression enclosed in parentheses, or several other things).  After the
630 Scheme expression is read, it is stored away as the value for an
631 @code{SCM_TOKEN} in the grammar.  Once the parser knows how to make use
632 of this token, it calls Guile for evaluating the Scheme expression.
633 Since the parser usually requires a bit of lookahead from the lexer to
634 make its parsing decisions, this separation of reading and evaluation
635 between lexer and parser is exactly what is needed to keep the execution
636 of LilyPond and Scheme expressions in sync.  For this reason, you should
637 use the hash mark@tie{}@code{#} for calling Scheme whenever this is
638 feasible.
639
640 Another way to call the Scheme interpreter from LilyPond is the use of
641 dollar@tie{}@code{$} instead of a hash mark for introducing Scheme
642 expressions.  In this case, Lilypond evaluates the code right after the
643 lexer has read it.  It checks the resulting type of the Scheme
644 expression and then picks a token type (one of several
645 @code{xxx_IDENTIFIER} in the syntax) for it.  It creates a @emph{copy}
646 of the value and uses that for the value of the token.  If the value of
647 the expression is void (Guile's value of @code{*unspecified*}), nothing
648 at all is passed to the parser.
649
650 This is, in fact, exactly the same mechanism that Lilypond employs when
651 you call any variable or music function by name, as @code{\name}, with
652 the only difference that its end is determined by the Lilypond lexer
653 without consulting the Scheme reader, and thus only variable names
654 consistent with the current Lilypond mode are accepted.
655
656 The immediate action of @code{$} can lead to surprises, @ref{Input
657 variables and Scheme}.  Using @code{#} where the parser supports it is
658 usually preferable.
659
660 Now let's take a look at some actual Scheme code.  Scheme procedures can
661 be defined in LilyPond input files:
662
663 @example
664 #(define (average a b c) (/ (+ a b c) 3))
665 @end example
666
667 Note that LilyPond comments (@code{%} and @code{%@{ %@}}) cannot
668 be used within Scheme code, even in a LilyPond input file, because
669 the Guile interpreter, not the LilyPond lexer, is reading
670 the Scheme expression.  Comments in Guile Scheme are entered
671 as follows:
672
673 @example
674 ; this is a single-line comment
675
676 #!
677   This a (non-nestable) Guile-style block comment
678   But these are rarely used by Schemers and never in
679   LilyPond source code
680 !#
681 @end example
682
683 For the rest of this section, we will assume that the data is entered
684 in a music file, so we add@tie{}@code{#}s at the beginning of each Scheme
685 expression.
686
687 All of the top-level Scheme expressions in a LilyPond input file can
688 be combined into a single Scheme expression by the use of the
689 @code{begin} statement:
690
691 @example
692 #(begin
693   (define foo 0)
694   (define bar 1))
695 @end example
696
697
698 @node LilyPond variables
699 @subsection LilyPond variables
700
701 LilyPond variables are stored internally in the form of Scheme
702 variables.  Thus,
703
704 @example
705 twelve = 12
706 @end example
707
708 @noindent
709 is equivalent to
710
711 @example
712 #(define twelve 12)
713 @end example
714
715 This means that LilyPond variables are available
716 for use in Scheme expressions.  For example, we could use
717
718 @example
719 twentyFour = #(* 2 twelve)
720 @end example
721
722 @noindent
723 which would result in the number 24 being stored in the
724 LilyPond (and Scheme) variable @code{twentyFour}.
725
726 The usual way to refer to Lilypond variables, @ref{LilyPond Scheme
727 syntax}, is to call them using a backslash, i.e., @code{\twentyFour}.
728 Since this creates a copy of the value for most of LilyPond's internal
729 types, in particular music expressions, music functions don't usually
730 create copies of material they change.  For this reason, music
731 expressions given with @code{#} should usually not contain material that
732 is not either created from scratch or explicitly copied rather than
733 directly referenced.
734
735 @node Input variables and Scheme
736 @subsection Input variables and Scheme
737
738 The input format supports the notion of variables: in the following
739 example, a music expression is assigned to a variable with the name
740 @code{traLaLa}.
741
742 @example
743 traLaLa = @{ c'4 d'4 @}
744 @end example
745
746 @noindent
747
748 There is also a form of scoping: in the following example, the
749 @code{\layout} block also contains a @code{traLaLa} variable, which is
750 independent of the outer @code{\traLaLa}.
751
752 @example
753 traLaLa = @{ c'4 d'4 @}
754 \layout @{ traLaLa = 1.0 @}
755 @end example
756
757 @c
758 In effect, each input file is a scope, and all @code{\header},
759 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
760 toplevel scope.
761
762 Both variables and scoping are implemented in the GUILE module system.
763 An anonymous Scheme module is attached to each scope.  An assignment of
764 the form:
765
766 @example
767 traLaLa = @{ c'4 d'4 @}
768 @end example
769
770 @noindent
771 is internally converted to a Scheme definition:
772
773 @example
774 (define traLaLa @var{Scheme value of `@code{... }'})
775 @end example
776
777 This means that LilyPond variables and Scheme variables may be freely
778 mixed.  In the following example, a music fragment is stored in the
779 variable @code{traLaLa}, and duplicated using Scheme.  The result is
780 imported in a @code{\score} block by means of a second variable
781 @code{twice}:
782
783 @lilypond[verbatim]
784 traLaLa = { c'4 d'4 }
785
786 #(define newLa (map ly:music-deep-copy
787   (list traLaLa traLaLa)))
788 #(define twice
789   (make-sequential-music newLa))
790
791 { \twice }
792 @end lilypond
793
794 @c Due to parser lookahead
795
796 This is actually a rather interesting example.  The assignment will only
797 take place after the parser has ascertained that nothing akin to
798 @code{\addlyrics} follows, so it needs to check what comes next.  It
799 reads @code{#} and the following Scheme expression @emph{without}
800 evaluating it, so it can go ahead with the assignment, and
801 @emph{afterwards} execute the Scheme code without problem.
802
803 The above example shows how to @q{export} music expressions from the
804 input to the Scheme interpreter.  The opposite is also possible.  By
805 placing it after @code{$}, a Scheme
806 value is interpreted as if it were entered in LilyPond syntax.
807 Instead of defining @code{\twice}, the example above could also have
808 been written as
809
810 @example
811 ...
812 @{ $(make-sequential-music (list newLa)) @}
813 @end example
814
815 You can use @code{$} with a Scheme expression anywhere you could use
816 @code{\@var{name}} after having assigned the Scheme expression to a
817 variable @var{name}.  This replacement happens in the @q{lexer}, so
818 Lilypond is not even aware of the difference.
819
820 One drawback, however, is that of timing.  If we had been using @code{$}
821 instead of @code{#} for defining @code{newLa} in the above example, the
822 following Scheme definition would have failed because @code{traLaLa}
823 would not yet have been defined.  For an explanation of this timing
824 problem, @ref{LilyPond Scheme syntax}.
825
826 In any case, evaluation of Scheme code happens in the parser at latest.
827 If you need it to be executed at a later point of time, @ref{Void scheme
828 functions}, or store it in a macro:
829
830 @example
831 #(define (nopc)
832   (ly:set-option 'point-and-click #f))
833
834 ...
835 #(nopc)
836 @{ c'4 @}
837 @end example
838
839 @knownissues
840
841 Mixing Scheme and LilyPond variables is not possible with the
842 @option{--safe} option.
843
844
845 @node Object properties
846 @subsection Object properties
847
848 Object properties are stored in LilyPond in the form of alist-chains,
849 which are lists of alists.  Properties are set by adding values at
850 the beginning of the property list.  Properties are read by retrieving
851 values from the alists.
852
853 Setting a new value for a property requires assigning a value to
854 the alist with both a key and a value.  The LilyPond syntax for doing
855 this is:
856
857 @example
858 \override Stem #'thickness = #2.6
859 @end example
860
861 This instruction adjusts the appearance of stems.  An alist entry
862 @code{'(thickness . 2.6)} is added to the property list of the
863 @code{Stem}
864 object.  @code{thickness} is measured relative to the thickness of
865 staff lines, so these stem lines will be @code{2.6} times the
866 width of staff lines.  This makes stems almost twice as thick as their
867 normal size.  To distinguish between variables defined in input files (like
868 @code{twentyFour} in the example above) and variables of internal
869 objects, we will call the latter @q{properties} and the former
870 @q{variables.}  So, the stem object has a @code{thickness} property,
871 while @code{twentyFour} is a variable.
872
873 @cindex properties vs. variables
874 @cindex variables vs. properties
875
876 @c  todo -- here we're getting interesting.  We're now introducing
877 @c  LilyPond variable types.  I think this deserves a section all
878 @c  its own
879
880 @node LilyPond compound variables
881 @subsection LilyPond compound variables
882
883 @subheading Offsets
884
885 Two-dimensional offsets (X and Y coordinates) are stored as @code{pairs}.
886 The @code{car} of the offset is the X coordinate, and the @code{cdr} is
887 the Y coordinate.
888
889 @example
890 \override TextScript #'extra-offset = #'(1 . 2)
891 @end example
892
893 This assigns the pair @code{(1 . 2)} to the @code{extra-offset}
894 property of the
895 TextScript object.  These numbers are measured in staff-spaces, so
896 this command moves the object 1 staff space to the right, and 2 spaces up.
897
898 Procedures for working with offsets are found in @file{scm/lily-library.scm}.
899
900 @subheading Extents
901
902 Pairs are also used to store intervals, which represent a range of numbers
903 from the minimum (the @code{car}) to the maximum (the @code{cdr}).
904 Intervals are used to store the X- and Y- extents of printable objects.
905 For X extents, the @code{car} is the left hand X coordinate, and the
906 @code{cdr} is the right hand X coordinate.  For Y extents, the @code{car}
907 is the bottom coordinate, and the @code{cdr} is the top coordinate.
908
909 Procedures for working with intervals are found in
910 @file{scm/lily-library.scm}.  These procedures should be used when possible
911 to ensure consistency of code.
912
913 @subheading Property alists
914
915 A property alist is a LilyPond data structure that is an alist whose
916 keys are properties and whose values are Scheme expressions that give
917 the desired value for the property.
918
919 LilyPond properties are Scheme symbols, such as @code{'thickness}.
920
921 @subheading Alist chains
922
923 An alist chain is a list containing property alists.
924
925 The set of all properties that will apply to a grob is typically
926 stored as an alist chain.  In order to find the value for a particular
927 property that a grob should have, each alist in the chain is searched in
928 order, looking for an entry containing the property key.  The first alist
929 entry found is returned, and the value is the property value.
930
931 The Scheme procedure @code{chain-assoc-get} is normally used to get
932 grob property values.
933
934 @node Internal music representation
935 @subsection Internal music representation
936
937 Internally, music is represented as a Scheme list.  The list contains
938 various elements that affect the printed output.  Parsing is the process
939 of converting music from the LilyPond input representation to the
940 internal Scheme representation.
941
942 When a music expression is parsed, it is converted into a set of
943 Scheme music objects.  The defining property of a music object is that
944 it takes up time.  The time it takes up is called its @emph{duration}.
945 Durations are expressed as a rational number that measures the length
946 of the music object in whole notes.
947
948 A music object has three kinds of types:
949 @itemize
950 @item
951 music name: Each music expression has a name.  For example, a note
952 leads to a @rinternals{NoteEvent}, and @code{\simultaneous} leads to
953 a @rinternals{SimultaneousMusic}.  A list of all expressions
954 available is in the Internals Reference manual, under
955 @rinternals{Music expressions}.
956
957 @item
958 @q{type} or interface: Each music name has several @q{types} or
959 interfaces, for example, a note is an @code{event}, but it is also a
960 @code{note-event}, a @code{rhythmic-event}, and a
961 @code{melodic-event}.  All classes of music are listed in the
962 Internals Reference, under
963 @rinternals{Music classes}.
964
965 @item
966 C++ object: Each music object is represented by an object of the C++
967 class @code{Music}.
968 @end itemize
969
970 The actual information of a music expression is stored in properties.
971 For example, a @rinternals{NoteEvent} has @code{pitch} and
972 @code{duration} properties that store the pitch and duration of that
973 note.  A list of all properties available can be found in the
974 Internals Reference, under @rinternals{Music properties}.
975
976 A compound music expression is a music object that contains other
977 music objects in its properties.  A list of objects can be stored in
978 the @code{elements} property of a music object, or a single @q{child}
979 music object in the @code{element} property.  For example,
980 @rinternals{SequentialMusic} has its children in @code{elements},
981 and @rinternals{GraceMusic} has its single argument in
982 @code{element}.  The body of a repeat is stored in the @code{element}
983 property of @rinternals{RepeatedMusic}, and the alternatives in
984 @code{elements}.
985
986 @node Building complicated functions
987 @section Building complicated functions
988
989 This section explains how to gather the information necessary
990 to create complicated music functions.
991
992 @menu
993 * Displaying music expressions::
994 * Music properties::
995 * Doubling a note with slurs (example)::
996 * Adding articulation to notes (example)::
997 @end menu
998
999 @node Displaying music expressions
1000 @subsection Displaying music expressions
1001
1002 @cindex internal storage
1003 @cindex displaying music expressions
1004 @cindex internal representation, displaying
1005 @cindex displayMusic
1006 @funindex \displayMusic
1007
1008 When writing a music function it is often instructive to inspect how
1009 a music expression is stored internally.  This can be done with the
1010 music function @code{\displayMusic}
1011
1012 @example
1013 @{
1014   \displayMusic @{ c'4\f @}
1015 @}
1016 @end example
1017
1018 @noindent
1019 will display
1020
1021 @example
1022 (make-music
1023   'SequentialMusic
1024   'elements
1025   (list (make-music
1026           'EventChord
1027           'elements
1028           (list (make-music
1029                   'NoteEvent
1030                   'duration
1031                   (ly:make-duration 2 0 1 1)
1032                   'pitch
1033                   (ly:make-pitch 0 0 0))
1034                 (make-music
1035                   'AbsoluteDynamicEvent
1036                   'text
1037                   "f")))))
1038 @end example
1039
1040 By default, LilyPond will print these messages to the console along
1041 with all the other messages.  To split up these messages and save
1042 the results of @code{\display@{STUFF@}}, redirect the output to
1043 a file.
1044
1045 @example
1046 lilypond file.ly >display.txt
1047 @end example
1048
1049 With a combined bit of Lilypond and Scheme magick, you can actually
1050 let Lilypond direct just this output to a file of its own:
1051
1052 @example
1053 @{
1054   $(with-output-to-file "display.txt"
1055       (lambda () #@{ \displayMusic @{ c'4\f @} #@}))
1056 @}
1057 @end example
1058
1059
1060 A bit of reformatting makes the above information easier to read:
1061
1062 @example
1063 (make-music 'SequentialMusic
1064   'elements (list (make-music 'EventChord
1065                     'elements (list (make-music 'NoteEvent
1066                                       'duration (ly:make-duration 2 0 1 1)
1067                                       'pitch (ly:make-pitch 0 0 0))
1068                                     (make-music 'AbsoluteDynamicEvent
1069                                       'text "f")))))
1070 @end example
1071
1072 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
1073 and its inner expressions are stored as a list in its @code{'elements}
1074 property.  A note is represented as an @code{EventChord} expression,
1075 containing a @code{NoteEvent} object (storing the duration and
1076 pitch properties) and any extra information (in this case, an
1077 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
1078
1079 @funindex{\void}
1080 @code{\displayMusic} returns the music it displays, so it will get
1081 interpreted as well as displayed.  To avoid interpretation, write
1082 @code{\void} before @code{\displayMusic}.
1083
1084 @node Music properties
1085 @subsection Music properties
1086
1087 TODO -- make sure we delineate between @emph{music} properties,
1088 @emph{context} properties, and @emph{layout} properties.  These
1089 are potentially confusing.
1090
1091 The @code{NoteEvent} object is the first object of the
1092 @code{'elements} property of @code{someNote}.
1093
1094 @example
1095 someNote = c'
1096 \displayMusic \someNote
1097 ===>
1098 (make-music
1099   'EventChord
1100   'elements
1101   (list (make-music
1102           'NoteEvent
1103           'duration
1104           (ly:make-duration 2 0 1 1)
1105           'pitch
1106           (ly:make-pitch 0 0 0))))
1107 @end example
1108
1109 The @code{display-scheme-music} function is the function used by
1110 @code{\displayMusic} to display the Scheme representation of a music
1111 expression.
1112
1113 @example
1114 #(display-scheme-music (first (ly:music-property someNote 'elements)))
1115 ===>
1116 (make-music
1117   'NoteEvent
1118   'duration
1119   (ly:make-duration 2 0 1 1)
1120   'pitch
1121   (ly:make-pitch 0 0 0))
1122 @end example
1123
1124 Then the note pitch is accessed through the @code{'pitch} property
1125 of the @code{NoteEvent} object,
1126
1127 @example
1128 #(display-scheme-music
1129    (ly:music-property (first (ly:music-property someNote 'elements))
1130                       'pitch))
1131 ===>
1132 (ly:make-pitch 0 0 0)
1133 @end example
1134
1135 The note pitch can be changed by setting this @code{'pitch} property,
1136
1137 @funindex \displayLilyMusic
1138
1139 @example
1140 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
1141                           'pitch)
1142        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
1143 \displayLilyMusic \someNote
1144 ===>
1145 d'
1146 @end example
1147
1148
1149 @node Doubling a note with slurs (example)
1150 @subsection Doubling a note with slurs (example)
1151
1152 Suppose we want to create a function that translates input like
1153 @code{a} into @code{a( a)}.  We begin by examining the internal
1154 representation of the desired result.
1155
1156 @example
1157 \displayMusic@{ a'( a') @}
1158 ===>
1159 (make-music
1160   'SequentialMusic
1161   'elements
1162   (list (make-music
1163           'EventChord
1164           'elements
1165           (list (make-music
1166                   'NoteEvent
1167                   'duration
1168                   (ly:make-duration 2 0 1 1)
1169                   'pitch
1170                   (ly:make-pitch 0 5 0))
1171                 (make-music
1172                   'SlurEvent
1173                   'span-direction
1174                   -1)))
1175         (make-music
1176           'EventChord
1177           'elements
1178           (list (make-music
1179                   'NoteEvent
1180                   'duration
1181                   (ly:make-duration 2 0 1 1)
1182                   'pitch
1183                   (ly:make-pitch 0 5 0))
1184                 (make-music
1185                   'SlurEvent
1186                   'span-direction
1187                   1)))))
1188 @end example
1189
1190 The bad news is that the @code{SlurEvent} expressions
1191 must be added @q{inside} the note (or more precisely,
1192 inside the @code{EventChord} expression).
1193
1194 Now we examine the input,
1195
1196 @example
1197 (make-music
1198   'SequentialMusic
1199   'elements
1200   (list (make-music
1201           'EventChord
1202           'elements
1203           (list (make-music
1204                   'NoteEvent
1205                   'duration
1206                   (ly:make-duration 2 0 1 1)
1207                   'pitch
1208                   (ly:make-pitch 0 5 0))))))
1209 @end example
1210
1211 So in our function, we need to clone this expression (so that we
1212 have two notes to build the sequence), add a @code{SlurEvent} to the
1213 @code{'elements} property of each one, and finally make a
1214 @code{SequentialMusic} with the two @code{EventChords}.
1215
1216 @example
1217 doubleSlur = #(define-music-function (parser location note) (ly:music?)
1218          "Return: @{ note ( note ) @}.
1219          `note' is supposed to be an EventChord."
1220          (let ((note2 (ly:music-deep-copy note)))
1221            (set! (ly:music-property note 'elements)
1222                  (cons (make-music 'SlurEvent 'span-direction -1)
1223                        (ly:music-property note 'elements)))
1224            (set! (ly:music-property note2 'elements)
1225                  (cons (make-music 'SlurEvent 'span-direction 1)
1226                        (ly:music-property note2 'elements)))
1227            (make-music 'SequentialMusic 'elements (list note note2))))
1228 @end example
1229
1230
1231 @node Adding articulation to notes (example)
1232 @subsection Adding articulation to notes (example)
1233
1234 The easy way to add articulation to notes is to merge two music
1235 expressions into one context, as explained in
1236 @ruser{Creating contexts}.  However, suppose that we want to write
1237 a music function that does this.
1238
1239 A @code{$variable} inside the @code{#@{...#@}} notation is like
1240 a regular @code{\variable} in classical LilyPond notation.  We
1241 know that
1242
1243 @example
1244 @{ \music -. -> @}
1245 @end example
1246
1247 @noindent
1248 will not work in LilyPond.  We could avoid this problem by attaching
1249 the articulation to a fake note,
1250
1251 @example
1252 @{ << \music s1*0-.-> @}
1253 @end example
1254
1255 @noindent
1256 but for the sake of this example, we will learn how to do this in
1257 Scheme.  We begin by examining our input and desired output,
1258
1259 @example
1260 %  input
1261 \displayMusic c4
1262 ===>
1263 (make-music
1264   'EventChord
1265   'elements
1266   (list (make-music
1267           'NoteEvent
1268           'duration
1269           (ly:make-duration 2 0 1 1)
1270           'pitch
1271           (ly:make-pitch -1 0 0))))
1272 =====
1273 %  desired output
1274 \displayMusic c4->
1275 ===>
1276 (make-music
1277   'EventChord
1278   'elements
1279   (list (make-music
1280           'NoteEvent
1281           'duration
1282           (ly:make-duration 2 0 1 1)
1283           'pitch
1284           (ly:make-pitch -1 0 0))
1285         (make-music
1286           'ArticulationEvent
1287           'articulation-type
1288           "marcato")))
1289 @end example
1290
1291 We see that a note (@code{c4}) is represented as an @code{EventChord}
1292 expression, with a @code{NoteEvent} expression in its elements list.  To
1293 add a marcato articulation, an @code{ArticulationEvent} expression must
1294 be added to the elements property of the @code{EventChord}
1295 expression.
1296
1297 To build this function, we begin with
1298
1299 @example
1300 (define (add-marcato event-chord)
1301   "Add a marcato ArticulationEvent to the elements of `event-chord',
1302   which is supposed to be an EventChord expression."
1303   (let ((result-event-chord (ly:music-deep-copy event-chord)))
1304     (set! (ly:music-property result-event-chord 'elements)
1305           (cons (make-music 'ArticulationEvent
1306                   'articulation-type "marcato")
1307                 (ly:music-property result-event-chord 'elements)))
1308     result-event-chord))
1309 @end example
1310
1311 The first line is the way to define a function in Scheme: the function
1312 name is @code{add-marcato}, and has one variable called
1313 @code{event-chord}.  In Scheme, the type of variable is often clear
1314 from its name.  (this is good practice in other programming languages,
1315 too!)
1316
1317 @example
1318 "Add a marcato..."
1319 @end example
1320
1321 @noindent
1322 is a description of what the function does.  This is not strictly
1323 necessary, but just like clear variable names, it is good practice.
1324
1325 @example
1326 (let ((result-event-chord (ly:music-deep-copy event-chord)))
1327 @end example
1328
1329 @code{let} is used to declare local variables.  Here we use one local
1330 variable, named @code{result-event-chord}, to which we give the value
1331 @code{(ly:music-deep-copy event-chord)}.  @code{ly:music-deep-copy} is
1332 a function specific to LilyPond, like all functions prefixed by
1333 @code{ly:}.  It is use to make a copy of a music
1334 expression.  Here we copy @code{event-chord} (the parameter of the
1335 function).  Recall that our purpose is to add a marcato to an
1336 @code{EventChord} expression.  It is better to not modify the
1337 @code{EventChord} which was given as an argument, because it may be
1338 used elsewhere.
1339
1340 Now we have a @code{result-event-chord}, which is a
1341 @code{NoteEventChord} expression and is a copy of
1342 @code{event-chord}.  We add the marcato to its @code{'elements}
1343 list property.
1344
1345 @example
1346 (set! place new-value)
1347 @end example
1348
1349 Here, what we want to set (the @q{place}) is the @code{'elements}
1350 property of @code{result-event-chord} expression.
1351
1352 @example
1353 (ly:music-property result-event-chord 'elements)
1354 @end example
1355
1356 @code{ly:music-property} is the function used to access music properties
1357 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
1358 see in the @code{\displayMusic} output above).  The new value is the
1359 former @code{'elements} property, with an extra item: the
1360 @code{ArticulationEvent} expression, which we copy from the
1361 @code{\displayMusic} output,
1362
1363 @example
1364 (cons (make-music 'ArticulationEvent
1365         'articulation-type "marcato")
1366       (ly:music-property result-event-chord 'elements))
1367 @end example
1368
1369 @code{cons} is used to add an element to a list without modifying
1370 the original list.  This is what we want: the same list as before,
1371 plus the new @code{ArticulationEvent} expression.  The order
1372 inside the @code{'elements} property is not important here.
1373
1374 Finally, once we have added the marcato articulation to its @code{elements}
1375 property, we can return @code{result-event-chord}, hence the last line of
1376 the function.
1377
1378 Now we transform the @code{add-marcato} function into a music
1379 function,
1380
1381 @example
1382 addMarcato = #(define-music-function (parser location event-chord)
1383                                      (ly:music?)
1384     "Add a marcato ArticulationEvent to the elements of `event-chord',
1385     which is supposed to be an EventChord expression."
1386     (let ((result-event-chord (ly:music-deep-copy event-chord)))
1387       (set! (ly:music-property result-event-chord 'elements)
1388             (cons (make-music 'ArticulationEvent
1389                     'articulation-type "marcato")
1390                   (ly:music-property result-event-chord 'elements)))
1391       result-event-chord))
1392 @end example
1393
1394 We may verify that this music function works correctly,
1395
1396 @example
1397 \displayMusic \addMarcato c4
1398 @end example
1399
1400
1401
1402
1403
1404 @ignore
1405 @menu
1406 * Tweaking with Scheme::
1407 @end menu
1408
1409 @c @nod e Tweaking with Scheme
1410 @c @sectio n Tweaking with Scheme
1411
1412 We have seen how LilyPond output can be heavily modified using
1413 commands like
1414 @code{\override TextScript #'extra-offset = ( 1 . -1)}.  But
1415 we have even more power if we use Scheme.  For a full explanation
1416 of this, see the @ref{Scheme tutorial}, and
1417 @ref{Interfaces for programmers}.
1418
1419 We can use Scheme to simply @code{\override} commands,
1420
1421 TODO Find a simple example
1422 @c This isn't a valid example with skylining
1423 @c It works fine without padText  -td
1424 @end ignore
1425
1426 @ignore
1427 @lilypond[quote,verbatim,ragged-right]
1428 padText = #(define-music-function (parser location padding) (number?)
1429 #{
1430   \once \override TextScript #'padding = #padding
1431 #})
1432
1433 \relative c''' {
1434   c4^"piu mosso" b a b
1435   \padText #1.8
1436   c4^"piu mosso" d e f
1437   \padText #2.6
1438   c4^"piu mosso" fis a g
1439 }
1440 @end lilypond
1441 @end ignore
1442
1443 @ignore
1444 We can use it to create new commands:
1445
1446 @c Check this is a valid example with skylining
1447 @c It is - 'padding still works
1448
1449
1450 @lilypond[quote,verbatim,ragged-right]
1451 tempoPadded = #(define-music-function (parser location padding tempotext)
1452   (number? string?)
1453 #{
1454   \once \override Score.MetronomeMark #'padding = $padding
1455   \tempo \markup { \bold #tempotext }
1456 #})
1457
1458 \relative c'' {
1459   \tempo \markup { "Low tempo" }
1460   c4 d e f g1
1461   \tempoPadded #4.0 #"High tempo"
1462   g4 f e d c1
1463 }
1464 @end lilypond
1465
1466
1467 Even music expressions can be passed in:
1468
1469 @lilypond[quote,verbatim,ragged-right]
1470 pattern = #(define-music-function (parser location x y) (ly:music? ly:music?)
1471 #{
1472   $x e8 a b $y b a e
1473 #})
1474
1475 \relative c''{
1476   \pattern c8 c8\f
1477   \pattern {d16 dis} { ais16-> b\p }
1478 }
1479 @end lilypond
1480 @end ignore