The ly package

Module contents

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.

Subpackages

Submodules

ly.slexer module

slexer – Stateful Lexer

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
class ly.slexer.FallthroughParser[source]

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().

fallthrough(state)[source]

Called when no match is returned by parse().

This implementation leaves the current parser and returns None (causing the State to continue parsing).

parse(text, pos)[source]

Match text at position pos and returns a Match Object or None.

class ly.slexer.Fridge(stateClass=<class 'ly.slexer.State'>)[source]

Bases: object

Stores frozen States under an integer number.

count()[source]

Returns the number of stored frozen states.

freeze(state)[source]

Stores a state and return an identifying integer.

thaw(num)[source]

Returns the state stored under the specified number.

class ly.slexer.Parser[source]

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.

default = None
fallthrough(state)[source]

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.

freeze()[source]

Return our instance values as a hashable tuple.

items = ()
parse(text, pos)[source]

Parse text from position pos and returns a Match Object or None.

re_flags = 0
classmethod thaw(attrs)[source]
token(match)[source]

Return a Token instance of the correct class.

The match object is returned by the parse() method.

update_state(state, token)[source]

Called by the default implementation of Token.update_state().

Does nothing by default.

class ly.slexer.State(initialParserClass)[source]

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.

depth()[source]

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(parser)[source]

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())
follow(token)[source]

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.

freeze()[source]

Return the current state as a tuple (hashable object).

leave()[source]

Leave the current parser and pop back to the previous.

The first parser (specified on instantiation) will never be left.

parser()[source]

Return the currently active Parser instance.

parsers()[source]

Return all active parsers, the most current one first.

replace(parser)[source]

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.

classmethod thaw(frozen)[source]

Reproduce a State object from the frozen state argument.

tokens(text, pos=0)[source]

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.

class ly.slexer.Token(string, pos)[source]

Bases: str

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.

end
pos
rx = None
classmethod test_match(match)[source]

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.

update_state(state)[source]

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.

ly.document module

DocumentBase and Document

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.

Cursor

Defines a range or position in a Document.

Runner

A Runner allows iterating back and forth over the tokens of a document.

Source

Iterate over tokens in a (part of a) Document, with or without state.

class ly.document.Cursor(doc, start=0, end=None)[source]

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.

blocks()[source]

Iterate over the selected blocks.

If there are multiple blocks and the cursor ends on the first position of the last selected block, that block is not included.

property document
end_block()[source]

Return the block the end attribute points at.

has_selection()[source]

Return True when there is some text selected.

lstrip(chars=None)[source]

Move start to the right, like Python’s lstrip() string method.

rstrip(chars=None)[source]

Move end to the left, like Python’s lstrip() string method.

select_all()[source]

Select all text.

select_end_of_block()[source]

Move end to the end of the block.

select_start_of_block()[source]

Move start to the start of the block.

start_block()[source]

Return the block the start attribute points at.

strip(chars=None)[source]

Strip chars from the selection, like Python’s strip() method.

text()[source]

Convenience method to return the selected text.

text_after()[source]

Return text after the cursor in it’s end block.

text_before()[source]

Return text before the cursor in it’s start block.

class ly.document.Document(text='', mode=None)[source]

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.

apply_changes()[source]

Apply the changes and update the tokens.

block(position)[source]

Return the text block at the specified character position.

copy()[source]

Return a full copy of the document.

index(block)[source]

Return the linenumber of the block (starting with 0).

initial_state()[source]

Return the state at the beginning of the document.

isvalid(block)[source]

Return True if the block is a valid block.

classmethod load(filename, encoding='utf-8', mode=None)[source]

Load the document from a file, using the specified encoding and mode.

mode()[source]

Return the mode (lilypond, html, etc). None means automatic mode.

modified = False
position(block)[source]

Return the position of the specified block.

setmode(mode)[source]

Sets the mode to one of the ly.lex modes.

Use None to auto-determine the mode.

setplaintext(text)[source]

Set the text of the document, sets modified to False.

state_end(block)[source]

Return the state at the end of the specified block.

text(block)[source]

Return the text of the specified block.

tokens(block)[source]

Return the tuple of tokens of the specified block.

class ly.document.DocumentBase[source]

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

apply_changes()[source]

Apply the changes and update the tokens.

block(position)[source]

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.)

blocks_backward(block)[source]

Iter backwards starting with the specified block.

blocks_forward(block)[source]

Iter forward starting with the specified block.

check_changes()[source]

Debugging method that checks for overlapping edits.

encoding = None
filename = None
index(block)[source]

Return the linenumber of the block (starting with 0).

initial_state()[source]

Return the state at the beginning of the document.

isblank(block)[source]

Return True if the block is empty or blank.

isvalid(block)[source]

Return True if the block is a valid block.

next_block(block)[source]

Return the next block, which may be invalid.

plaintext()[source]

The document contents as a plain text string.

position(block)[source]

Return the position of the specified block.

previous_block(block)[source]

Return the previous block, which may be invalid.

setplaintext(text)[source]

Sets the document contents to the text string.

size()[source]

Return the number of characters in the document.

state(block)[source]

Return the state at the start of the specified block.

state_end(block)[source]

Return the state at the end of the specified block.

text(block)[source]

Return the text of the specified block.

tokens(block)[source]

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.

tokens_with_position(block)[source]

Return a tuple of tokens of the specified block.

The pos and end attributes of every token point to the position in the Document, instead of to the position in the current block.

This makes it easier to iterate over tokens and change the document.

update_cursors()[source]

Updates the position of the registered Cursor instances.

class ly.document.Runner(doc, tokens_with_position=False)[source]

Bases: object

Iterates back and forth over tokens.

A Runner can stop anywhere and remembers its current token.

classmethod at(cursor, after_token=False, tokens_with_position=False)[source]

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.

backward()[source]

Yields tokens in backward direction across blocks.

backward_line()[source]

Yields tokens in backward direction in the current block.

copy()[source]

Return a new Runner at the current position.

property document

Return our Document.

forward()[source]

Yields tokens in forward direction across blocks.

forward_line()[source]

Yields tokens in forward direction in the current block.

move_to_block(block, at_end=False)[source]

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.

next(current_block=False)[source]

Return the next token or False if there is no more token. If current_block=True stop at the end of the current block.

next_block(at_end=False)[source]

Go to the next block, positioning the cursor at the start by default.

Returns False if there was no next block, else True.

position()[source]

Returns the position of the current token.

previous(current_block=False)[source]

Return the previous token or False if there is no more token. If current_block=True stop at the beginning of the current block.

previous_block(at_end=True)[source]

Go to the previous block, positioning the cursor at the end by default.

Returns False if there was no previous block, else True.

set_position(position, after_token=False)[source]

Positions the Runner at the specified 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.

token()[source]

Re-returns the last yielded token.

class ly.document.Source(cursor, state=None, partial=1, tokens_with_position=False)[source]

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.

consume(iterable, position)[source]

Consumes iterable (supposed to be reading from us) until position.

Returns the last token if that overlaps position.

property document

Return our Document.

next()
position(token)[source]

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.)

pushback(pushback=True)[source]

Yields the last yielded token again on the next request.

This can be called multiple times, but only the last token will be yielded again. You can also undo a call to pushback() using pushback(False).

token()[source]

Re-returns the last yielded token.

until_parser_end()[source]

Yield the tokens until the current parser is quit.

You can only use this method if you have a State enabled.

ly.docinfo module

Harvest information from a ly.document.DocumentBase instance.

class ly.docinfo.DocInfo(doc)[source]

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.

complete()[source]

Return whether the document is probably complete and could be compilable.

count_tokens(cls)[source]

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.

counted_tokens()[source]

Return a dictionary mapping classes to the number of instances of that class.

definitions()[source]

The list of LilyPond identifiers the document defines.

property document
find(token=None, cls=None, pos=0, endpos=- 1)[source]

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.

find_all(token=None, cls=None, pos=0, endpos=- 1)[source]

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.

global_staff_size()[source]

The global-staff-size, if set, else None.

has_output()[source]

Return True when the document probably generates output.

I.e. has notes, rests, markup or other output-generating commands.

include_args()[source]

The list of include command arguments.

language()[source]

The pitch language, None if not set in the document.

markup_definitions()[source]

The list of markup command definitions in the document.

mode()[source]

Return the mode, e.g. “lilypond”.

output_args()[source]

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”.

range(start=0, end=None)[source]

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.

scheme_load_args()[source]

The list of scheme (load) command arguments.

token_hash()[source]

Return an integer hash for all non-whitespace and non-comment tokens.

This hash does not change when only comments or whitespace are changed.

version()[source]

Return the version_string() as a tuple of ints, e.g. (2, 16, 2).

version_string()[source]

Return the version as a string, e.g. “2.19.8”.

Looks for the version LilyPond command. The string is returned without quotes. Returns None if there was no version command found.

ly.barcheck module

Add, check or remove bar checks in selected music.

class ly.barcheck.event[source]

Bases: object

A limited event type at a certain time.

append(node)[source]
ly.barcheck.insert(cursor, music=None)[source]

Insert bar checks within the selected range.

ly.barcheck.remove(cursor)[source]

Remove bar checks from the selected music.

ly.colorize module

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.

class ly.colorize.HtmlWriter[source]

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.

bgcolor = None
css_mapper = None
css_scheme = {None: {'keyword': {'font-weight': 'bold'}, 'function': {'font-weight': 'bold', 'color': '#0000c0'}, 'variable': {'color': '#0000ff'}, 'value': {'color': '#808000'}, 'string': {'color': '#c00000'}, 'escape': {'color': '#008080'}, 'comment': {'color': '#808080', 'font-style': 'italic'}, 'error': {'color': '#ff0000', 'text-decoration': 'underline', 'text-decoration-color': '#ff0000'}}, 'lilypond': {'duration': {'color': '#008080'}, 'markup': {'color': '#008000', 'font-weight': 'normal'}, 'lyricmode': {'color': '#006000'}, 'lyrictext': {'color': '#006000'}, 'grob': {'color': '#c000c0'}, 'context': {'font-weight': 'bold'}, 'slur': {'font-weight': 'bold'}, 'articulation': {'font-weight': 'bold', 'color': '#ff8000'}, 'dynamic': {'font-weight': 'bold', 'color': '#ff8000'}, 'fingering': {'color': '#ff8000'}, 'stringnumber': {'color': '#ff8000'}}, 'scheme': {}, 'html': {}, 'texinfo': {}, 'mup': {}}
document_id = 'document'
encoding = 'UTF-8'
fgcolor = None
full_html = True
html(cursor)[source]

Return the output HTML.

inline_style = False
linenumbers_bgcolor = '#eeeeee'
linenumbers_fgcolor = None
linenumbers_id = 'linenumbers'
number_lines = False
set_wrapper_attribute(attr)[source]

Choose attribute name for wrapper tag

set_wrapper_tag(tag)[source]

Define the tag to be used for wrapping the content

stylesheet_ref = None
title = ''
wrapper_attribute = 'id'
wrapper_tag = 'pre'
class ly.colorize.Mapper[source]

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.

ly.colorize.add_line_numbers(cursor, html, linenum_attrs=None, document_attrs=None)[source]

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”.

ly.colorize.css_attr(d)[source]

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.

class ly.colorize.css_class(mode, name, base)

Bases: tuple

base

Alias for field number 2

mode

Alias for field number 0

name

Alias for field number 1

ly.colorize.css_dict(css_style, scheme={None: {'keyword': {'font-weight': 'bold'}, 'function': {'font-weight': 'bold', 'color': '#0000c0'}, 'variable': {'color': '#0000ff'}, 'value': {'color': '#808000'}, 'string': {'color': '#c00000'}, 'escape': {'color': '#008080'}, 'comment': {'color': '#808080', 'font-style': 'italic'}, 'error': {'color': '#ff0000', 'text-decoration': 'underline', 'text-decoration-color': '#ff0000'}}, 'lilypond': {'duration': {'color': '#008080'}, 'markup': {'color': '#008000', 'font-weight': 'normal'}, 'lyricmode': {'color': '#006000'}, 'lyrictext': {'color': '#006000'}, 'grob': {'color': '#c000c0'}, 'context': {'font-weight': 'bold'}, 'slur': {'font-weight': 'bold'}, 'articulation': {'font-weight': 'bold', 'color': '#ff8000'}, 'dynamic': {'font-weight': 'bold', 'color': '#ff8000'}, 'fingering': {'color': '#ff8000'}, 'stringnumber': {'color': '#ff8000'}}, 'scheme': {}, 'html': {}, 'texinfo': {}, 'mup': {}})[source]

Return the css properties dict for the style, taken from the scheme.

This can be used for inline style attributes.

ly.colorize.css_group(selector, d)[source]

Return a “selector { items…}” part of a CSS stylesheet.

ly.colorize.css_item(i)[source]

Return “name: value;” where i = (name, value).

ly.colorize.css_mapper(mapping=None)[source]

Return a Mapper dict, mapping token classes to two CSS classes.

By default the mapping returned by default_mapping() is used.

class ly.colorize.css_style_attribute_formatter(scheme={None: {'keyword': {'font-weight': 'bold'}, 'function': {'font-weight': 'bold', 'color': '#0000c0'}, 'variable': {'color': '#0000ff'}, 'value': {'color': '#808000'}, 'string': {'color': '#c00000'}, 'escape': {'color': '#008080'}, 'comment': {'color': '#808080', 'font-style': 'italic'}, 'error': {'color': '#ff0000', 'text-decoration': 'underline', 'text-decoration-color': '#ff0000'}}, 'lilypond': {'duration': {'color': '#008080'}, 'markup': {'color': '#008000', 'font-weight': 'normal'}, 'lyricmode': {'color': '#006000'}, 'lyrictext': {'color': '#006000'}, 'grob': {'color': '#c000c0'}, 'context': {'font-weight': 'bold'}, 'slur': {'font-weight': 'bold'}, 'articulation': {'font-weight': 'bold', 'color': '#ff8000'}, 'dynamic': {'font-weight': 'bold', 'color': '#ff8000'}, 'fingering': {'color': '#ff8000'}, 'stringnumber': {'color': '#ff8000'}}, 'scheme': {}, 'html': {}, 'texinfo': {}, 'mup': {}})[source]

Bases: object

Return the inline style attribute for a specified style.

ly.colorize.default_mapping()[source]

Return a good default mapping from token class(es) to style and default style, per group.

ly.colorize.format_css_span_class(css_style)[source]

Return a string like ‘class=”mode-style base”’ for the specified style.

ly.colorize.format_html_document(body, title='', stylesheet=None, stylesheet_ref=None, encoding='UTF-8')[source]

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.

ly.colorize.format_stylesheet(scheme={None: {'keyword': {'font-weight': 'bold'}, 'function': {'font-weight': 'bold', 'color': '#0000c0'}, 'variable': {'color': '#0000ff'}, 'value': {'color': '#808000'}, 'string': {'color': '#c00000'}, 'escape': {'color': '#008080'}, 'comment': {'color': '#808080', 'font-style': 'italic'}, 'error': {'color': '#ff0000', 'text-decoration': 'underline', 'text-decoration-color': '#ff0000'}}, 'lilypond': {'duration': {'color': '#008080'}, 'markup': {'color': '#008000', 'font-weight': 'normal'}, 'lyricmode': {'color': '#006000'}, 'lyrictext': {'color': '#006000'}, 'grob': {'color': '#c000c0'}, 'context': {'font-weight': 'bold'}, 'slur': {'font-weight': 'bold'}, 'articulation': {'font-weight': 'bold', 'color': '#ff8000'}, 'dynamic': {'font-weight': 'bold', 'color': '#ff8000'}, 'fingering': {'color': '#ff8000'}, 'stringnumber': {'color': '#ff8000'}}, 'scheme': {}, 'html': {}, 'texinfo': {}, 'mup': {}})[source]

Return a formatted stylesheet for the stylesheet scheme dictionary.

ly.colorize.get_tokens(cursor)[source]

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.

ly.colorize.html(cursor, mapper, span=<function format_css_span_class>)[source]

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.

ly.colorize.html_escape(text)[source]

Escape &, < and >.

ly.colorize.html_escape_attr(text)[source]

Escape &, “, < and >.

ly.colorize.html_format_attrs(d)[source]

Format the attributes dict as a string.

The attributes are escaped correctly. A space is prepended for every assignment.

ly.colorize.map_tokens(cursor, mapper)[source]

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.

ly.colorize.melt_mapped_tokens(mapped_tokens)[source]

Melt adjacent tokens with the same mapping together.

class ly.colorize.style(name, base, classes)

Bases: tuple

base

Alias for field number 1

classes

Alias for field number 2

name

Alias for field number 0

ly.cursortools module

Routines manipulating ly.document.Cursor instances.

ly.cursortools.find_indent(iterable)[source]

Yield (token, is_indent, nest) for every occurring indent/dedent token.

The tokens are yielded from the specified iterable.

ly.cursortools.select_block(cursor)[source]

Try to select a meaningful block.

Searches backwards for an indenting token, then selects up to the corresponding dedenting token. If needed searches an extra level back to always extend the selection. Returns True if the cursor’s selection has changed.

ly.dom module

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.

class ly.dom.AddDuration[source]

Bases: object

Mixin to add a duration (as child).

ly(printer)[source]
class ly.dom.AddLyrics(parent=None)[source]

Bases: ly.dom.InputLyrics

after = 1
before = 1
may_remove_brackets = False
name = 'addlyrics'
class ly.dom.Assignment(name=None, parent=None, valueObj=None)[source]

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.

after = 1
before = 1
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

setValue(obj)[source]
value()[source]
class ly.dom.BlankLine(parent=None)[source]

Bases: ly.dom.Newline

A blank line.

before = 1
class ly.dom.Block(parent=None)[source]

Bases: ly.dom.Container

A vertical container type that puts everything on a new line.

after = 1
before = 1
defaultSpace = '\n'
class ly.dom.BlockComment(text='', parent=None)[source]

Bases: ly.dom.Comment

A block comment between %{ and %}

property after

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

property before

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Book(parent=None)[source]

Bases: ly.dom.Section

name = 'book'
class ly.dom.BookPart(parent=None)[source]

Bases: ly.dom.Section

name = 'bookpart'
class ly.dom.ChoirStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Chord(parent=None)[source]

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.

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.ChordMode(parent=None)[source]

Bases: ly.dom.InputMode

name = 'chordmode'
class ly.dom.ChordNames(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Clef(clef, parent=None)[source]

Bases: ly.dom.Leaf

A clef.

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Command(name, parent=None)[source]

Bases: ly.dom.Statement

Use this to create a LilyPond command supplying the name (or a Reference) when instantiating.

class ly.dom.CommandEnclosed(name, parent=None)[source]

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.

class ly.dom.Comment(text='', parent=None)[source]

Bases: ly.dom.Text

A LilyPond comment at the end of a line

after = 1
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Container(parent=None)[source]

Bases: ly.dom.LyNode

A node that concatenates its children on output

property after

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

property before

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int(‘0b100’, base=0) 4

defaultSpace = ' '
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Context(contextName='', parent=None)[source]

Bases: ly.dom.HandleVars, ly.dom.Section

A context section for use inside Layout or Midi sections.

name = 'context'
class ly.dom.ContextName(text='', parent=None)[source]

Bases: ly.dom.Text

Used to print a context name, like Score.

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.ContextProperty(prop, context=None, parent=None)[source]

Bases: ly.dom.Leaf

A Context.property or Context.layoutObject construct. Call e.g. ContextProperty(‘aDueText’, ‘Staff’) to get ‘Staff.aDueText’.

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.ContextType(cid=None, new=True, parent=None)[source]

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.

addInstrumentNameEngraverIfNecessary()[source]

Adds the Instrument_name_engraver to the node if it would need it to print instrument names.

after = 1
before = 1
ctype = None
getWith()[source]

Gets the attached with clause. Creates it if not there.

isAtom = True
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.CueVoice(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Devnull(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Document(parent=None)[source]

Bases: ly.dom.Container

A container type that puts everything on a new line. To be used as a full LilyPond document.

after = 1
defaultSpace = '\n'
class ly.dom.DrumMode(parent=None)[source]

Bases: ly.dom.InputMode

name = 'drummode'
class ly.dom.DrumStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.DrumVoice(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Duration(dur, dots=0, factor=1, parent=None)[source]

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).

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Dynamics(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Enclosed(parent=None)[source]

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.

after = 0
before = 0
isAtom = True
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

may_remove_brackets = False
post = '}'
pre = '{'
class ly.dom.FigureMode(parent=None)[source]

Bases: ly.dom.InputMode

name = 'figuremode'
class ly.dom.FiguredBass(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.FretBoards(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Global(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.GrandStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.GregorianTranscriptionStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.GregorianTranscriptionVoice(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.HandleVars[source]

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).

childClass

alias of ly.dom.Assignment

ifbasestring()[source]

Ensure that the method is only called for basestring objects. Otherwise the same method from the super class is called.

importNode(obj)[source]

Try to interpret the object and transform it into a Node object of the right species.

class ly.dom.Header(parent=None)[source]

Bases: ly.dom.HandleVars, ly.dom.Section

name = 'header'
class ly.dom.Identifier(name=None, parent=None)[source]

Bases: ly.dom.Leaf

An identifier, prints as name. Name may be a string or a Reference object.

isAtom = True
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Include(text='', parent=None)[source]

Bases: ly.dom.Line

a LilyPond include statement

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.InnerChoirStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.InnerStaffGroup(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.InputChords(parent=None)[source]

Bases: ly.dom.ChordMode

name = 'chords'
class ly.dom.InputDrums(parent=None)[source]

Bases: ly.dom.DrumMode

name = 'drums'
class ly.dom.InputFigures(parent=None)[source]

Bases: ly.dom.FigureMode

name = 'figures'
class ly.dom.InputLyrics(parent=None)[source]

Bases: ly.dom.LyricMode

name = 'lyrics'
class ly.dom.InputMode(parent=None)[source]

Bases: ly.dom.StatementEnclosed

The abstract base class for input modes such as lyricmode/lyrics, chordmode/chords etc.

class ly.dom.InputNotes(parent=None)[source]

Bases: ly.dom.NoteMode

name = 'notes'
class ly.dom.KeySignature(note=0, alter=0, mode='major', parent=None)[source]

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.

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Layout(parent=None)[source]

Bases: ly.dom.HandleVars, ly.dom.Section

name = 'layout'
class ly.dom.Leaf(parent=None)[source]

Bases: ly.dom.LyNode

A leaf node without children

class ly.dom.Line(text='', parent=None)[source]

Bases: ly.dom.Text

A text node that claims its own line.

after = 1
before = 1
class ly.dom.LineComment(text='', parent=None)[source]

Bases: ly.dom.Comment

A LilyPond comment that takes a full line

before = 1
class ly.dom.LyNode(parent=None)[source]

Bases: ly.node.WeakNode

Base class for LilyPond objects, based on Node, which takes care of the tree structure.

after = 0
before = 0
concat(other)[source]

Returns a string with newlines to concat this node to another one. If zero newlines are requested, an empty string is returned.

isAtom = False
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.LyricMode(parent=None)[source]

Bases: ly.dom.InputMode

name = 'lyricmode'
class ly.dom.Lyrics(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.LyricsTo(cid, parent=None)[source]

Bases: ly.dom.LyricMode

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

name = 'lyricsto'
class ly.dom.Mark(parent=None)[source]

Bases: ly.dom.Statement

The mark command.

name = 'mark'
class ly.dom.Markup(parent=None)[source]

Bases: ly.dom.StatementEnclosed

The markup command. You can add many children, in that case Markup automatically prints { and } around them.

name = 'markup'
class ly.dom.MarkupCommand(name, parent=None)[source]

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.

class ly.dom.MarkupEnclosed(name, parent=None)[source]

Bases: ly.dom.CommandEnclosed

A markup that auto-encloses all its arguments, like ‘italic’, ‘bold’ etc. You must supply the name.

class ly.dom.MensuralStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.MensuralVoice(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Midi(parent=None)[source]

Bases: ly.dom.HandleVars, ly.dom.Section

name = 'midi'
class ly.dom.Named[source]

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.

ly(printer)[source]
name = ''
class ly.dom.Newline(parent=None)[source]

Bases: ly.dom.LyNode

A newline.

after = 1
class ly.dom.NoteMode(parent=None)[source]

Bases: ly.dom.InputMode

name = 'notemode'
class ly.dom.NoteNames(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Paper(parent=None)[source]

Bases: ly.dom.HandleVars, ly.dom.Section

name = 'paper'
class ly.dom.Partial(dur, dots=0, factor=1, parent=None)[source]

Bases: ly.dom.Named, ly.dom.Duration

partial <duration> You should add a Duration element

after = 1
before = 1
name = 'partial'
class ly.dom.PianoStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Pitch(octave=0, note=0, alter=0, parent=None)[source]

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)

ly(printer)[source]

Print the pitch in the preferred language.

class ly.dom.Printer[source]

Bases: object

Performs certain operations on behalf of a LyNode tree, like quoting strings or translating pitch names, etc.

indent(node)[source]

Return a formatted printout of node (and its children)

indentGen(node, startIndent=0)[source]

A generator that walks on the output of the given node, and returns properly indented LilyPond code.

primary_quote_left = '‘'
primary_quote_right = '’'
quoteString(text)[source]
secondary_quote_left = '“'
secondary_quote_right = '”'
class ly.dom.QuotedString(text='', parent=None)[source]

Bases: ly.dom.Text

A string that is output inside double quotes.

isAtom = True
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Reference(name='')[source]

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.

class ly.dom.Relative(parent=None)[source]

Bases: ly.dom.Statement

relative <pitch> music

You should add a Pitch (optionally) and another music object, e.g. Sim or Seq, etc.

name = 'relative'
class ly.dom.RhythmicStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Scheme(text='', parent=None)[source]

Bases: ly.dom.Text

A Scheme expression, without the extra # prepended

isAtom = True
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.SchemeLily(parent=None)[source]

Bases: ly.dom.Enclosed

A LilyPond expression between #{ #} (inside scheme)

post = '#}'
pre = '#{'
class ly.dom.SchemeList(parent=None)[source]

Bases: ly.dom.Enclosed

A list of items enclosed in parentheses

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

post = ')'
pre = '('
class ly.dom.Score(parent=None)[source]

Bases: ly.dom.Section

name = 'score'
class ly.dom.ScoreContext(cid=None, new=True, parent=None)[source]

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.

ctype = 'Score'
class ly.dom.Section(parent=None)[source]

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.

after = 1
before = 1
may_remove_brackets = False
class ly.dom.Seq(parent=None)[source]

Bases: ly.dom.Enclosed

An SequentialMusic expression between { }

post = '}'
pre = '{'
class ly.dom.Seqr(parent=None)[source]

Bases: ly.dom.Seq

may_remove_brackets = True
class ly.dom.Sim(parent=None)[source]

Bases: ly.dom.Enclosed

An SimultaneousMusic expression between << >>

post = '>>'
pre = '<<'
class ly.dom.Simr(parent=None)[source]

Bases: ly.dom.Sim

may_remove_brackets = True
class ly.dom.Staff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.StaffGroup(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Statement(parent=None)[source]

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.

before = 0
isAtom = True
class ly.dom.StatementEnclosed(parent=None)[source]

Bases: ly.dom.Named, ly.dom.Enclosed

Base class for LilyPond commands that have a single bracket-enclosed list of arguments.

may_remove_brackets = True
class ly.dom.TabStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.TabVoice(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Tempo(duration, value, parent=None)[source]

Bases: ly.dom.Container

A tempo setting, like: tempo 4 = 100 May have a child markup or quoted string.

after = 1
before = 1
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Text(text='', parent=None)[source]

Bases: ly.dom.Leaf

A leaf node with arbitrary text

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.TextDur(text='', parent=None)[source]

Bases: ly.dom.AddDuration, ly.dom.Text

A text note with an optional duration as child.

class ly.dom.TimeSignature(num, beat, parent=None)[source]

Bases: ly.dom.Leaf

A time signature, like: time 4/4

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Transposition(parent=None)[source]

Bases: ly.dom.Statement

transposition <pitch> You should add a Pitch.

name = 'transposition'
class ly.dom.UserContext(ctype, cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

Represents a context the user creates. e.g. new MyStaff = cid << music >>

class ly.dom.VaticanaStaff(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.VaticanaVoice(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.Version(text='', parent=None)[source]

Bases: ly.dom.Line

a LilyPond version instruction

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.Voice(cid=None, new=True, parent=None)[source]

Bases: ly.dom.ContextType

class ly.dom.VoiceSeparator(parent=None)[source]

Bases: ly.dom.Leaf

A Voice Separator: \

ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

class ly.dom.With(parent=None)[source]

Bases: ly.dom.HandleVars, ly.dom.Section

If this item has no children, it prints nothing.

after = 0
before = 0
ly(printer)[source]

Returns printable output for this object. Can ask printer for certain settings, e.g. pitch language etc.

name = 'with'

ly.duration module

LilyPond information and logic concerning durations

ly.duration.base_scaling(tokens)[source]

Return (base, scaling) as two Fractions for the list of tokens.

ly.duration.base_scaling_string(duration)[source]

Return (base, scaling) as two Fractions for the specified string.

ly.duration.format_fraction(value)[source]

Format the value as “5/1” etc.

ly.duration.fraction(tokens)[source]

Return the duration of the Duration tokens as a Fraction.

ly.duration.fraction_string(duration)[source]

Return the duration of the specified string as a Fraction.

ly.duration.tostring(dur, dots=0, factor=1)[source]

Returns the LilyPond string representation of a given logarithmic duration.

Supports values from -3 up to and including 11. -2 = ‘longa’, 0 = ‘1’ (whole note), etc.

Adds the number of dots (defaults to 0) and the fraction factor if given.

ly.etreeutil module

Utility functions for use with xml.etree.ElementTree.

ly.etreeutil.indent(elem, indent_string='  ', level=0)[source]

Indent the XML in element.

Text content that is already non-whitespace is not changed.

ly.etreeutil.isblank(s)[source]

Return True if s is empty or whitespace only.

ly.indent module

Indent and auto-indent.

class ly.indent.Indenter[source]

Bases: object

compute_indent(document, block)[source]

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.

decrease_indent(cursor)[source]

Manually remove one level of indent from all lines of cursor.

get_indent(document, block)[source]

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.

increase_indent(cursor)[source]

Manually add indent to all lines of cursor.

indent(cursor, indent_blank_lines=False)[source]

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.

indent_tabs = False
indent_width = 2
class ly.indent.Line(document, block)[source]

Bases: object

Brings together all relevant information about a line (block).

is_special_scheme_keyword(token)[source]

Return True if token is a special Scheme word like “define”, etc.

The tokens in the list below and those that start with “def”, like “define”, do not follow the standard Scheme indentation patterns.

The list below and the “def” rule are from GNU Emacs source code, which sets the standard for GNU Guile Scheme indentation. See: emacs/lisp/progmodes/scheme.el See also: http://community.schemewiki.org/?scheme-style

ly.node module

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.

class ly.node.Node(parent=None)[source]

Bases: object

A list-like class to build tree structures with.

ancestors()[source]

Climb the tree up over the parents.

append(node)[source]

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.

backward()[source]

Iterate (backwards) over the preceding siblings.

clear()[source]

Remove all children.

copy()[source]

Return a deep copy of the node and its children

descendants(depth=- 1)[source]

Yield all the descendants, in tree order. Same as iter_depth().

dump()[source]

Return a string representation of the tree.

extend(iterable)[source]

Append every Node from iterable.

find(cls, depth=- 1)[source]

Yield all descendants if they are an instance of cls.

cls may also be a tuple of classes. This method uses iter_depth().

find_child(cls, depth=- 1)[source]

Return the first descendant that’s an instance of cls.

cls may also be a tuple of classes. This method uses iter_rings().

find_children(cls, depth=- 1)[source]

Yield all descendants if they are an instance of cls.

cls may also be a tuple of classes. This method uses iter_rings().

find_parent(cls)[source]

Find an ancestor that’s an instance of the given class.

cls may also be a tuple of classes.

forward()[source]

Iterate over the following siblings.

index(node)[source]

Return the index of the given child node.

insert(index, node)[source]

Insert a node at the specified index.

insert_before(other, node)[source]

Insert a node before the other node.

is_descendant_of(parent)[source]

Return True if self is a descendant of parent, else False.

iter_depth(depth=- 1)[source]

Iterate over all the children, and their children, etc.

Set depth to restrict the search to a certain depth, -1 is unrestricted.

iter_rings(depth=- 1)[source]

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.

next_sibling()[source]

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.

parent()[source]

The parent, or None if the node has no parent.

previous_sibling()[source]

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.

remove(node)[source]

Remove the given child node.

replace(old, new)[source]

Replace a child node with another node.

sort(key=None, reverse=False)[source]

Sorts the children, optionally using the key function.

Using a key function is recommended, or you must add comparison methods to your Node subclass.

toplevel()[source]

Return the toplevel parent Node of this node.

Remove all children and unlink() them as well.

class ly.node.WeakNode(parent=None)[source]

Bases: ly.node.Node

A Node type using a weak reference to the parent.

parent()[source]

The parent, or None if the node has no parent.

ly.pkginfo module

Meta-information about the LY package.

This information is used by the install script, and also for the command ly --version.

ly.pkginfo.name = 'python-ly'

name of the package

ly.pkginfo.version = '0.9.7'

the current version

ly.pkginfo.description = 'Tool and library for manipulating LilyPond files'

short description

ly.pkginfo.long_description = 'The python-ly package provides a Python library and a commandline tool that can be used to parse and manipulate LilyPond source files.'

long description

ly.pkginfo.maintainer = 'Wilbert Berendsen'

maintainer name

ly.pkginfo.maintainer_email = 'info@frescobaldi.org'

maintainer email

ly.pkginfo.url = 'https://github.com/wbsoft/python-ly'

homepage

ly.pkginfo.license = 'GPL'

license

ly.reformat module

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.

ly.reformat.break_indenters(cursor)[source]

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.

ly.reformat.move_long_comments(cursor)[source]

Move line comments with more than 2 comment characters to column 0.

ly.reformat.reformat(cursor, indenter)[source]

A do-it-all function improving the LilyPond source formatting.

ly.reformat.remove_trailing_whitespace(cursor)[source]

Removes whitespace from all lines in the cursor’s range.

ly.rhythm module

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.

class ly.rhythm.music_item(tokens, dur_tokens, may_remove, insert_pos, pos, end)

Bases: tuple

dur_tokens

Alias for field number 1

end

Alias for field number 5

insert_pos

Alias for field number 3

may_remove

Alias for field number 2

pos

Alias for field number 4

tokens

Alias for field number 0

ly.rhythm.music_items(cursor, command=False, chord=False, partial=1)[source]

Yield music_item instances describing rests, skips or pitches.

cursor is a ly.document.Cursor instance.

The following keyword arguments can be used:

  • command: whether to allow pitches in \relative, \transpose, etc.

  • chord: whether to allow pitches inside chords.

  • partial: ly.document.INSIDE (default), PARTIAL or OUTSIDE. See the documentation of ly.document.Source.__init__().

ly.rhythm.music_tokens(source, command=False, chord=False)[source]

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:

  • command: whether to allow pitches in \relative, \transpose, etc.

  • chord: whether to allow pitches inside chords.

This function is deprecated and will be removed. You should use music_items() instead.

ly.rhythm.preceding_duration(cursor)[source]

Return a preceding duration before the cursor, or an empty list.

ly.rhythm.remove_dups(iterable)[source]

Change reoccurring strings to ‘’ in iterable.

ly.rhythm.rhythm_dot(cursor)[source]

Add a dot to all durations.

ly.rhythm.rhythm_double(cursor)[source]

Doubles all duration values.

ly.rhythm.rhythm_explicit(cursor)[source]

Make all durations explicit.

ly.rhythm.rhythm_extract(cursor)[source]

Return a list of the durations from the cursor’s range.

ly.rhythm.rhythm_halve(cursor)[source]

Halves all duration values.

ly.rhythm.rhythm_implicit(cursor)[source]

Remove reoccurring durations.

ly.rhythm.rhythm_implicit_per_line(cursor)[source]

Remove reoccurring durations, but always write one on a new line.

ly.rhythm.rhythm_overwrite(cursor, durations)[source]

Apply a list of durations to the cursor’s range.

The durations list looks like [“4”, “8”, “”, “16.”,] etc.

ly.rhythm.rhythm_remove(cursor)[source]

Remove all durations.

ly.rhythm.rhythm_remove_fraction_scaling(cursor)[source]

Remove the scaling containing fractions (like *1/3) from all durations.

ly.rhythm.rhythm_remove_scaling(cursor)[source]

Remove the scaling (like *3, *1/3) from all durations.

ly.rhythm.rhythm_undot(cursor)[source]

Remove one dot from all durations.

ly.util module

Utility functions.

ly.util.int2letter(number, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ')[source]

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.

ly.util.int2roman(n)[source]

Convert an integer value to a roman number string.

E.g. 1 -> “I”, 12 -> “XII”, 2015 -> “MMXV”

n has to be > 1.

ly.util.int2text(number)[source]

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).

ly.util.mkid(*args)[source]

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"

ly.words module

LilyPond reserved words for auto completion and highlighting.