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

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.

get_subs(params=None)[source]

Return (presubs,postsubs) tuple.

is_conf_entry(param)[source]

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

isnext()[source]

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.

pop_blockname()[source]

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

push_blockname(blockname=None)[source]

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

short_name()[source]

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

translate()[source]

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

Validate block after the complete configuration has been loaded.

class leo.extensions.asciidoc.AbstractBlocks[source]

List of block definitions.

BLOCK_TYPE = None
PREFIX = ''
dump()[source]
isnext()[source]
load(sections)[source]

Load block definition from ‘sections’ dictionary.

validate()[source]

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

Substitute single quoted attribute values normally.

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

Static methods and attributes only.

static consume()[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]
add(listindex)[source]
static calloutid(calloutindex)[source]
calloutids(listindex)[source]
listclose()[source]
validate(maxlistindex)[source]
class leo.extensions.asciidoc.Cell(data, span_spec=None, align_spec=None, style=None)[source]
clone_reserve()[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()[source]

Dump configuration to stdout.

entries_section(section_name)[source]

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

expand_all_templates()[source]
expand_templates(entries)[source]

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

find_config_dir(*dirnames)[source]

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.

get_load_dirs()[source]

Return list of well known paths with conf files.

init(cmd)[source]

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

load_backend(dirs=None)[source]

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_filters(dirs=None)[source]

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.

load_miscellaneous(d)[source]

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(sect='replacements')[source]

Parse replacements section into self.replacements dictionary.

parse_specialsections()[source]

Parse specialsections section to self.specialsections dictionary.

parse_specialwords()[source]

Parse special words section into self.specialwords dictionary.

parse_tags()[source]

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(rep, replacements)[source]

Add pattern and replacement to replacements dictionary.

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

subs_specialchars(s)[source]

Perform special character substitution on string ‘s’.

subs_specialchars_reverse(s)[source]

Perform reverse special character substitution on string ‘s’.

subs_specialwords(s)[source]

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.

validate()[source]

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

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

Bases: leo.extensions.asciidoc.AbstractBlocks

List of delimited blocks.

BLOCK_TYPE

alias of DelimitedBlock

PREFIX = 'blockdef-'
load(sections)[source]

Update blocks defined in ‘sections’ dictionary.

validate()[source]
class leo.extensions.asciidoc.Document[source]

Bases: object

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

doctype
getbackend()[source]
getdoctype()[source]
load_lang()[source]

Load language configuration file.

parse_author(s)[source]

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.

process_author_names()[source]

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.

setbackend(backend)[source]
setdoctype(doctype)[source]
translate(has_header)[source]
update_attributes(attrs=None)[source]

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()[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(margin=0)[source]

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

static subs(options)[source]

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

static subs_1(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(style)[source]

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

static calc_style()[source]

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

check_index()[source]

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

Check that all necessary tags are present.

dump()[source]
isnext()[source]
load(name, entries)[source]
translate()[source]
translate_entry()[source]
translate_item()[source]
validate()[source]
class leo.extensions.asciidoc.Lists[source]

Bases: leo.extensions.asciidoc.AbstractBlocks

List of List objects.

BLOCK_TYPE

alias of List

PREFIX = 'listdef-'
TAGS = ('list', 'entry', 'item', 'text', 'label', 'term')
TYPES = ('bulleted', 'numbered', 'labeled', 'callout')
dump()[source]
initialize()[source]
load(sections)[source]
load_tags(sections)[source]

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

validate()[source]
class leo.extensions.asciidoc.Macro[source]
has_passthrough()[source]
load(entry)[source]
section_name(name=None)[source]

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

subs(text)[source]
subs_passthroughs(text, passthroughs)[source]

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

translate()[source]

Block macro translation.

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

Extract the passthrough text and replace with temporary placeholders.

isnext()[source]

Return matching macro if block macro is next on reader.

load(entries)[source]
match(prefix, name, text)[source]

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

restore_passthroughs(text)[source]

Replace passthough placeholders with the original passthrough text.

subs(text, prefix='', callouts=False)[source]
validate()[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.

stderr(msg='')[source]
stdout(msg)[source]
unsafe(msg)[source]
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

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

Bases: leo.extensions.asciidoc.AbstractBlocks

List of paragraph definitions.

BLOCK_TYPE

alias of Paragraph

PREFIX = 'paradef-'
initialize()[source]
load(sections)[source]
validate()[source]
class leo.extensions.asciidoc.Plugin[source]

–filter and –theme option commands.

CMDS = ('install', 'remove', 'list', 'build')
static build()[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()[source]

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

static list()[source]

List all plugin directories (global and local).

static remove()[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.

eof()[source]
read()[source]
read_ahead(count=1)[source]

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

read_lines(count=1)[source]

Return tuple containing count lines.

read_next()[source]
read_super()[source]
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.

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

READ_BUFFER_MIN = 10
close()[source]
closefile()[source]

Used by class methods to close nested include files.

eof()[source]

Returns True if all lines have been read.

open(fname)[source]
read(skip=False)[source]

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

read_next()[source]

Like read() but does not advance file pointer.

unread(cursor)[source]

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

Save section end.

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

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

static translate()[source]
static translate_body()[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'}
build_colspecs()[source]

Generate column related substitution attributes.

dump()[source]
get_style(prefix)[source]

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

get_tags(params)[source]
load(name, entries)[source]
static parse_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_csv(text)[source]

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

parse_psv_dsv(text)[source]

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

parse_rows(text)[source]

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

static parse_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.

translate()[source]
validate()[source]
validate_attributes()[source]

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

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

dump()[source]
isnext()[source]
load(name, entries)[source]
parse_csv(rows)[source]

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

parse_dsv(rows)[source]

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

parse_fixed(rows)[source]

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

Parse ruler calculating underline and ruler column widths.

split_rows(rows)[source]

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.

translate()[source]
validate()[source]
class leo.extensions.asciidoc.Tables[source]

Bases: leo.extensions.asciidoc.AbstractBlocks

List of tables.

BLOCK_TYPE

alias of Table

PREFIX = 'tabledef-'
TAGS = ('colspec', 'headrow', 'footrow', 'bodyrow', 'headdata', 'footdata', 'bodydata', 'paragraph')
dump()[source]
load(sections)[source]
load_tags(sections)[source]

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

validate()[source]
class leo.extensions.asciidoc.Tables_OLD[source]

Bases: leo.extensions.asciidoc.AbstractBlocks

List of tables.

BLOCK_TYPE

alias of Table_OLD

PREFIX = 'old_tabledef-'
load(sections)[source]
validate()[source]
class leo.extensions.asciidoc.Title[source]

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

attributes = {}
static dosubs()[source]

Perform title substitutions.

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

Return next section number at section ‘level’ formatted like 1.2.3.4.

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

Load and validate [titles] section entries dictionary.

static parse()[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()[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.

close()[source]
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_line(line=None)[source]
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.char_decode(s)[source]
leo.extensions.asciidoc.char_encode(s)[source]
leo.extensions.asciidoc.char_encoding()[source]
leo.extensions.asciidoc.char_len(s)[source]
leo.extensions.asciidoc.column_width(s)[source]
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.

leo.extensions.asciidoc.date_str(t)[source]

Convert seconds since the Epoch to formatted local date string.

leo.extensions.asciidoc.die(msg)[source]
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.

Doctests:

  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.

leo.extensions.asciidoc.get_args(val)[source]
leo.extensions.asciidoc.get_kwargs(val)[source]
leo.extensions.asciidoc.is_array(obj)[source]

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.

leo.extensions.asciidoc.is_name(s)[source]

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

leo.extensions.asciidoc.is_re(s)[source]

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

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

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

leo.extensions.asciidoc.localapp()[source]

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

leo.extensions.asciidoc.lstrip_list(s)[source]

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.

leo.extensions.asciidoc.parse_list(s)[source]

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.

leo.extensions.asciidoc.parse_to_list(val)[source]
leo.extensions.asciidoc.re_join(relist)[source]

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

leo.extensions.asciidoc.rstrip_list(s)[source]

Return list with empty items from end of list removed.

leo.extensions.asciidoc.safe()[source]
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.

leo.extensions.asciidoc.strip_list(s)[source]

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

leo.extensions.asciidoc.strip_quotes(s)[source]

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.
leo.extensions.asciidoc.subs_quotes(text)[source]

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

leo.extensions.asciidoc.symbolize(s)[source]

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.

leo.extensions.asciidoc.time_str(t)[source]

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

leo.extensions.asciidoc.usage(msg='')[source]
leo.extensions.asciidoc.userdir()[source]

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

copy()[source]
startsrc = None

line count starts with 1

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

Bases: object

apply()[source]

apply parsed patch return True on success

can_patch(filename)[source]

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
copy()[source]
header = None

headers for each file

hunkends = None

file endings statistics for every hunk

hunks = None

list of lists of hunks

parse(stream)[source]

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]
leo.extensions.patch_11_01.fromfile(filename)[source]

Parse patch file and return Patch() object

leo.extensions.patch_11_01.fromstring(s)[source]

Parse text string and return Patch() object

leo.extensions.patch_11_01.fromurl(url)[source]

Read patch from URL

sh Module

testExtension Module