extensions Package

extensions Package

asciidoc Module

asciidoc - converts an AsciiDoc text file to HTML or DocBook

Copyright (C) 2002-2010 Stuart Rackham. Free use of this software is granted under the terms of the GNU General Public License (GPL).

class leo.extensions.asciidoc.AbstractBlock[source]
blocknames = []

Write block definition to stdout.

error(msg, cursor=None, halt=False)[source]
get_param(name, params=None)[source]

Return named processing parameter from params dictionary. If the parameter is not in params look in self.parameters.


Return (presubs,postsubs) tuple.


Return True if param matches an allowed configuration file entry name.


Check if this block is next in document reader.

load(defname, entries)[source]

Update block definition from section ‘entries’ dictionary.

merge_attributes(attrs, params=[])[source]

Use the current block’s attribute list (attrs dictionary) to build a dictionary of block processing parameters (self.parameters) and tag substitution attributes (self.attributes).

1. Copy the default parameters (self.*) to self.parameters. self.parameters are used internally to render the current block. Optional params array of additional parameters.

2. Copy attrs to self.attributes. self.attributes are used for template and tag substitution in the current block.

3. If a style attribute was specified update self.parameters with the corresponding style parameters; if there are any style parameters remaining add them to self.attributes (existing attribute list entries take precedence).

4. Set named positional attributes in self.attributes if self.posattrs was specified.

5. Finally self.parameters is updated with any corresponding parameters specified in attrs.


On block exits restore previous (parent) ‘blockname’ attribute or undefine it if we’re no longer inside a block.


On block entry set the ‘blockname’ attribute. Only applies to delimited blocks, lists and tables.


Return the text following the first dash in the section name.


Translate block from document reader.

update_parameters(src, dst=None, all=False)[source]

Parse processing parameters from src dictionary to dst object. dst defaults to self.parameters. If all is True then copy src entries that aren’t parameter names.


Validate block after the complete configuration has been loaded.

class leo.extensions.asciidoc.AbstractBlocks[source]

List of block definitions.


Load block definition from ‘sections’ dictionary.


Validate the block definitions.

class leo.extensions.asciidoc.AttrDict[source]

Bases: dict

Like a dictionary except values can be accessed as attributes i.e. obj.foo can be used in addition to obj[‘foo’]. If an item is not present None is returned.

class leo.extensions.asciidoc.AttributeEntry[source]

Static methods and attributes only.

attributes = {}
static isnext()[source]
name = None
name2 = None
pattern = None
subs = None
static translate()[source]
value = None
class leo.extensions.asciidoc.AttributeList[source]

Static methods and attributes only.

attrs = {}
static consume(d={})[source]

Add attribute list to the dictionary ‘d’ and reset the list.

static initialize()[source]
static isnext()[source]
match = None
pattern = None
static style()[source]
static subs(attrs)[source]

Substitute single quoted attribute values normally.

static translate()[source]
class leo.extensions.asciidoc.BlockTitle[source]

Static methods and attributes only.

static consume(d={})[source]

If there is a title add it to dictionary ‘d’ then reset title.

static isnext()[source]
pattern = None
title = None
static translate()[source]
class leo.extensions.asciidoc.CalloutMap[source]
static calloutid(listnumber, calloutindex)[source]
class leo.extensions.asciidoc.Cell(data, span_spec=None, align_spec=None, style=None)[source]

Return a clone of self to reserve vertically spanned cell.

class leo.extensions.asciidoc.Column(width=None, align_spec=None, style=None)[source]

Table column.

class leo.extensions.asciidoc.Column_OLD[source]

Table column.

class leo.extensions.asciidoc.Config[source]

Methods to process configuration files.

ENTRIES_SECTIONS = ('tags', 'miscellaneous', 'attributes', 'specialcharacters', 'specialwords', 'macros', 'replacements', 'quotes', 'titles', 'paradef-.+', 'listdef-.+', 'blockdef-.+', 'tabledef-.+', 'tabletags-.+', 'listtags-.+', 'replacements[23]', 'old_tabledef-.+')

Dump configuration to stdout.


Return True if conf file section contains entries, not a markup template.


Expand any template::[] macros in a list of section entries.


Return path of configuration directory. Try all the well known locations. Return None if directory not found.

find_in_dirs(filename, dirs=None)[source]

Find conf files from dirs list. Return list of found file paths. Return empty list if not found in any of the locations.


Return list of well known paths with conf files.


Check Python version and locate the executable and configuration files directory. cmd is the asciidoc command or asciidoc.py path.


Load the backend configuration files from dirs list. If dirs not specified try all the well known locations. If a <backend>.conf file was found return it’s full path name, if not found return None.

load_file(fname, dir=None, include=[], exclude=[])[source]

Loads sections dictionary with sections from file fname. Existing sections are overlaid. The ‘include’ list contains the section names to be loaded. The ‘exclude’ list contains section names not to be loaded. Return False if no file was found in any of the locations.


Load filter configuration files from ‘filters’ directory in dirs list. If dirs not specified try all the well known locations. Suppress loading if a file named __noautoload__ is in same directory as the conf file unless the filter has been specified with the –filter command-line option (in which case it is loaded unconditionally).

load_from_dirs(filename, dirs=None, include=[])[source]

Load conf file from dirs list. If dirs not specified try all the well known locations. Return False if no file was sucessfully loaded.


Set miscellaneous configuration entries from dictionary ‘d’.

load_sections(sections, attrs=None)[source]

Loads sections dictionary. Each dictionary entry contains a list of lines. Updates ‘attrs’ with parsed [attributes] section entries.


Parse replacements section into self.replacements dictionary.


Parse specialsections section to self.specialsections dictionary.


Parse special words section into self.specialwords dictionary.


Parse [tags] section entries into self.tags dictionary.

section2tags(section, d={}, skipstart=False, skipend=False)[source]

Perform attribute substitution on ‘section’ using document attributes plus ‘d’ attributes. Return tuple (stag,etag) containing pre and post | placeholder tags. ‘skipstart’ and ‘skipend’ are used to suppress substitution.

static set_replacement(pat, rep, replacements)[source]

Add pattern and replacement to replacements dictionary.

subs_replacements(s, sect='replacements')[source]

Substitute patterns from self.replacements in ‘s’.

subs_section(section, d)[source]

Section attribute substitution using attributes from document.attributes and ‘d’. Lines containing undefinded attributes are deleted.


Perform special character substitution on string ‘s’.


Perform reverse special character substitution on string ‘s’.


Search for word patterns from self.specialwords in ‘s’ and substitute using corresponding macro.

tag(name, d=None)[source]

Returns (starttag,endtag) tuple named name from configuration file [tags] section. Raise error if not found. If a dictionary ‘d’ is passed then merge with document attributes and perform attribute substitution on tags.


Check the configuration for internal consistancy. Called after all configuration files have been loaded.

class leo.extensions.asciidoc.DelimitedBlock[source]

Bases: leo.extensions.asciidoc.AbstractBlock

load(name, entries)[source]
class leo.extensions.asciidoc.DelimitedBlocks[source]

Bases: leo.extensions.asciidoc.AbstractBlocks

List of delimited blocks.


alias of DelimitedBlock

PREFIX = 'blockdef-'

Update blocks defined in ‘sections’ dictionary.

class leo.extensions.asciidoc.Document[source]

Bases: object

consume_attributes_and_comments(comments_only=False, noblanks=False)[source]

Returns True if one or more attributes or comments were consumed. If ‘noblanks’ is True then consumation halts if a blank line is encountered.


Load language configuration file.


Return False if the author is malformed.

parse_header(doctype, backend)[source]

Parses header, sets corresponding document attributes and finalizes document doctype and backend properties. Returns False if the document does not have a header. ‘doctype’ and ‘backend’ are the doctype and backend option values passed on the command-line, None if no command-line option was not specified.


Calculate any missing author related attributes.

set_deprecated_attribute(old, new)[source]

Ensures the ‘old’ name of an attribute that was renamed to ‘new’ is still honored.


Set implicit attributes and attributes in ‘attrs’.

exception leo.extensions.asciidoc.EAsciiDoc[source]

Bases: exceptions.Exception

class leo.extensions.asciidoc.FloatingTitle[source]

Bases: leo.extensions.asciidoc.Title

Floated titles are translated differently.

static isnext()[source]
static translate()[source]
class leo.extensions.asciidoc.Header[source]

Static methods and attributes only.

RCS_ID_RE = '^\\$Id: \\S+ (?P<revnumber>\\S+) (?P<revdate>\\S+) \\S+ (?P<author>\\S+) (\\S+ )?\\$$'
REV_LINE_RE = '^(\\D*(?P<revnumber>.*?),)?(?P<revdate>.*?)(:\\s*(?P<revremark>.*))?$'
static parse()[source]
class leo.extensions.asciidoc.InsensitiveDict[source]

Bases: dict

Like a dictionary except key access is case insensitive. Keys are stored in lower case.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.[source]
has_key(k) → True if D has a key k, else False[source]
setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D[source]
update([E, ]**F) → None. Update D from dict/iterable E and F.[source]

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

class leo.extensions.asciidoc.Lex[source]

Lexical analysis routines. Static methods and attributes only.

static canonical_subs(options)[source]

Translate composite subs values.

static next()[source]

Returns class of next element on the input (None if EOF). The reader is assumed to be at the first line following a previous element, end of file or line one. Exits with the reader pointing to the first line of the next element or EOF (leading blank lines are skipped).

prev_cursor = None
prev_element = None
static set_margin(lines, margin=0)[source]

Utility routine that sets the left margin to ‘margin’ space in a block of non-blank lines.

static subs(lines, options)[source]

Perform inline processing specified by ‘options’ (in ‘options’ order) on sequence of ‘lines’.

static subs_1(s, options)[source]

Perform substitution specified in ‘options’ (in ‘options’ order).

class leo.extensions.asciidoc.List[source]

Bases: leo.extensions.asciidoc.AbstractBlock

NUMBER_STYLES = ('arabic', 'loweralpha', 'upperalpha', 'lowerroman', 'upperroman')
static calc_index(index, style)[source]

Return the ordinal number of (1…) of the list item index for the given list style.

static calc_style(index)[source]

Return the numbered list style (‘arabic’…) of the list item index. Return None if unrecognized style.


Check calculated self.ordinal (1,2,…) against the item number in the document (self.index) and check the number style is the same as the first item (self.number_style).


Check that all necessary tags are present.

load(name, entries)[source]
class leo.extensions.asciidoc.Lists[source]

Bases: leo.extensions.asciidoc.AbstractBlocks

List of List objects.


alias of List

PREFIX = 'listdef-'
TAGS = ('list', 'entry', 'item', 'text', 'label', 'term')
TYPES = ('bulleted', 'numbered', 'labeled', 'callout')

Load listtags-* conf file sections to self.tags.

class leo.extensions.asciidoc.Macro[source]

Return macro markup template section name based on macro name and prefix. Return None section not found.

subs_passthroughs(text, passthroughs)[source]

Replace macro attribute lists in text with placeholders. Substitute and append the passthrough attribute lists to the passthroughs list.


Block macro translation.

class leo.extensions.asciidoc.Macros[source]
SYS_RE = '(?u)^(?P<name>[\\\\]?\\w(\\w|-)*?)::(?P<target>\\S*?)(\\[(?P<attrlist>.*?)\\])$'
extract_passthroughs(text, prefix='')[source]

Extract the passthrough text and replace with temporary placeholders.


Return matching macro if block macro is next on reader.

match(prefix, name, text)[source]

Return re match object matching ‘text’ with macro type ‘prefix’, macro name ‘name’.


Replace passthough placeholders with the original passthrough text.

subs(text, prefix='', callouts=False)[source]
class leo.extensions.asciidoc.Message[source]

Message functions.

PROG = 'asciidoc'
deprecated(msg, linenos=True)[source]
error(msg, cursor=None, halt=False)[source]

Report fatal error. If halt=True raise EAsciiDoc exception. If halt=False don’t exit application, continue in the hope of reporting all fatal errors finishing with a non-zero exit code.

format(msg, prefix='', linenos=True, cursor=None, offset=0)[source]

Return formatted message string.

verbose(msg, linenos=True)[source]
warning(msg, linenos=True, offset=0)[source]
class leo.extensions.asciidoc.OrderedDict(d=None, **kwargs)[source]

Bases: dict

Dictionary ordered by insertion order. Python Cookbook: Ordered Dictionary, Submitter: David Benjamin. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747

clear() → None. Remove all items from D.[source]
copy() → a shallow copy of D[source]
items() → list of D's (key, value) pairs, as 2-tuples[source]
keys() → list of D's keys[source]
popitem() → (k, v), remove and return some (key, value) pair as a[source]

2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D[source]
update([E, ]**F) → None. Update D from dict/iterable E and F.[source]

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() → list of D's values[source]
class leo.extensions.asciidoc.Paragraph[source]

Bases: leo.extensions.asciidoc.AbstractBlock

load(name, entries)[source]
class leo.extensions.asciidoc.Paragraphs[source]

Bases: leo.extensions.asciidoc.AbstractBlocks

List of paragraph definitions.


alias of Paragraph

PREFIX = 'paradef-'
class leo.extensions.asciidoc.Plugin[source]

–filter and –theme option commands.

CMDS = ('install', 'remove', 'list', 'build')
static build(args)[source]

Create plugin Zip file. args[0] is Zip file name. args[1] is plugin directory.

static get_dir()[source]

Return plugins path (.asciidoc/filters or .asciidoc/themes) in user’s home direcory or None if user home not defined.

static install(args)[source]

Install plugin Zip file. args[0] is plugin zip file path. args[1] is optional destination plugins directory.

static list(args)[source]

List all plugin directories (global and local).

static remove(args)[source]

Delete plugin directory. args[0] is plugin name. args[1] is optional plugin directory (defaults to ~/.asciidoc/<plugin_name>).

type = None
class leo.extensions.asciidoc.Reader[source]

Bases: leo.extensions.asciidoc.Reader1

Wraps (well, sought of) Reader1 class and implements conditional text inclusion.


Same as read_lines() but does not advance the file pointer.


Return tuple containing count lines.

read_until(terminators, same_file=False)[source]

Like read() but reads lines up to (but not including) the first line that matches the terminator regular expression, regular expression object or list of regular expression objects. If same_file is True then the terminating pattern must occur in the file the was being read when the routine was called.

class leo.extensions.asciidoc.Reader1[source]

Line oriented AsciiDoc input file reader. Processes include and conditional inclusion system macros. Tabs are expanded and lines are right trimmed.


Used by class methods to close nested include files.


Returns True if all lines have been read.


Read next line. Return None if EOF. Expand tabs. Strip trailing white space. Maintain self.next read ahead buffer. If skip=True then conditional exclusion is active (ifdef and ifndef macros).


Like read() but does not advance file pointer.


Push the line (filename,linenumber,linetext) tuple back into the read buffer. Note that it’s up to the caller to restore the previous cursor.

class leo.extensions.asciidoc.Section[source]

Static methods and attributes only.

endtags = []
static gen_id(title)[source]

The normalized value of the id attribute is an NCName according to the ‘Namespaces in XML’ Recommendation: NCName ::= NCNameStartChar NCNameChar* NCNameChar ::= NameChar - ‘:’ NCNameStartChar ::= Letter | ‘_’ NameChar ::= Letter | Digit | ‘.’ | ‘-‘ | ‘_’ | ‘:’

ids = []
static savetag(level, etag)[source]

Save section end.

static set_id()[source]
static setlevel(level)[source]

Set document level and write open section close tags up to level.

static translate()[source]
static translate_body(terminator=<class leo.extensions.asciidoc.Title>)[source]
class leo.extensions.asciidoc.Table[source]

Bases: leo.extensions.asciidoc.AbstractBlock

ALIGN = {'<': 'left', '>': 'right', '^': 'center'}
FORMATS = ('psv', 'csv', 'dsv')
SEPARATORS = {'csv': ',', 'dsv': ':|\\n', 'psv': '((?<!\\S)((?P<span>[\\d.]+)(?P<op>[*+]))?(?P<align>[<\\^>.]{,3})?(?P<style>[a-z])?)?\\|'}
VALIGN = {'<': 'top', '>': 'bottom', '^': 'middle'}

Generate column related substitution attributes.


Return the style dictionary whose name starts with ‘prefix’.

load(name, entries)[source]
static parse_align_spec(align_spec)[source]

Parse AsciiDoc cell alignment specifier and return 2-tuple with horizonatal and vertical alignment names. Unspecified alignments set to None.

parse_cols(cols, halign, valign)[source]

Build list of column objects from table ‘cols’, ‘halign’ and ‘valign’ attributes.


Parse the table source text and return a list of rows, each row is a list of Cells.


Parse list of PSV or DSV table source text lines and return a list of Cells.


Parse the table source text into self.rows (a list of rows, each row is a list of Cells.

static parse_span_spec(span_spec)[source]

Parse AsciiDoc cell span specifier and return 2-tuple with horizonatal and vertical span counts. Set default values (1,1) if not specified.

subs_row(row, rowtype)[source]

Substitute the list of Cells using the data tag. Returns a list of marked up table cell elements.

subs_rows(rows, rowtype='body')[source]

Return a string of output markup from a list of rows, each row is a list of raw data text.


Validate and parse table attributes.

class leo.extensions.asciidoc.Table_OLD[source]

Bases: leo.extensions.asciidoc.AbstractBlock

ALIGNMENTS = {"'": 'right', '.': 'center', '`': 'left'}
COL_STOP = "(`|'|\\.)"
FORMATS = ('fixed', 'csv', 'dsv')

Generate colwidths and colspecs. This can only be done after the table arguments have been parsed since we use the table format.

load(name, entries)[source]

Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.


Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.


Parse the list of source table rows. Each row item in the returned list contains a list of cell data elements.

parse_rows(rows, rtag, dtag)[source]

Parse rows list using the row and data tags. Returns a substituted list of output lines.


Parse ruler calculating underline and ruler column widths.


Return a two item tuple containing a list of lines up to but not including the next underline (continued lines are joined ) and the tuple of all lines after the underline.

subs_row(data, dtag)[source]

Substitute the list of source row data elements using the data tag. Returns a substituted list of output table data items.

class leo.extensions.asciidoc.Tables[source]

Bases: leo.extensions.asciidoc.AbstractBlocks

List of tables.


alias of Table

PREFIX = 'tabledef-'
TAGS = ('colspec', 'headrow', 'footrow', 'bodyrow', 'headdata', 'footdata', 'bodydata', 'paragraph')

Load tabletags-* conf file sections to self.tags.

class leo.extensions.asciidoc.Tables_OLD[source]

Bases: leo.extensions.asciidoc.AbstractBlocks

List of tables.


alias of Table_OLD

PREFIX = 'old_tabledef-'
class leo.extensions.asciidoc.Title[source]

Processes Header and Section titles. Static methods and attributes only.

attributes = {}
static dosubs(title)[source]

Perform title substitutions.

static dump()[source]
dump_dict = {}
static getnumber(level)[source]

Return next section number at section ‘level’ formatted like

static isnext()[source]
level = 0
linecount = None
static load(entries)[source]

Load and validate [titles] section entries dictionary.

static parse(lines)[source]

Parse title at start of lines tuple.

pattern = None
section_numbers = [0, 0, 0, 0, 0]
sectname = None
static setsectname()[source]

Set Title section name: If the first positional or ‘template’ attribute is set use it, next search for section title in [specialsections], if not found use default ‘sect<level>’ name.

subs = ()
static translate(skipsubs=False)[source]

Parse the Title.attributes and Title.level from the reader. The real work has already been done by parse().

underlines = ('==', '--', '~~', '^^', '++')
class leo.extensions.asciidoc.Trace[source]

Bases: object

Used in conjunction with the ‘trace’ attribute to generate diagnostic output. There is a single global instance of this class named trace.

SUBS_NAMES = ('specialcharacters', 'quotes', 'specialwords', 'replacements', 'attributes', 'macros', 'callouts', 'replacements2', 'replacements3')
class leo.extensions.asciidoc.Writer[source]

Writes lines to output file.

open(fname, bom=None)[source]

bom is optional byte order mark. http://en.wikipedia.org/wiki/Byte-order_mark

write(*args, **kwargs)[source]

Iterates arguments, writes tuple and list arguments one line per element, else writes argument as single line. If no arguments writes blank line. If argument is None nothing is written. self.newline is appended to each line.

write_tag(tag, content, subs=None, d=None, **kwargs)[source]

Write content enveloped by tag. Substitutions specified in the ‘subs’ list are perform on the ‘content’.

leo.extensions.asciidoc.asciidoc(backend, doctype, confiles, infile, outfile, options)[source]

Convert AsciiDoc document to DocBook document of type doctype The AsciiDoc document is read from file object src the translated DocBook file written to file object dst.

leo.extensions.asciidoc.assign(dst, src)[source]

Assign all attributes from ‘src’ object to ‘dst’ object.

leo.extensions.asciidoc.create_zip(zip_file, src, skip_hidden=False)[source]

Create Zip file. If src is a directory archive all contained files and subdirectories, if src is a file archive the src file. Files and directories names starting with . are skipped if skip_hidden is True. Throws exception if error occurs.


Convert seconds since the Epoch to formatted local date string.

leo.extensions.asciidoc.dovetail(lines1, lines2)[source]

Append list or tuple of strings ‘lines2’ to list ‘lines1’. Join the last non-blank item in ‘lines1’ with the first non-blank item in ‘lines2’ into a single string.

leo.extensions.asciidoc.dovetail_tags(stag, content, etag)[source]

Merge the end tag with the first content line and the last content line with the end tag. This ensures verbatim elements don’t include extraneous opening and closing line breaks.

leo.extensions.asciidoc.dump_section(name, dict, f=<open file '<stdout>', mode 'w'>)[source]

Write parameters in ‘dict’ as in configuration file section format with section ‘name’.

leo.extensions.asciidoc.east_asian_widths = {'A': 1, 'F': 2, 'H': 1, 'N': 1, 'Na': 1, 'W': 2}

Mapping of result codes from unicodedata.east_asian_width() to character column widths.

leo.extensions.asciidoc.execute(cmd, opts, args)[source]

Execute asciidoc with command-line options and arguments. cmd is asciidoc command or asciidoc.py path. opts and args conform to values returned by getopt.getopt(). Raises SystemExit if an error occurs.


  1. Check execution:

    >>> import StringIO
    >>> infile = StringIO.StringIO('Hello *{author}*')
    >>> outfile = StringIO.StringIO()
    >>> opts = []
    >>> opts.append(('--backend','html4'))
    >>> opts.append(('--no-header-footer',None))
    >>> opts.append(('--attribute','author=Joe Bloggs'))
    >>> opts.append(('--out-file',outfile))
    >>> execute(__file__, opts, [infile])
    >>> print outfile.getvalue()
    <p>Hello <strong>Joe Bloggs</strong></p>
leo.extensions.asciidoc.extract_zip(zip_file, destdir)[source]

Unzip Zip file to destination directory. Throws exception if error occurs.

leo.extensions.asciidoc.file_in(fname, directory)[source]

Return True if file fname resides inside directory.

leo.extensions.asciidoc.filter_lines(filter_cmd, lines, attrs={})[source]

Run ‘lines’ through the ‘filter_cmd’ shell command and return the result. The ‘attrs’ dictionary contains additional filter attributes.


Return True if object is list or tuple type.

leo.extensions.asciidoc.is_attr_defined(attrs, dic)[source]

Check if the sequence of attributes is defined in dictionary ‘dic’. Valid ‘attrs’ sequence syntax: <attr> Return True if single attrbiute is defined. <attr1>,<attr2>,… Return True if one or more attributes are defined. <attr1>+<attr2>+… Return True if all the attributes are defined.


Return True if s is valid attribute, macro or tag name (starts with alpha containing alphanumeric and dashes only).


Return True if s is a valid regular expression else return False.

leo.extensions.asciidoc.is_safe_file(fname, directory=None)[source]

Return a list in which lines terminated with the backslash line continuation character are joined.


Return True if we are not executing the system wide version i.e. the configuration is in the executable’s directory.


Return list with empty items from start of list removed.

leo.extensions.asciidoc.parse_attributes(attrs, dict)[source]

Update a dictionary with name/value attributes from the attrs string. The attrs string is a comma separated list of values and keyword name=value pairs. Values must preceed keywords and are named ‘1’,‘2’… The entire attributes list is named ‘0’. If keywords are specified string values must be quoted. Examples:

attrs: ‘’ dict: {}

attrs: ‘hello,world’ dict: {‘2’: ‘world’, ‘0’: ‘hello,world’, ‘1’: ‘hello’}

attrs: ‘“hello”, planet=”earth”’ dict: {‘planet’: ‘earth’, ‘0’: ‘“hello”,planet=”earth”’, ‘1’: ‘hello’}

leo.extensions.asciidoc.parse_entries(entries, dict, unquote=False, unique_values=False, allow_name_only=False, escape_delimiter=True)[source]

Parse name=value entries from from lines of text in ‘entries’ into dictionary ‘dict’. Blank lines are skipped.

leo.extensions.asciidoc.parse_entry(entry, dict=None, unquote=False, unique_values=False, allow_name_only=False, escape_delimiter=True)[source]

Parse name=value entry to dictionary ‘dict’. Return tuple (name,value) or None if illegal entry. If name= then value is set to ‘’. If name and allow_name_only=True then value is set to ‘’. If name! and allow_name_only=True then value is set to None. Leading and trailing white space is striped from ‘name’ and ‘value’. ‘name’ can contain any printable characters. If the ‘=’ delimiter character is allowed in the ‘name’ then it must be escaped with a backslash and escape_delimiter must be True. If ‘unquote’ is True leading and trailing double-quotes are stripped from ‘name’ and ‘value’. If unique_values’ is True then dictionary entries with the same value are removed before the parsed entry is added.


Parse comma separated string of Python literals. Return a tuple of of parsed values.

leo.extensions.asciidoc.parse_named_attributes(s, attrs)[source]

Update a attrs dictionary with name=”value” attributes from the s string. Returns False if invalid syntax. Example: attrs: ‘star=”sun”,planet=”earth”’ dict: {‘planet’:’earth’, ‘star’:’sun’}

leo.extensions.asciidoc.parse_options(options, allowed, errmsg)[source]

Parse comma separated string of unquoted option names and return as a tuple of valid options. ‘allowed’ is a list of allowed option values. If allowed=() then all legitimate names are allowed. ‘errmsg’ is an error message prefix if an illegal option error is thrown.


Join list of regular expressions re1,re2,… to single regular expression (re1)|(re2)|…


Return list with empty items from end of list removed.

leo.extensions.asciidoc.safe_filename(fname, parentdir)[source]

Return file name which must reside in the parent file directory. Return None if file is not safe.

leo.extensions.asciidoc.show_help(topic, f=None)[source]

Print help topic to file object f.


Return list with empty items from start and end of list removed.


Trim white space and, if necessary, quote characters from s.

leo.extensions.asciidoc.subs_attrs(lines, dictionary=None)[source]

Substitute ‘lines’ of text with attributes from the global document.attributes dictionary and from ‘dictionary’ (‘dictionary’ entries take precedence). Return a tuple of the substituted lines. ‘lines’ containing undefined attributes are deleted. If ‘lines’ is a string then return a string.

  • Attribute references are substituted in the following order: simple, conditional, system.
  • Attribute references inside ‘dictionary’ entry values are substituted.

Quoted text is marked up and the resulting text is returned.

leo.extensions.asciidoc.subs_tag(tag, dict={})[source]

Perform attribute substitution and split tag string returning start, end tag tuple (c.f. Config.tag()).


Drop non-symbol characters and convert to lowercase.

leo.extensions.asciidoc.system(name, args, is_macro=False, attrs=None)[source]

Evaluate a system attribute ({name:args}) or system block macro (name::[args]). If is_macro is True then we are processing a system block macro otherwise it’s a system attribute. The attrs dictionary is updated by the counter and set system attributes. NOTE: The include1 attribute is used internally by the include1::[] macro and is not for public use.


Convert seconds since the Epoch to formatted local time string.

leo.extensions.asciidoc.update_attrs(attrs, dict)[source]

Update ‘attrs’ dictionary with parsed attributes in dictionary ‘dict’.


Return user’s home directory or None if it is not defined.

colors Module

Colors module provides a colors names database and functions to access it.

The database is a python dictionary with reduced colornames as keys and color data in the form ‘#RRGGBB’ as values.

The reudced color names are common color names with spaces and capitalization removed.

Functions to access the data base are:

This function will convert name and return it in ‘#RRGGBB’ format if possible otherwise it will do the sme for default.

If default can not be converted, None will be returned.

name and default are reduced by removing spaces and capitalization before looking them up in the database.

This function will first call getColor to convert name (or default) to ‘#RRGGBB’ format, then it will convert this and return it as a python tuple in the form (0-255, 0-255, 0-255).

Returns None if anything goes wrong.

leo.extensions.colors.getColor(name, default=None)[source]
leo.extensions.colors.getColorRGB(name, default=None)[source]

patch_11_01 Module

Patch utility to apply unified diffs

Brute-force line-by-line non-recursive parsing

Copyright (c) 2008-2011 anatoly techtonik Available under the terms of MIT license

Project home: http://code.google.com/p/python-patch/

$Id: patch.py 117 2011-01-09 16:38:03Z techtonik $ $HeadURL: https://python-patch.googlecode.com/svn/trunk/patch.py $

class leo.extensions.patch_11_01.Hunk[source]

Bases: object

Parsed hunk data container (hunk starts with @@ -R +R @@)

startsrc = None

line count starts with 1

class leo.extensions.patch_11_01.Patch(stream=None)[source]

Bases: object


apply parsed patch return True on success


Check if specified filename can be patched. Returns None if file can not be found among source filenames. False if patch can not be applied clearly. True otherwise.

Returns:True, False or None
header = None

headers for each file

hunkends = None

file endings statistics for every hunk

hunks = None

list of lists of hunks


parse unified diff

patch_stream(instream, hunks)[source]

Generator that yields stream patched with hunks iterable

Converts lineends in hunk lines to the best suitable format autodetected from input

source = None

list of source filenames

type = None

patch type - one of constants

write_hunks(srcname, tgtname, hunks)[source]

Parse patch file and return Patch() object


Parse text string and return Patch() object


Read patch from URL

sh Module

testExtension Module