]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/extending/scheme-tutorial.itely
Doc -- Extending, Scheme tutorial -- add hash-table section
[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 @code{key}, and the @code{cdr} of each element
293 is called the @code{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 We have been using lists all along.  A calculation, like @code{(+ 1 2)}
360 is also a list (containing the symbol @code{+} and the numbers 1
361 and@tie{}2).  Normally lists are interpreted as calculations, and the
362 Scheme interpreter substitutes the outcome of the calculation.  To enter a
363 list, we stop the evaluation.  This is done by quoting the list with a
364 quote @code{'} symbol.  So, for calculations do not use a quote.
365
366 Inside a quoted list or pair, there is no need to quote anymore.  The
367 following is a pair of symbols, a list of symbols and a list of lists
368 respectively,
369
370 @example
371 #'(stem . head)
372 #'(staff clef key-signature)
373 #'((1) (2))
374 @end example
375
376 Scheme can be used to do calculations.  It uses @emph{prefix}
377 syntax.  Adding 1 and@tie{}2 is written as @code{(+ 1 2)} rather than the
378 traditional @math{1+2}.
379
380 @lisp
381 (+ 1 2)
382   @result{} 3
383 @end lisp
384
385 The arrow @result{} shows that the result of evaluating @code{(+ 1 2)}
386 is@tie{}@code{3}.  Calculations may be nested; the result of a function may
387 be used for another calculation.
388
389 @lisp
390 (+ 1 (* 3 4))
391   @result{} (+ 1 12)
392   @result{} 13
393 @end lisp
394
395 These calculations are examples of evaluations; an expression like
396 @code{(* 3 4)} is replaced by its value @code{12}.
397
398 The same assignment can be done in completely in Scheme as well,
399
400 @example
401 #(define twentyFour (* 2 twelve))
402 @end example
403
404 @c this next section is confusing -- need to rewrite
405
406 The @emph{name} of a variable is also an expression, similar to a
407 number or a string.  It is entered as
408
409 @example
410 #'twentyFour
411 @end example
412
413 @funindex #'symbol
414 @cindex quoting in Scheme
415
416 The quote mark @code{'} prevents the Scheme interpreter from substituting
417 @code{24} for the @code{twentyFour}.  Instead, we get the name
418 @code{twentyFour}.
419
420 @node Scheme procedures
421 @subsection Scheme procedures
422
423 @unnumberedsubsubsec Predicates
424
425 @unnumberedsubsubsec Return values
426
427 TODO -- write about scheme procedures
428
429 @node Scheme conditionals
430 @subsection Scheme conditionals
431
432 @unnumberedsubsubsec if
433
434 @unnumberedsubsubsec cond
435
436
437 @node Scheme in LilyPond
438 @section Scheme in LilyPond
439
440
441 @menu
442 * LilyPond Scheme syntax::
443 * LilyPond variables::
444 * Input variables and Scheme::
445 * Object properties::
446 * LilyPond compound variables::
447 * Internal music representation::
448 @end menu
449
450 @node LilyPond Scheme syntax
451 @subsection LilyPond Scheme syntax
452
453 In a music file, snippets of Scheme code are introduced with the hash
454 mark @code{#}.  So, the previous examples translated to LilyPond are
455
456 @example
457 ##t ##f
458 #1 #-1.5
459 #"this is a string"
460 #"this
461 is
462 a string"
463 @end example
464
465 Note that LilyPond comments (@code{%} and @code{%@{ %@}}) cannot
466 be used within Scheme code.  Comments in Guile Scheme are entered
467 as follows:
468
469 @example
470 ; this is a single-line comment
471
472 #!
473   This a (non-nestable) Guile-style block comment
474   But these are rarely used by Schemers and never in
475   LilyPond source code
476 !#
477 @end example
478
479 Multiple consecutive scheme expressions in a music file can be
480 combined using the @code{begin} operator. This permits the number
481 of hash marks to be reduced to one.
482
483 @example
484 #(begin
485   (define foo 0)
486   (define bar 1))
487 @end example
488
489 @c todo -- # introduces a scheme *expression*
490 @c         need the concept of an expression
491
492 If @code{#} is followed by an opening parenthesis, @code{(}, as in
493 the example above, the parser will remain in Scheme mode until
494 a matching closing parenthesis, @code{)}, is found, so further
495 @code{#} symbols to introduce a Scheme section are not required.
496
497 For the rest of this section, we will assume that the data is entered
498 in a music file, so we add @code{#}s everywhere.
499
500 @node LilyPond variables
501 @subsection LilyPond variables
502
503
504 TODO -- make this read right
505
506 A similar thing
507 happens with variables.  After defining a variable
508
509 @example
510 twelve = 12
511 @end example
512
513 @noindent
514 variables can also be used in expressions, here
515
516 @example
517 twentyFour = (* 2 twelve)
518 @end example
519
520 @noindent
521 the number 24 is stored in the variable @code{twentyFour}.
522
523 @node Input variables and Scheme
524 @subsection Input variables and Scheme
525
526 The input format supports the notion of variables: in the following
527 example, a music expression is assigned to a variable with the name
528 @code{traLaLa}.
529
530 @example
531 traLaLa = @{ c'4 d'4 @}
532 @end example
533
534 @noindent
535
536 There is also a form of scoping: in the following example, the
537 @code{\layout} block also contains a @code{traLaLa} variable, which is
538 independent of the outer @code{\traLaLa}.
539 @example
540 traLaLa = @{ c'4 d'4 @}
541 \layout @{ traLaLa = 1.0 @}
542 @end example
543 @c
544 In effect, each input file is a scope, and all @code{\header},
545 @code{\midi}, and @code{\layout} blocks are scopes nested inside that
546 toplevel scope.
547
548 Both variables and scoping are implemented in the GUILE module system.
549 An anonymous Scheme module is attached to each scope.  An assignment of
550 the form
551 @example
552 traLaLa = @{ c'4 d'4 @}
553 @end example
554
555 @noindent
556 is internally converted to a Scheme definition
557 @example
558 (define traLaLa @var{Scheme value of `@code{... }'})
559 @end example
560
561 This means that input variables and Scheme variables may be freely
562 mixed.  In the following example, a music fragment is stored in the
563 variable @code{traLaLa}, and duplicated using Scheme.  The result is
564 imported in a @code{\score} block by means of a second variable
565 @code{twice}:
566
567 @lilypond[verbatim]
568 traLaLa = { c'4 d'4 }
569
570 %% dummy action to deal with parser lookahead
571 #(display "this needs to be here, sorry!")
572
573 #(define newLa (map ly:music-deep-copy
574   (list traLaLa traLaLa)))
575 #(define twice
576   (make-sequential-music newLa))
577
578 { \twice }
579 @end lilypond
580
581 @c Due to parser lookahead
582
583 In this example, the assignment happens after the parser has
584 verified that nothing interesting happens after
585 @code{traLaLa = @{ ... @}}.  Without the dummy statement in the
586 above example, the @code{newLa} definition is executed before
587 @code{traLaLa} is defined, leading to a syntax error.
588
589 The above example shows how to @q{export} music expressions from the
590 input to the Scheme interpreter.  The opposite is also possible.  By
591 wrapping a Scheme value in the function @code{ly:export}, a Scheme
592 value is interpreted as if it were entered in LilyPond syntax.
593 Instead of defining @code{\twice}, the example above could also have
594 been written as
595
596 @example
597 ...
598 @{ #(ly:export (make-sequential-music (list newLa))) @}
599 @end example
600
601 Scheme code is evaluated as soon as the parser encounters it.  To
602 define some Scheme code in a macro (to be called later), use
603 @ref{Void functions}, or
604
605 @example
606 #(define (nopc)
607   (ly:set-option 'point-and-click #f))
608
609 ...
610 #(nopc)
611 @{ c'4 @}
612 @end example
613
614 @knownissues
615
616 Mixing Scheme and LilyPond variables is not possible with the
617 @code{--safe} option.
618
619
620
621
622 @node Object properties
623 @subsection Object properties
624
625 This syntax will be used very frequently, since many of the layout
626 tweaks involve assigning (Scheme) values to internal variables, for
627 example
628
629 @example
630 \override Stem #'thickness = #2.6
631 @end example
632
633 This instruction adjusts the appearance of stems.  The value @code{2.6}
634 is put into the @code{thickness} variable of a @code{Stem}
635 object.  @code{thickness} is measured relative to the thickness of
636 staff lines, so these stem lines will be @code{2.6} times the
637 width of staff lines.  This makes stems almost twice as thick as their
638 normal size.  To distinguish between variables defined in input files (like
639 @code{twentyFour} in the example above) and variables of internal
640 objects, we will call the latter @q{properties} and the former
641 @q{variables.}  So, the stem object has a @code{thickness} property,
642 while @code{twentyFour} is an variable.
643
644 @cindex properties vs. variables
645 @cindex variables vs. properties
646
647 @c  todo -- here we're getting interesting.  We're now introducing
648 @c  LilyPond variable types.  I think this deserves a section all
649 @c  its own
650
651 @node LilyPond compound variables
652 @subsection LilyPond compound variables
653
654 @unnumberedsubsubsec Offsets
655
656 Two-dimensional offsets (X and Y coordinates) as well as object sizes
657 (intervals with a left and right point) are entered as @code{pairs}.  A
658 pair@footnote{In Scheme terminology, the pair is called @code{cons},
659 and its two elements are called @code{car} and @code{cdr} respectively.}
660 is entered as @code{(first . second)} and, like symbols, they must be quoted,
661
662 @example
663 \override TextScript #'extra-offset = #'(1 . 2)
664 @end example
665
666 This assigns the pair (1, 2) to the @code{extra-offset} property of the
667 TextScript object.  These numbers are measured in staff-spaces, so
668 this command moves the object 1 staff space to the right, and 2 spaces up.
669
670 @unnumberedsubsubsec Extents
671
672 todo -- write something about extents
673
674 @unnumberedsubsubsec Property alists
675
676 todo -- write something about property alists
677
678 @unnumberedsubsubsec Alist chains
679
680 todo -- write something about alist chains
681
682 @node Internal music representation
683 @subsection Internal music representation
684
685 When a music expression is parsed, it is converted into a set of
686 Scheme music objects.  The defining property of a music object is that
687 it takes up time.  Time is a rational number that measures the length
688 of a piece of music in whole notes.
689
690 A music object has three kinds of types:
691 @itemize
692 @item
693 music name: Each music expression has a name.  For example, a note
694 leads to a @rinternals{NoteEvent}, and @code{\simultaneous} leads to
695 a @rinternals{SimultaneousMusic}.  A list of all expressions
696 available is in the Internals Reference manual, under
697 @rinternals{Music expressions}.
698
699 @item
700 @q{type} or interface: Each music name has several @q{types} or
701 interfaces, for example, a note is an @code{event}, but it is also a
702 @code{note-event}, a @code{rhythmic-event}, and a
703 @code{melodic-event}.  All classes of music are listed in the
704 Internals Reference, under
705 @rinternals{Music classes}.
706
707 @item
708 C++ object: Each music object is represented by an object of the C++
709 class @code{Music}.
710 @end itemize
711
712 The actual information of a music expression is stored in properties.
713 For example, a @rinternals{NoteEvent} has @code{pitch} and
714 @code{duration} properties that store the pitch and duration of that
715 note.  A list of all properties available can be found in the
716 Internals Reference, under @rinternals{Music properties}.
717
718 A compound music expression is a music object that contains other
719 music objects in its properties.  A list of objects can be stored in
720 the @code{elements} property of a music object, or a single @q{child}
721 music object in the @code{element} property.  For example,
722 @rinternals{SequentialMusic} has its children in @code{elements},
723 and @rinternals{GraceMusic} has its single argument in
724 @code{element}.  The body of a repeat is stored in the @code{element}
725 property of @rinternals{RepeatedMusic}, and the alternatives in
726 @code{elements}.
727
728 @node Building complicated functions
729 @section Building complicated functions
730
731 This section explains how to gather the information necessary
732 to create complicated music functions.
733
734 @menu
735 * Displaying music expressions::
736 * Music properties::
737 * Doubling a note with slurs (example)::
738 * Adding articulation to notes (example)::
739 @end menu
740
741
742 @node Displaying music expressions
743 @subsection Displaying music expressions
744
745 @cindex internal storage
746 @cindex displaying music expressions
747 @cindex internal representation, displaying
748 @cindex displayMusic
749 @funindex \displayMusic
750
751 When writing a music function it is often instructive to inspect how
752 a music expression is stored internally.  This can be done with the
753 music function @code{\displayMusic}
754
755 @example
756 @{
757   \displayMusic @{ c'4\f @}
758 @}
759 @end example
760
761 @noindent
762 will display
763
764 @example
765 (make-music
766   'SequentialMusic
767   'elements
768   (list (make-music
769           'EventChord
770           'elements
771           (list (make-music
772                   'NoteEvent
773                   'duration
774                   (ly:make-duration 2 0 1 1)
775                   'pitch
776                   (ly:make-pitch 0 0 0))
777                 (make-music
778                   'AbsoluteDynamicEvent
779                   'text
780                   "f")))))
781 @end example
782
783 By default, LilyPond will print these messages to the console along
784 with all the other messages.  To split up these messages and save
785 the results of @code{\display@{STUFF@}}, redirect the output to
786 a file.
787
788 @example
789 lilypond file.ly >display.txt
790 @end example
791
792 With a bit of reformatting, the above information is
793 easier to read,
794
795 @example
796 (make-music 'SequentialMusic
797   'elements (list (make-music 'EventChord
798                     'elements (list (make-music 'NoteEvent
799                                       'duration (ly:make-duration 2 0 1 1)
800                                       'pitch (ly:make-pitch 0 0 0))
801                                     (make-music 'AbsoluteDynamicEvent
802                                       'text "f")))))
803 @end example
804
805 A @code{@{ ... @}} music sequence has the name @code{SequentialMusic},
806 and its inner expressions are stored as a list in its @code{'elements}
807 property.  A note is represented as an @code{EventChord} expression,
808 containing a @code{NoteEvent} object (storing the duration and
809 pitch properties) and any extra information (in this case, an
810 @code{AbsoluteDynamicEvent} with a @code{"f"} text property.
811
812
813 @node Music properties
814 @subsection Music properties
815
816 The @code{NoteEvent} object is the first object of the
817 @code{'elements} property of @code{someNote}.
818
819 @example
820 someNote = c'
821 \displayMusic \someNote
822 ===>
823 (make-music
824   'EventChord
825   'elements
826   (list (make-music
827           'NoteEvent
828           'duration
829           (ly:make-duration 2 0 1 1)
830           'pitch
831           (ly:make-pitch 0 0 0))))
832 @end example
833
834 The @code{display-scheme-music} function is the function used by
835 @code{\displayMusic} to display the Scheme representation of a music
836 expression.
837
838 @example
839 #(display-scheme-music (first (ly:music-property someNote 'elements)))
840 ===>
841 (make-music
842   'NoteEvent
843   'duration
844   (ly:make-duration 2 0 1 1)
845   'pitch
846   (ly:make-pitch 0 0 0))
847 @end example
848
849 Then the note pitch is accessed through the @code{'pitch} property
850 of the @code{NoteEvent} object,
851
852 @example
853 #(display-scheme-music
854    (ly:music-property (first (ly:music-property someNote 'elements))
855                       'pitch))
856 ===>
857 (ly:make-pitch 0 0 0)
858 @end example
859
860 The note pitch can be changed by setting this @code{'pitch} property,
861
862 @funindex \displayLilyMusic
863
864 @example
865 #(set! (ly:music-property (first (ly:music-property someNote 'elements))
866                           'pitch)
867        (ly:make-pitch 0 1 0)) ;; set the pitch to d'.
868 \displayLilyMusic \someNote
869 ===>
870 d'
871 @end example
872
873
874 @node Doubling a note with slurs (example)
875 @subsection Doubling a note with slurs (example)
876
877 Suppose we want to create a function that translates input like
878 @code{a} into @code{a( a)}.  We begin by examining the internal
879 representation of the desired result.
880
881 @example
882 \displayMusic@{ a'( a') @}
883 ===>
884 (make-music
885   'SequentialMusic
886   'elements
887   (list (make-music
888           'EventChord
889           'elements
890           (list (make-music
891                   'NoteEvent
892                   'duration
893                   (ly:make-duration 2 0 1 1)
894                   'pitch
895                   (ly:make-pitch 0 5 0))
896                 (make-music
897                   'SlurEvent
898                   'span-direction
899                   -1)))
900         (make-music
901           'EventChord
902           'elements
903           (list (make-music
904                   'NoteEvent
905                   'duration
906                   (ly:make-duration 2 0 1 1)
907                   'pitch
908                   (ly:make-pitch 0 5 0))
909                 (make-music
910                   'SlurEvent
911                   'span-direction
912                   1)))))
913 @end example
914
915 The bad news is that the @code{SlurEvent} expressions
916 must be added @q{inside} the note (or more precisely,
917 inside the @code{EventChord} expression).
918
919 Now we examine the input,
920
921 @example
922 (make-music
923   'SequentialMusic
924   'elements
925   (list (make-music
926           'EventChord
927           'elements
928           (list (make-music
929                   'NoteEvent
930                   'duration
931                   (ly:make-duration 2 0 1 1)
932                   'pitch
933                   (ly:make-pitch 0 5 0))))))
934 @end example
935
936 So in our function, we need to clone this expression (so that we
937 have two notes to build the sequence), add @code{SlurEvents} to the
938 @code{'elements} property of each one, and finally make a
939 @code{SequentialMusic} with the two @code{EventChords}.
940
941 @example
942 doubleSlur = #(define-music-function (parser location note) (ly:music?)
943          "Return: @{ note ( note ) @}.
944          `note' is supposed to be an EventChord."
945          (let ((note2 (ly:music-deep-copy note)))
946            (set! (ly:music-property note 'elements)
947                  (cons (make-music 'SlurEvent 'span-direction -1)
948                        (ly:music-property note 'elements)))
949            (set! (ly:music-property note2 'elements)
950                  (cons (make-music 'SlurEvent 'span-direction 1)
951                        (ly:music-property note2 'elements)))
952            (make-music 'SequentialMusic 'elements (list note note2))))
953 @end example
954
955
956 @node Adding articulation to notes (example)
957 @subsection Adding articulation to notes (example)
958
959 The easy way to add articulation to notes is to merge two music
960 expressions into one context, as explained in
961 @ruser{Creating contexts}.  However, suppose that we want to write
962 a music function that does this.
963
964 A @code{$variable} inside the @code{#@{...#@}} notation is like
965 a regular @code{\variable} in classical LilyPond notation.  We
966 know that
967
968 @example
969 @{ \music -. -> @}
970 @end example
971
972 @noindent
973 will not work in LilyPond.  We could avoid this problem by attaching
974 the articulation to a fake note,
975
976 @example
977 @{ << \music s1*0-.-> @}
978 @end example
979
980 @noindent
981 but for the sake of this example, we will learn how to do this in
982 Scheme.  We begin by examining our input and desired output,
983
984 @example
985 %  input
986 \displayMusic c4
987 ===>
988 (make-music
989   'EventChord
990   'elements
991   (list (make-music
992           'NoteEvent
993           'duration
994           (ly:make-duration 2 0 1 1)
995           'pitch
996           (ly:make-pitch -1 0 0))))
997 =====
998 %  desired output
999 \displayMusic c4->
1000 ===>
1001 (make-music
1002   'EventChord
1003   'elements
1004   (list (make-music
1005           'NoteEvent
1006           'duration
1007           (ly:make-duration 2 0 1 1)
1008           'pitch
1009           (ly:make-pitch -1 0 0))
1010         (make-music
1011           'ArticulationEvent
1012           'articulation-type
1013           "marcato")))
1014 @end example
1015
1016 We see that a note (@code{c4}) is represented as an @code{EventChord}
1017 expression, with a @code{NoteEvent} expression in its elements list.  To
1018 add a marcato articulation, an @code{ArticulationEvent} expression must
1019 be added to the elements property of the @code{EventChord}
1020 expression.
1021
1022 To build this function, we begin with
1023
1024 @example
1025 (define (add-marcato event-chord)
1026   "Add a marcato ArticulationEvent to the elements of `event-chord',
1027   which is supposed to be an EventChord expression."
1028   (let ((result-event-chord (ly:music-deep-copy event-chord)))
1029     (set! (ly:music-property result-event-chord 'elements)
1030           (cons (make-music 'ArticulationEvent
1031                   'articulation-type "marcato")
1032                 (ly:music-property result-event-chord 'elements)))
1033     result-event-chord))
1034 @end example
1035
1036 The first line is the way to define a function in Scheme: the function
1037 name is @code{add-marcato}, and has one variable called
1038 @code{event-chord}.  In Scheme, the type of variable is often clear
1039 from its name.  (this is good practice in other programming languages,
1040 too!)
1041
1042 @example
1043 "Add a marcato..."
1044 @end example
1045
1046 @noindent
1047 is a description of what the function does.  This is not strictly
1048 necessary, but just like clear variable names, it is good practice.
1049
1050 @example
1051 (let ((result-event-chord (ly:music-deep-copy event-chord)))
1052 @end example
1053
1054 @code{let} is used to declare local variables.  Here we use one local
1055 variable, named @code{result-event-chord}, to which we give the value
1056 @code{(ly:music-deep-copy event-chord)}.  @code{ly:music-deep-copy} is
1057 a function specific to LilyPond, like all functions prefixed by
1058 @code{ly:}.  It is use to make a copy of a music
1059 expression.  Here we copy @code{event-chord} (the parameter of the
1060 function).  Recall that our purpose is to add a marcato to an
1061 @code{EventChord} expression.  It is better to not modify the
1062 @code{EventChord} which was given as an argument, because it may be
1063 used elsewhere.
1064
1065 Now we have a @code{result-event-chord}, which is a
1066 @code{NoteEventChord} expression and is a copy of
1067 @code{event-chord}.  We add the marcato to its @code{'elements}
1068 list property.
1069
1070 @example
1071 (set! place new-value)
1072 @end example
1073
1074 Here, what we want to set (the @q{place}) is the @code{'elements}
1075 property of @code{result-event-chord} expression.
1076
1077 @example
1078 (ly:music-property result-event-chord 'elements)
1079 @end example
1080
1081 @code{ly:music-property} is the function used to access music properties
1082 (the @code{'elements}, @code{'duration}, @code{'pitch}, etc, that we
1083 see in the @code{\displayMusic} output above).  The new value is the
1084 former @code{'elements} property, with an extra item: the
1085 @code{ArticulationEvent} expression, which we copy from the
1086 @code{\displayMusic} output,
1087
1088 @example
1089 (cons (make-music 'ArticulationEvent
1090         'articulation-type "marcato")
1091       (ly:music-property result-event-chord 'elements))
1092 @end example
1093
1094 @code{cons} is used to add an element to a list without modifying
1095 the original list.  This is what we want: the same list as before,
1096 plus the new @code{ArticulationEvent} expression.  The order
1097 inside the @code{'elements} property is not important here.
1098
1099 Finally, once we have added the marcato articulation to its @code{elements}
1100 property, we can return @code{result-event-chord}, hence the last line of
1101 the function.
1102
1103 Now we transform the @code{add-marcato} function into a music
1104 function,
1105
1106 @example
1107 addMarcato = #(define-music-function (parser location event-chord)
1108                                      (ly:music?)
1109     "Add a marcato ArticulationEvent to the elements of `event-chord',
1110     which is supposed to be an EventChord expression."
1111     (let ((result-event-chord (ly:music-deep-copy event-chord)))
1112       (set! (ly:music-property result-event-chord 'elements)
1113             (cons (make-music 'ArticulationEvent
1114                     'articulation-type "marcato")
1115                   (ly:music-property result-event-chord 'elements)))
1116       result-event-chord))
1117 @end example
1118
1119 We may verify that this music function works correctly,
1120
1121 @example
1122 \displayMusic \addMarcato c4
1123 @end example
1124
1125
1126
1127
1128
1129
1130 @ignore
1131 @menu
1132 * Tweaking with Scheme::
1133 @end menu
1134
1135 @c @node Tweaking with Scheme
1136 @c @section Tweaking with Scheme
1137
1138 We have seen how LilyPond output can be heavily modified using
1139 commands like
1140 @code{\override TextScript #'extra-offset = ( 1 . -1)}.  But
1141 we have even more power if we use Scheme.  For a full explanation
1142 of this, see the @ref{Scheme tutorial}, and
1143 @ref{Interfaces for programmers}.
1144
1145 We can use Scheme to simply @code{\override} commands,
1146
1147 TODO Find a simple example
1148 @c This isn't a valid example with skylining
1149 @c It works fine without padText  -td
1150 @end ignore
1151
1152 @ignore
1153 @lilypond[quote,verbatim,ragged-right]
1154 padText = #(define-music-function (parser location padding) (number?)
1155 #{
1156   \once \override TextScript #'padding = #$padding
1157 #})
1158
1159 \relative c''' {
1160   c4^"piu mosso" b a b
1161   \padText #1.8
1162   c4^"piu mosso" d e f
1163   \padText #2.6
1164   c4^"piu mosso" fis a g
1165 }
1166 @end lilypond
1167 @end ignore
1168
1169 @ignore
1170 We can use it to create new commands:
1171
1172 @c Check this is a valid example with skylining
1173 @c It is - 'padding still works
1174
1175
1176 @lilypond[quote,verbatim,ragged-right]
1177 tempoPadded = #(define-music-function (parser location padding tempotext)
1178   (number? string?)
1179 #{
1180   \once \override Score.MetronomeMark #'padding = $padding
1181   \tempo \markup { \bold $tempotext }
1182 #})
1183
1184 \relative c'' {
1185   \tempo \markup { "Low tempo" }
1186   c4 d e f g1
1187   \tempoPadded #4.0 #"High tempo"
1188   g4 f e d c1
1189 }
1190 @end lilypond
1191
1192
1193 Even music expressions can be passed in:
1194
1195 @lilypond[quote,verbatim,ragged-right]
1196 pattern = #(define-music-function (parser location x y) (ly:music? ly:music?)
1197 #{
1198   $x e8 a b $y b a e
1199 #})
1200
1201 \relative c''{
1202   \pattern c8 c8\f
1203   \pattern {d16 dis} { ais16-> b\p }
1204 }
1205 @end lilypond
1206 @end ignore