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