### 3.4.4 Saving typing with variables and functions

By this point, you’ve seen this kind of thing:

hornNotes = \relative { c''4 b dis c }

\score {
{
\hornNotes
}
}


You may even realize that this could be useful in minimalist music:

fragmentA = \relative { a'4 a8. b16 }
fragmentB = \relative { a'8. gis16 ees4 }

violin = \new Staff {
\fragmentA \fragmentA |
\fragmentB \fragmentA |
}

\score {
{
\violin
}
}


However, you can also use these variables (also known as macros, or user-defined commands) for tweaks:

dolce = \markup { \italic \bold dolce }

centreText = { \once \override TextScript.self-alignment-X = #CENTER }

fthenp =_\markup {
\dynamic f \italic \small { 2nd } \hspace #0.1 \dynamic p
}

violin = \relative {
\repeat volta 2 {
c''4._\dolce b8 a8 g a b |
\centreText
c4.^"hi there!" d8 e f g d |
c4.\fthenp b8 c4 c-. |
}
}

\score {
{
\violin
}
}


These variables are obviously useful for saving typing. But they’re worth considering even if you only use them once – they reduce complexity. Let’s look at the previous example without any variables. It’s a lot harder to read, especially the last line.

violin = \relative {
\repeat volta 2 {
c''4._\markup { \italic \bold dolce } b8 a8 g a b |
\once \override TextScript.self-alignment-X = #CENTER
c4.^"hi there!" d8 e f g d |
c4._\markup {
\dynamic f \italic \small { 2nd } \hspace #0.1 \dynamic p
}
b8 c4 c-. |
}
}


Remember ‘post-events’? Articulations, fingerings, anything that has to be added after a note (see Structure of a note entry), often prefixed with a dash or a direction modifier. In fact, even these events can be stored in a variable – in which case the usual curly braces are not wanted, since you wouldn’t use them between a note and its articulations.

If such a definition includes a prefix, then the variable can be used directly after the note – unless you want to change its direction, in which case you can insert a modifier that will take precedence:

articulationVar = -^-!

artEsprVar = \articulationVar ^\espressivo

\relative c' {
c\articulationVar d e2^\articulationVar
d2\artEsprVar c_\artEsprVar
}


So far we’ve seen static substitution – when LilyPond sees \centreText, it replaces it with the stuff that we’ve defined it to be (ie the stuff to the right of centreText=).

LilyPond can handle non-static substitution, too (you can think of these as functions).

padText =
#(define-music-function
(number?)
#{
#})

\relative {
c''4^"piu mosso" b a b

Using variables is also a good way to reduce work if the LilyPond input syntax changes (see Updating files with convert-ly). If you have a single definition (such as \dolce) for all your input files (see Style sheets), then if the syntax changes, you only need to update your single \dolce definition, instead of making changes throughout every ‘.ly’ file.