Difference between revisions of "LilyPond"

From Wiki
Jump to navigation Jump to search
m (remove empty category music)
(adapt to current working setup)
(21 intermediate revisions by 3 users not shown)
Line 1: Line 1:
 
< [[Graphics]] | [[Using Graphics]] >
 
< [[Graphics]] | [[Using Graphics]] >
  
[http://lilypond.org LilyPond] is a great music engraver, and you can include LilyPond in ConTeXt source using [[modules:t-lilypond|the lilypond module]].
+
[http://lilypond.org LilyPond] is a great music engraver, and you can include LilyPond in ConTeXt source using [https://github.com/adityam/filter the filter module] with some setup. This is different from using the lilypond-book preprocessor with LaTeX. (For LaTeX there’s also a package that works similar to our ConTeXt setup here: [https://github.com/jperon/lyluatex lyluatex].)
  
== Deprecation Warning ==
+
== Simple Filter Setup ==
  
The LilyPond module doesn't work any more with recent versions of ConTeXt. You can simply replace it with the [http://modules.contextgarden.net/filter Filter module] like this:
+
This works with ConTeXt MkII and MkIV, but takes only the first page of multi-pages scores, and you must create the folder "lilytemp" manually:
  
 
<texcode>
 
<texcode>
Line 16: Line 16:
 
directory=lilytemp/, % directory for LilyPond's files
 
directory=lilytemp/, % directory for LilyPond's files
 
output={\externalfilterbasefile.pdf},
 
output={\externalfilterbasefile.pdf},
filtercommand={lilypond -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts -ddelete-intermediate-files -o"lilytemp/\externalfilterbasefile" "\externalfilterinputfile"}]
+
filtercommand={lilypond -dbackend=eps -ddelete-intermediate-files -o"lilytemp/\externalfilterbasefile" "\externalfilterinputfile"}]
 
</texcode>
 
</texcode>
  
You can't use <cmd>setuplilypond</cmd> any more, but there is a better replacement: Collect your LilyPond settings in a .ly file, put it in your lilytemp directory and include it from within your lilypond block like this:
+
== Multi Page Filter Setup ==
 +
 
 +
This uses Lua and therefore only works with ConTeXt MkIV. It includes all pages of multi-page scores.
 +
It doesn’t look into the complete (multi-page) PDF, but reads a "-system.count" auxiliary file written by LilyPond that contains the number of systems (pages) and includes the single-system PDFs.
  
 
<texcode>
 
<texcode>
\startlilypond
+
\def\LILYTEMP{lilytemp} % name of folder for LilyPond/buffer files
\include "mysettings.ly"
 
...
 
\stoplilypond
 
</texcode>
 
  
Here's an example of placing score snippets in the body of the text, with fonts in the score & body matching:
+
\def\ParseLilypondFile#1% #1 is the name of the output file
 +
  {\ctxlua{thirddata.parselilypondfile("#1")}}
  
<texcode>
+
\startluacode
\unprotect
+
thirddata = thirddata or {}
 +
 +
-- create temp folder if missing
 +
if not lfs.isdir("\LILYTEMP") then
 +
  lfs.mkdir("\LILYTEMP")
 +
end
 +
 +
function thirddata.parselilypondfile(name)
 +
  -- include all systems (pages)
 +
  -- name is like \LILYTEMP/mainfile-temp-lilypond-21.pdf
 +
  logs.report("LILYPOND","name='" .. name .. "'")
 +
  local scname = string.gsub(name, '%.pdf$', '-systems.count')
 +
  local syco = tonumber(io.loaddata(scname)) or 0
 +
 
 +
  for nr = 1, syco do
 +
    logs.report("LILYPOND","including system no." .. nr)
 +
    context("\\externalfigure[" .. string.gsub(name, '%.pdf$', '-' .. nr) .. "]")
 +
  end
 +
end
 +
\stopluacode
  
 
\usemodule[filter]
 
\usemodule[filter]
 +
\defineexternalfilter[lilypond]
 +
[continue=yes,
 +
        cache=yes,
 +
readcommand=\ParseLilypondFile,
 +
directory=\LILYTEMP/,
 +
output={\externalfilterbasefile.pdf},
 +
filtercommand={lilypond -dbackend=eps -ddelete-intermediate-files -o"\LILYTEMP/\externalfilterbasefile/" "\externalfilterinputfile"},]
 +
</texcode>
  
\traceexternalfilters
 
  
\defineexternalfilter
+
== LilyPond Settings ==
  [lilypond]
 
  [\c!output=\externalfilterbasefile.pdf,
 
  \c!filtercommand=\lilypondcommand,
 
  \c!continue=\v!yes,
 
  \c!readcommand=\readlilypondoutput,
 
  %\c!directory=output,
 
  ]
 
  
% frame=on is for testing
+
Collect your LilyPond settings in a .ly file, put it in your lilytemp directory and include it from within your lilypond block like this:
\def\readlilypondoutput#1{\setupfloats[location=right,frame=off]\placefigure[]{From \sc{http://lsr.dsi.unimi.it/LSR/Search?q=piano}}{\externalfigure[#1]}}
 
 
 
\def\lilypondcommand%
 
{lilypond -dbackend=eps -dno-gs-load-fonts -dinclude-eps-fonts \externalfilterinputfile}
 
\protect
 
 
 
\setuplayout[textwidth=6in] % matches line-width below
 
\usetypescript[palatino]
 
\setupbodyfont[palatino,13pt]
 
 
 
\starttext
 
 
 
\input zapf
 
  
 +
<texcode>
 
\startlilypond
 
\startlilypond
\layout{
+
\include "mysettings.ly"
  indent=0\mm
+
...
  ragged-right = ##f
 
}
 
\paper  {
 
myStaffSize = #20
 
#(define fonts
 
  (make-pango-font-tree "palatino"
 
"palatino"
 
"palatino"
 
              (/ myStaffSize 20)))
 
  line-width=6\in
 
  oddFooterMarkup=##f
 
  oddHeaderMarkup=##f
 
  bookTitleMarkup = ##f
 
  scoreTitleMarkup = ##f
 
}
 
global = {
 
  \key c \major
 
  \time 4/4
 
}
 
 
 
sopMusic = \relative c'' {
 
  c4 c c8[( b)] c4
 
}
 
sopWords = \lyricmode {
 
  hi hi hi hi
 
}
 
 
 
altoMusic = \relative c' {
 
  e4 f d e
 
}
 
altoWords =\lyricmode {
 
  ha ha ha ha
 
}
 
 
 
tenorMusic = \relative c' {
 
  g4 a f g
 
}
 
tenorWords = \lyricmode {
 
  hu hu hu hu
 
}
 
 
 
bassMusic = \relative c {
 
  c4 c g c
 
}
 
bassWords = \lyricmode {
 
  ho ho ho hø
 
}
 
 
 
\score {
 
  <<
 
    \new ChoirStaff <<
 
      \new Lyrics = "sopranos"
 
      \new Staff = "women" <<
 
        \new Voice = "sopranos" { \voiceOne << \global \sopMusic >> }
 
        \new Voice = "altos" { \voiceTwo << \global \altoMusic >> }
 
      >>
 
      \new Lyrics = "altos"
 
      \new Lyrics = "tenors"
 
      \new Staff = "men" <<
 
        \clef bass
 
        \new Voice = "tenors" { \voiceOne << \global \tenorMusic >> }
 
        \new Voice = "basses" { \voiceTwo << \global \bassMusic >> }
 
      >>
 
      \new Lyrics = "basses"
 
      \context Lyrics = "sopranos" \lyricsto "sopranos" \sopWords
 
      \context Lyrics = "altos" \lyricsto "altos" \altoWords
 
      \context Lyrics = "tenors" \lyricsto "tenors" \tenorWords
 
      \context Lyrics = "basses" \lyricsto "basses" \bassWords
 
    >>
 
    \new PianoStaff <<
 
      \new Staff <<
 
        \set Staff.printPartCombineTexts = ##f
 
        \partcombine
 
        << \global \sopMusic >>
 
        << \global \altoMusic >>
 
      >>
 
      \new Staff <<
 
        \clef bass
 
        \set Staff.printPartCombineTexts = ##f
 
        \partcombine
 
        << \global \tenorMusic >>
 
        << \global \bassMusic >>
 
      >>
 
    >>
 
  >>
 
}
 
 
\stoplilypond
 
\stoplilypond
\input zapf
 
\stoptext
 
 
</texcode>
 
</texcode>
  
== Setup ==
+
You can avoid this \include line following [http://modules.contextgarden.net/dl/t-filter/doc/context/third/filter/filter.txt filter module documentation], section "Prepend and append text".
 +
In short: you can inline your complete LilyPond settings or at least the include line:
  
* First you need a working, recent [http://www.lilypond.org LilyPond] installation (version 2.12.x) plus dependencies like GhostScript.
 
* Install the lilypond module via [[ConTeXt_Minimals#Installing_third_party_modules|ConTeXt minimals]], or get it from [[modules:t-lilypond|ConteXt garden]] or [http://github.com/fiee/ConTeXt/tree/master/t-lilypond/ github] and install it in one of your TeX trees.
 
* Include the lilypond module
 
 
<texcode>
 
<texcode>
\usemodule[lilypond]
+
\startbuffer[lilypond::settings]
 +
\include "mysettings.ly"
 +
\stopbuffer
 +
 
 +
\defineexternalfilter[lilypond][
 +
...
 +
bufferbefore={lilypond::settings},
 +
...]
 
</texcode>
 
</texcode>
* If you want, you can change the default settings using <tt>\setuplilypond</tt>
 
* If you need lyrics with accented characters (e.g. umlauts), you '''must''' typeset in UTF-8 encoding (see [[Encodings_and_Regimes]]), because LilyPond doesn't understand anything else. And you need to use UTF-8 without BOM (byte order marker), because ConTeXt doesn't understand BOMs.
 
* Versions from May 2009 on work with LuaTeX ''only.'' Supported is only the latest beta of MkIV.
 
  
=== options ===
+
=== Sample Include File ===
{| style="border: solid 1px black; padding: 0.5em; vertical-align: top; width: 80%;"
 
|- style="border: solid 1px black; padding: 0.5em; vertical-align: top; background: #eeeeee;"
 
! option !! values !! default !! meaning
 
|-
 
| staffsize || number (pt) || 20 || height of the staff
 
|-
 
| linewidth || measure || <cmd>localhsize</cmd> || width of the staff
 
|-
 
| betweensystemspace || measure || 54pt || space between systems
 
|-
 
| align || yes/no || depends on fragment || ragged-right = (not align)
 
|-
 
| indent || measure || 0pt || first line indent
 
|-
 
| time || yes/no || yes || count the time (i.e. show time signature, draw bars, split the staff)?
 
|-
 
| clef || yes/no || yes || show the clef?
 
|-
 
| fragment || yes/no || no || typeset only a snippet (instead of a whole line)?
 
|-
 
| barnumbers || yes/no || no || show measure numbers?
 
|-
 
| showempty || yes/no || no || drop empty staves?
 
|-
 
| seriffont || "name" || "Tex Gyre Schola" || serif font (e.g. for Lyrics and \markup; was Century Schoolbook L before)
 
|-
 
| sansfont || "name" || "LMSans10" || sans serif font (e.g. for chords)
 
|-
 
| monofont || "name" || "LMTypewriter10" || monospace font (normally not used)
 
|-
 
| tmpdir || "name" || "./lilytemp" || directory for temporary files (.tmp, .md5, .eps); gets created if not existant
 
|-
 
| imgdir || "name" || "./lilypdfs" || directory for LilyPond PDFs; gets created if not existant
 
|}
 
  
== Snippets ==
+
"mysettings.ly" could look like this:
  
 
<texcode>
 
<texcode>
There are some notes \lilypond{ \relative{bes a c b} } embedded in this line.
+
\version "2.18.2"
</texcode>
+
#(ly:set-option (quote no-point-and-click))
 +
#(set-global-staff-size 14)
 +
 
 +
% --- start of setup for single-line output files ---
 +
#(define default-toplevel-book-handler
 +
  print-book-with-defaults-as-systems )
 +
 
 +
#(define toplevel-book-handler
 +
  (lambda ( . rest)
 +
  (set! output-empty-score-list #f)
 +
  (apply print-book-with-defaults rest)))
  
== Sections ==
+
#(define toplevel-music-handler
 +
  (lambda ( . rest)
 +
  (apply collect-music-for-book rest)))
  
E.g. for a songbook you want to place big chunks of LilyPond output (i.e. note staffs) in your text. It behaves like any other graphics, especially similar to embedded [[MetaPost]] code:
+
#(define toplevel-score-handler
 +
  (lambda ( . rest)
 +
  (apply collect-scores-for-book rest)))
  
<texcode>
+
#(define toplevel-text-handler
\section{A Tune}
+
  (lambda ( . rest)
 +
  (apply collect-scores-for-book rest)))
  
\startlilypond
+
#(set! output-empty-score-list #t)
\relative {
 
\repeat volta 2 {
 
\partial 4 e4 |
 
a2 c4 d |
 
e2 f4 e |
 
d2. c4 |
 
b4. c8 d4 e |
 
a,2 c4 d |
 
e2 f4 e |
 
g,2 a |
 
\partial 2. b2. |
 
}
 
\repeat volta 2 {
 
\partial 4 r4 |
 
f' g f d |
 
e f e c |
 
a b c d |
 
e2. e4 |
 
f g f8 e d4 |
 
e f e c |
 
a c b8 a g4 |
 
}
 
\alternative {
 
{ \partial 2. g2. }
 
{ \partial 2. a2. }
 
}
 
}
 
\stoplilypond
 
  
There's nothing to say about this tune yet; someone heard it from Lúnasa.
+
% --- stop single-line setup ---
</texcode>
 
  
<texcode>
+
\paper {
\section{Starlight (round)}
+
#(define dump-extents #t)
 +
indent = 0\mm
 +
ragged-bottom = ##t
 +
ragged-last-bottom = ##t
 +
print-page-number = ##f
 +
line-width = 120\mm
 +
oddFooterMarkup  = ##f
 +
oddHeaderMarkup  = ##f
 +
bookTitleMarkup  = ##f
 +
scoreTitleMarkup = ##f
 +
}
  
\startlilypond
+
\layout {
<<
+
#(layout-set-staff-size 14) % beware, this resets fonts!
\context Staff = onlyone <<
+
% set fonts for rm / ss / tt
\clef treble
+
#(define fonts (make-pango-font-tree "TeX Gyre Schola" "LMSans10" "LMTypewriter10 Regular" (/ 14 20)))
\key a \major
+
\context { \Score
\time 6/8
+
\remove "Bar_number_engraver"
\context Voice = one {
+
\override PaperColumn #'keep-inside-line = ##t
\relative c'' {
+
}
a4.^\markup{1.} e' |
+
        % some example settings
e8( d cis) b4. |
+
\context { \Staff
e4.^\markup{2.} d4 d8 |
+
  \override TimeSignature #'style = #'numbered
cis( b) a b4 e,8 |
+
}
a4 a8 gis( a) b |
+
\context { \ChordNames
cis4 cis8 b( cis d) |
+
chordChanges = ##t
cis( d) e e4 e,8 |
+
majorSevenSymbol = \markup{ 7+ }
fis4 fis8 gis4.
 
}
 
}
 
>>
 
\lyricsto one \new Lyrics {
 
\lyricmode {
 
Star -- light, star -- bright,
 
first star I see to -- night;
 
I wish I may, I wish I might
 
have the wish I wish to -- night.
 
 
}
 
}
 
}
 
}
>>
 
  
\stoplilypond
 
 
</texcode>
 
</texcode>
  
== Font hints ==
+
Please look up the meaning of settings in [http://lilypond.org/doc/v2.22/Documentation/web/manuals LilyPond’s great documentation]!
  
LilyPond depends on the fonts that pango/fontconfig can find. But not even all of those will work, e.g. no fonts from the TeX tree (don't know why), only one face per font file etc.
+
If you’d like to exchange measures like text width between ConTeXt and LilyPond, you could write those into the LilyPond buffer (see below).
Therefore it doesn't use ConTeXt's font setup.
 
  
If you want to know which fonts of your system LilyPond can see with which names, try
+
To give LilyPond measures to ConTeXt, you would need to write them into a temp file (using Scheme) and read that in again (using Lua).
lilypond -dshow-available-fonts any
+
For the time being this is left as an exercise to the user. ;)
(The 3rd parameter is necessary, but can be anything.)
 
  
LilyPond's default text font is Century Schoolbook. You can use it in ConTeXt like this:
+
Unfortunately you can’t define LilyPond’s text (lyrics) size with an absolute value, but only relative to staff size...
  
<texcode>
+
== Named Buffers ==
\usetypescriptfile[type-otf]
 
  
\starttypescript[wiki][songbook]
+
Normally, your LilyPond snippets just get a running number. If you re-order your scores, each one gets re-rendered.
\usetypescript [serif] [schoolbook]
 
\definetypeface [songbook] [rm] [serif] [schola] [default]
 
\definetypeface [songbook] [ss] [sans]  [default][default]
 
\definetypeface [songbook] [tt] [mono]  [default][default]
 
\stoptypescript
 
  
\usetypescript [wiki] [songbook]
+
You can avoid that if you name your LilyPond snippets: just add <tt>[name=myfunnyname]</tt> to {{cmd|startlilypond}}.
\setupbodyfont[songbook, rm, 8.5pt]
 
</texcode>
 
  
== Current workarounds ==
+
If you have just one LilyPond part per component (e.g. songs in a songbook), you could use <tt>[name=\currentcomponent]</tt>.
  
This section lists workarounds needed in some circumstances; we surely hope to move them to [[#Older_Workarounds|'''Older Workarounds''']] as soon as possible!
+
== Automatical width adaption ==
  
=== Something (LilyPond, GhostScript etc.) isn't found ===
+
If you want to set your note line width automatically to your current text width, try this:
  
Depending on your setup (path, installation directories, ...) you must call the lilypond app with the full path.
+
  -- this goes after "create temp folder"
 +
  io.savedata("\LILYTEMP/texsettings.ly", "\\paper { line-width = " ..
 +
string.gsub(number.todimen(tex.dimen.textwidth),"pt","\\pt") .. " } \n")
  
If <tt>pstopdf</tt> can't create PDFs (but LilyPond has made EPS files) it might be that you must set the environment variable <tt>GS_LIB</tt> for GhostScript.
+
and then adapt your snippets or preamble buffer:
 +
<texcode>
 +
\include "../mysettings.ly"
 +
\include "texsettings.ly"
 +
</texcode>
  
=== LilyPond pre-2.12 ===
+
You must comment/delete the "line-width" setting in mysettings.ly, otherwise it doesn’t work.
  
The module as of 2009-05-03 works only with LilyPond 2.12 (probably also with some versions of 2.11).
+
== Example ==
  
For older versions of LilyPond please use an older version of the module. 2008-09 fits LilyPond 2.10
+
Here's an example of placing score snippets in the body of the text, with fonts in the score & body matching:
 
 
=== Typesetting fret diagrams ===
 
 
 
Lilypond has commands to typeset fret diagrams for the guitar chords. The most important one is called <code>\fret-diagram</code> and if you want to use it, you need to play a bit with the catcode of the <code>minus</code> sign since ConTeXt is apparently confused by this. In addition, you can't type the example found in [http://lilypond.org/doc/v2.10/Documentation/user/lilypond/Overview-of-text-markup-commands#index-g_t_0040code_007bfret_002ddiagram_007d-935 the Lilypond documentation] on its own because Lilypond won't accept a score with only markup (the fret diagram) and nothing else; you have to place the markup on the page.
 
 
 
All in all, something like this will work:
 
  
 
<texcode>
 
<texcode>
\usemodule[lilypond]
+
\def\LILYTEMP{lilytemp} % name of folder for LilyPond/buffer files
\starttext
 
\catcode`\-=11
 
  
D chord:
+
\def\ParseLilypondFile#1% #1 is the name of the output file
\blank
+
  {\ctxlua{thirddata.parselilypondfile("#1")}}
  
\startlilypond
+
\startluacode
d'' ^ \markup { \fret-diagram #"s:0.75;f:1;6-x;5-x;4-o;3-2-1;2-3-3;1-2-2;" }
+
thirddata = thirddata or {}
\stoplilypond
 
\catcode`\-=12
 
  
\stoptext
+
-- create temp folder if missing
</texcode>
+
if not lfs.isdir("\LILYTEMP") then
 +
  lfs.mkdir("\LILYTEMP")
 +
end
  
If you find a real solution to the <code>catcode</code> problem, please document it here, or report it to the list -- [[User:Arthur|Arthur]]
+
function thirddata.parselilypondfile(name)
 +
  -- include all systems (pages)
 +
  -- name is like \LILYTEMP/mainfile-temp-lilypond-21.pdf
 +
  logs.report("LILYPOND","name='" .. name .. "'")
 +
  local scname = string.gsub(name, '%.pdf$', '-systems.count')
 +
  local syco = tonumber(io.loaddata(scname)) or 0
  
== Developer's Corner ==
+
  for nr = 1, syco do
 +
    logs.report("LILYPOND","including system no." .. nr)
 +
    context("\\setupfloats[location=right,frame=off]\\placefigure[none]{}{\\externalfigure[" .. string.gsub(name, '%.pdf$', '-' .. nr) .. "]}")
 +
  end
 +
end
 +
\stopluacode
  
For information how the integration works, please check the module code and its PDF version (both available from [[modules:t-lilypond|LilyPond on Modules]]). Unlike <tt>lilypond-book</tt> for LaTeX, the module does not use a precompiling step and thus can react to local width changes and the like, even if the LilyPond code is stored in a buffer.
+
\usemodule[filter]
 +
\defineexternalfilter[lilypond]
 +
  [continue=yes,
 +
        cache=yes,
 +
  readcommand=\ParseLilypondFile,
 +
  directory=\LILYTEMP/,
 +
  output={\externalfilterbasefile.pdf},
 +
  filtercommand={lilypond -dbackend=eps -dinclude-eps-fonts -dno-gs-load-fonts -o"\LILYTEMP/\externalfilterbasefile" "\externalfilterinputfile"}]
  
Known bugs:
+
\setuplayout[textwidth=6in] % matches line-width below
* LilyPond's EPS bounding box is sometimes a bit too small, so sometimes the content is cropped. Perhaps call eps2eps or the like to fix that?
+
\definefontfeature[main][protrusion=quality, expansion=quality]
 +
\definefontfamily[mainface][rm][Adobe Jenson Pro][features=main]
 +
\setupbodyfont[mainface,13pt]
 +
\setupalign[hz,hanging]
  
Things that have not been implemented yet include:
+
\starttext
* work with existing PDFs on systems where LilyPond isn't installed.
 
* make lilypond call back on ConTeXt for included TeX (cf. [http://lsr.dsi.unimi.it/LSR/Item?id=107])
 
* get information from LilyPond about the baseline, for run-in music fragments
 
* tell LilyPond how much space is left on the first page
 
* check and probably work on proper multi-page music
 
* it's not possible to set variables in LilyPond
 
* lots of features
 
  
To remember:
+
\input zapf
* see [http://lilypond.org/doc/v2.12/Documentation/ LilyPond Docs]!
 
  
--[[User:ChristopherCreutzig|Christopher Creutzig]] after ideas by [[User:Hraban|Hraban]]
+
\startlilypond
  
== Older Workarounds ==
+
\layout{
 +
  indent=0\mm
 +
  ragged-right = ##f
 +
}
 +
\paper  {
 +
myStaffSize = #20
 +
  #(define fonts
 +
    (make-pango-font-tree "Adobe Jenson Pro"
 +
                          "Myriad Pro"
 +
                          "Myriad Pro"
 +
(/ myStaffSize 20)))
 +
line-width=6\in
 +
  oddFooterMarkup=##f
 +
  oddHeaderMarkup=##f
 +
  bookTitleMarkup = ##f
 +
  scoreTitleMarkup = ##f
 +
}
 +
melody = \relative c'' {
 +
  \clef treble
 +
  \key c \major
 +
  \time 4/4
  
'''Beware: These relate to the old version of the module and older versions of LilyPond (earlier than 2.7)! Nowadays, LilyPond and epstopdf get called via texmfstart, that works without patching!'''
+
  a b c d
 +
}
  
=== Fonts with ConTeXt MkII ===
+
text = \lyricmode {
 +
Aaa Bee Cee Dee
 +
}
  
For the latest versions of the module work with ConTeXt MkIV (LuaTeX) exclusively, so we moved this to "Older":
+
upper = \relative c'' {
 +
  \clef treble
 +
  \key c \major
 +
  \time 2/4
  
<texcode>
+
  a4 b c d
\starttypescript[wiki][songbook]
+
}
\usetypescript [serif] [schoolbook] [\defaultencoding]
 
\definetypeface [songbook] [rm] [serif] [schoolbook] [default] [encoding=\defaultencoding]
 
\definetypeface [songbook] [ss] [sans]  [default][default] [encoding=ec]
 
\definetypeface [songbook] [tt] [mono]  [default][default] [encoding=ec]
 
\stoptypescript
 
  
\usetypescript [wiki] [songbook]
+
lower = \relative c {
\setupbodyfont[songbook, rm, 8.5pt]
+
  \clef bass
</texcode>
+
  \key c \major
 +
  \time 2/4
  
=== LilyPond is not found ===
+
  a2 c
 +
}
  
Calling lilypond from command line in Windows fails.
+
\score {
 +
  <<
 +
    \new Voice = "mel" { \autoBeamOff \melody }
 +
    \new Lyrics \lyricsto mel \text
 +
    \new PianoStaff <<
 +
      \new Staff = "upper" \upper
 +
      \new Staff = "lower" \lower
 +
    >>
 +
  >>
 +
  \layout {
 +
    \context { \Staff \RemoveEmptyStaves }
 +
  }
 +
}
  
You have two options:
+
\stoplilypond
* modify the module, so that lilypond is called with the whole path (<code>C:/prog/lilypond/usr/bin/lilypond</code> for example instead of <code>lilypond</code> alone).
+
\input tufte
* place a <code>lilypond.bat</code> somewhere in your search path, calling
 
c:/prog/lilypond/usr/bin/lilypond %1 %2 %3 %4 %5 %6 %7 %8 %9
 
  
Calling lilypond from ConTeXt via shell exit (write18) in MacOS X also fails, even if the shell's path is right. (Seems more like write18 wouldn't use the environment.) Modify the module (try <tt>which lilypond</tt> to get its path).
+
\stoptext
 +
</texcode>
  
LilyPond 2.7.26 comes without a command line "version", at least in the MacOS X edition, i.e. the <tt>lilypond.sh</tt> script is missing.
+
== Too many open files ==
Here's it's relevant content:
 
 
 
#!/bin/sh
 
## where was the app installed?
 
INSTALLDIR=/Applications
 
 
if [ "$1" == "--print-appdir" ]; then
 
  echo "$INSTALLDIR/LilyPond.app/"
 
  exit 0
 
fi
 
 
# where to put the output
 
export LILYPOND_DESTDIR=`pwd`
 
 
# run the program
 
python "$INSTALLDIR/LilyPond.app/Contents/Resources/lilycall.py" \
 
  "$INSTALLDIR/LilyPond.app/" $@
 
  
Save this as <tt>lilypond.sh</tt>, make it executable and symlink it into a directory on your path, e.g.
+
With bigger projects and the above setup you might run into "too many open files" errors, at least in older Linux, OSX and other Unix-like OSes.
chmod a+x lilypond.sh
+
Ask your shell about the open files maximum and set it higher:
sudo ln -s lilypond.sh /usr/local/bin/lilypond
 
  
=== LilyPond stops with an 'Unbound variable' error ===
+
  $ ulimit -n
 +
  256
 +
  $ ulimit -S -n 2048
  
The [http://modules.contextgarden.net/t-lilypond LilyPond module] as of 2005-09-12 uses some commands in its header that work only with LilyPond 2.6 (at least no more with 2.7.25); replace "ly:parser-print-score" with "print-score-with-defaults" and "ly:music-scorify" with "scorify-music" for LilyPond 2.7 series.
 
  
 
[[Category:Modules]]
 
[[Category:Modules]]
[[Category:Requests]]
 

Revision as of 18:21, 25 January 2021

< Graphics | Using Graphics >

LilyPond is a great music engraver, and you can include LilyPond in ConTeXt source using the filter module with some setup. This is different from using the lilypond-book preprocessor with LaTeX. (For LaTeX there’s also a package that works similar to our ConTeXt setup here: lyluatex.)

Simple Filter Setup

This works with ConTeXt MkII and MkIV, but takes only the first page of multi-pages scores, and you must create the folder "lilytemp" manually:

\def\readPDFfile#1{\externalfigure[#1]}

\usemodule[filter]
\defineexternalfilter[lilypond]
	[continue=yes,
	readcommand=\readPDFfile,
	directory=lilytemp/, % directory for LilyPond's files
	output={\externalfilterbasefile.pdf},
	filtercommand={lilypond -dbackend=eps -ddelete-intermediate-files -o"lilytemp/\externalfilterbasefile" "\externalfilterinputfile"}]

Multi Page Filter Setup

This uses Lua and therefore only works with ConTeXt MkIV. It includes all pages of multi-page scores. It doesn’t look into the complete (multi-page) PDF, but reads a "-system.count" auxiliary file written by LilyPond that contains the number of systems (pages) and includes the single-system PDFs.

\def\LILYTEMP{lilytemp} % name of folder for LilyPond/buffer files

\def\ParseLilypondFile#1% #1 is the name of the output file
  {\ctxlua{thirddata.parselilypondfile("#1")}}

\startluacode
 thirddata = thirddata or {}
 
 -- create temp folder if missing
 if not lfs.isdir("\LILYTEMP") then
   lfs.mkdir("\LILYTEMP")
 end
 
 function thirddata.parselilypondfile(name)
   -- include all systems (pages)
   -- name is like \LILYTEMP/mainfile-temp-lilypond-21.pdf
   logs.report("LILYPOND","name='" .. name .. "'")
   local scname = string.gsub(name, '%.pdf$', '-systems.count')
   local syco = tonumber(io.loaddata(scname)) or 0
   
   for nr = 1, syco do
     logs.report("LILYPOND","including system no." .. nr)
     context("\\externalfigure[" .. string.gsub(name, '%.pdf$', '-' .. nr) .. "]")
   end
 end
\stopluacode

\usemodule[filter]
\defineexternalfilter[lilypond]
	[continue=yes,
        cache=yes,
	readcommand=\ParseLilypondFile,
	directory=\LILYTEMP/,
	output={\externalfilterbasefile.pdf},
	filtercommand={lilypond -dbackend=eps -ddelete-intermediate-files -o"\LILYTEMP/\externalfilterbasefile/" "\externalfilterinputfile"},]


LilyPond Settings

Collect your LilyPond settings in a .ly file, put it in your lilytemp directory and include it from within your lilypond block like this:

\startlilypond
\include "mysettings.ly"
...
\stoplilypond

You can avoid this \include line following filter module documentation, section "Prepend and append text". In short: you can inline your complete LilyPond settings or at least the include line:

\startbuffer[lilypond::settings]
\include "mysettings.ly"
\stopbuffer

\defineexternalfilter[lilypond][
	...
	bufferbefore={lilypond::settings},
	...]

Sample Include File

"mysettings.ly" could look like this:

\version "2.18.2"
#(ly:set-option (quote no-point-and-click))
#(set-global-staff-size 14)

% --- start of setup for single-line output files ---
#(define default-toplevel-book-handler
  print-book-with-defaults-as-systems )

#(define toplevel-book-handler
  (lambda ( . rest)
  (set! output-empty-score-list #f)
  (apply print-book-with-defaults rest)))

#(define toplevel-music-handler
  (lambda ( . rest)
   (apply collect-music-for-book rest)))

#(define toplevel-score-handler
  (lambda ( . rest)
   (apply collect-scores-for-book rest)))

#(define toplevel-text-handler
  (lambda ( . rest)
   (apply collect-scores-for-book rest)))

#(set! output-empty-score-list #t)

% --- stop single-line setup ---

\paper {
	#(define dump-extents #t)
	indent = 0\mm
	ragged-bottom = ##t
	ragged-last-bottom = ##t
	print-page-number = ##f
	line-width = 120\mm
	oddFooterMarkup  = ##f
	oddHeaderMarkup  = ##f
	bookTitleMarkup  = ##f
	scoreTitleMarkup = ##f
}

\layout {
	#(layout-set-staff-size 14) % beware, this resets fonts!
	% set fonts for rm / ss / tt 
	#(define fonts (make-pango-font-tree "TeX Gyre Schola" "LMSans10" "LMTypewriter10 Regular" (/ 14 20)))
 	\context { \Score
		\remove "Bar_number_engraver"
		\override PaperColumn #'keep-inside-line = ##t
 	}
        % some example settings
	\context { \Staff
  		\override TimeSignature #'style = #'numbered
 	}
	\context { \ChordNames
		chordChanges = ##t
		majorSevenSymbol = \markup{ 7+ }
	}
}

Please look up the meaning of settings in LilyPond’s great documentation!

If you’d like to exchange measures like text width between ConTeXt and LilyPond, you could write those into the LilyPond buffer (see below).

To give LilyPond measures to ConTeXt, you would need to write them into a temp file (using Scheme) and read that in again (using Lua). For the time being this is left as an exercise to the user. ;)

Unfortunately you can’t define LilyPond’s text (lyrics) size with an absolute value, but only relative to staff size...

Named Buffers

Normally, your LilyPond snippets just get a running number. If you re-order your scores, each one gets re-rendered.

You can avoid that if you name your LilyPond snippets: just add [name=myfunnyname] to \startlilypond.

If you have just one LilyPond part per component (e.g. songs in a songbook), you could use [name=\currentcomponent].

Automatical width adaption

If you want to set your note line width automatically to your current text width, try this:

 -- this goes after "create temp folder"
 io.savedata("\LILYTEMP/texsettings.ly", "\\paper { line-width = " .. 
	string.gsub(number.todimen(tex.dimen.textwidth),"pt","\\pt") .. " } \n")

and then adapt your snippets or preamble buffer:

\include "../mysettings.ly"
\include "texsettings.ly"

You must comment/delete the "line-width" setting in mysettings.ly, otherwise it doesn’t work.

Example

Here's an example of placing score snippets in the body of the text, with fonts in the score & body matching:

\def\LILYTEMP{lilytemp} % name of folder for LilyPond/buffer files

\def\ParseLilypondFile#1% #1 is the name of the output file
  {\ctxlua{thirddata.parselilypondfile("#1")}}

\startluacode
 thirddata = thirddata or {}

 -- create temp folder if missing
 if not lfs.isdir("\LILYTEMP") then
   lfs.mkdir("\LILYTEMP")
 end

 function thirddata.parselilypondfile(name)
   -- include all systems (pages)
   -- name is like \LILYTEMP/mainfile-temp-lilypond-21.pdf
   logs.report("LILYPOND","name='" .. name .. "'")
   local scname = string.gsub(name, '%.pdf$', '-systems.count')
   local syco = tonumber(io.loaddata(scname)) or 0

   for nr = 1, syco do
     logs.report("LILYPOND","including system no." .. nr)
     context("\\setupfloats[location=right,frame=off]\\placefigure[none]{}{\\externalfigure[" .. string.gsub(name, '%.pdf$', '-' .. nr) .. "]}")
   end
 end
\stopluacode

\usemodule[filter]
\defineexternalfilter[lilypond]
  [continue=yes,
        cache=yes,
  readcommand=\ParseLilypondFile,
  directory=\LILYTEMP/,
  output={\externalfilterbasefile.pdf},
  filtercommand={lilypond -dbackend=eps -dinclude-eps-fonts -dno-gs-load-fonts -o"\LILYTEMP/\externalfilterbasefile" "\externalfilterinputfile"}]

 \setuplayout[textwidth=6in] % matches line-width below
\definefontfeature[main][protrusion=quality, expansion=quality]
\definefontfamily[mainface][rm][Adobe Jenson Pro][features=main]
\setupbodyfont[mainface,13pt]
\setupalign[hz,hanging]

\starttext

\input zapf

\startlilypond

\layout{
  indent=0\mm
  ragged-right = ##f
}
\paper  {
myStaffSize = #20
  #(define fonts
    (make-pango-font-tree "Adobe Jenson Pro"
                          "Myriad Pro"
                          "Myriad Pro"
(/ myStaffSize 20)))
line-width=6\in
  oddFooterMarkup=##f
  oddHeaderMarkup=##f
  bookTitleMarkup = ##f
  scoreTitleMarkup = ##f
 }
melody = \relative c'' {
  \clef treble
  \key c \major
  \time 4/4

  a b c d
}

text = \lyricmode {
Aaa Bee Cee Dee
}

upper = \relative c'' {
  \clef treble
  \key c \major
  \time 2/4

  a4 b c d
}

lower = \relative c {
  \clef bass
  \key c \major
  \time 2/4

  a2 c
}

\score {
  <<
    \new Voice = "mel" { \autoBeamOff \melody }
    \new Lyrics \lyricsto mel \text
    \new PianoStaff <<
      \new Staff = "upper" \upper
      \new Staff = "lower" \lower
    >>
  >>
  \layout {
    \context { \Staff \RemoveEmptyStaves }
  }
}

\stoplilypond
\input tufte

\stoptext

Too many open files

With bigger projects and the above setup you might run into "too many open files" errors, at least in older Linux, OSX and other Unix-like OSes. Ask your shell about the open files maximum and set it higher:

 $ ulimit -n
 256
 $ ulimit -S -n 2048