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