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().
- class ly.slexer.Fridge(stateClass=<class 'ly.slexer.State'>)[source]¶
Bases:
object
Stores frozen States under an integer 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.
- items = ()¶
- re_flags = 0¶
- 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.
- leave()[source]¶
Leave the current parser and pop back to the previous.
The first parser (specified on instantiation) will never be left.
- 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.
- 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¶
- 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.
- classmethod load(filename, encoding='utf-8', mode=None)[source]¶
Load the document from a file, using the specified encoding and mode.
- modified = False¶
- 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
- 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.)
- encoding = None¶
- filename = None¶
- 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.
- 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.
- property document¶
Return our Document.
- 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.
- 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.
- 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.)
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.
- 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.
- 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.
- has_output()[source]¶
Return True when the document probably generates output.
I.e. has notes, rests, markup or other output-generating commands.
- 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.
ly.barcheck module¶
Add, check or remove bar checks in 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¶
- inline_style = False¶
- linenumbers_bgcolor = '#eeeeee'¶
- linenumbers_fgcolor = None¶
- linenumbers_id = 'linenumbers'¶
- number_lines = False¶
- 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_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_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.cursortools module¶
Routines manipulating ly.document.Cursor instances.
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.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¶
- 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
- 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.
- 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.
- 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¶
- 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 = ' '¶
- 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.
- 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’.
- 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¶
- isAtom = True¶
- 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).
- 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
- 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¶
- class ly.dom.Include(text='', parent=None)[source]¶
Bases:
ly.dom.Line
a LilyPond include statement
- 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.
- 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¶
- 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.
- 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)
- class ly.dom.Printer[source]¶
Bases:
object
Performs certain operations on behalf of a LyNode tree, like quoting strings or translating pitch names, etc.
- 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 = '’'¶
- 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¶
- 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¶
- 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¶
- class ly.dom.Text(text='', parent=None)[source]¶
Bases:
ly.dom.Leaf
A leaf node with arbitrary text
- 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
- 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
- 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: \
- 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.etreeutil module¶
Utility functions for use with xml.etree.ElementTree.
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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- class ly.node.WeakNode(parent=None)[source]¶
Bases:
ly.node.Node
A Node type using a weak reference to the 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.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.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_fraction_scaling(cursor)[source]¶
Remove the scaling containing fractions (like
*1/3
) 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.