]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/extending/scheme-tutorial.itely
Merge branch 'lilypond/translation' of ssh://git.sv.gnu.org/srv/git/lilypond
[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.  See TRANSLATION for details.
8 @end ignore
9
10 @c \version "2.12.0"
11
12 @node Scheme tutorial
13 @chapter Scheme tutorial
14
15 @funindex #
16 @cindex Scheme
17 @cindex GUILE
18 @cindex Scheme, in-line code
19 @cindex accessing Scheme
20 @cindex evaluating Scheme
21 @cindex LISP
22
23 LilyPond uses the Scheme programming language, both as part of the
24 input syntax, and as internal mechanism to glue modules of the program
25 together.  This section is a very brief overview of entering data in
26 Scheme.  If you want to know more about Scheme, see
27 @uref{http://@/www@/.schemers@/.org}.
28
29 LilyPond uses the GNU Guile implementation of Scheme, which is
30 based on the Scheme @qq{R5RS} standard. If you are learning Scheme
31 to use with LilyPond, working with a different implementation (or
32 referring to a different standard) is not recommended. Information
33 on guile can be found at @uref{http://www.gnu.org/software/guile/}.
34 The @qq{R5RS} Scheme standard is located at
35 @uref{http://www.schemers.org/Documents/Standards/R5RS/}.
36
37 @menu
38 * Introduction to Scheme::
39 * Scheme in LilyPond::
40 * Building complicated functions::
41 @end menu
42
43 @node Introduction to Scheme
44 @section Introduction to Scheme
45
46 We begin with an introduction to Scheme.  For this brief introduction,
47 we will use the GUILE interpreter to explore how the language works.
48 Once we are familiar with Scheme, we will show how the language can
49 be integrated in LilyPond files.
50
51
52 @menu
53 * Scheme sandbox::
54 * Scheme variables::
55 * Scheme simple data types::
56 * Scheme compound data types::
57 * Calculations in Scheme::
58 * Scheme procedures::
59 * Scheme conditionals::
60 @end menu
61
62 @node Scheme sandbox
63 @subsection Scheme sandbox
64
65 The LilyPond installation includes the Guile implementation of
66 Scheme.  On most systems you can experiment in a Scheme sandbox by
67 opening a terminal window and typing @q{guile}.  On some systems,
68 notably Windows, you may need to set the environment variable
69 @code{GUILE_LOAD_PATH} to the directory @code{../usr/shr/guile/1.8}
70 in the LilyPond installation. For the full path to this directory
71 see @rlearning{Other sources of information}.  Alternatively, Windows
72 users may simply choose @q{Run} from the Start menu and enter
73 @q{guile}.
74
75 Once the guile sandbox is running, you will received a guile prompt:
76
77 @lisp
78 guile>
79 @end lisp
80
81 You can enter Scheme expressions at this prompt to experiment with Scheme.
82
83 @node Scheme variables
84 @subsection Scheme variables
85
86 Scheme variables can have any valid scheme value, including a Scheme
87 procedure.
88
89 Scheme variables are created with @code{define}:
90
91 @lisp
92 guile> (define a 2)
93 guile>
94 @end lisp
95
96 Scheme variables can be evaluated at the guile prompt simply by
97 typing the variable name:
98
99 @lisp
100 guile> a
101 2
102 guile>
103 @end lisp
104
105 Scheme variables can be printed on the display by use of the display function:
106
107 @lisp
108 guile> (display a)
109 2guile>
110 @end lisp
111
112 @noindent
113 Note that the value @code{2} and the guile prompt @code{guile} both
114 showed up on the same line.  This can be avoided by calling the newline
115 procedure or displaying a newline character.
116
117 @lisp
118 guile> (display a)(newline)
119 2
120 guile> (display a)(display "\n")
121 2
122 guile>
123 @end lisp
124
125 Once a variable has been created, its value can be changed with @code{set!}:
126
127 @lisp
128 guile> (set! a 12345)
129 guile> a
130 12345
131 guile>
132 @end lisp
133
134 @node Scheme simple data types
135 @subsection Scheme simple data types
136
137 The most basic concept in a language is data typing: numbers, character
138 strings, lists, etc.  Here is a list of simple Scheme data types that are
139 often used with LilyPond.
140
141 @table @asis
142 @item Booleans
143 Boolean values are True or False.  The Scheme for True is @code{#t}
144 and False is @code{#f}.
145 @funindex ##t
146 @funindex ##f
147
148 @item Numbers
149 Numbers are entered in the standard fashion,
150 @code{1} is the (integer) number one, while @code{-1.5} is a
151 floating point number (a non-integer number).
152
153 @item Strings
154 Strings are enclosed in double quotes,
155
156 @example
157 "this is a string"
158 @end example
159
160 Strings may span several lines:
161
162 @example
163 "this
164 is
165 a string"
166 @end example
167
168 @noindent
169 and the newline characters at the end of each line will be included
170 in the string.
171
172 Newline characters can also be added by including @code{\n} in the
173 string.
174
175 @example
176 "this\nis a\nmultiline string"
177 @end example
178
179
180 Quotation marks and backslashes are added to strings
181 by preceding them with a backslash.
182 The string @code{\a said "b"} is entered as
183
184 @example
185 "\\a said \"b\""
186 @end example
187
188 @end table
189
190 There are additional Scheme data types that are not discussed here.
191 For a complete listing see the Guile reference guide,
192 @uref{http://www.gnu.org/software/guile/manual/html_node/Simple-Data-Types.html}.
193
194 @node Scheme compound data types
195 @subsection Scheme compound data types
196
197 There are also compound data types in Scheme.  The  types commonly used in
198 LilyPond programming include pairs, lists, alists, and hash tables.
199
200 @unnumberedsubsubsec Pairs
201
202 The foundational compound data type of Scheme is the @code{pair}.  As
203 might be expected from its name, a pair is two values glued together.
204 The operator used to form a pair is called @code{cons}.
205
206 @lisp
207 guile> (cons 4 5)
208 (4 . 5)
209 guile>
210 @end lisp
211
212 Note that the pair is displayed as two items surrounded by
213 parentheses and separated by whitespace, a period (@code{.}), and
214 more whitespace.  The period is @emph{not} a decimal point, but
215 rather an indicator of the pair.
216
217 Pairs can also be entered as literal values by preceding them with
218 a single quote character.
219
220 @lisp
221 guile> '(4 . 5)
222 (4 . 5)
223 guile>
224 @end lisp
225
226 The two elements of a pair may be any valid Scheme value:
227
228 @lisp
229 guile> (cons #t #f)
230 (#t . #f)
231 guile> '("blah-blah" . 3.1415926535)
232 ("blah-blah" . 3.1415926535)
233 guile>
234 @end lisp
235
236 The first and second elements of the pair can be accessed by the
237 Scheme procedures @code{car} and @code{cdr}, respectively.
238
239 @lisp
240 guile> (define mypair (cons 123 "hello there")
241 ... )
242 guile> (car mypair)
243 123
244 guile> (cdr mypair)
245 "hello there"
246 guile>
247 @end lisp
248
249 @noindent
250
251 Note:  @code{cdr} is pronounced "could-er", according Sussman and
252 Abelson, see
253 @uref{http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html#footnote_Temp_133}
254
255
256 @unnumberedsubsubsec Lists
257
258 A very common Scheme data structure is the @emph{list}.  Formally, a
259 list is defined as either the empty list (represented as @code{'()},
260 or a pair whose @code{cdr} is a list.
261
262 There are many ways of creating lists.  Perhaps the most common is
263 with the @code{list} procedure:
264
265 @lisp
266 guile> (list 1 2 3 "abc" 17.5)
267 (1 2 3 "abc" 17.5)
268 @end lisp
269
270 As can be seen, a list is displayed in the form of individual elements
271 separated by whitespace and enclosed in parentheses.  Unlike a pair,
272 there is no period between the elements.
273
274 A list can also be entered as a literal list by enclosing its
275 elements in parentheses, and adding a quote:
276
277 @lisp
278 guile> '(17 23 "foo" "bar" "bazzle")
279 (17 23 "foo" "bar" "bazzle")
280 @end lisp
281
282 Lists are a central part of Scheme.  In, fact, Scheme is considered
283 a dialect of lisp, where @q{lisp} is an abbreviation for
284 @q{List Processing}.  Scheme expressions are all lists.
285
286 @unnumberedsubsubsec Association lists (alists)
287
288 A special type of list is an @emph{association list} or @emph{alist}.
289 An alist is used to store data for easy retrieval.
290
291 Alists are lists whose elements are pairs.  The @code{car} of each
292 element is called the @emph{key}, and the @code{cdr} of each element
293 is called the @emph{value}.  The Scheme procedure @code{assoc} is
294 used to retrieve an entry from the alist, and @code{cdr} is used to
295 retrieve the value:
296
297 @lisp
298 guile> (define my-alist '((1  . "A") (2 . "B") (3 . "C")))
299 guile> my-alist
300 ((1 . "A") (2 . "B") (3 . "C"))
301 guile> (assoc 2 my-alist)
302 (2 . "B")
303 guile> (cdr (assoc 2 my-alist))
304 "B"
305 guile>
306 @end lisp
307
308 Alists are widely used in LilyPond to store properties and other data.
309
310 @unnumberedsubsubsec Hash tables
311
312 A data structure that is used occasionally in LilyPond.  A hash table
313 is similar to an array, but the indexes to the array can be any type
314 of Scheme value, not just integers.
315
316 Hash tables are more efficient than alists if there is a lot of data
317 to store and the data changes very infrequently.
318
319 The syntax to create hash tables is a bit complex, but you
320 can see examples of it in the LilyPond source.
321
322 @lisp
323 guile> (define h (make-hash-table 10))
324 guile> h
325 #<hash-table 0/31>
326 guile> (hashq-set! h 'key1 "val1")
327 "val1"
328 guile> (hashq-set! h 'key2 "val2")
329 "val2"
330 guile> (hashq-set! h 3 "val3")
331 "val3"
332 @end lisp
333
334 Values are retrieved from hash tables with @code{hashq-ref}.
335
336 @lisp
337 guile> (hashq-ref h 3)
338 "val3"
339 guile> (hashq-ref h 'key2)
340 "val2"
341 guile>
342 @end lisp
343
344 Keys and values are retrieved as a pair with @code{hashq-get-handle}.
345 This is a preferred way, because it will return @code{#f} if a key is
346 not found.
347
348 @lisp
349 guile> (hashq-get-handle h 'key1)
350 (key1 . "val1")
351 guile> (hashq-get-handle h 'frob)
352 #f
353 guile>
354 @end lisp
355
356 @node Calculations in Scheme
357 @subsection Calculations in Scheme
358
359 @ignore
360 We have been using lists all along.  A calculation, like @code{(+ 1 2)}
361 is also a list (containing the symbol @code{+} and the numbers 1
362 and@tie{}2).  Normally lists are interpreted as calculations, and the
363 Scheme interpreter substitutes the outcome of the calculation.  To enter a
364 list, we stop the evaluation.  This is done by quoting the list with a
365 quote @code{'} symbol.  So, for calculations do not use a quote.
366
367 Inside a quoted list or pair, there is no need to quote anymore.  The
368 following is a pair of symbols, a list of symbols and a list of lists
369 respectively,
370
371 @example
372 #'(stem . head)
373 #'(staff clef key-signature)
374 #'((1) (2))
375 @end example
376 @end ignore
377
378 Scheme can be used to do calculations.  It uses @emph{prefix}
379 syntax.  Adding 1 and@tie{}2 is written as @code{(+ 1 2)} rather than the
380 traditional @math{1+2}.
381
382 @lisp
383 guile> (+ 1 2)
384 3
385 @end lisp
386
387 Calculations may be nested; the result of a function may
388 be used for another calculation.
389
390 @lisp
391 guile> (+ 1 (* 3 4))
392 13
393 guile> (+ 1 (* 3 4))
394 @end lisp
395
396 These calculations are examples of evaluations; an expression like
397 @code{(* 3 4)} is replaced by its value @code{12}.
398
399 When the scheme parser encounters an expression that is a list, the
400 first element of the list is treated as a procedure to be evaluated
401 with the arguments of the remainder of the list.  Therefore, all operators
402 in Scheme are prefix operators.
403
404 If the first element of a Scheme expression that is a list passed to the parser
405 is @emph{not} an operator or procedure, an error will occur:
406
407 @lisp
408 guile> (1 2 3)
409
410 Backtrace:
411 In current input:
412   52: 0* [1 2 3]
413
414 <unnamed port>:52:1: In expression (1 2 3):
415 <unnamed port>:52:1: Wrong type to apply: 1
416 ABORT: (misc-error)
417 guile>
418 @end lisp
419
420 Here you can see that the interpreter was trying to treat 1 as an operator
421 or procedure, and it couldn't.  Hence the error is "Wrong type to apply: 1".
422
423 To create a list, then , we need to use the list operator, or we need to
424 quote the list so that the interpreter will not try to evaluate it.
425
426 @lisp
427 guile> (list 1 2 3)
428 (1 2 3)
429 guile> '(1 2 3)
430 (1 2 3)
431 guile>
432 @end lisp
433
434 This is an error that can appear as you are working with Scheme in LilyPond.
435
436 @ignore
437 The same assignment can be done in completely in Scheme as well,
438
439 @example
440 #(define twentyFour (* 2 twelve))
441 @end example
442
443 @c this next section is confusing -- need to rewrite
444
445 The @emph{name} of a variable is also an expression, similar to a
446 number or a string.  It is entered as
447
448 @example
449 #'twentyFour
450 @end example
451
452 @funindex #'symbol
453 @cindex quoting in Scheme
454
455 The quote mark @code{'} prevents the Scheme interpreter from substituting
456 @code{24} for the @code{twentyFour}.  Instead, we get the name
457 @code{twentyFour}.
458 @end ignore
459
460
461 @node Scheme procedures
462 @subsection Scheme procedures
463
464 @unnumberedsubsubsec Predicates
465
466 @unnumberedsubsubsec Return values
467
468 TODO -- write about scheme procedures
469
470 @node Scheme conditionals
471 @subsection Scheme conditionals
472
473 @unnumberedsubsubsec if
474
475 @unnumberedsubsubsec cond
476
477
478 @node Scheme in LilyPond
479 @section Scheme in LilyPond
480
481
482 @menu
483 * LilyPond Scheme syntax::
484 * LilyPond variables::
485 * Input variables and Scheme::
486 * Object properties::
487 * LilyPond compound variables::
488 * Internal music representation::
489 @end menu
490
491 @node LilyPond Scheme syntax
492 @subsection LilyPond Scheme syntax
493
494 In a music file, snippets of Scheme code are introduced with the hash
495 mark @code{#}.  So, the previous examples translated to LilyPond are
496
497 @example
498 ##t ##f
499 #1 #-1.5
500 #"this is a string"
501 #"this
502 is
503 a string"
504 @end example
505
506 Note that LilyPond comments (@code{%} and @code{%@{ %@}}) cannot
507 be used within Scheme code.  Comments in Guile Scheme are entered
508 as follows:
509
510 @example
511 ; this is a single-line comment
512
513 #!
514   This a (non-nestable) Guile-style block comment
515   But these are rarely used by Schemers and never in
516   LilyPond source code
517 !#
518 @end example
519
520 Multiple consecutive scheme expressions in a music file can be
521 combined using the @code{begin} operator. This permits the number
522 of hash marks to be reduced to one.
523
524 @example
525 #(begin
526   (define foo 0)
527   (define bar 1))
528 @end example
529
530 @c todo -- # introduces a scheme *expression*
531 @c         need the concept of an expression
532
533 If @code{#} is followed by an opening parenthesis, @code{(}, as in
534 the example above, the parser will remain in Scheme mode until
535 a matching closing parenthesis, @code{)}, is found, so further
536 @code{#} symbols to introduce a Scheme section are not required.
537
538 For the rest of this section, we will assume that the data is entered
539 in a music file, so we add @code{#}s everywhere.
540
541 @node LilyPond variables
542 @subsection LilyPond variables
543
544
545 TODO -- make this read right
546
547 A similar thing
548 happens with variables.  After defining a variable
549
550 @example
551 twelve = 12
552 @end example
553
554 @noindent
555 variables can also be used in expressions, here
556
557 @example
558 twentyFour = (* 2 twelve)
559 @end example
560
561 @noindent
562 the number 24 is stored in the variable @code{twentyFour}.
563
564 @node Input variables and Scheme
565 @subsection Input variables and Scheme
566
567 The input format supports the notion of variables: in the following
568 example, a music expression is assigned to a variable with the name
569 @code{traLaLa}.
570
571 @example
572 traLaLa = @{ c'4 d'4 @}
573 @end example
574
575 @noindent
576
577 There is also a form of scoping: in the following example, the
578 @code{\layout} block also contains a @code{traLaLa} variable, which is
579 independent of the outer @code{\traLaLa}.
580 @example
581 traLaLa = @{ c'4 d'4 @}
582 \layout @{ traLaLa = 1.0 @}
583 @end example
584 @c
585 In effect, each input file is a scope, and all @code{\header},
586 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
587 toplevel scope.
588
589 Both variables and scoping are implemented in the GUILE module system.
590 An anonymous Scheme module is attached to each scope.  An assignment of
591 the form
592 @example
593 traLaLa = @{ c'4 d'4 @}
594 @end example
595
596 @noindent
597 is internally converted to a Scheme definition
598 @example
599 (define traLaLa @var{Scheme value of `@code{... }'})
600 @end example
601
602 This means that input variables and Scheme variables may be freely
603 mixed.  In the following example, a music fragment is stored in the
604 variable @code{traLaLa}, and duplicated using Scheme.  The result is
605 imported in a @code{\score} block by means of a second variable
606 @code{twice}:
607
608 @lilypond[verbatim]
609 traLaLa = { c'4 d'4 }
610
611 %% dummy action to deal with parser lookahead
612 #(display "this needs to be here, sorry!")
613
614 #(define newLa (map ly:music-deep-copy
615   (list traLaLa traLaLa)))
616 #(define twice
617   (make-sequential-music newLa))
618
619 { \twice }
620 @end lilypond
621
622 @c Due to parser lookahead
623
624 In this example, the assignment happens after the parser has
625 verified that nothing interesting happens after
626 @code{traLaLa = @{ ... @}}.  Without the dummy statement in the
627 above example, the @code{newLa} definition is executed before
628 @code{traLaLa} is defined, leading to a syntax error.
629
630 The above example shows how to @q{export} music expressions from the
631 input to the Scheme interpreter.  The opposite is also possible.  By
632 wrapping a Scheme value in the function @code{ly:export}, a Scheme
633 value is interpreted as if it were entered in LilyPond syntax.
634 Instead of defining @code{\twice}, the example above could also have
635 been written as
636
637 @example
638 ...
639 @{ #(ly:export (make-sequential-music (list newLa))) @}
640 @end example
641
642 Scheme code is evaluated as soon as the parser encounters it.  To
643 define some Scheme code in a macro (to be called later), use
644 @ref{Void functions}, or
645
646 @example
647 #(define (nopc)
648   (ly:set-option 'point-and-click #f))
649
650 ...
651 #(nopc)
652 @{ c'4 @}
653 @end example
654
655 @knownissues
656
657 Mixing Scheme and LilyPond variables is not possible with the
658 @code{--safe} option.
659
660
661
662
663 @node Object properties
664 @subsection Object properties
665
666 This syntax will be used very frequently, since many of the layout
667 tweaks involve assigning (Scheme) values to internal variables, for
668 example
669
670 @example
671 \override Stem #'thickness = #2.6
672 @end example
673
674 This instruction adjusts the appearance of stems.  The value @code{2.6}
675 is put into the @code{thickness} variable of a @code{Stem}
676 object.  @code{thickness} is measured relative to the thickness of
677 staff lines, so these stem lines will be @code{2.6} times the
678 width of staff lines.  This makes stems almost twice as thick as their
679 normal size.  To distinguish between variables defined in input files (like
680 @code{twentyFour} in the example above) and variables of internal
681 objects, we will call the latter @q{properties} and the former
682 @q{variables.}  So, the stem object has a @code{thickness} property,
683 while @code{twentyFour} is an variable.
684
685 @cindex properties vs. variables
686 @cindex variables vs. properties
687
688 @c  todo -- here we're getting interesting.  We're now introducing
689 @c  LilyPond variable types.  I think this deserves a section all
690 @c  its own
691
692 @node LilyPond compound variables
693 @subsection LilyPond compound variables
694
695 @unnumberedsubsubsec Offsets
696
697 Two-dimensional offsets (X and Y coordinates) as well as object sizes
698 (intervals with a left and right point) are entered as @code{pairs}.  A
699 pair@footnote{In Scheme terminology, the pair is called @code{cons},
700 and its two elements are called @code{car} and @code{cdr} respectively.}
701 is entered as @code{(first . second)} and, like symbols, they must be quoted,
702
703 @example
704 \override TextScript #'extra-offset = #'(1 . 2)
705 @end example
706
707 This assigns the pair (1, 2) to the @code{extra-offset} property of the
708 TextScript object.  These numbers are measured in staff-spaces, so
709 this command moves the object 1 staff space to the right, and 2 spaces up.
710
711 @unnumberedsubsubsec Extents
712
713 todo -- write something about extents
714
715 @unnumberedsubsubsec Property alists
716
717 todo -- write something about property alists
718
719 @unnumberedsubsubsec Alist chains
720
721 todo -- write something about alist chains
722
723 @node Internal music representation
724 @subsection Internal music representation
725
726 When a music expression is parsed, it is converted into a set of
727 Scheme music objects.  The defining property of a music object is that
728 it takes up time.  Time is a rational number that measures the length
729 of a piece of music in whole notes.
730
731 A music object has three kinds of types:
732 @itemize
733 @item
734 music name: Each music expression has a name.  For example, a note
735 leads to a @rinternals{NoteEvent}, and @code{\simultaneous} leads to
736 a @rinternals{SimultaneousMusic}.  A list of all expressions
737 available is in the Internals Reference manual, under
738 @rinternals{Music expressions}.
739
740 @item
741 @q{type} or interface: Each music name has several @q{types} or
742 interfaces, for example, a note is an @code{event}, but it is also a
743 @code{note-event}, a @code{rhythmic-event}, and a
744 @code{melodic-event}.  All classes of music are listed in the
745 Internals Reference, under
746 @rinternals{Music classes}.
747
748 @item
749 C++ object: Each music object is represented by an object of the C++
750 class @code{Music}.
751 @end itemize
752
753 The actual information of a music expression is stored in properties.
754 For example, a @rinternals{NoteEvent} has @code{pitch} and
755 @code{duration} properties that store the pitch and duration of that
756 note.  A list of all properties available can be found in the
757 Internals Reference, under @rinternals{Music properties}.
758
759 A compound music expression is a music object that contains other
760 music objects in its properties.  A list of objects can be stored in
761 the @code{elements} property of a music object, or a single @q{child}
762 music object in the @code{element} property.  For example,
763 @rinternals{SequentialMusic} has its children in @code{elements},
764 and @rinternals{GraceMusic} has its single argument in
765 @code{element}.  The body of a repeat is stored in the @code{element}
766 property of @rinternals{RepeatedMusic}, and the alternatives in
767 @code{elements}.
768
769 @node Building complicated functions
770 @section Building complicated functions
771
772 This section explains how to gather the information necessary
773 to create complicated music functions.
774
775 @menu
776 * Displaying music expressions::
777 * Music properties::
778 * Doubling a note with slurs (example)::
779 * Adding articulation to notes (example)::
780 @end menu
781
782
783 @node Displaying music expressions
784 @subsection Displaying music expressions
785
786 @cindex internal storage
787 @cindex displaying music expressions
788 @cindex internal representation, displaying
789 @cindex displayMusic
790 @funindex \displayMusic
791
792 When writing a music function it is often instructive to inspect how
793 a music expression is stored internally.  This can be done with the
794 music function @code{\displayMusic}
795
796 @example
797 @{
798   \displayMusic @{ c'4\f @}
799 @}
800 @end example
801
802 @noindent
803 will display
804
805 @example
806 (make-music
807   'SequentialMusic
808   'elements
809   (list (make-music
810           'EventChord
811           'elements
812           (list (make-music
813                   'NoteEvent
814                   'duration
815                   (ly:make-duration 2 0 1 1)
816                   'pitch
817                   (ly:make-pitch 0 0 0))
818                 (make-music
819                   'AbsoluteDynamicEvent
820                   'text
821                   "f")))))
822 @end example
823
824 By default, LilyPond will print these messages to the console along
825 with all the other messages.  To split up these messages and save
826 the results of @code{\display@{STUFF@}}, redirect the output to
827 a file.
828
829 @example
830 lilypond file.ly >display.txt
831 @end example
832
833 With a bit of reformatting, the above information is
834 easier to read,
835
836 @example
837 (make-music 'SequentialMusic
838   'elements (list (make-music 'EventChord
839                     'elements (list (make-music 'NoteEvent
840                                       'duration (ly:make-duration 2 0 1 1)
841                                       'pitch (ly:make-pitch 0 0 0))
842                                     (make-music 'AbsoluteDynamicEvent
843                                       'text "f")))))
844 @end example
845
846 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
847 and its inner expressions are stored as a list in its @code{'elements}
848 property.  A note is represented as an @code{EventChord} expression,
849 containing a @code{NoteEvent} object (storing the duration and
850 pitch properties) and any extra information (in this case, an
851 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
852
853
854 @node Music properties
855 @subsection Music properties
856
857 The @code{NoteEvent} object is the first object of the
858 @code{'elements} property of @code{someNote}.
859
860 @example
861 someNote = c'
862 \displayMusic \someNote
863 ===>
864 (make-music
865   'EventChord
866   'elements
867   (list (make-music
868           'NoteEvent
869           'duration
870           (ly:make-duration 2 0 1 1)
871           'pitch
872           (ly:make-pitch 0 0 0))))
873 @end example
874
875 The @code{display-scheme-music} function is the function used by
876 @code{\displayMusic} to display the Scheme representation of a music
877 expression.
878
879 @example
880 #(display-scheme-music (first (ly:music-property someNote 'elements)))
881 ===>
882 (make-music
883   'NoteEvent
884   'duration
885   (ly:make-duration 2 0 1 1)
886   'pitch
887   (ly:make-pitch 0 0 0))
888 @end example
889
890 Then the note pitch is accessed through the @code{'pitch} property
891 of the @code{NoteEvent} object,
892
893 @example
894 #(display-scheme-music
895    (ly:music-property (first (ly:music-property someNote 'elements))
896                       'pitch))
897 ===>
898 (ly:make-pitch 0 0 0)
899 @end example
900
901 The note pitch can be changed by setting this @code{'pitch} property,
902
903 @funindex \displayLilyMusic
904
905 @example
906 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
907                           'pitch)
908        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
909 \displayLilyMusic \someNote
910 ===>
911 d'
912 @end example
913
914
915 @node Doubling a note with slurs (example)
916 @subsection Doubling a note with slurs (example)
917
918 Suppose we want to create a function that translates input like
919 @code{a} into @code{a( a)}.  We begin by examining the internal
920 representation of the desired result.
921
922 @example
923 \displayMusic@{ a'( a') @}
924 ===>
925 (make-music
926   'SequentialMusic
927   'elements
928   (list (make-music
929           'EventChord
930           'elements
931           (list (make-music
932                   'NoteEvent
933                   'duration
934                   (ly:make-duration 2 0 1 1)
935                   'pitch
936                   (ly:make-pitch 0 5 0))
937                 (make-music
938                   'SlurEvent
939                   'span-direction
940                   -1)))
941         (make-music
942           'EventChord
943           'elements
944           (list (make-music
945                   'NoteEvent
946                   'duration
947                   (ly:make-duration 2 0 1 1)
948                   'pitch
949                   (ly:make-pitch 0 5 0))
950                 (make-music
951                   'SlurEvent
952                   'span-direction
953                   1)))))
954 @end example
955
956 The bad news is that the @code{SlurEvent} expressions
957 must be added @q{inside} the note (or more precisely,
958 inside the @code{EventChord} expression).
959
960 Now we examine the input,
961
962 @example
963 (make-music
964   'SequentialMusic
965   'elements
966   (list (make-music
967           'EventChord
968           'elements
969           (list (make-music
970                   'NoteEvent
971                   'duration
972                   (ly:make-duration 2 0 1 1)
973                   'pitch
974                   (ly:make-pitch 0 5 0))))))
975 @end example
976
977 So in our function, we need to clone this expression (so that we
978 have two notes to build the sequence), add @code{SlurEvents} to the
979 @code{'elements} property of each one, and finally make a
980 @code{SequentialMusic} with the two @code{EventChords}.
981
982 @example
983 doubleSlur = #(define-music-function (parser location note) (ly:music?)
984          "Return: @{ note ( note ) @}.
985          `note' is supposed to be an EventChord."
986          (let ((note2 (ly:music-deep-copy note)))
987            (set! (ly:music-property note 'elements)
988                  (cons (make-music 'SlurEvent 'span-direction -1)
989                        (ly:music-property note 'elements)))
990            (set! (ly:music-property note2 'elements)
991                  (cons (make-music 'SlurEvent 'span-direction 1)
992                        (ly:music-property note2 'elements)))
993            (make-music 'SequentialMusic 'elements (list note note2))))
994 @end example
995
996
997 @node Adding articulation to notes (example)
998 @subsection Adding articulation to notes (example)
999
1000 The easy way to add articulation to notes is to merge two music
1001 expressions into one context, as explained in
1002 @ruser{Creating contexts}.  However, suppose that we want to write
1003 a music function that does this.
1004
1005 A @code{$variable} inside the @code{#@{...#@}} notation is like
1006 a regular @code{\variable} in classical LilyPond notation.  We
1007 know that
1008
1009 @example
1010 @{ \music -. -> @}
1011 @end example
1012
1013 @noindent
1014 will not work in LilyPond.  We could avoid this problem by attaching
1015 the articulation to a fake note,
1016
1017 @example
1018 @{ << \music s1*0-.-> @}
1019 @end example
1020
1021 @noindent
1022 but for the sake of this example, we will learn how to do this in
1023 Scheme.  We begin by examining our input and desired output,
1024
1025 @example
1026 %  input
1027 \displayMusic c4
1028 ===>
1029 (make-music
1030   'EventChord
1031   'elements
1032   (list (make-music
1033           'NoteEvent
1034           'duration
1035           (ly:make-duration 2 0 1 1)
1036           'pitch
1037           (ly:make-pitch -1 0 0))))
1038 =====
1039 %  desired output
1040 \displayMusic c4->
1041 ===>
1042 (make-music
1043   'EventChord
1044   'elements
1045   (list (make-music
1046           'NoteEvent
1047           'duration
1048           (ly:make-duration 2 0 1 1)
1049           'pitch
1050           (ly:make-pitch -1 0 0))
1051         (make-music
1052           'ArticulationEvent
1053           'articulation-type
1054           "marcato")))
1055 @end example
1056
1057 We see that a note (@code{c4}) is represented as an @code{EventChord}
1058 expression, with a @code{NoteEvent} expression in its elements list.  To
1059 add a marcato articulation, an @code{ArticulationEvent} expression must
1060 be added to the elements property of the @code{EventChord}
1061 expression.
1062
1063 To build this function, we begin with
1064
1065 @example
1066 (define (add-marcato event-chord)
1067   "Add a marcato ArticulationEvent to the elements of `event-chord',
1068   which is supposed to be an EventChord expression."
1069   (let ((result-event-chord (ly:music-deep-copy event-chord)))
1070     (set! (ly:music-property result-event-chord 'elements)
1071           (cons (make-music 'ArticulationEvent
1072                   'articulation-type "marcato")
1073                 (ly:music-property result-event-chord 'elements)))
1074     result-event-chord))
1075 @end example
1076
1077 The first line is the way to define a function in Scheme: the function
1078 name is @code{add-marcato}, and has one variable called
1079 @code{event-chord}.  In Scheme, the type of variable is often clear
1080 from its name.  (this is good practice in other programming languages,
1081 too!)
1082
1083 @example
1084 "Add a marcato..."
1085 @end example
1086
1087 @noindent
1088 is a description of what the function does.  This is not strictly
1089 necessary, but just like clear variable names, it is good practice.
1090
1091 @example
1092 (let ((result-event-chord (ly:music-deep-copy event-chord)))
1093 @end example
1094
1095 @code{let} is used to declare local variables.  Here we use one local
1096 variable, named @code{result-event-chord}, to which we give the value
1097 @code{(ly:music-deep-copy event-chord)}.  @code{ly:music-deep-copy} is
1098 a function specific to LilyPond, like all functions prefixed by
1099 @code{ly:}.  It is use to make a copy of a music
1100 expression.  Here we copy @code{event-chord} (the parameter of the
1101 function).  Recall that our purpose is to add a marcato to an
1102 @code{EventChord} expression.  It is better to not modify the
1103 @code{EventChord} which was given as an argument, because it may be
1104 used elsewhere.
1105
1106 Now we have a @code{result-event-chord}, which is a
1107 @code{NoteEventChord} expression and is a copy of
1108 @code{event-chord}.  We add the marcato to its @code{'elements}
1109 list property.
1110
1111 @example
1112 (set! place new-value)
1113 @end example
1114
1115 Here, what we want to set (the @q{place}) is the @code{'elements}
1116 property of @code{result-event-chord} expression.
1117
1118 @example
1119 (ly:music-property result-event-chord 'elements)
1120 @end example
1121
1122 @code{ly:music-property} is the function used to access music properties
1123 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
1124 see in the @code{\displayMusic} output above).  The new value is the
1125 former @code{'elements} property, with an extra item: the
1126 @code{ArticulationEvent} expression, which we copy from the
1127 @code{\displayMusic} output,
1128
1129 @example
1130 (cons (make-music 'ArticulationEvent
1131         'articulation-type "marcato")
1132       (ly:music-property result-event-chord 'elements))
1133 @end example
1134
1135 @code{cons} is used to add an element to a list without modifying
1136 the original list.  This is what we want: the same list as before,
1137 plus the new @code{ArticulationEvent} expression.  The order
1138 inside the @code{'elements} property is not important here.
1139
1140 Finally, once we have added the marcato articulation to its @code{elements}
1141 property, we can return @code{result-event-chord}, hence the last line of
1142 the function.
1143
1144 Now we transform the @code{add-marcato} function into a music
1145 function,
1146
1147 @example
1148 addMarcato = #(define-music-function (parser location event-chord)
1149                                      (ly:music?)
1150     "Add a marcato ArticulationEvent to the elements of `event-chord',
1151     which is supposed to be an EventChord expression."
1152     (let ((result-event-chord (ly:music-deep-copy event-chord)))
1153       (set! (ly:music-property result-event-chord 'elements)
1154             (cons (make-music 'ArticulationEvent
1155                     'articulation-type "marcato")
1156                   (ly:music-property result-event-chord 'elements)))
1157       result-event-chord))
1158 @end example
1159
1160 We may verify that this music function works correctly,
1161
1162 @example
1163 \displayMusic \addMarcato c4
1164 @end example
1165
1166
1167
1168
1169
1170
1171 @ignore
1172 @menu
1173 * Tweaking with Scheme::
1174 @end menu
1175
1176 @c @node Tweaking with Scheme
1177 @c @section Tweaking with Scheme
1178
1179 We have seen how LilyPond output can be heavily modified using
1180 commands like
1181 @code{\override TextScript #'extra-offset = ( 1 . -1)}.  But
1182 we have even more power if we use Scheme.  For a full explanation
1183 of this, see the @ref{Scheme tutorial}, and
1184 @ref{Interfaces for programmers}.
1185
1186 We can use Scheme to simply @code{\override} commands,
1187
1188 TODO Find a simple example
1189 @c This isn't a valid example with skylining
1190 @c It works fine without padText  -td
1191 @end ignore
1192
1193 @ignore
1194 @lilypond[quote,verbatim,ragged-right]
1195 padText = #(define-music-function (parser location padding) (number?)
1196 #{
1197   \once \override TextScript #'padding = #$padding
1198 #})
1199
1200 \relative c''' {
1201   c4^"piu mosso" b a b
1202   \padText #1.8
1203   c4^"piu mosso" d e f
1204   \padText #2.6
1205   c4^"piu mosso" fis a g
1206 }
1207 @end lilypond
1208 @end ignore
1209
1210 @ignore
1211 We can use it to create new commands:
1212
1213 @c Check this is a valid example with skylining
1214 @c It is - 'padding still works
1215
1216
1217 @lilypond[quote,verbatim,ragged-right]
1218 tempoPadded = #(define-music-function (parser location padding tempotext)
1219   (number? string?)
1220 #{
1221   \once \override Score.MetronomeMark #'padding = $padding
1222   \tempo \markup { \bold $tempotext }
1223 #})
1224
1225 \relative c'' {
1226   \tempo \markup { "Low tempo" }
1227   c4 d e f g1
1228   \tempoPadded #4.0 #"High tempo"
1229   g4 f e d c1
1230 }
1231 @end lilypond
1232
1233
1234 Even music expressions can be passed in:
1235
1236 @lilypond[quote,verbatim,ragged-right]
1237 pattern = #(define-music-function (parser location x y) (ly:music? ly:music?)
1238 #{
1239   $x e8 a b $y b a e
1240 #})
1241
1242 \relative c''{
1243   \pattern c8 c8\f
1244   \pattern {d16 dis} { ais16-> b\p }
1245 }
1246 @end lilypond
1247 @end ignore