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