The dom.util module

Some utility functions.


Return a key to determine the importance of the whitespace.

This is used by e.g. the collapse_whitespace() function. A two-tuple is returned: (newlines, spaces), where the first value is the number of newlines in the text, and the second value the number of spaces.


Return the “most important” whitespace of the specified strings.

This is used to combine whitespace requirements. For example, newlines are preferred over single spaces, and a single space is preferred over an empty string. For example:

>>> collapse_whitespace(['\n', ' '])
>>> collapse_whitespace([' ', ''])
' '

Concatenate text fragments collapsing whitespace before and after the fragments.

fragments is an iterable of (before, text, after) tuples, where before and after are whitespace. If a text is empty, the whitespace before and after are collapsed into the other surrounding whitespace. Returns a tree-tuple (before, text, after) containing the first before value, the combined text, and the last after value.

add_newlines(node, text, block_separator='\n', max_blank_lines=10)[source]

Set whitespace properties of the node and all its descendents according to the original text.

Only nodes with an origin are affected. When a node appears on a new line, the space_before property is set; when the tail part of a node appears on a new line, the space_before_tail property is set.

It is possible to set the block_separator (by default a single newline); and the maximum amount of consecutive blank lines, using max_blank_lines.

This can be useful before re-indenting or reformatting a document completely, to retain some aspects of the original formatting.

replace_unknown(tree, text)[source]

Replace all Unknown nodes with Text nodes containing the respective text.

The text should be the text the DOM tree was generated from. Do this before writing out a node using write() or write_indented() or related methods.


Yield child nodes of the DOM node, skipping inheritants of base.Comment.


Pop and return comments off the end of node (and/or its children).


Return the LilyPond version in the node’s document as a tuple of ints.

Returns the empty tuple if the version is not set.