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