LilyPondParser

class lilypondparsertools.LilyPondParser(default_language='english', debug=False)

A LilyPond syntax parser.

>>> import abjad
>>> parser = abjad.lilypondparsertools.LilyPondParser()
>>> string = r"\new Staff { c'4 ( d'8 e' fs'2) \fermata }"
>>> staff = parser(string)
>>> show(staff) 
>>> f(staff)
\new Staff {
    c'4 (
    d'8
    e'8
    fs'2 -\fermata )
}

The LilyPond parser understands most spanners, articulations and dynamics:

>>> string = r'''
... \new Staff {
...     c'8 \f \> (
...     d' -_ [
...     e' ^>
...     f' \ppp \<
...     g' \startTrillSpan \(
...     a' \)
...     b' ] \stopTrillSpan
...     c'' ) \accent \sfz
... }
... '''
>>> staff = parser(string)
>>> show(staff) 

The LilyPond parser understands contexts and markup:

>>> string = r'''\new Score <<
...     \new Staff = "Treble Staff" {
...         \new Voice = "Treble Voice" {
...             c' ^\markup { \bold Treble! }
...         }
...     }
...     \new Staff = "Bass Staff" {
...         \new Voice = "Bass Voice" {
...             \clef bass
...             c, _\markup { \italic Bass! }
...         }
...     }
... >>
... '''
>>> score = parser(string)
>>> show(score) 

The LilyPond parser also understands certain aspects of LilyPond file layouts, such as header blocks:

>>> string = r'''
... \header {
...     composername = "Foo von Bar"
...     composer = \markup { by \bold \composername }
...     title = \markup { The ballad of \composername }
...     tagline = \markup { "" }
... }
... \score {
...     \new Staff {
...         \time 3/4
...         g' ( b' d'' )
...         e''4. ( c''8 c'4 )
...     }
... }
... '''
>>> blocks = parser(string)
>>> show(blocks) 

The LilyPond parser supports a small number of LilyPond music functions, such as relative and transpose.

Note

Music functions which mutate the score during compilation result in a normalized Abjad score structure. The resulting structure corresponds to the music as it appears on the page, rather than as it was input to the parser:

>>> string = r'''
... \new Staff \relative c {
...     c32 d e f g a b c d e f g a b c d e f g a b c
... }
... '''
>>> staff = parser(string)
>>> show(staff) 

The LilyPond parser defaults to English note names, but any of the other languages supported by LilyPond may be used:

>>> parser = abjad.lilypondparsertools.LilyPondParser('nederlands')
>>> string = '{ c des e fis }'
>>> container = parser(string)
>>> show(container) 

Briefly, LilyPondParser understands theses aspects of LilyPond syntax:

  • Notes, chords, rests, skips and multi-measure rests
  • Durations, dots, and multipliers
  • All pitchnames, and octave ticks
  • Simple markup (i.e. c'4 ^ "hello!")
  • Most articulations
  • Most spanners, incl. beams, slurs, phrasing slurs, ties, and glissandi
  • Most context types via \new and \context, as well as context ids (i.e. \new Staff = "foo" { })
  • Variable assigns (ie global = { \time 3/4 } \new Staff { \global })
  • Many music functions:
    • \acciaccatura
    • \appoggiatura
    • \bar
    • \breathe
    • \clef
    • \grace
    • \key
    • \transpose
    • \language
    • \makeClusters
    • \mark
    • \oneVoice
    • \relative
    • \skip
    • \slashedGrace
    • \time
    • \times
    • \transpose
    • \voiceOne, \voiceTwo, \voiceThree, \voiceFour

LilyPondParser currently DOES NOT understand many other aspects of LilyPond syntax:

  • \markup
  • \book, \bookpart, \header, \layout, \midi, \paper
  • \repeat and \alternative
  • Lyrics
  • \chordmode, \drummode or \figuremode
  • Property operations, such as \override, \revert, \set, \unset, and \once
  • Music functions which generate or extensively mutate musical structures
  • Embedded Scheme statements (anything beginning with #)

Lineage

digraph InheritanceGraph { graph [background=transparent, bgcolor=transparent, color=lightslategrey, fontname=Arial, outputorder=edgesfirst, overlap=prism, penwidth=2, rankdir=LR, root="__builtin__.object", splines=spline, style="dotted, rounded", truecolor=true]; node [colorscheme=pastel19, fontname=Arial, fontsize=12, penwidth=2, style="filled, rounded"]; edge [color=lightsteelblue2, penwidth=2]; subgraph cluster_abctools { graph [label=abctools]; "abjad.tools.abctools.AbjadObject.AbjadObject" [color=1, group=0, label=AbjadObject, shape=box]; "abjad.tools.abctools.AbjadObject.AbstractBase" [color=1, group=0, label=AbstractBase, shape=box]; "abjad.tools.abctools.Parser.Parser" [color=1, group=0, label=Parser, shape=oval, style=bold]; "abjad.tools.abctools.AbjadObject.AbjadObject" -> "abjad.tools.abctools.Parser.Parser"; "abjad.tools.abctools.AbjadObject.AbstractBase" -> "abjad.tools.abctools.AbjadObject.AbjadObject"; } subgraph cluster_lilypondparsertools { graph [label=lilypondparsertools]; "abjad.tools.lilypondparsertools.LilyPondParser.LilyPondParser" [color=black, fontcolor=white, group=2, label=<<B>LilyPondParser</B>>, shape=box, style="filled, rounded"]; } subgraph cluster_builtins { graph [label=builtins]; "builtins.object" [color=2, group=1, label=object, shape=box]; } "abjad.tools.abctools.Parser.Parser" -> "abjad.tools.lilypondparsertools.LilyPondParser.LilyPondParser"; "builtins.object" -> "abjad.tools.abctools.AbjadObject.AbstractBase"; }

Bases

Attribute summary

available_languages Tuple of pitch-name languages supported by LilyPondParser.
debug True if the parser runs in debugging mode.
default_language Gets and sets default language of parser.
lexer The parser’s PLY Lexer instance.
lexer_rules_object Lexer rules object of LilyPond parser.
list_known_contexts() Lists all LilyPond contexts recognized by LilyPond parser.
list_known_dynamics() Lists all dynamics recognized by LilyPond parser.
list_known_grobs() Lists all LilyPond grobs recognized by LilyPond parser.
list_known_languages() Lists all note-input languages recognized by LilyPond parser.
list_known_markup_functions() Lists all markup functions recognized by LilyPond parser.
list_known_music_functions() Lists all music functions recognized by LilyPond parser.
logger The parser’s Logger instance.
logger_path The output path for the parser’s logfile.
output_path The output path for files associated with the parser.
parser The parser’s PLY LRParser instance.
parser_rules_object Parser rules object of LilyPond parser.
pickle_path The output path for the parser’s pickled parsing tables.
register_markup_function(name, signature) Registers a custom markup function globally with LilyPondParser.
tokenize(input_string) Tokenize input string and print results.
__call__(input_string) Calls LilyPond parser on input_string.
__eq__(argument) Is true when ID of argument equals ID of Abjad object.
__format__([format_specification]) Formats Abjad object.
__hash__() Hashes Abjad object.
__ne__(argument) Is true when Abjad object does not equal argument.
__repr__() Gets interpreter representation of Abjad object.

Read-only properties

LilyPondParser.available_languages

Tuple of pitch-name languages supported by LilyPondParser.

>>> parser = abjad.lilypondparsertools.LilyPondParser()
>>> for language in parser.available_languages:
...     print(language)
...
catalan
deutsch
english
espanol
español
français
italiano
nederlands
norsk
portugues
suomi
svenska
vlaams

Returns tuple.

(Parser).debug

True if the parser runs in debugging mode.

(Parser).lexer

The parser’s PLY Lexer instance.

LilyPondParser.lexer_rules_object

Lexer rules object of LilyPond parser.

(Parser).logger

The parser’s Logger instance.

(Parser).logger_path

The output path for the parser’s logfile.

(Parser).output_path

The output path for files associated with the parser.

(Parser).parser

The parser’s PLY LRParser instance.

LilyPondParser.parser_rules_object

Parser rules object of LilyPond parser.

(Parser).pickle_path

The output path for the parser’s pickled parsing tables.

Read/write properties

LilyPondParser.default_language

Gets and sets default language of parser.

>>> parser = abjad.lilypondparsertools.LilyPondParser()
>>> parser.default_language
'english'
>>> parser('{ c df e fs }')
Container('c4 df4 e4 fs4')
>>> parser.default_language = 'nederlands'
>>> parser.default_language
'nederlands'
>>> parser('{ c des e fis }')
Container('c4 df4 e4 fs4')

Returns string.

Methods

(Parser).tokenize(input_string)

Tokenize input string and print results.

Class & static methods

static LilyPondParser.list_known_contexts()

Lists all LilyPond contexts recognized by LilyPond parser.

>>> class_ = abjad.lilypondparsertools.LilyPondParser
>>> for context in class_.list_known_contexts():
...     print(context)
...
ChoirStaff
ChordNames
CueVoice
Devnull
DrumStaff
DrumVoice
Dynamics
FiguredBass
FretBoards
Global
GrandStaff
GregorianTranscriptionStaff
GregorianTranscriptionVoice
KievanStaff
KievanVoice
Lyrics
MensuralStaff
MensuralVoice
NoteNames
NullVoice
PetrucciStaff
PetrucciVoice
PianoStaff
RhythmicStaff
Score
Staff
StaffGroup
TabStaff
TabVoice
VaticanaStaff
VaticanaVoice
Voice

Returns list.

static LilyPondParser.list_known_dynamics()

Lists all dynamics recognized by LilyPond parser.

>>> class_ = abjad.lilypondparsertools.LilyPondParser
>>> for dynamic in class_.list_known_dynamics():
...     print(dynamic)
...
f
ff
fff
ffff
fffff
fp
fz
mf
mp
p
pp
ppp
pppp
ppppp
rfz
sf
sff
sfp
sfz
sp
spp

Returns tuple.

static LilyPondParser.list_known_grobs()

Lists all LilyPond grobs recognized by LilyPond parser.

>>> class_ = abjad.lilypondparsertools.LilyPondParser
>>> for grob in class_.list_known_grobs():
...     print(grob)
...
Accidental
AccidentalCautionary
AccidentalPlacement
AccidentalSuggestion
Ambitus
AmbitusAccidental
AmbitusLine
AmbitusNoteHead
Arpeggio
BalloonTextItem
BarLine
BarNumber
BassFigure
BassFigureAlignment
BassFigureAlignmentPositioning
BassFigureBracket
BassFigureContinuation
BassFigureLine
Beam
BendAfter
BreakAlignGroup
BreakAlignment
BreathingSign
ChordName
Clef
ClefModifier
ClusterSpanner
ClusterSpannerBeacon
CombineTextScript
CueClef
CueEndClef
Custos
DotColumn
Dots
DoublePercentRepeat
DoublePercentRepeatCounter
DoubleRepeatSlash
DynamicLineSpanner
DynamicText
DynamicTextSpanner
Episema
Fingering
FingeringColumn
Flag
FootnoteItem
FootnoteSpanner
FretBoard
Glissando
GraceSpacing
GridLine
GridPoint
Hairpin
HorizontalBracket
InstrumentName
InstrumentSwitch
KeyCancellation
KeySignature
KievanLigature
LaissezVibrerTie
LaissezVibrerTieColumn
LedgerLineSpanner
LeftEdge
LigatureBracket
LyricExtender
LyricHyphen
LyricSpace
LyricText
MeasureCounter
MeasureGrouping
MelodyItem
MensuralLigature
MetronomeMark
MultiMeasureRest
MultiMeasureRestNumber
MultiMeasureRestText
NonMusicalPaperColumn
NoteCollision
NoteColumn
NoteHead
NoteName
NoteSpacing
OttavaBracket
PaperColumn
ParenthesesItem
PercentRepeat
PercentRepeatCounter
PhrasingSlur
PianoPedalBracket
RehearsalMark
RepeatSlash
RepeatTie
RepeatTieColumn
Rest
RestCollision
Script
ScriptColumn
ScriptRow
Slur
SostenutoPedal
SostenutoPedalLineSpanner
SpacingSpanner
SpanBar
SpanBarStub
StaffGrouper
StaffSpacing
StaffSymbol
StanzaNumber
Stem
StemStub
StemTremolo
StringNumber
StrokeFinger
SustainPedal
SustainPedalLineSpanner
System
SystemStartBar
SystemStartBrace
SystemStartBracket
SystemStartSquare
TabNoteHead
TextScript
TextSpanner
Tie
TieColumn
TimeSignature
TrillPitchAccidental
TrillPitchGroup
TrillPitchHead
TrillSpanner
TupletBracket
TupletNumber
UnaCordaPedal
UnaCordaPedalLineSpanner
VaticanaLigature
VerticalAlignment
VerticalAxisGroup
VoiceFollower
VoltaBracket
VoltaBracketSpanner

Returns tuple.

static LilyPondParser.list_known_languages()

Lists all note-input languages recognized by LilyPond parser.

>>> class_ = abjad.lilypondparsertools.LilyPondParser
>>> for language in class_.list_known_languages():
...     print(language)
...
catalan
deutsch
english
espanol
español
français
italiano
nederlands
norsk
portugues
suomi
svenska
vlaams

Returns list.

static LilyPondParser.list_known_markup_functions()

Lists all markup functions recognized by LilyPond parser.

>>> class_  = abjad.lilypondparsertools.LilyPondParser
>>> for name in class_.list_known_markup_functions():
...     print(name)
...
abs-fontsize
arrow-head
auto-footnote
backslashed-digit
beam
bold
box
bracket
caps
center-align
center-column
char
circle
column
column-lines
combine
compound-meter
concat
customTabClef
dir-column
doubleflat
doublesharp
draw-circle
draw-dashed-line
draw-dotted-line
draw-hline
draw-line
dynamic
ellipse
epsfile
eyeglasses
fermata
fill-line
fill-with-pattern
filled-box
finger
first-visible
flat
fontCaps
fontsize
footnote
fraction
fret-diagram
fret-diagram-terse
fret-diagram-verbose
fromproperty
general-align
halign
harp-pedal
hbracket
hcenter-in
hspace
huge
italic
justified-lines
justify
justify-field
justify-line
justify-string
large
larger
left-align
left-brace
left-column
line
lookup
lower
magnify
map-markup-commands
markalphabet
markletter
medium
musicglyph
natural
normal-size-sub
normal-size-super
normal-text
normalsize
note
note-by-number
null
number
on-the-fly
oval
override
override-lines
pad
pad-around
pad-to-box
pad-x
page-link
page-ref
parenthesize
path
pattern
postscript
property-recursive
put-adjacent
raise
replace
rest
rest-by-number
right-align
right-brace
right-column
roman
rotate
rounded-box
sans
scale
score
score-lines
semiflat
semisharp
sesquiflat
sesquisharp
sharp
simple
slashed-digit
small
smallCaps
smaller
stencil
strut
sub
super
table-of-contents
teeny
text
tied-lyric
tiny
translate
translate-scaled
transparent
triangle
typewriter
underline
upright
vcenter
verbatim-file
vspace
whiteout
whiteout-box
with-color
with-dimensions
with-link
with-url
woodwind-diagram
wordwrap
wordwrap-field
wordwrap-internal
wordwrap-lines
wordwrap-string
wordwrap-string-internal

Returns list.

static LilyPondParser.list_known_music_functions()

Lists all music functions recognized by LilyPond parser.

>>> class_ = abjad.lilypondparsertools.LilyPondParser
>>> for name in class_.list_known_music_functions():
...     print(name)
...
acciaccatura
appoggiatura
bar
breathe
clef
grace
key
language
makeClusters
mark
relative
skip
time
times
transpose

Returns list.

classmethod LilyPondParser.register_markup_function(name, signature)

Registers a custom markup function globally with LilyPondParser.

>>> name = 'my-custom-markup-function'
>>> signature = ['markup?']
>>> class_ = abjad.lilypondparsertools.LilyPondParser
>>> class_.register_markup_function(name, signature)
>>> parser = abjad.lilypondparsertools.LilyPondParser()
>>> string = r"\markup { \my-custom-markup-function { foo bar baz } }"
>>> parser(string)
Markup(contents=[MarkupCommand('my-custom-markup-function', ['foo', 'bar', 'baz'])])

signature should be a sequence of zero or more type-predicate names, as understood by LilyPond. Consult LilyPond’s documentation for a complete list of all understood type-predicates.

Returns none.

Special methods

LilyPondParser.__call__(input_string)

Calls LilyPond parser on input_string.

Returns Abjad components.

(AbjadObject).__eq__(argument)

Is true when ID of argument equals ID of Abjad object. Otherwise false.

Returns true or false.

(AbjadObject).__format__(format_specification='')

Formats Abjad object.

Set format_specification to ‘’ or ‘storage’. Interprets ‘’ equal to ‘storage’.

Returns string.

(AbjadObject).__hash__()

Hashes Abjad object.

Required to be explicitly redefined on Python 3 if __eq__ changes.

Returns integer.

(AbjadObject).__ne__(argument)

Is true when Abjad object does not equal argument. Otherwise false.

Returns true or false.

(AbjadObject).__repr__()

Gets interpreter representation of Abjad object.

Returns string.