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