]> git.donarmstrong.com Git - lilypond.git/blob - ly/music-functions-init.ly
Issue 4426: Remove bar checks at the end of \parallelMusic passages
[lilypond.git] / ly / music-functions-init.ly
1 %%%% -*- Mode: Scheme -*-
2
3 %%%% This file is part of LilyPond, the GNU music typesetter.
4 %%%%
5 %%%% Copyright (C) 2003--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
6 %%%%                          Jan Nieuwenhuizen <janneke@gnu.org>
7 %%%%
8 %%%% LilyPond is free software: you can redistribute it and/or modify
9 %%%% it under the terms of the GNU General Public License as published by
10 %%%% the Free Software Foundation, either version 3 of the License, or
11 %%%% (at your option) any later version.
12 %%%%
13 %%%% LilyPond is distributed in the hope that it will be useful,
14 %%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
15 %%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 %%%% GNU General Public License for more details.
17 %%%%
18 %%%% You should have received a copy of the GNU General Public License
19 %%%% along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
20
21 \version "2.19.22"
22
23
24 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25 %% this file is alphabetically sorted.
26 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
27
28 %% need SRFI-1 for filter; optargs for lambda*
29 #(use-modules (srfi srfi-1)
30               (ice-9 optargs))
31
32 %% TODO: using define-music-function in a .scm causes crash.
33
34 absolute =
35 #(define-music-function (music)
36    (ly:music?)
37    (_i "Make @var{music} absolute.  This does not actually change the
38 music itself but rather hides it from surrounding @code{\\relative}
39 and @code{\\fixed} commands.")
40    (make-music 'RelativeOctaveMusic 'element music))
41
42 acciaccatura =
43 #(def-grace-function startAcciaccaturaMusic stopAcciaccaturaMusic
44    (_i "Create an acciaccatura from the following music expression"))
45
46 %% keep these two together
47 instrument-definitions = #'()
48 addInstrumentDefinition =
49 #(define-void-function
50    (name lst) (string? list?)
51    (_i "Create instrument @var{name} with properties @var{list}.")
52    (set! instrument-definitions (acons name lst instrument-definitions)))
53
54 addQuote =
55 #(define-void-function (name music) (string? ly:music?)
56    (_i "Define @var{music} as a quotable music expression named
57 @var{name}")
58    (add-quotable (*parser*) name music))
59
60 %% keep these two together
61 afterGraceFraction = #(cons 6 8)
62 afterGrace =
63 #(define-music-function (main grace) (ly:music? ly:music?)
64    (_i "Create @var{grace} note(s) after a @var{main} music expression.")
65    (let ((main-length (ly:music-length main))
66          (fraction  (ly:parser-lookup (*parser*) 'afterGraceFraction)))
67      (make-simultaneous-music
68       (list
69        main
70        (make-sequential-music
71         (list
72
73          (make-music 'SkipMusic
74                      'duration (ly:make-duration
75                                 0 0
76                                 (* (ly:moment-main-numerator main-length)
77                                    (car fraction))
78                                 (* (ly:moment-main-denominator main-length)
79                                    (cdr fraction))))
80          (make-music 'GraceMusic
81                      'element grace)))))))
82
83
84 %% music identifiers not allowed at top-level,
85 %% so this is a music-function instead.
86 allowPageTurn =
87 #(define-music-function () ()
88    (_i "Allow a page turn. May be used at toplevel (ie between scores or
89 markups), or inside a score.")
90    (make-music 'EventChord
91                'page-marker #t
92                'page-turn-permission 'allow
93                'elements (list (make-music 'PageTurnEvent
94                                            'break-permission 'allow))))
95
96 alterBroken =
97 #(define-music-function (property arg item)
98   (symbol-list-or-symbol? list? symbol-list-or-music?)
99   (_i "Override @var{property} for pieces of broken spanner @var{item}
100 with values @var{arg}.  @var{item} may either be music in the form of
101 a starting spanner event, or a symbol list in the form
102 @samp{Context.Grob} or just @samp{Grob}.  Iff @var{item} is in the
103 form of a spanner event, @var{property} may also have the form
104 @samp{Grob.property} for specifying a directed tweak.")
105   (if (ly:music? item)
106       (if (eq? (ly:music-property item 'span-direction) START)
107           #{ \tweak #property #(value-for-spanner-piece arg) #item #}
108           (begin
109             (ly:music-warning item (_ "not a spanner"))
110             item))
111       (let* ((p (check-grob-path item (*parser*) (*location*)
112                                  #:default 'Bottom
113                                  #:min 2
114                                  #:max 2))
115              (name (and p (second p)))
116              (description
117               (and name (assoc-get name all-grob-descriptions))))
118         (if (and description
119                  (member 'spanner-interface
120                          (assoc-get 'interfaces
121                                     (assoc-get 'meta description))))
122             #{
123               \override #item . #property =
124               #(value-for-spanner-piece arg)
125             #}
126             (begin
127               (ly:input-warning (*location*) (_ "not a spanner name, `~a'") name)
128               (make-music 'Music))))))
129
130 appendToTag =
131 #(define-music-function (tag more music)
132    (symbol? ly:music? ly:music?)
133    (_i "Append @var{more} to the @code{elements} of all music
134 expressions in @var{music} that are tagged with @var{tag}.")
135    (music-map (lambda (m)
136                 (if (memq tag (ly:music-property m 'tags))
137                     (set! (ly:music-property m 'elements)
138                           (append (ly:music-property m 'elements)
139                                   (list more))))
140                 m)
141               music))
142
143 applyContext =
144 #(define-music-function (proc) (procedure?)
145    (_i "Modify context properties with Scheme procedure @var{proc}.")
146    (make-music 'ApplyContext
147                'procedure proc))
148
149 applyMusic =
150 #(define-music-function (func music) (procedure? ly:music?)
151    (_i"Apply procedure @var{func} to @var{music}.")
152    (func music))
153
154 applyOutput =
155 #(define-music-function (ctx proc) (symbol? procedure?)
156    (_i "Apply function @code{proc} to every layout object in context @code{ctx}")
157    (make-music 'ApplyOutputEvent
158                'procedure proc
159                'context-type ctx))
160
161 appoggiatura =
162 #(def-grace-function startAppoggiaturaMusic stopAppoggiaturaMusic
163    (_i "Create an appoggiatura from @var{music}"))
164
165 % for regression testing purposes.
166 assertBeamQuant =
167 #(define-music-function (l r) (pair? pair?)
168    (_i "Testing function: check whether the beam quants @var{l} and @var{r} are correct")
169    (make-grob-property-override 'Beam 'positions (check-quant-callbacks l r)))
170
171 % for regression testing purposes.
172 assertBeamSlope =
173 #(define-music-function (comp) (procedure?)
174    (_i "Testing function: check whether the slope of the beam is the same as @code{comp}")
175    (make-grob-property-override 'Beam 'positions (check-slope-callbacks comp)))
176
177 autochange =
178 #(define-music-function (music) (ly:music?)
179    (_i "Make voices that switch between staves automatically")
180    (make-autochange-music (*parser*) music))
181
182
183
184 balloonGrobText =
185 #(define-music-function (grob-name offset text)
186    (symbol? number-pair? markup?)
187    (_i "Attach @var{text} to @var{grob-name} at offset @var{offset}
188  (use like @code{\\once})")
189    (make-event-chord
190     (list
191      (make-music 'AnnotateOutputEvent
192                  'symbol grob-name
193                  'X-offset (car offset)
194                  'Y-offset (cdr offset)
195                  'text text))))
196
197 balloonText =
198 #(define-event-function (offset text) (number-pair? markup?)
199    (_i "Attach @var{text} at @var{offset} (use like @code{\\tweak})")
200    (make-music 'AnnotateOutputEvent
201                'X-offset (car offset)
202                'Y-offset (cdr offset)
203                'text text))
204
205 bar =
206 #(define-music-function (type) (string?)
207    (_i "Insert a bar line of type @var{type}")
208    (context-spec-music
209     (make-property-set 'whichBar type)
210     'Timing))
211
212 barNumberCheck =
213 #(define-music-function (n) (integer?)
214    (_i "Print a warning if the current bar number is not @var{n}.")
215    (make-music 'ApplyContext
216                'procedure
217                (lambda (c)
218                  (let ((cbn (ly:context-property c 'currentBarNumber)))
219                    (if (and  (number? cbn) (not (= cbn n)))
220                        (ly:input-warning (*location*)
221                                          "Barcheck failed got ~a expect ~a"
222                                          cbn n))))))
223
224 beamExceptions =
225 #(define-scheme-function (music) (ly:music?)
226    (_i "Extract a value suitable for setting
227 @code{Timing.beamExceptions} from the given pattern with explicit
228 beams in @var{music}.  A bar check @code{|} has to be used between
229 bars of patterns in order to reset the timing.")
230    (extract-beam-exceptions music))
231
232 bendAfter =
233 #(define-event-function (delta) (real?)
234    (_i "Create a fall or doit of pitch interval @var{delta}.")
235    (make-music 'BendAfterEvent
236                'delta-step delta))
237
238 bookOutputName =
239 #(define-void-function (newfilename) (string?)
240    (_i "Direct output for the current book block to @var{newfilename}.")
241    (set! (paper-variable (*parser*) #f 'output-filename) newfilename))
242
243 bookOutputSuffix =
244 #(define-void-function (newsuffix) (string?)
245    (_i "Set the output filename suffix for the current book block to
246 @var{newsuffix}.")
247    (set! (paper-variable (*parser*) #f 'output-suffix) newsuffix))
248
249 %% \breathe is defined as a music function rather than an event identifier to
250 %% ensure it gets useful input location information: as an event identifier,
251 %% it would have to be wrapped in an EventChord to prevent it from being
252 %% treated as a post_event by the parser
253 breathe =
254 #(define-music-function () ()
255    (_i "Insert a breath mark.")
256    (make-music 'BreathingEvent))
257
258 clef =
259 #(define-music-function (type) (string?)
260    (_i "Set the current clef to @var{type}.")
261    (make-clef-set type))
262
263
264 compoundMeter =
265 #(define-music-function (args) (pair?)
266   (_i "Create compound time signatures. The argument is a Scheme list of
267 lists. Each list describes one fraction, with the last entry being the
268 denominator, while the first entries describe the summands in the
269 enumerator. If the time signature consists of just one fraction,
270 the list can be given directly, i.e. not as a list containing a single list.
271 For example, a time signature of (3+1)/8 + 2/4 would be created as
272 @code{\\compoundMeter #'((3 1 8) (2 4))}, and a time signature of (3+2)/8
273 as @code{\\compoundMeter #'((3 2 8))} or shorter
274 @code{\\compoundMeter #'(3 2 8)}.")
275   (let* ((mlen (calculate-compound-measure-length args))
276          (beat (calculate-compound-base-beat args))
277          (beatGrouping (calculate-compound-beat-grouping args))
278          (timesig (cons (ly:moment-main-numerator mlen)
279                         (ly:moment-main-denominator mlen))))
280   #{
281     \once \override Timing.TimeSignature.stencil = #(lambda (grob)
282       (grob-interpret-markup grob (make-compound-meter-markup args)))
283     \set Timing.timeSignatureFraction = #timesig
284     \set Timing.baseMoment = #beat
285     \set Timing.beatStructure = #beatGrouping
286     \set Timing.beamExceptions = #'()
287     \set Timing.measureLength = #mlen
288   #} ))
289
290 compressMMRests =
291 #(define-music-function (music) (ly:music?)
292   (_i "Remove the empty bars created by multi-measure rests,
293 leaving just the first bar containing the MM rest itself.")
294    (music-map
295     (lambda (m)
296       (if (eq? 'MultiMeasureRestMusic (ly:music-property m 'name))
297           #{ \once \set Score.skipBars = ##t #m #}
298           #{ #m #} ))
299     music))
300
301 crossStaff =
302 #(define-music-function (notes) (ly:music?)
303   (_i "Create cross-staff stems")
304   #{
305   \temporary \override Stem.cross-staff = #cross-staff-connect
306   \temporary \override Flag.style = #'no-flag
307   #notes
308   \revert Stem.cross-staff
309   \revert Flag.style
310 #})
311
312 cueClef =
313 #(define-music-function (type) (string?)
314   (_i "Set the current cue clef to @var{type}.")
315   (make-cue-clef-set type))
316
317 cueClefUnset =
318 #(define-music-function () ()
319   (_i "Unset the current cue clef.")
320   (make-cue-clef-unset))
321
322 cueDuring =
323 #(define-music-function
324    (what dir main-music) (string? ly:dir? ly:music?)
325    (_i "Insert contents of quote @var{what} corresponding to @var{main-music},
326 in a CueVoice oriented by @var{dir}.")
327    (make-music 'QuoteMusic
328                'element main-music
329                'quoted-context-type 'CueVoice
330                'quoted-context-id "cue"
331                'quoted-music-name what
332                'quoted-voice-direction dir))
333
334 cueDuringWithClef =
335 #(define-music-function
336    (what dir clef main-music) (string? ly:dir? string? ly:music?)
337    (_i "Insert contents of quote @var{what} corresponding to @var{main-music},
338 in a CueVoice oriented by @var{dir}.")
339    (make-music 'QuoteMusic
340                'element main-music
341                'quoted-context-type 'CueVoice
342                'quoted-context-id "cue"
343                'quoted-music-name what
344                'quoted-music-clef clef
345                'quoted-voice-direction dir))
346
347
348
349 displayLilyMusic =
350 #(define-music-function (port music) ((output-port?) ly:music?)
351    (_i "Display the LilyPond input representation of @var{music}
352 to @var{port}, defaulting to the console.")
353    (let ((port (or port (current-output-port))))
354      (newline port)
355      (display-lily-music music (*parser*) port))
356    music)
357
358 displayMusic =
359 #(define-music-function (port music) ((output-port?) ly:music?)
360    (_i "Display the internal representation of @var{music} to
361 @var{port}, default to the console.")
362    (let ((port (or port (current-output-port))))
363      (newline port)
364      (display-scheme-music music port))
365    music)
366
367 displayScheme =
368 #(define-scheme-function (port expr) ((output-port?) scheme?)
369    (_i "Display the internal representation of @var{expr} to
370 @var{port}, default to the console.")
371    (let ((port (or port (current-output-port))))
372      (newline port)
373      (display-scheme-music expr port))
374    expr)
375
376
377
378 endSpanners =
379 #(define-music-function (music) (ly:music?)
380    (_i "Terminate the next spanner prematurely after exactly one note
381 without the need of a specific end spanner.")
382    (let* ((start-span-evs (filter (lambda (ev)
383                                     (equal? (ly:music-property ev 'span-direction)
384                                             START))
385                                   (extract-typed-music music 'span-event)))
386           (stop-span-evs
387            (map (lambda (m)
388                   (music-clone m 'span-direction STOP))
389                 start-span-evs))
390           (end-ev-chord (make-music 'EventChord
391                                     'elements stop-span-evs))
392           (total (make-music 'SequentialMusic
393                              'elements (list music
394                                              end-ev-chord))))
395      total))
396
397 eventChords =
398 #(define-music-function (music) (ly:music?)
399    (_i "Compatibility function wrapping @code{EventChord} around
400 isolated rhythmic events occuring since version 2.15.28, after
401 expanding repeat chords @samp{q}.")
402    (event-chord-wrap! music (*parser*)))
403
404 featherDurations=
405 #(define-music-function (factor argument) (ly:moment? ly:music?)
406    (_i "Adjust durations of music in @var{argument} by rational @var{factor}.")
407    (let ((orig-duration (ly:music-length argument))
408          (multiplier (ly:make-moment 1 1)))
409
410      (for-each
411       (lambda (mus)
412         (if (< 0 (ly:moment-main-denominator (ly:music-length mus)))
413             (begin
414               (ly:music-compress mus multiplier)
415               (set! multiplier (ly:moment-mul factor multiplier)))))
416       (extract-named-music argument '(EventChord NoteEvent RestEvent SkipEvent)))
417      (ly:music-compress
418       argument
419       (ly:moment-div orig-duration (ly:music-length argument)))
420
421      argument))
422
423 finger =
424 #(define-event-function (finger) (number-or-markup?)
425    (_i "Apply @var{finger} as a fingering indication.")
426
427    (make-music
428             'FingeringEvent
429             (if (number? finger) 'digit 'text)
430             finger))
431
432 fixed =
433 #(define-music-function (pitch music)
434    (ly:pitch? ly:music?)
435    (_i "Use the octave of @var{pitch} as the default octave for @var{music}.")
436    (let ((octave-marks (1+ (ly:pitch-octave pitch))))
437      (cond ((not (= 0 octave-marks))
438             (ly:music-transpose music (ly:make-pitch octave-marks 0 0))
439             ;;In order to leave unchanged the notes in any enclosed
440             ;; \absolute or \fixed or \relative, make a cancelling shift
441             (map (lambda (m)
442                    (ly:music-transpose m (ly:make-pitch (- octave-marks) 0 0)))
443                  (extract-named-music music 'RelativeOctaveMusic)))))
444    (make-music 'RelativeOctaveMusic 'element music))
445
446 footnote =
447 #(define-music-function (mark offset footnote item)
448    ((markup?) number-pair? markup? symbol-list-or-music?)
449    (_i "Make the markup @var{footnote} a footnote on @var{item}.  The
450 footnote is marked with a markup @var{mark} moved by @var{offset} with
451 respect to the marked music.
452
453 If @var{mark} is not given or specified as @var{\\default}, it is
454 replaced by an automatically generated sequence number.  If @var{item}
455 is a symbol list of form @samp{Grob} or @samp{Context.Grob}, then
456 grobs of that type will be marked at the current time step in the
457 given context (default @code{Bottom}).
458
459 If @var{item} is music, the music will get a footnote attached to a
460 grob immediately attached to the event, like @var{\\tweak} does.  For
461 attaching a footnote to an @emph{indirectly} caused grob, write
462 @code{\\single\\footnote}, use @var{item} to specify the grob, and
463 follow it with the music to annotate.
464
465 Like with @code{\\tweak}, if you use a footnote on a following
466 post-event, the @code{\\footnote} command itself needs to be attached
467 to the preceding note or rest as a post-event with @code{-}.")
468    (let ((mus (make-music
469                'FootnoteEvent
470                'X-offset (car offset)
471                'Y-offset (cdr offset)
472                'automatically-numbered (not mark)
473                'text (or mark (make-null-markup))
474                'footnote-text footnote)))
475      #{ \once \tweak footnote-music #mus #item #}))
476
477 grace =
478 #(def-grace-function startGraceMusic stopGraceMusic
479    (_i "Insert @var{music} as grace notes."))
480
481 grobdescriptions =
482 #(define-scheme-function (descriptions) (list?)
483    (_i "Create a context modification from @var{descriptions}, a list
484 in the format of @code{all-grob-descriptions}.")
485    (ly:make-context-mod
486     (map (lambda (p)
487            (list 'assign (car p) (ly:make-grob-properties (cdr p))))
488          descriptions)))
489
490 harmonicByFret = #(define-music-function (fret music) (number? ly:music?)
491   (_i "Convert @var{music} into mixed harmonics; the resulting notes resemble
492 harmonics played on a fretted instrument by touching the strings at @var{fret}.")
493   #{
494     \set harmonicDots = ##t
495     \temporary \override TabNoteHead.stencil = #(tab-note-head::print-custom-fret-label (number->string fret))
496     \temporary \override NoteHead.Y-extent = #grob::always-Y-extent-from-stencil
497     \temporary \override NoteHead.stencil = #(lambda (grob) (ly:grob-set-property! grob 'style 'harmonic-mixed)
498                                             (ly:note-head::print grob))
499     #(make-harmonic
500        (calc-harmonic-pitch (fret->pitch (number->string fret)) music))
501     \unset harmonicDots
502     \revert TabNoteHead.stencil
503     \revert NoteHead.Y-extent
504     \revert NoteHead.stencil
505   #})
506
507 harmonicByRatio = #(define-music-function (ratio music) (number? ly:music?)
508     (_i "Convert @var{music} into mixed harmonics; the resulting notes resemble
509 harmonics played on a fretted instrument by touching the strings at the point
510 given through @var{ratio}.")
511   #{
512     \set harmonicDots = ##t
513     \temporary \override TabNoteHead.stencil = #(tab-note-head::print-custom-fret-label (ratio->fret ratio))
514     \temporary \override NoteHead.Y-extent = #(ly:make-unpure-pure-container ly:grob::stencil-height)
515     \temporary \override NoteHead.stencil = #(lambda (grob) (ly:grob-set-property! grob 'style 'harmonic-mixed)
516                                             (ly:note-head::print grob))
517     #(make-harmonic
518       (calc-harmonic-pitch (ratio->pitch ratio) music))
519     \unset harmonicDots
520     \revert TabNoteHead.stencil
521     \revert NoteHead.Y-extent
522     \revert NoteHead.stencil
523   #})
524
525 hide =
526 #(define-music-function (item) (symbol-list-or-music?)
527    (_i "Set @var{item}'s @samp{transparent} property to @code{#t},
528 making it invisible while still retaining its dimensions.
529
530 If @var{item} is a symbol list of form @code{GrobName} or
531 @code{Context.GrobName}, the result is an override for the grob name
532 specified by it.  If @var{item} is a music expression, the result is
533 the same music expression with an appropriate tweak applied to it.")
534    #{ \tweak transparent ##t #item #})
535
536 inStaffSegno =
537 #(define-music-function () ()
538    (_i "Put the segno variant 'varsegno' at this position into the staff,
539 compatible with the repeat command.")
540    (make-music 'ApplyContext
541                'procedure
542                (lambda (ctx)
543                  (let ((score-ctx (ly:context-find ctx 'Score)))
544                    (if (ly:context? score-ctx)
545                      (let ((old-rc (ly:context-property score-ctx 'repeatCommands '())))
546                        (if (eq? (memq 'segno-display old-rc) #f)
547                          (ly:context-set-property! score-ctx 'repeatCommands (cons 'segno-display old-rc)))))))))
548
549 instrumentSwitch =
550 #(define-music-function
551    (name) (string?)
552    (_i "Switch instrument to @var{name}, which must be predefined with
553 @code{\\addInstrumentDefinition}.")
554    (let* ((handle (assoc name instrument-definitions))
555           (instrument-def (if handle (cdr handle) '())))
556
557      (if (not handle)
558          (ly:input-warning (*location*) "No such instrument: ~a" name))
559      (context-spec-music
560       (make-music 'SimultaneousMusic
561                   'elements
562                   (map (lambda (kv)
563                          (make-property-set
564                           (car kv)
565                           (cdr kv)))
566                        instrument-def))
567       'Staff)))
568
569
570
571 keepWithTag =
572 #(define-music-function (tags music)
573    (symbol-list-or-symbol? ly:music?)
574    (_i "Include only elements of @var{music} that are tagged with one
575 of the tags in @var{tags}.  @var{tags} may be either a single symbol
576 or a list of symbols.
577
578 Each tag may be declared as a member of at most one tag group (defined
579 with @code{\\tagGroup}).  If none of a @var{music} element's tags
580 share a tag group with one of the specified @var{tags}, the element is
581 retained.")
582    (music-filter
583     (tags-keep-predicate tags)
584     music))
585
586 key =
587 #(define-music-function (tonic pitch-alist)
588    ((ly:pitch? '()) (list? '()))
589    (_i "Set key to @var{tonic} and scale @var{pitch-alist}.
590 If both are null, just generate @code{KeyChangeEvent}.")
591    (cond ((null? tonic) (make-music 'KeyChangeEvent))
592          ((null? pitch-alist)
593           (ly:parser-error (*parser*) (_ "second argument must be pitch list")
594                            (*location*))
595           (make-music 'SequentialMusic 'void #t))
596          (else
597           (ly:music-transpose
598            (make-music 'KeyChangeEvent
599                 'tonic (ly:make-pitch 0 0 0)
600                 'pitch-alist pitch-alist)
601            tonic))))
602
603 killCues =
604 #(define-music-function (music) (ly:music?)
605    (_i "Remove cue notes from @var{music}.")
606    (music-map
607     (lambda (mus)
608       (if (and (string? (ly:music-property mus 'quoted-music-name))
609                (string=? (ly:music-property mus 'quoted-context-id "") "cue"))
610           (ly:music-property mus 'element)
611           mus))
612     music))
613
614
615
616 label =
617 #(define-music-function (label) (symbol?)
618    (_i "Create @var{label} as a bookmarking label.")
619    (make-music 'EventChord
620                'page-marker #t
621                'page-label label
622                'elements (list (make-music 'LabelEvent
623                                            'page-label label))))
624
625
626 language =
627 #(define-void-function (language) (string?)
628    (_i "Set note names for language @var{language}.")
629    (note-names-language (*parser*) language))
630
631 languageSaveAndChange =
632 #(define-void-function (language) (string?)
633   (_i "Store the previous pitchnames alist, and set a new one.")
634   (set! previous-pitchnames pitchnames)
635   (note-names-language (*parser*) language))
636
637 languageRestore =
638 #(define-void-function () ()
639    (_i "Restore a previously-saved pitchnames alist.")
640    (if previous-pitchnames
641        (begin
642         (set! pitchnames previous-pitchnames)
643         (ly:parser-set-note-names (*parser*) pitchnames))
644       (ly:input-warning (*location*) (_ "No other language was defined previously. Ignoring."))))
645
646
647 magnifyMusic =
648 #(define-music-function (mag music) (positive? ly:music?)
649    (_i "Magnify the notation of @var{music} without changing the
650 staff-size, using @var{mag} as a size factor.  Stems, beams,
651 slurs, ties, and horizontal spacing are adjusted automatically.")
652
653    ;; these props are NOT allowed to shrink below default size
654    (define unshrinkable-props
655      '(
656        ;; stems
657        (Stem thickness)
658
659        ;; slurs
660        (Slur line-thickness)
661        (Slur thickness)
662        (PhrasingSlur line-thickness)
663        (PhrasingSlur thickness)
664
665        ;; ties
666        (Tie line-thickness)
667        (Tie thickness)
668        (LaissezVibrerTie line-thickness)
669        (LaissezVibrerTie thickness)
670        (RepeatTie line-thickness)
671        (RepeatTie thickness)
672        ))
673
674    ;; these props ARE allowed to shrink below default size
675    (define shrinkable-props
676      (let ((baseline-skip-props
677              (find-named-props 'baseline-skip all-grob-descriptions))
678            (word-space-props
679              (find-named-props 'word-space all-grob-descriptions)))
680        (append
681          baseline-skip-props
682          word-space-props
683          '(
684            ;; TODO: uncomment spacing-increment here once Issue 3987 is fixed
685            ;; override at the 'Score level
686            ;(SpacingSpanner spacing-increment)
687
688            ;; lengths and heights
689            (Beam length-fraction)
690            (Stem length-fraction)
691            (Stem beamlet-default-length)
692            (Stem double-stem-separation)
693            (Slur height-limit)
694            (Slur minimum-length)
695            (PhrasingSlur height-limit)
696            (PhrasingSlur minimum-length)
697
698            ;; Beam.beam-thickness is dealt with separately below
699            ))))
700    #{
701      \context Bottom {
702        %% TODO: uncomment \newSpacingSection once Issue 3990 is fixed
703        %\newSpacingSection
704        #(scale-fontSize 'magnifyMusic mag)
705        #(scale-props    'magnifyMusic mag #f unshrinkable-props)
706        #(scale-props    'magnifyMusic mag #t shrinkable-props)
707        #(scale-beam-thickness mag)
708
709        #music
710
711        %% TODO: uncomment \newSpacingSection once Issue 3990 is fixed
712        %\newSpacingSection
713        %% reverse engineer the former fontSize value instead of using \unset
714        #(revert-fontSize 'magnifyMusic mag)
715        #(revert-props    'magnifyMusic mag (append unshrinkable-props
716                                                    shrinkable-props
717                                                    '((Beam beam-thickness))))
718      }
719    #})
720
721 magnifyStaff =
722 #(define-music-function (mag) (positive?)
723    (_i "Change the size of the staff, adjusting notation size and
724 horizontal spacing automatically, using @var{mag} as a size factor.")
725
726    ;; these props are NOT allowed to shrink below default size
727    (define unshrinkable-props
728      '((StaffSymbol thickness)))
729
730    ;; these props ARE allowed to shrink below default size
731    (define shrinkable-props
732      (let* ((baseline-skip-props
733               (find-named-props 'baseline-skip all-grob-descriptions))
734             (word-space-props
735               (find-named-props 'word-space all-grob-descriptions))
736             (space-alist-props
737               (find-named-props 'space-alist all-grob-descriptions)))
738        (append
739          baseline-skip-props
740          word-space-props
741          space-alist-props
742          '(
743            ;; override at the 'Score level
744            (SpacingSpanner spacing-increment)
745
746            (StaffSymbol staff-space)
747            (BarLine kern)
748            (BarLine segno-kern)
749            (BarLine hair-thickness)
750            (BarLine thick-thickness)
751            (Stem beamlet-default-length)
752            (Stem double-stem-separation)
753            ))))
754
755    #{
756      \stopStaff
757
758      %% revert settings from last time
759      %% (but only if \magnifyStaff has already been used
760      %% and the staff magnification is changing)
761      #(revert-fontSize 'magnifyStaff mag)
762      #(revert-props    'magnifyStaff mag (append unshrinkable-props
763                                                  shrinkable-props))
764
765      %% scale settings
766      %% (but only if staff magnification is changing
767      %% and does not equal 1)
768      #(scale-fontSize 'magnifyStaff mag)
769      #(scale-props    'magnifyStaff mag #f unshrinkable-props)
770      #(scale-props    'magnifyStaff mag #t shrinkable-props)
771
772      %% this might cause problems until Issue 3990 is fixed
773      \newSpacingSection
774
775      \startStaff
776      \set Staff.magnifyStaffValue = #mag
777    #})
778
779 makeClusters =
780 #(define-music-function (arg) (ly:music?)
781    (_i "Display chords in @var{arg} as clusters.")
782    (music-map note-to-cluster arg))
783
784 modalInversion =
785 #(define-music-function (around to scale music)
786     (ly:pitch? ly:pitch? ly:music? ly:music?)
787     (_i "Invert @var{music} about @var{around} using @var{scale} and
788 transpose from @var{around} to @var{to}.")
789     (let ((inverter (make-modal-inverter around to scale)))
790       (change-pitches music inverter)
791       music))
792
793 modalTranspose =
794 #(define-music-function (from to scale music)
795     (ly:pitch? ly:pitch? ly:music? ly:music?)
796     (_i "Transpose @var{music} from pitch @var{from} to pitch @var{to}
797 using @var{scale}.")
798     (let ((transposer (make-modal-transposer from to scale)))
799       (change-pitches music transposer)
800       music))
801
802 inversion =
803 #(define-music-function
804    (around to music) (ly:pitch? ly:pitch? ly:music?)
805    (_i "Invert @var{music} about @var{around} and
806 transpose from @var{around} to @var{to}.")
807    (music-invert around to music))
808
809 mark =
810 #(define-music-function
811    (label) ((scheme? '()))
812   "Make the music for the \\mark command."
813   (let* ((set (and (integer? label)
814                    (context-spec-music (make-property-set 'rehearsalMark label)
815                                       'Score)))
816          (ev (make-music 'MarkEvent
817                          'origin (*location*))))
818
819     (if set
820         (make-sequential-music (list set ev))
821         (begin
822           (set! (ly:music-property ev 'label) label)
823           ev))))
824
825 musicMap =
826 #(define-music-function (proc mus) (procedure? ly:music?)
827    (_i "Apply @var{proc} to @var{mus} and all of the music it contains.")
828    (music-map proc mus))
829
830 %% noPageBreak and noPageTurn are music functions (not music indentifiers),
831 %% because music identifiers are not allowed at top-level.
832 noPageBreak =
833 #(define-music-function () ()
834    (_i "Forbid a page break.  May be used at toplevel (i.e., between scores or
835 markups), or inside a score.")
836    (make-music 'EventChord
837                'page-marker #t
838                'page-break-permission 'forbid
839                'elements (list (make-music 'PageBreakEvent
840                                            'break-permission '()))))
841
842 noPageTurn =
843 #(define-music-function () ()
844    (_i "Forbid a page turn.  May be used at toplevel (i.e., between scores or
845 markups), or inside a score.")
846    (make-music 'EventChord
847                'page-marker #t
848                'page-turn-permission 'forbid
849                'elements (list (make-music 'PageTurnEvent
850                                            'break-permission '()))))
851
852
853
854 octaveCheck =
855 #(define-music-function (pitch) (ly:pitch?)
856    (_i "Octave check.")
857    (make-music 'RelativeOctaveCheck
858                'pitch pitch))
859
860 offset =
861 #(define-music-function (property offsets item)
862   (symbol-list-or-symbol? scheme? symbol-list-or-music?)
863    (_i "Offset the default value of @var{property} of @var{item} by
864 @var{offsets}.  If @var{item} is a string, the result is
865 @code{\\override} for the specified grob type.  If @var{item} is
866 a music expression, the result is the same music expression with an
867 appropriate tweak applied.")
868   (if (ly:music? item)
869       ; In case of a tweak, grob property path is Grob.property
870       (let ((prop-path (check-grob-path
871                          (if (symbol? property)
872                              (list property)
873                              property)
874                          (*parser*) (*location*)
875                          #:start 1 #:default #t #:min 2 #:max 2)))
876         (if prop-path
877             ; If the head of the grob property path is a symbol--i.e.,
878             ; a grob name, produce a directed tweak.  Otherwise, create
879             ; an ordinary tweak.
880             (if (symbol? (car prop-path))
881                 #{
882                   \tweak #prop-path #(offsetter (second prop-path) offsets) #item
883                 #}
884                 #{
885                   \tweak #(second prop-path) #(offsetter (second prop-path) offsets) #item
886                 #})
887             item))
888       ; In case of an override, grob property path is Context.Grob.property.
889       (let ((prop-path (check-grob-path
890                          (append item
891                                  (if (symbol? property)
892                                      (list property)
893                                      property))
894                          (*parser*) (*location*)
895                          #:default 'Bottom #:min 3 #:max 3)))
896         (if prop-path
897             #{
898               \override #prop-path = #(offsetter (third prop-path) offsets)
899             #}
900             (make-music 'Music)))))
901
902 omit =
903 #(define-music-function (item) (symbol-list-or-music?)
904    (_i "Set @var{item}'s @samp{stencil} property to @code{#f},
905 effectively omitting it without taking up space.
906
907 If @var{item} is a symbol list of form @code{GrobName} or
908 @code{Context.GrobName}, the result is an override for the grob name
909 specified by it.  If @var{item} is a music expression, the result is
910 the same music expression with an appropriate tweak applied to it.")
911    #{ \tweak stencil ##f #item #})
912
913 once =
914 #(define-music-function (music) (ly:music?)
915    (_i "Set @code{once} to @code{#t} on all layout instruction events
916 in @var{music}.  This will complain about music with an actual
917 duration.  As a special exception, if @var{music} contains
918 @samp{tweaks} it will be silently ignored in order to allow for
919 @code{\\once \\tweak} to work as both one-time override and proper
920 tweak.")
921    (if (not (pair? (ly:music-property music 'tweaks)))
922        (for-some-music
923         (lambda (m)
924           (cond ((music-is-of-type? m 'layout-instruction-event)
925                  (set! (ly:music-property m 'once) #t)
926                  #t)
927                 ((ly:duration? (ly:music-property m 'duration))
928                  (ly:music-warning m (_ "Cannot apply \\once to timed music"))
929                  #t)
930                 (else #f)))
931         music))
932    music)
933
934 ottava =
935 #(define-music-function (octave) (integer?)
936    (_i "Set the octavation.")
937    (make-music 'OttavaMusic
938                'ottava-number octave))
939
940 overrideTimeSignatureSettings =
941 #(define-music-function
942    (time-signature base-moment beat-structure beam-exceptions)
943    (fraction? fraction? list? list?)
944
945    (_i "Override @code{timeSignatureSettings}
946 for time signatures of @var{time-signature} to have settings
947 of @var{base-moment}, @var{beat-structure}, and @var{beam-exceptions}.")
948
949    ;; TODO -- add warning if largest value of grouping is
950    ;;       greater than time-signature.
951   (let ((setting (make-setting base-moment beat-structure beam-exceptions)))
952     (override-time-signature-setting time-signature setting)))
953
954 overrideProperty =
955 #(define-music-function (grob-property-path value)
956    (symbol-list? scheme?)
957
958    (_i "Set the grob property specified by @var{grob-property-path} to
959 @var{value}.  @var{grob-property-path} is a symbol list of the form
960 @code{Context.GrobName.property} or @code{GrobName.property}, possibly
961 with subproperties given as well.")
962    (let ((p (check-grob-path grob-property-path (*parser*) (*location*)
963                              #:default 'Bottom
964                              #:min 3)))
965      (if p
966          (make-music 'ApplyOutputEvent
967                      'context-type (first p)
968                      'procedure
969                      (lambda (grob orig-context context)
970                        (if (equal?
971                             (cdr (assoc 'name (ly:grob-property grob 'meta)))
972                             (second p))
973                            (ly:grob-set-nested-property!
974                             grob (cddr p) value))))
975          (make-music 'Music))))
976
977
978
979
980
981
982 %% pageBreak and pageTurn are music functions (iso music indentifiers),
983 %% because music identifiers are not allowed at top-level.
984 pageBreak =
985 #(define-music-function () ()
986    (_i "Force a page break.  May be used at toplevel (i.e., between scores or
987 markups), or inside a score.")
988    (make-music 'EventChord
989                'page-marker #t
990                'line-break-permission 'force
991                'page-break-permission 'force
992                'elements (list (make-music 'LineBreakEvent
993                                            'break-permission 'force)
994                                (make-music 'PageBreakEvent
995                                            'break-permission 'force))))
996
997 pageTurn =
998 #(define-music-function () ()
999    (_i "Force a page turn between two scores or top-level markups.")
1000    (make-music 'EventChord
1001                'page-marker #t
1002                'line-break-permission 'force
1003                'page-break-permission 'force
1004                'page-turn-permission 'force
1005                'elements (list (make-music 'LineBreakEvent
1006                                            'break-permission 'force)
1007                                (make-music 'PageBreakEvent
1008                                            'break-permission 'force)
1009                                (make-music 'PageTurnEvent
1010                                            'break-permission 'force))))
1011
1012 parallelMusic =
1013 #(define-void-function (voice-ids music) (list? ly:music?)
1014    (_i "Define parallel music sequences, separated by '|' (bar check signs),
1015 and assign them to the identifiers provided in @var{voice-ids}.
1016
1017 @var{voice-ids}: a list of music identifiers (symbols containing only letters)
1018
1019 @var{music}: a music sequence, containing BarChecks as limiting expressions.
1020
1021 Example:
1022
1023 @verbatim
1024   \\parallelMusic #'(A B C) {
1025     c c | d d | e e |
1026     d d | e e | f f |
1027   }
1028 <==>
1029   A = { c c | d d | }
1030   B = { d d | e e | }
1031   C = { e e | f f | }
1032 @end verbatim
1033
1034 The last bar checks in a sequence are not copied to the result in
1035 order to facilitate ending the last entry at non-bar boundaries.
1036 ")
1037    (define voice-count (length voice-ids))
1038    (define (bar-check? m)
1039      "Checks whether m is a bar check."
1040      (eq? (ly:music-property m 'name) 'BarCheck))
1041    (define (recurse-and-split-list lst)
1042      "Return either a list of music lists split along barchecks, or @code{#f}."
1043      (if (any bar-check? lst)
1044          (let* ((voices (apply circular-list (make-list voice-count '())))
1045                 (current-voices voices)
1046                 (current-sequence '()))
1047            ;;
1048            ;; utilities
1049            (define (push-music m)
1050              "Push the music expression into the current sequence"
1051              (set! current-sequence (cons m current-sequence)))
1052            (define (change-voice)
1053              "Store the previously built sequence into the current voice and
1054 change to the following voice."
1055              (set-car! current-voices
1056                        (cons current-sequence
1057                              (car current-voices)))
1058              (set! current-sequence '())
1059              (set! current-voices (cdr current-voices)))
1060            (for-each (lambda (m)
1061                        (let ((split? (recurse-and-split m)))
1062                          (if split?
1063                              (for-each
1064                               (lambda (m)
1065                                 (push-music m)
1066                                 (change-voice))
1067                               split?)
1068                              (begin
1069                                (push-music m)
1070                                (if (bar-check? m) (change-voice))))))
1071                      lst)
1072            (if (pair? current-sequence) (change-voice))
1073            ;; Un-circularize voices
1074            (set! voices (list-head voices voice-count))
1075
1076            ;; Remove trailing bar checks to facilitate ending a
1077            ;; sequence on a non-bar, reverse partial sequences and sequences
1078            (set! voices (map!
1079                          (lambda (l)
1080                            (map! reverse!
1081                                  (reverse!
1082                                   (if (and (pair? l) (pair? (car l))
1083                                            (bar-check? (caar l)))
1084                                       (cons (cdar l) (cdr l))
1085                                       l))))
1086                          voices))
1087
1088            ;; check sequence length
1089            (apply for-each (lambda seqs
1090                              (define (seq-len seq)
1091                                (reduce ly:moment-add
1092                                        (ly:make-moment 0)
1093                                        (map ly:music-length seq)))
1094                              (let ((moment-reference (seq-len (car seqs))))
1095                                (for-each (lambda (seq)
1096                                            (if (not (equal? (seq-len seq)
1097                                                             moment-reference))
1098                                                (ly:music-warning
1099                                                 (if (pair? seq)
1100                                                     (last seq)
1101                                                     (caar seqs))
1102                                                 (_ "Bars in parallel music don't have the same length"))))
1103                                          seqs)))
1104                   voices)
1105            (map concatenate! voices))
1106          (let ((deeper (map recurse-and-split lst)))
1107            (and (any pair? deeper)
1108                 (apply zip (map
1109                             (lambda (m split)
1110                               (or split
1111                                   (ly:music-deep-copy (make-list voice-count m))))
1112                             lst deeper))))))
1113    (define (recurse-and-split music)
1114      "This returns either a list of music split along barchecks, or
1115 @code{#f}."
1116      (let* ((elt (ly:music-property music 'element))
1117             (elts (ly:music-property music 'elements))
1118             (split-elt (and (ly:music? elt) (recurse-and-split elt)))
1119             (split-elts (and (pair? elts) (recurse-and-split-list elts))))
1120        (and (or split-elt split-elts)
1121             (map
1122              (lambda (e es)
1123                (apply music-clone music
1124                       (append
1125                        ;; reassigning the origin of the parent only
1126                        ;; makes sense if the first expression in the
1127                        ;; result is from a distributed origin
1128                        (let ((origin
1129                               (if (ly:music? elt)
1130                                   (and (ly:music? e) (ly:music-property e 'origin #f))
1131                                   (and (pair? es) (ly:music-property (car es) 'origin #f)))))
1132                          (if origin (list 'origin origin) '()))
1133                        (if (ly:music? e) (list 'element e) '())
1134                        (if (pair? es) (list 'elements es) '()))))
1135              (or split-elt (circular-list #f))
1136              (or split-elts (circular-list #f))))))
1137    (let ((voices (recurse-and-split music)))
1138      (if voices
1139          ;;
1140          ;; bind voice identifiers to the voices
1141          (for-each (lambda (voice-id voice)
1142                      (ly:parser-define! (*parser*) voice-id voice))
1143                    voice-ids voices)
1144          (ly:music-warning music
1145                            (_ "ignoring parallel music without barchecks")))))
1146
1147 parenthesize =
1148 #(define-music-function (arg) (ly:music?)
1149    (_i "Tag @var{arg} to be parenthesized.")
1150
1151    (if (memq 'event-chord (ly:music-property arg 'types))
1152        ;; arg is an EventChord -> set the parenthesize property
1153        ;; on all child notes and rests
1154        (for-each
1155         (lambda (ev)
1156           (if (or (memq 'note-event (ly:music-property ev 'types))
1157                   (memq 'rest-event (ly:music-property ev 'types)))
1158               (set! (ly:music-property ev 'parenthesize) #t)))
1159         (ly:music-property arg 'elements))
1160        ;; No chord, simply set property for this expression:
1161        (set! (ly:music-property arg 'parenthesize) #t))
1162    arg)
1163
1164 #(define (make-directed-part-combine-music
1165           parser direction chord-range part1 part2
1166           one-context-settings
1167           two-context-settings
1168           shared-context-settings)
1169
1170    (let* ((pc-music (make-part-combine-music
1171                      parser (list part1 part2) direction chord-range))
1172           (L1 (ly:music-length part1))
1173           (L2 (ly:music-length part2))
1174           ;; keep the contexts alive for the full duration
1175           (skip (make-skip-music (make-duration-of-length
1176                                   (if (ly:moment<? L1 L2) L2 L1)))))
1177      #{ \context Staff <<
1178           \context Voice = "one" \with #one-context-settings { #skip }
1179           \context Voice = "two" \with #two-context-settings { #skip }
1180           \context Voice = "shared" \with #shared-context-settings { #skip }
1181           \context Voice = "solo" { #skip }
1182           \context NullVoice = "null" { #skip }
1183           #pc-music
1184           #(make-part-combine-marks
1185             default-part-combine-mark-state-machine
1186             (ly:music-property pc-music 'split-list))
1187         >> #} ))
1188
1189 partcombine =
1190 #(define-music-function (chord-range part1 part2)
1191    ((number-pair? '(0 . 8)) ly:music? ly:music?)
1192    (_i "Take the music in @var{part1} and @var{part2} and return
1193 a music expression containing simultaneous voices, where @var{part1}
1194 and @var{part2} are combined into one voice where appropriate.
1195 Optional @var{chord-range} sets the distance in steps between notes
1196 that may be combined into a chord or unison.")
1197    (make-directed-part-combine-music (*parser*) #f chord-range part1 part2
1198     #{ \with { \voiceOne \override DynamicLineSpanner.direction = #UP } #}
1199     #{ \with { \voiceTwo \override DynamicLineSpanner.direction = #DOWN } #}
1200     #{ #} ))
1201
1202 partcombineUp =
1203 #(define-music-function (chord-range part1 part2)
1204    ((number-pair? '(0 . 8)) ly:music? ly:music?)
1205    (_i "Take the music in @var{part1} and @var{part2} and typeset so
1206 that they share a staff with stems directed upward.")
1207    (make-directed-part-combine-music (*parser*) UP chord-range part1 part2
1208     #{ \with { \voiceOne \override DynamicLineSpanner.direction = #UP } #}
1209     #{ \with { \voiceThree \override DynamicLineSpanner.direction = #UP } #}
1210     #{ \with { \voiceOne \override DynamicLineSpanner.direction = #UP } #} ))
1211
1212 partcombineDown =
1213 #(define-music-function (chord-range part1 part2)
1214    ((number-pair? '(0 . 8)) ly:music? ly:music?)
1215    (_i "Take the music in @var{part1} and @var{part2} and typeset so
1216 that they share a staff with stems directed downward.")
1217    (make-directed-part-combine-music (*parser*) DOWN chord-range part1 part2
1218     #{ \with { \voiceFour \override DynamicLineSpanner.direction = #DOWN } #}
1219     #{ \with { \voiceTwo \override DynamicLineSpanner.direction = #DOWN } #}
1220     #{ \with { \voiceTwo \override DynamicLineSpanner.direction = #DOWN } #} ))
1221
1222 partcombineForce =
1223 #(define-music-function (type once) (boolean-or-symbol? boolean?)
1224    (_i "Override the part-combiner.")
1225    (make-music 'EventChord
1226                'elements (list (make-music 'PartCombineForceEvent
1227                                            'forced-type type
1228                                            'once once))))
1229 partcombineApart = \partcombineForce #'apart ##f
1230 partcombineApartOnce = \partcombineForce #'apart ##t
1231 partcombineChords = \partcombineForce #'chords ##f
1232 partcombineChordsOnce = \partcombineForce #'chords ##t
1233 partcombineUnisono = \partcombineForce #'unisono ##f
1234 partcombineUnisonoOnce = \partcombineForce #'unisono ##t
1235 partcombineSoloI = \partcombineForce #'solo1 ##f
1236 partcombineSoloIOnce = \partcombineForce #'solo1 ##t
1237 partcombineSoloII = \partcombineForce #'solo2 ##f
1238 partcombineSoloIIOnce = \partcombineForce #'solo2 ##t
1239 partcombineAutomatic = \partcombineForce ##f ##f
1240 partcombineAutomaticOnce = \partcombineForce ##f ##t
1241
1242 partial =
1243 #(define-music-function (dur) (ly:duration?)
1244   (_i "Make a partial measure.")
1245
1246   ;; We use `descend-to-context' here instead of `context-spec-music' to
1247   ;; ensure \partial still works if the Timing_translator is moved
1248     (descend-to-context
1249      (context-spec-music (make-music 'PartialSet
1250                                      'origin (*location*)
1251                                      'duration dur)
1252                          'Timing)
1253      'Score))
1254
1255 pitchedTrill =
1256 #(define-music-function
1257    (main-note secondary-note)
1258    (ly:music? ly:music?)
1259    (_i "Print a trill with @var{main-note} as the main note of the trill and
1260 print @var{secondary-note} as a stemless note head in parentheses.")
1261    (let* ((get-notes (lambda (ev-chord)
1262                        (extract-named-music ev-chord 'NoteEvent)))
1263           (sec-note-events (get-notes secondary-note))
1264           (trill-events (extract-named-music main-note 'TrillSpanEvent)))
1265      (if (pair? sec-note-events)
1266          (begin
1267            (let* ((trill-pitch (ly:music-property (car sec-note-events) 'pitch))
1268                   (forced (ly:music-property (car sec-note-events) 'force-accidental)))
1269
1270              (if (ly:pitch? trill-pitch)
1271                  (for-each (lambda (m)
1272                              (ly:music-set-property! m 'pitch trill-pitch)) trill-events)
1273                  (begin
1274                    (ly:input-warning (*location*) (_ "Second argument of \\pitchedTrill should be single note: "))
1275                    (display sec-note-events)))
1276
1277              (if (eq? forced #t)
1278                  (for-each (lambda (m)
1279                              (ly:music-set-property! m 'force-accidental forced))
1280                            trill-events)))))
1281      main-note))
1282
1283 pushToTag =
1284 #(define-music-function (tag more music)
1285    (symbol? ly:music? ly:music?)
1286    (_i "Add @var{more} to the front of @code{elements} of all music
1287 expressions in @var{music} that are tagged with @var{tag}.")
1288    (music-map (lambda (m)
1289                 (if (memq tag (ly:music-property m 'tags))
1290                     (set! (ly:music-property m 'elements)
1291                           (cons more (ly:music-property m 'elements))))
1292                 m)
1293               music))
1294
1295 quoteDuring =
1296 #(define-music-function (what main-music) (string? ly:music?)
1297    (_i "Indicate a section of music to be quoted.  @var{what} indicates the name
1298 of the quoted voice, as specified in an @code{\\addQuote} command.
1299 @var{main-music} is used to indicate the length of music to be quoted;
1300 usually contains spacers or multi-measure rests.")
1301    (make-music 'QuoteMusic
1302                'element main-music
1303                'quoted-music-name what))
1304
1305 relative =
1306 #(define-music-function (pitch music)
1307    ((ly:pitch?) ly:music?)
1308    (_i "Make @var{music} relative to @var{pitch}.  If @var{pitch} is
1309 omitted, the first note in @var{music} is given in absolute pitch.")
1310    ;; When \relative has no clear decision (can only happen with
1311    ;; scales with an even number of steps), it goes down (see
1312    ;; pitch.cc).  The following formula puts out f for both the normal
1313    ;; 7-step scale as well as for a "shortened" scale missing the
1314    ;; final b.  In either case, a first note of c will end up as c,
1315    ;; namely pitch (-1, 0, 0).
1316    (ly:make-music-relative! music
1317                             (or pitch
1318                                 (ly:make-pitch
1319                                  -1
1320                                  (quotient
1321                                   ;; size of current scale:
1322                                   (ly:pitch-steps (ly:make-pitch 1 0))
1323                                   2))))
1324    (make-music 'RelativeOctaveMusic
1325                'element music))
1326
1327 removeWithTag =
1328 #(define-music-function (tags music)
1329    (symbol-list-or-symbol? ly:music?)
1330    (_i "Remove elements of @var{music} that are tagged with one of the
1331 tags in @var{tags}.  @var{tags} may be either a single symbol or a list
1332 of symbols.")
1333    (music-filter
1334     (tags-remove-predicate tags)
1335     music))
1336
1337 resetRelativeOctave =
1338 #(define-music-function (pitch) (ly:pitch?)
1339    (_i "Set the octave inside a \\relative section.")
1340
1341    (make-music 'SequentialMusic
1342                'to-relative-callback
1343                (lambda (music last-pitch) pitch)))
1344
1345 retrograde =
1346 #(define-music-function (music)
1347     (ly:music?)
1348     (_i "Return @var{music} in reverse order.")
1349     (retrograde-music music))
1350
1351 revertTimeSignatureSettings =
1352 #(define-music-function
1353    (time-signature)
1354    (pair?)
1355
1356    (_i "Revert @code{timeSignatureSettings}
1357 for time signatures of @var{time-signature}.")
1358    (revert-time-signature-setting time-signature))
1359
1360 rightHandFinger =
1361 #(define-event-function (finger) (number-or-markup?)
1362    (_i "Apply @var{finger} as a fingering indication.")
1363
1364    (make-music
1365             'StrokeFingerEvent
1366             (if (number? finger) 'digit 'text)
1367             finger))
1368
1369 scaleDurations =
1370 #(define-music-function (fraction music)
1371    (fraction? ly:music?)
1372    (_i "Multiply the duration of events in @var{music} by @var{fraction}.")
1373    (ly:music-compress music
1374                       (ly:make-moment (car fraction) (cdr fraction))))
1375
1376 settingsFrom =
1377 #(define-scheme-function (ctx music)
1378    ((symbol?) ly:music?)
1379    (_i "Take the layout instruction events from @var{music}, optionally
1380 restricted to those applying to context type @var{ctx}, and return
1381 a context modification duplicating their effect.")
1382    (let ((mods (ly:make-context-mod)))
1383      (define (musicop m)
1384        (if (music-is-of-type? m 'layout-instruction-event)
1385            (ly:add-context-mod
1386             mods
1387             (case (ly:music-property m 'name)
1388               ((PropertySet)
1389                (list 'assign
1390                      (ly:music-property m 'symbol)
1391                      (ly:music-property m 'value)))
1392               ((PropertyUnset)
1393                (list 'unset
1394                      (ly:music-property m 'symbol)))
1395               ((OverrideProperty)
1396                (cons* 'push
1397                       (ly:music-property m 'symbol)
1398                       (ly:music-property m 'grob-value)
1399                       (cond
1400                        ((ly:music-property m 'grob-property #f) => list)
1401                        (else
1402                         (ly:music-property m 'grob-property-path)))))
1403               ((RevertProperty)
1404                (cons* 'pop
1405                       (ly:music-property m 'symbol)
1406                       (cond
1407                        ((ly:music-property m 'grob-property #f) => list)
1408                        (else
1409                         (ly:music-property m 'grob-property-path)))))))
1410            (case (ly:music-property m 'name)
1411              ((ApplyContext)
1412               (ly:add-context-mod mods
1413                                   (list 'apply
1414                                         (ly:music-property m 'procedure))))
1415              ((ContextSpeccedMusic)
1416               (if (or (not ctx)
1417                       (eq? ctx (ly:music-property m 'context-type)))
1418                   (musicop (ly:music-property m 'element))))
1419              (else
1420               (let ((callback (ly:music-property m 'elements-callback)))
1421                 (if (procedure? callback)
1422                     (for-each musicop (callback m))))))))
1423      (musicop music)
1424      mods))
1425
1426 shape =
1427 #(define-music-function (offsets item)
1428    (list? symbol-list-or-music?)
1429    (_i "Offset control-points of @var{item} by @var{offsets}.  The
1430 argument is a list of number pairs or list of such lists.  Each
1431 element of a pair represents an offset to one of the coordinates of a
1432 control-point.  If @var{item} is a string, the result is
1433 @code{\\once\\override} for the specified grob type.  If @var{item} is
1434 a music expression, the result is the same music expression with an
1435 appropriate tweak applied.")
1436    (define (shape-curve grob)
1437      (let* ((orig (ly:grob-original grob))
1438             (siblings (if (ly:spanner? grob)
1439                           (ly:spanner-broken-into orig) '()))
1440             (total-found (length siblings))
1441             (function (assoc-get 'control-points
1442                                  (reverse (ly:grob-basic-properties grob))))
1443             (coords (function grob)))
1444
1445        (define (offset-control-points offsets)
1446          (if (null? offsets)
1447              coords
1448              (map
1449                (lambda (x y) (coord-translate x y))
1450                coords offsets)))
1451
1452        (define (helper sibs offs)
1453          (if (pair? offs)
1454              (if (eq? (car sibs) grob)
1455                  (offset-control-points (car offs))
1456                  (helper (cdr sibs) (cdr offs)))
1457              coords))
1458
1459        ;; we work with lists of lists
1460        (if (or (null? offsets)
1461                (not (list? (car offsets))))
1462            (set! offsets (list offsets)))
1463
1464        (if (>= total-found 2)
1465            (helper siblings offsets)
1466            (offset-control-points (car offsets)))))
1467    #{ \once \tweak control-points #shape-curve #item #})
1468
1469 shiftDurations =
1470 #(define-music-function (dur dots arg)
1471    (integer? integer? ly:music?)
1472    (_i "Change the duration of @var{arg} by adding @var{dur} to the
1473 @code{durlog} of @var{arg} and @var{dots} to the @code{dots} of @var{arg}.")
1474
1475    (shift-duration-log arg dur dots))
1476
1477 single =
1478 #(define-music-function (overrides music)
1479    (ly:music? ly:music?)
1480    (_i "Convert @var{overrides} to tweaks and apply them to @var{music}.
1481 This does not convert @code{\\revert}, @code{\\set} or @code{\\unset}.")
1482    (set! (ly:music-property music 'tweaks)
1483          (fold-some-music
1484           (lambda (m) (eq? (ly:music-property m 'name)
1485                            'OverrideProperty))
1486           (lambda (m tweaks)
1487             (let ((p (cond
1488                       ((ly:music-property m 'grob-property #f) => list)
1489                       (else
1490                        (ly:music-property m 'grob-property-path)))))
1491               (acons (cons (ly:music-property m 'symbol) ;grob name
1492                            (if (pair? (cdr p))
1493                                p ;grob property path
1494                                (car p))) ;grob property
1495                      (ly:music-property m 'grob-value)
1496                      tweaks)))
1497           (ly:music-property music 'tweaks)
1498           overrides))
1499    music)
1500
1501 skip =
1502 #(define-music-function (dur) (ly:duration?)
1503   (_i "Skip forward by @var{dur}.")
1504   (make-music 'SkipMusic
1505               'duration dur))
1506
1507
1508 slashedGrace =
1509 #(def-grace-function startSlashedGraceMusic stopSlashedGraceMusic
1510    (_i "Create slashed graces (slashes through stems, but no slur) from
1511 the following music expression"))
1512
1513 spacingTweaks =
1514 #(define-music-function (parameters) (list?)
1515    (_i "Set the system stretch, by reading the 'system-stretch property of
1516 the `parameters' assoc list.")
1517    #{
1518      \overrideProperty Score.NonMusicalPaperColumn.line-break-system-details
1519      #(list (cons 'alignment-extra-space (cdr (assoc 'system-stretch parameters)))
1520              (cons 'system-Y-extent (cdr (assoc 'system-Y-extent parameters))))
1521    #})
1522
1523 styledNoteHeads =
1524 #(define-music-function (style heads music)
1525    (symbol? symbol-list-or-symbol? ly:music?)
1526    (_i "Set @var{heads} in @var{music} to @var{style}.")
1527    (style-note-heads heads style music))
1528
1529 tag =
1530 #(define-music-function (tags music) (symbol-list-or-symbol? ly:music?)
1531    (_i "Tag the following @var{music} with @var{tags} and return the
1532 result, by adding the single symbol or symbol list @var{tags} to the
1533 @code{tags} property of @var{music}.")
1534
1535    (set!
1536     (ly:music-property music 'tags)
1537     ((if (symbol? tags) cons append)
1538      tags
1539      (ly:music-property music 'tags)))
1540    music)
1541
1542 tagGroup =
1543 #(define-void-function (tags) (symbol-list?)
1544    (_i "Define a tag group comprising the symbols in the symbol list
1545 @var{tags}.  Tag groups must not overlap.")
1546    (let ((err (define-tag-group tags)))
1547      (if err (ly:parser-error (*parser*) err (*location*)))))
1548
1549 temporary =
1550 #(define-music-function (music)
1551    (ly:music?)
1552    (_i "Make any @code{\\override} in @var{music} replace an existing
1553 grob property value only temporarily, restoring the old value when a
1554 corresponding @code{\\revert} is executed.  This is achieved by
1555 clearing the @samp{pop-first} property normally set on
1556 @code{\\override}s.
1557
1558 An @code{\\override}/@/@code{\\revert} sequence created by using
1559 @code{\\temporary} and @code{\\undo} on the same music containing
1560 overrides will cancel out perfectly or cause a@tie{}warning.
1561
1562 Non-property-related music is ignored, warnings are generated for any
1563 property-changing music that isn't an @code{\\override}.")
1564    (define warned #f)
1565    (for-some-music
1566     (lambda (m)
1567       (and (or (music-is-of-type? m 'layout-instruction-event)
1568                (music-is-of-type? m 'context-specification)
1569                (music-is-of-type? m 'apply-context)
1570                (music-is-of-type? m 'time-signature-music))
1571            (case (ly:music-property m 'name)
1572              ((OverrideProperty)
1573               (if (ly:music-property m 'pop-first #f)
1574                   (set! (ly:music-property m 'pop-first) '()))
1575               (if (ly:music-property m 'once #f)
1576                   (set! (ly:music-property m 'once) '()))
1577               #t)
1578              ((ContextSpeccedMusic)
1579               #f)
1580              (else
1581               (if (not warned)
1582                   (begin
1583                     (ly:input-warning (*location*) (_ "Cannot make ~a revertible")
1584                                       (ly:music-property m 'name))
1585                     (set! warned #t)))
1586               #t))))
1587     music)
1588    music)
1589
1590 time =
1591 #(define-music-function (beat-structure fraction)
1592    ((number-list? '()) fraction?)
1593    (_i "Set @var{fraction} as time signature, with optional
1594 number list @var{beat-structure} before it.")
1595   (make-music 'TimeSignatureMusic
1596               'numerator (car fraction)
1597               'denominator (cdr fraction)
1598               'beat-structure beat-structure))
1599
1600 times =
1601 #(define-music-function (fraction music)
1602    (fraction? ly:music?)
1603    (_i "Scale @var{music} in time by @var{fraction}.")
1604   (make-music 'TimeScaledMusic
1605               'element (ly:music-compress music (ly:make-moment (car fraction) (cdr fraction)))
1606               'numerator (car fraction)
1607               'denominator (cdr fraction)))
1608
1609 transpose =
1610 #(define-music-function
1611    (from to music)
1612    (ly:pitch? ly:pitch? ly:music?)
1613
1614    (_i "Transpose @var{music} from pitch @var{from} to pitch @var{to}.")
1615    (make-music 'TransposedMusic
1616                'element (ly:music-transpose music (ly:pitch-diff to from))))
1617
1618 transposedCueDuring =
1619 #(define-music-function
1620    (what dir pitch main-music)
1621    (string? ly:dir? ly:pitch? ly:music?)
1622
1623    (_i "Insert notes from the part @var{what} into a voice called @code{cue},
1624 using the transposition defined by @var{pitch}.  This happens
1625 simultaneously with @var{main-music}, which is usually a rest.  The
1626 argument @var{dir} determines whether the cue notes should be notated
1627 as a first or second voice.")
1628
1629    (make-music 'QuoteMusic
1630                'element main-music
1631                'quoted-context-type 'CueVoice
1632                'quoted-context-id "cue"
1633                'quoted-music-name what
1634                'quoted-voice-direction dir
1635                ;; following is inverse of instrumentTransposition for
1636                ;; historical reasons
1637                'quoted-transposition pitch))
1638
1639 transposition =
1640 #(define-music-function (pitch) (ly:pitch?)
1641    (_i "Set instrument transposition")
1642
1643    (context-spec-music
1644     (make-property-set 'instrumentTransposition pitch)
1645     'Staff))
1646
1647 tuplet =
1648 #(define-music-function (ratio tuplet-span music)
1649    (fraction? (ly:duration? '()) ly:music?)
1650    (_i "Scale the given @var{music} to tuplets.  @var{ratio} is a
1651 fraction that specifies how many notes are played in place of the
1652 nominal value: it will be @samp{3/2} for triplets, namely three notes
1653 being played in place of two.  If the optional duration
1654 @var{tuplet-span} is specified, it is used instead of
1655 @code{tupletSpannerDuration} for grouping the tuplets.
1656 For example,
1657 @example
1658 \\tuplet 3/2 4 @{ c8 c c c c c @}
1659 @end example
1660 will result in two groups of three tuplets, each group lasting for a
1661 quarter note.")
1662    (make-music 'TimeScaledMusic
1663                'element (ly:music-compress
1664                          music
1665                          (ly:make-moment (cdr ratio) (car ratio)))
1666                'numerator (cdr ratio)
1667                'denominator (car ratio)
1668                'duration tuplet-span))
1669
1670 tupletSpan =
1671 #(define-music-function (tuplet-span)
1672    ((ly:duration?))
1673    (_i "Set @code{tupletSpannerDuration}, the length into which
1674 @code{\\tuplet} without an explicit @samp{tuplet-span} argument of its
1675 own will group its tuplets, to the duration @var{tuplet-span}.  To
1676 revert to the default of not subdividing the contents of a @code{\\tuplet}
1677 command without explicit @samp{tuplet-span}, use
1678 @example
1679 \\tupletSpan \\default
1680 @end example
1681 ")
1682    (if tuplet-span
1683        #{ \set tupletSpannerDuration = #(ly:duration-length tuplet-span) #}
1684        #{ \unset tupletSpannerDuration #}))
1685
1686 tweak =
1687 #(define-music-function (prop value item)
1688    (symbol-list-or-symbol? scheme? symbol-list-or-music?)
1689    (_i "Add a tweak to the following @var{item}, usually music.
1690 Layout objects created by @var{item} get their property @var{prop}
1691 set to @var{value}.  If @var{prop} has the form @samp{Grob.property}, like with
1692 @example
1693 \\tweak Accidental.color #red cis'
1694 @end example
1695 an indirectly created grob (@samp{Accidental} is caused by
1696 @samp{NoteHead}) can be tweaked; otherwise only directly created grobs
1697 are affected.
1698
1699 As a special case, @var{item} may be a symbol list specifying a grob
1700 path, in which case @code{\\override} is called on it instead of
1701 creating tweaked music.  This is mainly useful when using
1702 @code{\\tweak} as as a component for building other functions.
1703
1704 If this use case would call for @code{\\once \\override} rather than a
1705 plain @code{\\override}, writing @code{\\once \\tweak @dots{}} can be
1706 convenient.
1707
1708 @var{prop} can contain additional elements in which case a nested
1709 property (inside of an alist) is tweaked.")
1710    (if (ly:music? item)
1711        (let ((p (check-grob-path prop (*parser*) (*location*)
1712                                  #:start 1
1713                                  #:default #t
1714                                  #:min 2)))
1715          (if p
1716              (set! (ly:music-property item 'tweaks)
1717                    (acons (cond ((pair? (cddr p)) p)
1718                                 ((symbol? (car p))
1719                                  (cons (car p) (cadr p)))
1720                                 (else (cadr p)))
1721                           value
1722                           (ly:music-property item 'tweaks))))
1723          item)
1724        ;; We could just throw this at \override and let it sort this
1725        ;; out on its own, but this way we should get better error
1726        ;; diagnostics.
1727        (let ((p (check-grob-path
1728                  (append item (if (symbol? prop) (list prop) prop))
1729                  (*parser*) (*location*)
1730                  #:default 'Bottom #:min 3)))
1731          (if p
1732              #{ \override #p = #value #}
1733              (make-music 'Music)))))
1734
1735 undo =
1736 #(define-music-function (music)
1737    (ly:music?)
1738    (_i "Convert @code{\\override} and @code{\\set} in @var{music} to
1739 @code{\\revert} and @code{\\unset}, respectively.  Any reverts and
1740 unsets already in @var{music} cause a warning.  Non-property-related music is ignored.")
1741    (define warned #f)
1742    (let loop
1743        ((music music))
1744      (let
1745          ((lst
1746            (fold-some-music
1747             (lambda (m) (or (music-is-of-type? m 'layout-instruction-event)
1748                             (music-is-of-type? m 'context-specification)
1749                             (music-is-of-type? m 'apply-context)
1750                             (music-is-of-type? m 'time-signature-music)))
1751             (lambda (m overrides)
1752               (case (ly:music-property m 'name)
1753                 ((OverrideProperty)
1754                  (cons
1755                   (make-music 'RevertProperty
1756                               'symbol (ly:music-property m 'symbol)
1757                               'grob-property-path
1758                               (cond
1759                                ((ly:music-property m 'grob-property #f) => list)
1760                                (else
1761                                 (ly:music-property m 'grob-property-path))))
1762                   overrides))
1763                 ((PropertySet)
1764                  (cons
1765                   (make-music 'PropertyUnset
1766                               'symbol (ly:music-property m 'symbol))
1767                   overrides))
1768                 ((ContextSpeccedMusic)
1769                  (cons
1770                   (make-music 'ContextSpeccedMusic
1771                               'element (loop (ly:music-property m 'element))
1772                               'context-type (ly:music-property m 'context-type))
1773                   overrides))
1774                 (else
1775                  (if (not warned)
1776                      (begin
1777                        (ly:input-warning (*location*) (_ "Cannot revert ~a")
1778                                          (ly:music-property m 'name))
1779                        (set! warned #t)))
1780                  overrides)))
1781             '()
1782             music)))
1783        (cond
1784         ((null? lst) (make-music 'Music))
1785         ((null? (cdr lst)) (car lst))
1786         (else (make-sequential-music lst))))))
1787
1788 unfoldRepeats =
1789 #(define-music-function (music) (ly:music?)
1790    (_i "Force any @code{\\repeat volta}, @code{\\repeat tremolo} or
1791 @code{\\repeat percent} commands in @var{music} to be interpreted
1792 as @code{\\repeat unfold}.")
1793    (unfold-repeats music))
1794
1795 void =
1796 #(define-void-function (arg) (scheme?)
1797    (_i "Accept a scheme argument, return a void expression.
1798 Use this if you want to have a scheme expression evaluated
1799 because of its side-effects, but its value ignored."))
1800
1801 withMusicProperty =
1802 #(define-music-function (sym val music)
1803    (symbol? scheme? ly:music?)
1804    (_i "Set @var{sym} to @var{val} in @var{music}.")
1805
1806    (set! (ly:music-property music sym) val)
1807    music)