A package of modules dealing with LilyPond and the LilyPond format.
The ly module supports both Python2 and Python3. This is a short description of some modules:
- ly.slexer: generic tools to build parsers using regular expressions
- ly.node: a generic list-like node object to build tree structures with
- ly.document: a tokenized text document (LilyPond file)
- ly.docinfo: harvests and caches various information from a LilyPond document
- ly.lex: a parser for LilyPond, Scheme, and other formats, using slexer
- ly.music: a tree structure of the contents of a document
- ly.pitch: functions for translating, transposing etc
- ly.rhythm: functions dealing with rhythm
- ly.indent: indent LilyPond text
- ly.reformat: format LilyPond text
- ly.dom: (deprecated) tree structure to build LilyPond text from
- ly.words: words for highlighting and autocompletion
- ly.data: layout objects, properties, interfaces, font glyphs etc extracted from LilyPond
- ly.cli: the implementation of the command-line ‘ly’ script
A LilyPond document (source file) is held by a ly.document.Document. The Document class automatically parses and tokenizes the text, also when its contents are changed.
A music tree can be built from a document using the ly.music module. In the near future, music trees can be built from scratch and also generate LilyPond output from scratch. At that moment, ly.dom is deprecated.
The functions in ly.pitch, such as transpose and translate currently access the tokens in the document, but in the future they will work on the music tree.
parses text, searching for tokens represented by a regular expression.
Only depends on the standard Python re module.
You need to create at least one subclass of Parser, and a subclass of Token for every type of text to search for. Then you list the token class names in the ‘items’ tuple of the Parser subclass definition.
Different contexts can be parsed by creating multiple Parser subclasses. A Parser searches for tokens using the list of Token classes. (Token is simply a subclass of str in Python 3 and of unicode in Python 2). Every Token subclass has the regular expression part to search for in its ‘rx’ class attribute.
You start parsing text by instantiating a State (you don’t need to subclass that) with the Parser subclass you want to parse the text with. Then you iterate over the generated tokens using the tokens(text) method of the State instance. You can use the tokens just as strings (e.g. if token == ‘text’...) but you can also test for the type of the token (e.g. if isinstance(token, Number)...). The tokens also carry a ‘pos’ and an ‘end’ attribute, specifying their position in the parsed text string.
A token may cause a different Parser to be entered, of the current Parser to be left, etc. This is done by implementing the update_state() method of the Token subclass. This method is called automatically when the Token is instantiated.
The State maintains the parsing state (the list of active Parser instances). A State can be frozen to be thawed later to resume parsing text starting in a particular context. A Fridge can be used to store and recover a state under a simple integer number.
How to use slexer:
from slexer import Token, Parser, State
# create token classes:
class Word(Token):
rx = r'\w+'
class Number(Token):
rx = r'\d+'
class String(Token):
pass
class StringStart(String):
rx = '"'
def update_state(self, state):
state.enter(PString())
class StringEnd(String):
rx = '"'
def update_state(self, state):
state.leave()
# create parsers:
class PTest(Parser):
'''Looks for numbers, words and the double quote.'''
items = (
Number,
Word,
StringStart,
)
class PString(Parser):
'''Returns String by default, quits at double quote.'''
default = String
items = (
StringEnd,
)
s = State(PTest)
for t in s.tokens(
'een tekst met 7 woorden, '
'een "tekst met 2 aanhalingstekens" '
'en 2 of 3 nummers'):
print(t.__class__, t)
Running the above code, the result is:
<class '__main__.Word'> een
<class '__main__.Word'> tekst
<class '__main__.Word'> met
<class '__main__.Number'> 7
<class '__main__.Word'> woorden
<class '__main__.Word'> een
<class '__main__.StringStart'> "
<class '__main__.String'> tekst met 2 aanhalingstekens
<class '__main__.StringEnd'> "
<class '__main__.Word'> en
<class '__main__.Number'> 2
<class '__main__.Word'> of
<class '__main__.Number'> 3
<class '__main__.Word'> nummers
Bases: unicode
Represents a parsed piece of text.
The subclass determines the type.
You should put the regular expression string in the rx class attribute. In the rx string, you may not use named groups starting with “g_”.
To add token types to a Parser class, list the token class in the items attribute of the Parser class.
Should return True if the match should indeed instantiate this class.
This class method is only called if multiple Token classes in the Parser’s items list have the same rx attribute. This method is then called for every matching Token subclass until one returns True. That token is then instantiated. (The method is not called for the last class in the list that have the same rx attribute, and also not if there is only one class with that rx attribute.)
The default implementation always returns True.
Lets the token update the state, e.g. enter a different parser.
This method is called by the State upon instantiation of the tokens.
Don’t use it later on to have a State follow already instantiated Tokens because the FallthroughParser type can also change the state without generating a Token. Use State.follow() to have a State follow instantiated Tokens.
The default implementation lets the Parser decide on state change.
Bases: object
Abstract base class for Parsers.
When creating Parser subclasses, you should set the ‘items’ attribute to a tuple of Token subclasses. On class construction, a large regular expression pattern is built by combining the expressions from the ‘rx’ attributes of the Token subclasses.
Additionally, you may implement the update_state() method which is called by the default implementation of update_state() in Token.
Called when no match is returned by parse().
If this function returns True, the tokenizer stops parsing, assuming all text has been consumed. If this function returns False or None, it should alter the state (switch parsers) and parsing continues using the new Parser.
The default implementation simply returns True.
Bases: ly.slexer.Parser
Base class for parsers that ‘match’ instead of ‘search’ for a pattern.
You can also implement the fallthrough() method to do something with the state if there is no match. The default is to leave the current parser. See Parser().
Bases: object
Maintains state while parsing text.
You instantiate a State object with an initial parser class. Then you use tokens(text) to start parsing for tokens.
The state is basically a list of Parser instances; the last one is the active one. The enter() and leave() methods respectively enter a new parser or leave the current parser.
You can’t leave() the initial parser instance.
Return the number of parsers currently active (1 or more).
You can use this e.g. to keep parsing until some context ends:
tokens = state.tokens(text) # iterator
depth = state.depth()
for token in tokens:
if state.depth() < depth:
break
# do something
Enter a new parser.
Note: ‘parser’ is an instantiated Parser subclass. Most times this method will be called from with the update_state() method of a Token subclass (or from a Parser subclass, which is also possible: the default implementation of Token.update_state() calls Parser.update_state(), which does nothing by default).
E.g. in the Token subclass:
def update_state(self, state):
state.enter(SomeDifferentParser())
Act as if the token has been instantiated with the current state.
You need this when you already have the parsed tokens, (e.g. cached or saved somehow) but want to know which parser created them.
This method changes state according to the token. Basically it calls the update_state() method of the token instance, but it does some more work behind the scenes to ensure that the FallthroughParser type (see below) also is handled correctly.
Leave the current parser and pop back to the previous.
The first parser (specified on instantiation) will never be left.
Replace the current parser with a new one.
Somewhat equivalent to:
state.leave()
state.enter(SomeDifferentParser)
But using this method you can also replace the first parser.
Parse a text string using our state info.
Yields Token instances. All tokens are a subclass of str (or unicode in Python 2.x) and have a pos and an end attribute, describing their position in the original string. If the current parser defines a ‘default’ class attribute, it is the Token subclass to use for pieces of text that would otherwise be skipped.
Represents a LilyPond source document (the text contents).
The Document implementation keeps the document in a (unicode) text string, but you can inherit from the DocumentBase class to support other representations of the text content.
Modifying is preferably done inside a context (the with statement), e.g.:
d = Document('some string')
with d:
d[5:5] = 'different '
d.plaintext() --> 'some different string'
Changes are applied when the context is exited, also the modified part of the document is re-tokenized. Changes may not overlap.
You may modify the document outside a context, in which case the document is re-tokenized immediately. This is much slower however when performing multiple changes after each other.
The tokens(block) method returns a tuple of tokens for the specified block. Depending on the implementation, a block describes a line in the LilyPond source document. It is not expected to have any methods, except that the ‘==’ operator is supported between two blocks, and returns True if both refer to the same line of text in the source document.
Defines a range or position in a Document.
A Runner allows iterating back and forth over the tokens of a document.
Iterate over tokens in a (part of a) Document, with or without state.
Bases: object
Defines a certain range (selection) in a Document.
You may change the start and end attributes yourself. Both must be an integer, end may also be None, denoting the end of the document.
As long as you keep a reference to the Cursor, its positions are updated when the document changes. When text is inserted at the start position, it remains the same. But when text is inserted at the end of a cursor, the end position moves along with the new text. E.g.:
d = Document('hi there, folks!')
c = Cursor(d, 8, 8)
with d:
d[8:8] = 'new text'
c.start, c.end --> (8, 16)
Many tools in the ly module use this object to describe (part of) a document.
Bases: ly.document.DocumentBase
A plain text LilyPond source document that auto-updates the tokens.
The modified attribute is set to True as soon as the document is changed, but the setplaintext() method sets it to False.
Load the document from a file, using the specified encoding and mode.
Bases: object
Abstract base class for Document instances.
You should inherit the following methods:
setplaintext __len__ __getitem__ block index position text tokens isvalid initial_state state_end apply_changes
You may inherit (e.g. to get speed improvements):
plaintext next_block previous_block blocks_forward blocks_backward state
You may use the following attributes:
filename (None) # can represent the filename of the document on disk encoding (None) # can represent the encoding of the document when reading/writing to disk
Return the text block at the specified character position.
The text block itself has no methods, but it can be used as an argument to other methods of this class.
(Blocks do have to support the ‘==’ operator.)
Return the tuple of tokens of the specified block.
The pos and end attributes of every token point to the position of the token in the block.
Bases: object
Iterates back and forth over tokens.
A Runner can stop anywhere and remembers its current token.
Create and init from a Cursor.
The Runner is positioned so that yielding forward starts with the first complete token after the cursor’s start position.
Set after_token to True if you want to position the cursor after the token, so that it gets yielded when you go backward.
If tokens_with_position is True, uses the tokens_with_position() method to get the tokens, else (by default), the tokens() method is used.
Positions the Runner at the start of the given text block.
If at_end == True, the iterator is positioned past the end of the block.
Go to the next block, positioning the cursor at the start by default.
Returns False if there was no next block, else True.
Go to the previous block, positioning the cursor at the end by default.
Returns False if there was no previous block, else True.
Bases: object
Helper iterator.
Iterates over the (block, tokens) tuples from a Document (or a part thereof). Stores the current block in the block attribute and the tokens (which also is a generator) in the tokens attribute.
Iterating over the source object itself just yields the tokens, while the block attribute contains the current block.
You can also iterate over the tokens attribute, which will yield the remaining tokens of the current block and then stop.
If you specify a state, the tokens will update the state. If you specify state = True, the state will be taken from the document.
Consumes iterable (supposed to be reading from us) until position.
Returns the last token if that overlaps position.
Returns the position of the token in the current block.
If the iterator was instantiated with tokens_with_position == True, this position is the same as the token.pos attribute, and the current block does not matter. (In that case you’ll probably not use this method.)
Harvest information from a ly.document.DocumentBase instance.
Bases: object
Harvest information from a ly.document.DocumentBase instance.
All tokens are saved in the tokens attribute as a tuple. Newline tokens are added between all lines. All corresponding classes are in the classes attribute as a tuple. This makes quick search and access possible.
The tokens are requested from the document using the tokens_with_position() method, so you can always locate them back in the original document using their pos attribute.
DocInfo does not update when the document changes, you should just instantiate a new one.
Return the number of tokens that are (a subclass) of the specified class.
If you only want the number of instances of the exact class (not a subclass of) you can use info.classes.count(cls), where info is a DocInfo instance.
Return a dictionary mapping classes to the number of instances of that class.
Return the index of the first specified token and/or class after pos.
If token is None, the cls should be specified. If cls is given, the token should be an instance of the specified class. If endpos is given, never searches beyond endpos. Returns -1 if the token is not found.
Yield all indices of the first specified token and/or class after pos.
If token is None, the cls should be specified. If cls is given, the token should be an instance of the specified class. If endpos is given, never searches beyond endpos. Returns -1 if the token is not found.
Return True when the document probably generates output.
I.e. has notes, rests, markup or other output-generating commands.
The list of arguments of constructs defining the name of output documents.
This looks at the bookOutputName, bookOutputSuffix and define output-suffix commands.
Every argument is a two tuple(type, argument) where type is either “suffix” or “name”.
Return a new instance of the DocInfo class for the selected range.
Only the tokens completely contained within the range start..end are added to the new instance. This can be used to perform fast searches on a subset of a document.
Add, check or remove bar checks in selected music.
Classes and functions to colorize (syntax-highlight) parsed source.
Highlighting is based on CSS properties and their values, although the Mapping object can map a token’s class to any object or value.
The Mapping object normally maps a token’s class basically to a CSS class and possibly a base CSS class. This way you can define base styles (e.g. string, comment, etc) and have specific classes (e.g. LilyPond string, Scheme comment) inherit from that base style. This CSS class is described by the css_class named tuple, with its three fields: mode, name, base. E.g. (‘lilypond’, ‘articulation’, ‘keyword’). The base field may be None.
The css classes are mapped to dictionaries of css properties, like {‘font-weight’: ‘bold’, ‘color’: ‘#4800ff’}, etc.
A scheme (a collection of styles) is simply a dictionary mapping the mode to a dictionary of CSS dictionaries. The base styles are in the [None] item of the scheme dictionary.
Bases: object
A do-it-all object to create syntax highlighted HTML.
You can set the instance attributes to configure the behaviour in all details. Then call the html(cursor) method to get the HTML.
Bases: dict
Maps token classes to arbitrary values, which can be highlighting styles.
Mapper behaves like a dict, you set items with a token class as key to an arbitrary value.
But getting items can be done using a token. The token class’s method resolution order is walked up and the value for the first available class found in the keys is returned. The class is also cached to speed up requests for other tokens.
Combines the html (returned by html()) with the line numbers in a HTML table.
The linenum_attrs are put in the <td> tag for the line numbers. The default value is: {“style”: “background: #eeeeee;”}. The document_attrs are put in the <td> tag for the document. The default is empty.
By default, the id for the linenumbers <td> is set to “linenumbers”, and the id for the document <td> is set to “document”.
Return a dictionary with a ‘style’ key.
The value is the style items in d formatted with css_item() joined with spaces. If d is empty, an empty dictionary is returned.
Bases: tuple
css_class(mode, name, base)
Alias for field number 2
Alias for field number 0
Alias for field number 1
Return the css properties dict for the style, taken from the scheme.
This can be used for inline style attributes.
Return a “selector { items...}” part of a CSS stylesheet.
Return a Mapper dict, mapping token classes to two CSS classes.
By default the mapping returned by default_mapping() is used.
Bases: object
Return the inline style attribute for a specified style.
Return a good default mapping from token class(es) to style and default style, per group.
Return a string like ‘class=”mode-style base”’ for the specified style.
Return a complete HTML document.
The body is put inside body tags unchanged. The title is html-escaped. If stylesheet_ref is given, it is put as a <link> reference in the HTML; if stylesheet is given, it is put verbatim in a <style> section in the HTML. The encoding is set in the meta http-equiv field, but the returned HTML is in normal Python unicode (python2) or str (python3) format, you should encode it yourself in the same encoding (by default utf-8) when writing it to a file.
Return a formatted stylesheet for the stylesheet scheme dictionary.
Return the list of tokens for the cursor.
Tokens that are partially inside the cursor’s selection are re-created so that they fall exactly within the selection.
This can be used to convert a highlighted part of a document to e.g. HTML.
Return a HTML string with the tokens wrapped in <span class=> elements.
The span argument is a function returning an attribute for the <span> tag for the specified style. By default the format_css_span_class() function is used, that returns a ‘class=”group style base”’ string. You’ll want to wrap the HTML inside <pre> tokens and add a CSS stylesheet.
Format the attributes dict as a string.
The attributes are escaped correctly. A space is prepended for every assignment.
Yield a two-tuple(token, style) for every token.
The style is what mapper[token] returns. Style may be None, which also happens with unparsed (not-tokenized) text.
Routines manipulating ly.document.Cursor instances.
This module is deprecated. When ly.music is able to generate LilyPond code from scratch, this module will be removed.
LilyPond DOM
(c) 2008-2011 Wilbert Berendsen License: GPL.
A simple Document Object Model for LilyPond documents.
The purpose is to easily build a LilyPond document with good syntax, not to fully understand all features LilyPond supports. (This DOM does not enforce a legal LilyPond file.)
All elements of a LilyPond document inherit Node.
Note: elements keep a weak reference to their parent.
Bases: ly.dom.InputLyrics
Bases: ly.dom.Container
A varname = value construct with it’s value as its first child The name can be a string or a Reference object: so that everywhere where this varname is referenced, the name is the same.
Bases: ly.dom.Newline
A blank line.
Bases: ly.dom.Container
A vertical container type that puts everything on a new line.
Bases: ly.dom.Comment
A block comment between %{ and %}
Bases: ly.dom.Section
Bases: ly.dom.Section
Bases: ly.dom.ContextType
Bases: ly.dom.Container
A chord containing one of more Pitches and optionally one Duration. This is a bit of a hack, awaiting real music object support.
Bases: ly.dom.InputMode
Bases: ly.dom.ContextType
Bases: ly.dom.Leaf
A clef.
Bases: ly.dom.Statement
Use this to create a LilyPond command supplying the name (or a Reference) when instantiating.
Bases: ly.dom.StatementEnclosed
Use this to print LilyPond commands that have a single bracket-enclosed list of arguments. The command name is supplied to the constructor.
Bases: ly.dom.Text
A LilyPond comment at the end of a line
Bases: ly.dom.LyNode
A node that concatenates its children on output
Bases: ly.dom.HandleVars, ly.dom.Section
A context section for use inside Layout or Midi sections.
Bases: ly.dom.Text
Used to print a context name, like Score.
Bases: ly.dom.Leaf
A Context.property or Context.layoutObject construct. Call e.g. ContextProperty(‘aDueText’, ‘Staff’) to get ‘Staff.aDueText’.
Bases: ly.dom.Container
new or context Staff = ‘bla’ with { } << music >>
A with (With) element is added automatically as the first child as soon as you use our convenience methods that manipulate the variables in with. If the with element is empty, it does not print anything. You should add one other music object to this.
Adds the Instrument_name_engraver to the node if it would need it to print instrument names.
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.Container
A container type that puts everything on a new line. To be used as a full LilyPond document.
Bases: ly.dom.InputMode
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.Leaf
A duration with duration (in logarithmic form): (-2 ... 8), where -2 = longa, -1 = breve, 0 = 1, 1 = 2, 2 = 4, 3 = 8, 4 = 16, etc, dots (number of dots), factor (Fraction giving the scaling of the duration).
Bases: ly.dom.ContextType
Bases: ly.dom.Container
Encloses all children between brackets: { ... } If may_remove_brackets is True in subclasses, the brackets are removed if there is only one child and that child is an atom (i.e. a single LilyPond expression.
Bases: ly.dom.InputMode
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: object
A powerful mixin class to facilitate handling unique variable assignments inside a Container more. E.g.: >>> h = Header() >>> h[‘composer’] = “Johann Sebastian Bach” creates a subnode (by default Assignment) with the name ‘composer’, and that node again gets an autogenerated subnode of type QuotedString (if the argument wasn’t already a Node).
alias of Assignment
Bases: ly.dom.HandleVars, ly.dom.Section
Bases: ly.dom.Leaf
An identifier, prints as name. Name may be a string or a Reference object.
Bases: ly.dom.Line
a LilyPond include statement
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.ChordMode
Bases: ly.dom.DrumMode
Bases: ly.dom.FigureMode
Bases: ly.dom.LyricMode
Bases: ly.dom.StatementEnclosed
The abstract base class for input modes such as lyricmode/lyrics, chordmode/chords etc.
Bases: ly.dom.NoteMode
Bases: ly.dom.Leaf
A key signature expression, like:
key c major The pitch should be given in the arguments note and alter and is written out in the document’s language.
Bases: ly.dom.HandleVars, ly.dom.Section
Bases: ly.dom.LyNode
A leaf node without children
Bases: ly.dom.Text
A text node that claims its own line.
Bases: ly.dom.Comment
A LilyPond comment that takes a full line
Bases: ly.node.WeakNode
Base class for LilyPond objects, based on Node, which takes care of the tree structure.
Returns a string with newlines to concat this node to another one. If zero newlines are requested, an empty string is returned.
Bases: ly.dom.InputMode
Bases: ly.dom.ContextType
Bases: ly.dom.LyricMode
Bases: ly.dom.Statement
The mark command.
Bases: ly.dom.StatementEnclosed
The markup command. You can add many children, in that case Markup automatically prints { and } around them.
Bases: ly.dom.Command
A markup command with more or no arguments, that does not auto-enclose its arguments. Useful for commands like note-by-number or hspace.
You must supply the name. Its arguments are its children. If one argument can be a markup list, use a Enclosed() construct for that.
Bases: ly.dom.CommandEnclosed
A markup that auto-encloses all its arguments, like ‘italic’, ‘bold’ etc. You must supply the name.
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.HandleVars, ly.dom.Section
Bases: object
Mixin to print a name before the contents of the container. format() is called on the self.name attribute, so it may also be a Reference.
Bases: ly.dom.LyNode
A newline.
Bases: ly.dom.InputMode
Bases: ly.dom.ContextType
Bases: ly.dom.HandleVars, ly.dom.Section
Bases: ly.dom.Named, ly.dom.Duration
partial <duration> You should add a Duration element
Bases: ly.dom.ContextType
Bases: ly.dom.Leaf
A pitch with octave, note, alter. octave is specified by an integer, zero for the octave containing middle C. note is a number from 0 to 6, with 0 corresponding to pitch C and 6 corresponding to pitch B. alter is the number of whole tones for alteration (can be int or Fraction)
Bases: object
Performs certain operations on behalf of a LyNode tree, like quoting strings or translating pitch names, etc.
A generator that walks on the output of the given node, and returns properly indented LilyPond code.
Bases: ly.dom.Text
A string that is output inside double quotes.
Bases: object
A simple object that keeps a name, to use as a (context) identifier. Set the name attribute to the name you want to display, and on all places in the document the name will show up.
Bases: ly.dom.Statement
relative <pitch> music
You should add a Pitch (optionally) and another music object, e.g. Sim or Seq, etc.
Bases: ly.dom.ContextType
Bases: ly.dom.Text
A Scheme expression, without the extra # prepended
Bases: ly.dom.Enclosed
A LilyPond expression between #{ #} (inside scheme)
Bases: ly.dom.Enclosed
A list of items enclosed in parentheses
Bases: ly.dom.Section
Bases: ly.dom.ContextType
Represents the Score context in LilyPond, but the name would collide with the Score class that represents score { } constructs.
Because the latter is used more often, use ScoreContext to get new Score etc.
Bases: ly.dom.StatementEnclosed
Very much like a Statement. Use as base class for book { }, score { } etc. By default never removes the brackets and always starts on a new line.
Bases: ly.dom.Enclosed
An SequentialMusic expression between { }
Bases: ly.dom.Seq
Bases: ly.dom.Enclosed
An SimultaneousMusic expression between << >>
Bases: ly.dom.Sim
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.Named, ly.dom.Container
Base class for statements with arguments. The statement is read in the name attribute, the arguments are the children.
Bases: ly.dom.Named, ly.dom.Enclosed
Base class for LilyPond commands that have a single bracket-enclosed list of arguments.
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.Container
A tempo setting, like: tempo 4 = 100 May have a child markup or quoted string.
Bases: ly.dom.Leaf
A leaf node with arbitrary text
Bases: ly.dom.AddDuration, ly.dom.Text
A text note with an optional duration as child.
Bases: ly.dom.Leaf
A time signature, like: time 4/4
Bases: ly.dom.Statement
transposition <pitch> You should add a Pitch.
Bases: ly.dom.ContextType
Represents a context the user creates. e.g. new MyStaff = cid << music >>
Bases: ly.dom.ContextType
Bases: ly.dom.ContextType
Bases: ly.dom.Line
a LilyPond version instruction
Bases: ly.dom.ContextType
Bases: ly.dom.Leaf
A Voice Separator: \
Bases: ly.dom.HandleVars, ly.dom.Section
If this item has no children, it prints nothing.
LilyPond information and logic concerning durations
Return (base, scaling) as two Fractions for the list of tokens.
Return (base, scaling) as two Fractions for the specified string.
Utility functions for use with xml.etree.ElementTree.
Indent and auto-indent.
Bases: object
Return the indent the specified block should have.
Returns False if the block is not indentable, e.g. when it is part of a multiline string.
This method is used to determine the indent of one line, and just looks to previous lines, copying the indent of the line where the current indent depth starts, and/or adding a level of indent or alignment space.
Use this method only for one line or the first of a group you’re indenting.
Return the indent the block currently has.
Returns False if the block is not indentable, e.g. when it is part of a multiline string.
Indent all lines in the cursor’s range.
If indent_blank_lines is True, the indent of blank lines is made larger if necessary. If False (the default), the indent of blank lines if not changed if it is shorter than it should be.
The Node class.
(c) 2008-2011 Wilbert Berendsen License: GPL.
This module contains the Node class that can be used as a simple DOM (Document Object Model) for building a tree structure.
A Node has children with list-like access methods and keeps also a reference to its parent. A Node can have one parent; appending a Node to another Node causes it to be removed from its parent node (if any).
To iterate over the children of a Node:
for n in node:
do_something(n)
To get the list of children of a Node:
children = list(node)
Of course you can get the children directly using:
child = node[3]
You should inherit from Node to make meaningful tree node types, e.g. to add custom attributes or multiple sub-types.
A WeakNode class is provided as well, which uses a weak reference to the parent, so that no cyclic references are created which might improve garbage collection.
Bases: object
A list-like class to build tree structures with.
Append a node to the current node.
It will be reparented, that means it will be removed from it’s former parent if it had one.
Yield all descendants if they are an instance of cls.
cls may also be a tuple of classes. This method uses iter_depth().
Return the first descendant that’s an instance of cls.
cls may also be a tuple of classes. This method uses iter_rings().
Yield all descendants if they are an instance of cls.
cls may also be a tuple of classes. This method uses iter_rings().
Find an ancestor that’s an instance of the given class.
cls may also be a tuple of classes.
Iterate over all the children, and their children, etc.
Set depth to restrict the search to a certain depth, -1 is unrestricted.
Iterate over the children in rings, depth last.
This method returns the closest descendants first. Set depth to restrict the search to a certain depth, -1 is unrestricted.
Return the sibling object just after us in our parents list.
Returns None if this is the last child, or if we have no parent.
Return the sibling object just before us in our parents list.
Returns None if this is the first child, or if we have no parent.
Bases: ly.node.Node
A Node type using a weak reference to the parent.
Meta-information about the LY package.
This information is used by the install script, and also for the command ly --version.
name of the package
the current version
short description
long description
maintainer name
maintainer email
homepage
license
Formatting tools to improve the readability of a ly.document.Document without changing the semantic meaning of the LilyPond source.
Basically the tools only change whitespace to make the source-code more readable.
See also ly.indent.
Add newlines around indent and dedent tokens where needed.
If there is stuff after a { or << (that’s not closed on the same line) it is put on a new line, and if there if stuff before a } or >>, the } or >> is put on a new line.
It is necessary to run the indenter again over the same part of the document, as it will look garbled with the added newlines.
Move line comments with more than 2 comment characters to column 0.
Implementation of the tools to edit durations of selected music.
Durations are represented simply by lists of ly.lex.lilypond.Duration tokens.
All functions expect a ly.document.Cursor with the selected range.
Bases: tuple
music_item(tokens, dur_tokens, may_remove, insert_pos, pos, end)
Alias for field number 1
Alias for field number 5
Alias for field number 3
Alias for field number 2
Alias for field number 4
Alias for field number 0
Yield music_item instances describing rests, skips or pitches.
cursor is a ly.document.Cursor instance.
The following keyword arguments can be used:
DEPRECATED. Yield lists of tokens describing rests, skips or pitches.
source is a ly.document.Source instance following the state.
The following keyword arguments can be used:
This function is deprecated and will be removed. You should use music_items() instead.
Return a preceding duration before the cursor, or an empty list.
Remove reoccurring durations, but always write one on a new line.
Apply a list of durations to the cursor’s range.
The durations list looks like [“4”, “8”, “”, “16.”,] etc.
Remove the scaling containing fractions (like *1/3) from all durations.
Utility functions.
Converts an integer to one or more letters.
E.g. 1 -> A, 2 -> B, ... 26 -> Z, 27 -> AA, etc. Zero returns the empty string.
chars is the string to pick characters from, defaulting to string.ascii_uppercase.
Convert an integer value to a roman number string.
E.g. 1 -> “I”, 12 -> “XII”, 2015 -> “MMXV”
n has to be > 1.
Converts an integer to the English language name of that integer.
E.g. converts 1 to “One”. Supports numbers 0 to 999999. This can be used in LilyPond identifiers (that do not support digits).
Makes a lower-camel-case identifier of the strings in args.
All strings are concatenated with the first character of every string uppercased, except for the first character, which is lowercased.
Examples:
mkid("Violin") ==> "violin"
mkid("soprano", "verse") ==> "sopranoVerse"
mkid("scoreOne", "choirII") ==> "scoreOneChoirII"
LilyPond reserved words for auto completion and highlighting.