desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Return dict with unpicklable references removed.'
| def __getstate__(self):
| state = self.__dict__.copy()
state['reporter'] = None
state['transformer'] = None
return state
|
'Return a DOM representation of this document.'
| def asdom(self, dom=None):
| if (dom is None):
import xml.dom.minidom as dom
domroot = dom.Document()
domroot.appendChild(self._dom_node(domroot))
return domroot
|
'`self.nameids` maps names to IDs, while `self.nametypes` maps names to
booleans representing hyperlink type (True==explicit,
False==implicit). This method updates the mappings.
The following state transition table shows how `self.nameids` ("ids")
and `self.nametypes` ("types") change with new input (a call to this
method), and what actions are performed ("implicit"-type system
messages are INFO/1, and "explicit"-type system messages are ERROR/3):
Old State Input Action New State Notes
ids types new type sys.msg. dupname ids types
- - explicit - - new True
- - implicit - - new False
None False explicit - - new True
old False explicit implicit old new True
None True explicit explicit new None True
old True explicit explicit new,old None True [#]_
None False implicit implicit new None False
old False implicit implicit new,old None False
None True implicit implicit new None True
old True implicit implicit new old True
.. [#] Do not clear the name-to-id map or invalidate the old target if
both old and new targets are external and refer to identical URIs.
The new target is invalidated regardless.'
| def set_name_id_map(self, node, id, msgnode=None, explicit=None):
| for name in node['names']:
if self.nameids.has_key(name):
self.set_duplicate_name_id(node, id, name, msgnode, explicit)
else:
self.nameids[name] = id
self.nametypes[name] = explicit
|
'Call self."``visit_`` + node class name" with `node` as
parameter. If the ``visit_...`` method does not exist, call
self.unknown_visit.'
| def dispatch_visit(self, node):
| node_name = node.__class__.__name__
method = getattr(self, ('visit_' + node_name), self.unknown_visit)
self.document.reporter.debug(('docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)))
return method(node)
|
'Call self."``depart_`` + node class name" with `node` as
parameter. If the ``depart_...`` method does not exist, call
self.unknown_departure.'
| def dispatch_departure(self, node):
| node_name = node.__class__.__name__
method = getattr(self, ('depart_' + node_name), self.unknown_departure)
self.document.reporter.debug(('docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)))
return method(node)
|
'Called when entering unknown `Node` types.
Raise an exception unless overridden.'
| def unknown_visit(self, node):
| if (node.document.settings.strict_visitor or (node.__class__.__name__ not in self.optional)):
raise NotImplementedError(('%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)))
|
'Called before exiting unknown `Node` types.
Raise exception unless overridden.'
| def unknown_departure(self, node):
| if (node.document.settings.strict_visitor or (node.__class__.__name__ not in self.optional)):
raise NotImplementedError(('%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)))
|
'Override for generic, uniform traversals.'
| def default_visit(self, node):
| raise NotImplementedError
|
'Override for generic, uniform traversals.'
| def default_departure(self, node):
| raise NotImplementedError
|
'Copy the current node, and make it the new acting parent.'
| def default_visit(self, node):
| newnode = node.copy()
self.parent.append(newnode)
self.parent_stack.append(self.parent)
self.parent = newnode
|
'Restore the previous acting parent.'
| def default_departure(self, node):
| self.parent = self.parent_stack.pop()
|
'Initialize a `StateMachine` object; add state objects.
Parameters:
- `state_classes`: a list of `State` (sub)classes.
- `initial_state`: a string, the class name of the initial state.
- `debug`: a boolean; produce verbose output if true (nonzero).'
| def __init__(self, state_classes, initial_state, debug=0):
| self.input_lines = None
'`StringList` of input lines (without newlines).\n Filled by `self.run()`.'
self.input_offset = 0
'Offset of `self.input_lines` from the beginning of the file.'
self.line = None
'Current input line.'
self.line_offset = (-1)
'Current input line offset from beginning of `self.input_lines`.'
self.debug = debug
'Debugging mode on/off.'
self.initial_state = initial_state
'The name of the initial state (key to `self.states`).'
self.current_state = initial_state
'The name of the current state (key to `self.states`).'
self.states = {}
'Mapping of {state_name: State_object}.'
self.add_states(state_classes)
self.observers = []
'List of bound methods or functions to call whenever the current\n line changes. Observers are called with one argument, ``self``.\n Cleared at the end of `run()`.'
|
'Remove circular references to objects no longer required.'
| def unlink(self):
| for state in self.states.values():
state.unlink()
self.states = None
|
'Run the state machine on `input_lines`. Return results (a list).
Reset `self.line_offset` and `self.current_state`. Run the
beginning-of-file transition. Input one line at a time and check for a
matching transition. If a match is found, call the transition method
and possibly change the state. Store the context returned by the
transition method to be passed on to the next transition matched.
Accumulate the results returned by the transition methods in a list.
Run the end-of-file transition. Finally, return the accumulated
results.
Parameters:
- `input_lines`: a list of strings without newlines, or `StringList`.
- `input_offset`: the line offset of `input_lines` from the beginning
of the file.
- `context`: application-specific storage.
- `input_source`: name or path of source of `input_lines`.'
| def run(self, input_lines, input_offset=0, context=None, input_source=None):
| self.runtime_init()
if isinstance(input_lines, StringList):
self.input_lines = input_lines
else:
self.input_lines = StringList(input_lines, source=input_source)
self.input_offset = input_offset
self.line_offset = (-1)
self.current_state = self.initial_state
if self.debug:
print >>sys.stderr, ('\nStateMachine.run: input_lines (line_offset=%s):\n| %s' % (self.line_offset, '\n| '.join(self.input_lines)))
transitions = None
results = []
state = self.get_state()
try:
if self.debug:
print >>sys.stderr, '\nStateMachine.run: bof transition'
(context, result) = state.bof(context)
results.extend(result)
while 1:
try:
try:
self.next_line()
if self.debug:
(source, offset) = self.input_lines.info(self.line_offset)
print >>sys.stderr, ('\nStateMachine.run: line (source=%r, offset=%r):\n| %s' % (source, offset, self.line))
(context, next_state, result) = self.check_line(context, state, transitions)
except EOFError:
if self.debug:
print >>sys.stderr, ('\nStateMachine.run: %s.eof transition' % state.__class__.__name__)
result = state.eof(context)
results.extend(result)
break
else:
results.extend(result)
except TransitionCorrection as exception:
self.previous_line()
transitions = (exception.args[0],)
if self.debug:
print >>sys.stderr, ('\nStateMachine.run: TransitionCorrection to state "%s", transition %s.' % (state.__class__.__name__, transitions[0]))
continue
except StateCorrection as exception:
self.previous_line()
next_state = exception.args[0]
if (len(exception.args) == 1):
transitions = None
else:
transitions = (exception.args[1],)
if self.debug:
print >>sys.stderr, ('\nStateMachine.run: StateCorrection to state "%s", transition %s.' % (next_state, transitions[0]))
else:
transitions = None
state = self.get_state(next_state)
except:
if self.debug:
self.error()
raise
self.observers = []
return results
|
'Return current state object; set it first if `next_state` given.
Parameter `next_state`: a string, the name of the next state.
Exception: `UnknownStateError` raised if `next_state` unknown.'
| def get_state(self, next_state=None):
| if next_state:
if (self.debug and (next_state != self.current_state)):
print >>sys.stderr, ('\nStateMachine.get_state: Changing state from "%s" to "%s" (input line %s).' % (self.current_state, next_state, self.abs_line_number()))
self.current_state = next_state
try:
return self.states[self.current_state]
except KeyError:
raise UnknownStateError(self.current_state)
|
'Load `self.line` with the `n`\'th next line and return it.'
| def next_line(self, n=1):
| try:
try:
self.line_offset += n
self.line = self.input_lines[self.line_offset]
except IndexError:
self.line = None
raise EOFError
return self.line
finally:
self.notify_observers()
|
'Return 1 if the next line is blank or non-existant.'
| def is_next_line_blank(self):
| try:
return (not self.input_lines[(self.line_offset + 1)].strip())
except IndexError:
return 1
|
'Return 1 if the input is at or past end-of-file.'
| def at_eof(self):
| return (self.line_offset >= (len(self.input_lines) - 1))
|
'Return 1 if the input is at or before beginning-of-file.'
| def at_bof(self):
| return (self.line_offset <= 0)
|
'Load `self.line` with the `n`\'th previous line and return it.'
| def previous_line(self, n=1):
| self.line_offset -= n
if (self.line_offset < 0):
self.line = None
else:
self.line = self.input_lines[self.line_offset]
self.notify_observers()
return self.line
|
'Jump to absolute line offset `line_offset`, load and return it.'
| def goto_line(self, line_offset):
| try:
try:
self.line_offset = (line_offset - self.input_offset)
self.line = self.input_lines[self.line_offset]
except IndexError:
self.line = None
raise EOFError
return self.line
finally:
self.notify_observers()
|
'Return source of line at absolute line offset `line_offset`.'
| def get_source(self, line_offset):
| return self.input_lines.source((line_offset - self.input_offset))
|
'Return line offset of current line, from beginning of file.'
| def abs_line_offset(self):
| return (self.line_offset + self.input_offset)
|
'Return line number of current line (counting from 1).'
| def abs_line_number(self):
| return ((self.line_offset + self.input_offset) + 1)
|
'Return a contiguous block of text.
If `flush_left` is true, raise `UnexpectedIndentationError` if an
indented line is encountered before the text block ends (with a blank
line).'
| def get_text_block(self, flush_left=0):
| try:
block = self.input_lines.get_text_block(self.line_offset, flush_left)
self.next_line((len(block) - 1))
return block
except UnexpectedIndentationError as error:
(block, source, lineno) = error
self.next_line((len(block) - 1))
raise
|
'Examine one line of input for a transition match & execute its method.
Parameters:
- `context`: application-dependent storage.
- `state`: a `State` object, the current state.
- `transitions`: an optional ordered list of transition names to try,
instead of ``state.transition_order``.
Return the values returned by the transition method:
- context: possibly modified from the parameter `context`;
- next state name (`State` subclass name);
- the result output of the transition, a list.
When there is no match, ``state.no_match()`` is called and its return
value is returned.'
| def check_line(self, context, state, transitions=None):
| if (transitions is None):
transitions = state.transition_order
state_correction = None
if self.debug:
print >>sys.stderr, ('\nStateMachine.check_line: state="%s", transitions=%r.' % (state.__class__.__name__, transitions))
for name in transitions:
(pattern, method, next_state) = state.transitions[name]
match = self.match(pattern)
if match:
if self.debug:
print >>sys.stderr, ('\nStateMachine.check_line: Matched transition "%s" in state "%s".' % (name, state.__class__.__name__))
return method(match, context, next_state)
else:
if self.debug:
print >>sys.stderr, ('\nStateMachine.check_line: No match in state "%s".' % state.__class__.__name__)
return state.no_match(context, transitions)
|
'Return the result of a regular expression match.
Parameter `pattern`: an `re` compiled regular expression.'
| def match(self, pattern):
| return pattern.match(self.line)
|
'Initialize & add a `state_class` (`State` subclass) object.
Exception: `DuplicateStateError` raised if `state_class` was already
added.'
| def add_state(self, state_class):
| statename = state_class.__name__
if self.states.has_key(statename):
raise DuplicateStateError(statename)
self.states[statename] = state_class(self, self.debug)
|
'Add `state_classes` (a list of `State` subclasses).'
| def add_states(self, state_classes):
| for state_class in state_classes:
self.add_state(state_class)
|
'Initialize `self.states`.'
| def runtime_init(self):
| for state in self.states.values():
state.runtime_init()
|
'Report error details.'
| def error(self):
| (type, value, module, line, function) = _exception_data()
print >>sys.stderr, ('%s: %s' % (type, value))
print >>sys.stderr, ('input line %s' % self.abs_line_number())
print >>sys.stderr, ('module %s, line %s, function %s' % (module, line, function))
|
'The `observer` parameter is a function or bound method which takes two
arguments, the source and offset of the current line.'
| def attach_observer(self, observer):
| self.observers.append(observer)
|
'Initialize a `State` object; make & add initial transitions.
Parameters:
- `statemachine`: the controlling `StateMachine` object.
- `debug`: a boolean; produce verbose output if true (nonzero).'
| def __init__(self, state_machine, debug=0):
| self.transition_order = []
'A list of transition names in search order.'
self.transitions = {}
'\n A mapping of transition names to 3-tuples containing\n (compiled_pattern, transition_method, next_state_name). Initialized as\n an instance attribute dynamically (instead of as a class attribute)\n because it may make forward references to patterns and methods in this\n or other classes.\n '
self.add_initial_transitions()
self.state_machine = state_machine
'A reference to the controlling `StateMachine` object.'
self.debug = debug
'Debugging mode on/off.'
if (self.nested_sm is None):
self.nested_sm = self.state_machine.__class__
if (self.nested_sm_kwargs is None):
self.nested_sm_kwargs = {'state_classes': [self.__class__], 'initial_state': self.__class__.__name__}
|
'Initialize this `State` before running the state machine; called from
`self.state_machine.run()`.'
| def runtime_init(self):
| pass
|
'Remove circular references to objects no longer required.'
| def unlink(self):
| self.state_machine = None
|
'Make and add transitions listed in `self.initial_transitions`.'
| def add_initial_transitions(self):
| if self.initial_transitions:
(names, transitions) = self.make_transitions(self.initial_transitions)
self.add_transitions(names, transitions)
|
'Add a list of transitions to the start of the transition list.
Parameters:
- `names`: a list of transition names.
- `transitions`: a mapping of names to transition tuples.
Exceptions: `DuplicateTransitionError`, `UnknownTransitionError`.'
| def add_transitions(self, names, transitions):
| for name in names:
if self.transitions.has_key(name):
raise DuplicateTransitionError(name)
if (not transitions.has_key(name)):
raise UnknownTransitionError(name)
self.transition_order[:0] = names
self.transitions.update(transitions)
|
'Add a transition to the start of the transition list.
Parameter `transition`: a ready-made transition 3-tuple.
Exception: `DuplicateTransitionError`.'
| def add_transition(self, name, transition):
| if self.transitions.has_key(name):
raise DuplicateTransitionError(name)
self.transition_order[:0] = [name]
self.transitions[name] = transition
|
'Remove a transition by `name`.
Exception: `UnknownTransitionError`.'
| def remove_transition(self, name):
| try:
del self.transitions[name]
self.transition_order.remove(name)
except:
raise UnknownTransitionError(name)
|
'Make & return a transition tuple based on `name`.
This is a convenience function to simplify transition creation.
Parameters:
- `name`: a string, the name of the transition pattern & method. This
`State` object must have a method called \'`name`\', and a dictionary
`self.patterns` containing a key \'`name`\'.
- `next_state`: a string, the name of the next `State` object for this
transition. A value of ``None`` (or absent) implies no state change
(i.e., continue with the same state).
Exceptions: `TransitionPatternNotFound`, `TransitionMethodNotFound`.'
| def make_transition(self, name, next_state=None):
| if (next_state is None):
next_state = self.__class__.__name__
try:
pattern = self.patterns[name]
if (not hasattr(pattern, 'match')):
pattern = re.compile(pattern)
except KeyError:
raise TransitionPatternNotFound(('%s.patterns[%r]' % (self.__class__.__name__, name)))
try:
method = getattr(self, name)
except AttributeError:
raise TransitionMethodNotFound(('%s.%s' % (self.__class__.__name__, name)))
return (pattern, method, next_state)
|
'Return a list of transition names and a transition mapping.
Parameter `name_list`: a list, where each entry is either a transition
name string, or a 1- or 2-tuple (transition name, optional next state
name).'
| def make_transitions(self, name_list):
| stringtype = type('')
names = []
transitions = {}
for namestate in name_list:
if (type(namestate) is stringtype):
transitions[namestate] = self.make_transition(namestate)
names.append(namestate)
else:
transitions[namestate[0]] = self.make_transition(*namestate)
names.append(namestate[0])
return (names, transitions)
|
'Called when there is no match from `StateMachine.check_line()`.
Return the same values returned by transition methods:
- context: unchanged;
- next state name: ``None``;
- empty result list.
Override in subclasses to catch this event.'
| def no_match(self, context, transitions):
| return (context, None, [])
|
'Handle beginning-of-file. Return unchanged `context`, empty result.
Override in subclasses.
Parameter `context`: application-defined storage.'
| def bof(self, context):
| return (context, [])
|
'Handle end-of-file. Return empty result.
Override in subclasses.
Parameter `context`: application-defined storage.'
| def eof(self, context):
| return []
|
'A "do nothing" transition method.
Return unchanged `context` & `next_state`, empty result. Useful for
simple state changes (actionless transitions).'
| def nop(self, match, context, next_state):
| return (context, next_state, [])
|
'Return a block of indented lines of text, and info.
Extract an indented block where the indent is unknown for all lines.
:Parameters:
- `until_blank`: Stop collecting at the first blank line if true
(1).
- `strip_indent`: Strip common leading indent if true (1,
default).
:Return:
- the indented block (a list of lines of text),
- its indent,
- its first line offset from BOF, and
- whether or not it finished with a blank line.'
| def get_indented(self, until_blank=0, strip_indent=1):
| offset = self.abs_line_offset()
(indented, indent, blank_finish) = self.input_lines.get_indented(self.line_offset, until_blank, strip_indent)
if indented:
self.next_line((len(indented) - 1))
while (indented and (not indented[0].strip())):
indented.trim_start()
offset += 1
return (indented, indent, offset, blank_finish)
|
'Return an indented block and info.
Extract an indented block where the indent is known for all lines.
Starting with the current line, extract the entire text block with at
least `indent` indentation (which must be whitespace, except for the
first line).
:Parameters:
- `indent`: The number of indent columns/characters.
- `until_blank`: Stop collecting at the first blank line if true
(1).
- `strip_indent`: Strip `indent` characters of indentation if true
(1, default).
:Return:
- the indented block,
- its first line offset from BOF, and
- whether or not it finished with a blank line.'
| def get_known_indented(self, indent, until_blank=0, strip_indent=1):
| offset = self.abs_line_offset()
(indented, indent, blank_finish) = self.input_lines.get_indented(self.line_offset, until_blank, strip_indent, block_indent=indent)
self.next_line((len(indented) - 1))
while (indented and (not indented[0].strip())):
indented.trim_start()
offset += 1
return (indented, offset, blank_finish)
|
'Return an indented block and info.
Extract an indented block where the indent is known for the first line
and unknown for all other lines.
:Parameters:
- `indent`: The first line\'s indent (# of columns/characters).
- `until_blank`: Stop collecting at the first blank line if true
(1).
- `strip_indent`: Strip `indent` characters of indentation if true
(1, default).
- `strip_top`: Strip blank lines from the beginning of the block.
:Return:
- the indented block,
- its indent,
- its first line offset from BOF, and
- whether or not it finished with a blank line.'
| def get_first_known_indented(self, indent, until_blank=0, strip_indent=1, strip_top=1):
| offset = self.abs_line_offset()
(indented, indent, blank_finish) = self.input_lines.get_indented(self.line_offset, until_blank, strip_indent, first_indent=indent)
self.next_line((len(indented) - 1))
if strip_top:
while (indented and (not indented[0].strip())):
indented.trim_start()
offset += 1
return (indented, indent, offset, blank_finish)
|
'Initialize a `StateSM` object; extends `State.__init__()`.
Check for indent state machine attributes, set defaults if not set.'
| def __init__(self, state_machine, debug=0):
| State.__init__(self, state_machine, debug)
if (self.indent_sm is None):
self.indent_sm = self.nested_sm
if (self.indent_sm_kwargs is None):
self.indent_sm_kwargs = self.nested_sm_kwargs
if (self.known_indent_sm is None):
self.known_indent_sm = self.indent_sm
if (self.known_indent_sm_kwargs is None):
self.known_indent_sm_kwargs = self.indent_sm_kwargs
|
'Add whitespace-specific transitions before those defined in subclass.
Extends `State.add_initial_transitions()`.'
| def add_initial_transitions(self):
| State.add_initial_transitions(self)
if (self.patterns is None):
self.patterns = {}
self.patterns.update(self.ws_patterns)
(names, transitions) = self.make_transitions(self.ws_initial_transitions)
self.add_transitions(names, transitions)
|
'Handle blank lines. Does nothing. Override in subclasses.'
| def blank(self, match, context, next_state):
| return self.nop(match, context, next_state)
|
'Handle an indented text block. Extend or override in subclasses.
Recursively run the registered state machine for indented blocks
(`self.indent_sm`).'
| def indent(self, match, context, next_state):
| (indented, indent, line_offset, blank_finish) = self.state_machine.get_indented()
sm = self.indent_sm(debug=self.debug, **self.indent_sm_kwargs)
results = sm.run(indented, input_offset=line_offset)
return (context, next_state, results)
|
'Handle a known-indent text block. Extend or override in subclasses.
Recursively run the registered state machine for known-indent indented
blocks (`self.known_indent_sm`). The indent is the length of the
match, ``match.end()``.'
| def known_indent(self, match, context, next_state):
| (indented, line_offset, blank_finish) = self.state_machine.get_known_indented(match.end())
sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs)
results = sm.run(indented, input_offset=line_offset)
return (context, next_state, results)
|
'Handle an indented text block (first line\'s indent known).
Extend or override in subclasses.
Recursively run the registered state machine for known-indent indented
blocks (`self.known_indent_sm`). The indent is the length of the
match, ``match.end()``.'
| def first_known_indent(self, match, context, next_state):
| (indented, line_offset, blank_finish) = self.state_machine.get_first_known_indented(match.end())
sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs)
results = sm.run(indented, input_offset=line_offset)
return (context, next_state, results)
|
'Return the result of a regular expression search.
Overrides `StateMachine.match()`.
Parameter `pattern`: `re` compiled regular expression.'
| def match(self, pattern):
| return pattern.search(self.line)
|
'Remove items from the start of the list, without touching the parent.'
| def trim_start(self, n=1):
| if (n > len(self.data)):
raise IndexError(("Size of trim too large; can't trim %s items from a list of size %s." % (n, len(self.data))))
elif (n < 0):
raise IndexError('Trim size must be >= 0.')
del self.data[:n]
del self.items[:n]
if self.parent:
self.parent_offset += n
|
'Remove items from the end of the list, without touching the parent.'
| def trim_end(self, n=1):
| if (n > len(self.data)):
raise IndexError(("Size of trim too large; can't trim %s items from a list of size %s." % (n, len(self.data))))
elif (n < 0):
raise IndexError('Trim size must be >= 0.')
del self.data[(- n):]
del self.items[(- n):]
|
'Return source & offset for index `i`.'
| def info(self, i):
| try:
return self.items[i]
except IndexError:
if (i == len(self.data)):
return (self.items[(i - 1)][0], None)
else:
raise
|
'Return source for index `i`.'
| def source(self, i):
| return self.info(i)[0]
|
'Return offset for index `i`.'
| def offset(self, i):
| return self.info(i)[1]
|
'Break link between this list and parent list.'
| def disconnect(self):
| self.parent = None
|
'Trim `length` characters off the beginning of each item, in-place,
from index `start` to `end`. No whitespace-checking is done on the
trimmed text. Does not affect slice parent.'
| def trim_left(self, length, start=0, end=sys.maxint):
| self.data[start:end] = [line[length:] for line in self.data[start:end]]
|
'Return a contiguous block of text.
If `flush_left` is true, raise `UnexpectedIndentationError` if an
indented line is encountered before the text block ends (with a blank
line).'
| def get_text_block(self, start, flush_left=0):
| end = start
last = len(self.data)
while (end < last):
line = self.data[end]
if (not line.strip()):
break
if (flush_left and (line[0] == ' ')):
(source, offset) = self.info(end)
raise UnexpectedIndentationError(self[start:end], source, (offset + 1))
end += 1
return self[start:end]
|
'Extract and return a StringList of indented lines of text.
Collect all lines with indentation, determine the minimum indentation,
remove the minimum indentation from all indented lines (unless
`strip_indent` is false), and return them. All lines up to but not
including the first unindented line will be returned.
:Parameters:
- `start`: The index of the first line to examine.
- `until_blank`: Stop collecting at the first blank line if true.
- `strip_indent`: Strip common leading indent if true (default).
- `block_indent`: The indent of the entire block, if known.
- `first_indent`: The indent of the first line, if known.
:Return:
- a StringList of indented lines with mininum indent removed;
- the amount of the indent;
- a boolean: did the indented block finish with a blank line or EOF?'
| def get_indented(self, start=0, until_blank=0, strip_indent=1, block_indent=None, first_indent=None):
| indent = block_indent
end = start
if ((block_indent is not None) and (first_indent is None)):
first_indent = block_indent
if (first_indent is not None):
end += 1
last = len(self.data)
while (end < last):
line = self.data[end]
if (line and ((line[0] != ' ') or ((block_indent is not None) and line[:block_indent].strip()))):
blank_finish = ((end > start) and (not self.data[(end - 1)].strip()))
break
stripped = line.lstrip()
if (not stripped):
if until_blank:
blank_finish = 1
break
elif (block_indent is None):
line_indent = (len(line) - len(stripped))
if (indent is None):
indent = line_indent
else:
indent = min(indent, line_indent)
end += 1
else:
blank_finish = 1
block = self[start:end]
if ((first_indent is not None) and block):
block.data[0] = block.data[0][first_indent:]
if (indent and strip_indent):
block.trim_left(indent, start=(first_indent is not None))
return (block, (indent or 0), blank_finish)
|
'Pad all double-width characters in self by appending `pad_char` to each.
For East Asian language support.'
| def pad_double_width(self, pad_char):
| if hasattr(unicodedata, 'east_asian_width'):
east_asian_width = unicodedata.east_asian_width
else:
return
for i in range(len(self.data)):
line = self.data[i]
if isinstance(line, types.UnicodeType):
new = []
for char in line:
new.append(char)
if (east_asian_width(char) in 'WF'):
new.append(pad_char)
self.data[i] = ''.join(new)
|
'Replace all occurrences of substring `old` with `new`.'
| def replace(self, old, new):
| for i in range(len(self.data)):
self.data[i] = self.data[i].replace(old, new)
|
'Encode special characters in `text` & return.'
| def encode(self, text):
| text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('"', '"')
text = text.replace('>', '>')
text = text.replace('@', '@')
text = text.replace(u'\xa0', ' ')
return text
|
'Try to hide a mailto: URL from harvesters.'
| def cloak_mailto(self, uri):
| return uri.replace('@', '%40')
|
'Try to hide the link text of a email link from harversters.'
| def cloak_email(self, addr):
| addr = addr.replace('@', '<span>@</span>')
addr = addr.replace('.', '<span>.</span>')
return addr
|
'Cleanse, HTML encode, and return attribute value text.'
| def attval(self, text, whitespace=re.compile('[\n\r DCTB \x0b\x0c]')):
| encoded = self.encode(whitespace.sub(' ', text))
if (self.in_mailto and self.settings.cloak_email_addresses):
encoded = encoded.replace('%40', '%40')
encoded = encoded.replace('.', '.')
return encoded
|
'Construct and return a start tag given a node (id & class attributes
are extracted), tag name, and optional attributes.'
| def starttag(self, node, tagname, suffix='\n', empty=0, **attributes):
| tagname = tagname.lower()
prefix = []
atts = {}
ids = []
for (name, value) in attributes.items():
atts[name.lower()] = value
classes = node.get('classes', [])
if atts.has_key('class'):
classes.append(atts['class'])
if classes:
atts['class'] = ' '.join(classes)
assert (not atts.has_key('id'))
ids.extend(node.get('ids', []))
if atts.has_key('ids'):
ids.extend(atts['ids'])
del atts['ids']
if ids:
atts['id'] = ids[0]
for id in ids[1:]:
if empty:
prefix.append(('<span id="%s"></span>' % id))
else:
suffix += ('<span id="%s"></span>' % id)
attlist = atts.items()
attlist.sort()
parts = [tagname]
for (name, value) in attlist:
assert (value is not None)
if isinstance(value, ListType):
values = [unicode(v) for v in value]
parts.append(('%s="%s"' % (name.lower(), self.attval(' '.join(values)))))
else:
parts.append(('%s="%s"' % (name.lower(), self.attval(unicode(value)))))
if empty:
infix = ' /'
else:
infix = ''
return ((''.join(prefix) + ('<%s%s>' % (' '.join(parts), infix))) + suffix)
|
'Construct and return an XML-compatible empty tag.'
| def emptytag(self, node, tagname, suffix='\n', **attributes):
| return self.starttag(node, tagname, suffix, empty=1, **attributes)
|
'Set class `class_` on the visible child no. index of `node`.
Do nothing if node has fewer children than `index`.'
| def set_class_on_child(self, node, class_, index=0):
| children = [n for n in node if (not isinstance(n, nodes.Invisible))]
try:
child = children[index]
except IndexError:
return
child['classes'].append(class_)
|
'Check for a simple list that can be rendered compactly.'
| def check_simple_list(self, node):
| visitor = SimpleListChecker(self.document)
try:
node.walk(visitor)
except nodes.NodeFound:
return None
else:
return 1
|
'Escape double-dashes in comment text.'
| def visit_comment(self, node, sub=re.compile('-(?=-)').sub):
| self.body.append(('<!-- %s -->\n' % sub('- ', node.astext())))
raise nodes.SkipNode
|
'The \'start\' attribute does not conform to HTML 4.01\'s strict.dtd, but
CSS1 doesn\'t help. CSS2 isn\'t widely enough supported yet to be
usable.'
| def visit_enumerated_list(self, node):
| atts = {}
if node.has_key('start'):
atts['start'] = node['start']
if node.has_key('enumtype'):
atts['class'] = node['enumtype']
old_compact_simple = self.compact_simple
self.context.append((self.compact_simple, self.compact_p))
self.compact_p = None
self.compact_simple = self.is_compactable(node)
if (self.compact_simple and (not old_compact_simple)):
atts['class'] = (atts.get('class', '') + ' simple').strip()
self.body.append(self.starttag(node, 'ol', **atts))
|
'Process text to prevent tokens from wrapping.'
| def visit_literal(self, node):
| self.body.append(self.starttag(node, 'tt', '', CLASS='docutils literal'))
text = node.astext()
for token in self.words_and_spaces.findall(text):
if token.strip():
self.body.append(('<span class="pre">%s</span>' % self.encode(token)))
elif (token in ('\n', ' ')):
self.body.append(token)
else:
self.body.append(((' ' * (len(token) - 1)) + ' '))
self.body.append('</tt>')
raise nodes.SkipNode
|
'Determine if the <p> tags around paragraph ``node`` can be omitted.'
| def should_be_compact_paragraph(self, node):
| if (isinstance(node.parent, nodes.document) or isinstance(node.parent, nodes.compound)):
return 0
for (key, value) in node.attlist():
if (node.is_not_default(key) and (not ((key == 'classes') and (value in ([], ['first'], ['last'], ['first', 'last']))))):
return 0
first = isinstance(node.parent[0], nodes.label)
for child in node.parent.children[first:]:
if isinstance(child, nodes.Invisible):
continue
if (child is node):
break
return 0
parent_length = len([n for n in node.parent if (not isinstance(n, (nodes.Invisible, nodes.label)))])
if (self.compact_simple or self.compact_field_list or (self.compact_p and (parent_length == 1))):
return 1
return 0
|
'Internal only.'
| def visit_substitution_definition(self, node):
| raise nodes.SkipNode
|
'Leave the end tag to `self.visit_definition()`, in case there\'s a
classifier.'
| def depart_term(self, node):
| pass
|
'Only 6 section levels are supported by HTML.'
| def visit_title(self, node):
| check_id = 0
close_tag = '</p>\n'
if isinstance(node.parent, nodes.topic):
self.body.append(self.starttag(node, 'p', '', CLASS='topic-title first'))
elif isinstance(node.parent, nodes.sidebar):
self.body.append(self.starttag(node, 'p', '', CLASS='sidebar-title'))
elif isinstance(node.parent, nodes.Admonition):
self.body.append(self.starttag(node, 'p', '', CLASS='admonition-title'))
elif isinstance(node.parent, nodes.table):
self.body.append(self.starttag(node, 'caption', ''))
close_tag = '</caption>\n'
elif isinstance(node.parent, nodes.document):
self.body.append(self.starttag(node, 'h1', '', CLASS='title'))
close_tag = '</h1>\n'
self.in_document_title = len(self.body)
else:
assert isinstance(node.parent, nodes.section)
h_level = ((self.section_level + self.initial_header_level) - 1)
atts = {}
if ((len(node.parent) >= 2) and isinstance(node.parent[1], nodes.subtitle)):
atts['CLASS'] = 'with-subtitle'
self.body.append(self.starttag(node, ('h%s' % h_level), '', **atts))
atts = {}
if node.hasattr('refid'):
atts['class'] = 'toc-backref'
atts['href'] = ('#' + node['refid'])
if atts:
self.body.append(self.starttag({}, 'a', '', **atts))
close_tag = ('</a></h%s>\n' % h_level)
else:
close_tag = ('</h%s>\n' % h_level)
self.context.append(close_tag)
|
'Invisible nodes should be ignored.'
| def invisible_visit(self, node):
| raise nodes.SkipNode
|
'Locate & copy theme files.
A theme may be explicitly based on another theme via a \'__base__\'
file. The default base theme is \'default\'. Files are accumulated
from the specified theme, any base themes, and \'default\'.'
| def copy_theme(self):
| settings = self.document.settings
path = find_theme(settings.theme)
theme_paths = [path]
self.theme_files_copied = {}
required_files_copied = {}
self.theme_file_path = ('%s/%s' % ('ui', settings.theme))
if settings._destination:
dest = os.path.join(os.path.dirname(settings._destination), 'ui', settings.theme)
if (not os.path.isdir(dest)):
os.makedirs(dest)
else:
return
default = 0
while path:
for f in os.listdir(path):
if (f == self.base_theme_file):
continue
if (self.copy_file(f, path, dest) and (f in self.required_theme_files)):
required_files_copied[f] = 1
if default:
break
base_theme_file = os.path.join(path, self.base_theme_file)
if os.path.isfile(base_theme_file):
lines = open(base_theme_file).readlines()
for line in lines:
line = line.strip()
if (line and (not line.startswith('#'))):
path = find_theme(line)
if (path in theme_paths):
path = None
else:
theme_paths.append(path)
break
else:
path = None
else:
path = None
if (not path):
path = find_theme(self.default_theme)
theme_paths.append(path)
default = 1
if (len(required_files_copied) != len(self.required_theme_files)):
required = list(self.required_theme_files)
for f in required_files_copied.keys():
required.remove(f)
raise docutils.ApplicationError(('Theme files not found: %s' % ', '.join([('%r' % f) for f in required])))
|
'Copy file `name` from `source_dir` to `dest_dir`.
Return 1 if the file exists in either `source_dir` or `dest_dir`.'
| def copy_file(self, name, source_dir, dest_dir):
| source = os.path.join(source_dir, name)
dest = os.path.join(dest_dir, name)
if self.theme_files_copied.has_key(dest):
return 1
else:
self.theme_files_copied[dest] = 1
if os.path.isfile(source):
if self.files_to_skip_pattern.search(source):
return None
settings = self.document.settings
if (os.path.exists(dest) and (not settings.overwrite_theme_files)):
settings.record_dependencies.add(dest)
else:
src_file = open(source, 'rb')
src_data = src_file.read()
src_file.close()
dest_file = open(dest, 'wb')
dest_dir = dest_dir.replace(os.sep, '/')
dest_file.write(src_data.replace('ui/default', dest_dir[dest_dir.rfind('ui/'):]))
dest_file.close()
settings.record_dependencies.add(source)
return 1
if os.path.isfile(dest):
return 1
|
'Process a document into its final form.
Translate `document` (a Docutils document tree) into the Writer\'s
native format, and write it out to its `destination` (a
`docutils.io.Output` subclass object).
Normally not overridden or extended in subclasses.'
| def write(self, document, destination):
| self.document = document
self.language = languages.get_language(document.settings.language_code)
self.destination = destination
self.translate()
output = self.destination.write(self.output)
return output
|
'Do final translation of `self.document` into `self.output`. Called
from `write`. Override in subclasses.
Usually done with a `docutils.nodes.NodeVisitor` subclass, in
combination with a call to `docutils.nodes.Node.walk()` or
`docutils.nodes.Node.walkabout()`. The ``NodeVisitor`` subclass must
support all standard elements (listed in
`docutils.nodes.node_class_names`) and possibly non-standard elements
used by the current Reader as well.'
| def translate(self):
| raise NotImplementedError('subclass must override this method')
|
'Assemble the `self.parts` dictionary. Extend in subclasses.'
| def assemble_parts(self):
| self.parts['whole'] = self.output
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
|
'Encode special characters in ``text`` and return it.
If attval is true, preserve as much as possible verbatim (used
in attribute value encoding). If attval is \'width\' or
\'height\', `text` is interpreted as a length value.'
| def encode(self, text, attval=None):
| if (attval in ('width', 'height')):
match = re.match('([0-9.]+)(\\S*)$', text)
assert match, ('%s="%s" must be a length' % (attval, text))
(value, unit) = match.groups()
if (unit == '%'):
value = str((float(value) / 100))
unit = '\\DECrelativeunit'
elif (unit in ('', 'px')):
value = str((float(value) * 0.75))
unit = '\\DECpixelunit'
return ('%s%s' % (value, unit))
if attval:
get = self.att_map.get
else:
get = self.character_map.get
text = ''.join([get(c, c) for c in text])
if ((self.literal_block or self.inline_literal) and (not attval)):
text = text.replace('\r\n', '\n')
if self.literal_block:
text = text.replace('\n', '\\mbox{}\\\\{}')
replace_fn = self.encode_replace_for_literal_block_spaces
else:
replace_fn = self.encode_replace_for_inline_literal_spaces
text = re.sub('\\s+', replace_fn, text)
text = text.replace('-', '\\mbox{-}')
text = text.replace("'", '{\\DECtextliteralsinglequote}')
return text
elif (not attval):
text = re.sub('\\s+', '{ }', text)
L = []
for part in text.split(self.character_map['"']):
if L:
L.append(((self.left_quote and '{\\DECtextleftdblquote}') or '{\\DECtextrightdblquote}'))
self.left_quote = (not self.left_quote)
L.append(part)
return ''.join(L)
else:
return text
|
'Append text, stripping newlines, producing nice LaTeX code.'
| def append(self, text, newline='%\n'):
| lines = [(((' ' * self.indentation_level) + line) + newline) for line in text.splitlines(0)]
self.body.append(''.join(lines))
|
'Return true if `paragraph` should be first-line-indented.'
| def is_indented(self, paragraph):
| assert isinstance(paragraph, nodes.paragraph)
siblings = [n for n in paragraph.parent if (self.is_visible(n) and (not isinstance(n, nodes.Titular)))]
index = siblings.index(paragraph)
if (('continued' in paragraph['classes']) or ((index > 0) and isinstance(siblings[(index - 1)], nodes.transition))):
return 0
return (index > 0)
|
'Return text (a unicode object) with all unencodable characters
replaced with \'?\'.
Thus, the returned unicode string is guaranteed to be encodable.'
| def _make_encodable(self, text):
| encoding = self.settings.output_encoding
return text.encode(encoding, 'replace').decode(encoding)
|
'Insert the comment unchanged into the document, replacing
unencodable characters with \'?\'.
(This is done in order not to fail if comments contain unencodable
characters, because our default encoding is not UTF-8.)'
| def visit_comment(self, node):
| self.append('\n'.join([('% ' + self._make_encodable(line)) for line in node.astext().splitlines(0)]), newline='\n')
raise nodes.SkipChildren
|
'Add LaTeX handling code for backlinks of footnote or citation
node `node`. `type` is either \'footnote\' or \'citation\'.'
| def process_backlinks(self, node, type):
| self.append('\\renewcommand{\\DEVsinglebackref}{}')
self.append('\\renewcommand{\\DEVmultiplebackrefs}{}')
if (len(node['backrefs']) > 1):
refs = []
for i in range(len(node['backrefs'])):
refs.append(('\\DECmulti%sbacklink{%s}{%s}' % (type, node['backrefs'][i], (i + 1))))
self.append(('\\renewcommand{\\DEVmultiplebackrefs}{(%s){ }}' % ', '.join(refs)))
elif (len(node['backrefs']) == 1):
self.append(('\\renewcommand{\\DEVsinglebackref}{%s}' % node['backrefs'][0]))
|
'Compare attribute names `a1` and `a2`. Used in
propagate_attributes to determine propagation order.
See built-in function `cmp` for return value.'
| def attribute_cmp(self, a1, a2):
| if ((a1 in self.attribute_order) and (a2 in self.attribute_order)):
return cmp(self.attribute_order.index(a1), self.attribute_order.index(a2))
if ((a1 in self.attribute_order) != (a2 in self.attribute_order)):
return (((a1 in self.attribute_order) and (-1)) or 1)
else:
return cmp(a1, a2)
|
'Return True if the node contents should be passed in
\DN<nodename>{<contents>} and \DECattr{}{}{}{}{<contents>}.
Return False if the node contents should be passed in
\DECvisit<nodename> <contents> \DECdepart<nodename>, and no
attribute handler should be called.'
| def pass_contents(self, node):
| return (not isinstance(node, (nodes.document, nodes.section)))
|
'Two nodes for which `needs_space` is true need auxiliary space.'
| def needs_space(self, node):
| return ((isinstance(node, nodes.Body) or isinstance(node, nodes.topic)) and (not (self.is_invisible(node) or isinstance(node.parent, nodes.TextElement))))
|
'Always add space around nodes for which `always_needs_space()`
is true, regardless of whether the other node needs space as
well. (E.g. transition next to section.)'
| def always_needs_space(self, node):
| return isinstance(node, nodes.transition)
|
'Return the section name at the given level for the specific
document class.
Level is 1,2,3..., as level 0 is the title.'
| def section(self, level):
| sections = ['section', 'subsection', 'subsubsection', 'paragraph', 'subparagraph']
if (self.document_class in ('book', 'report', 'scrreprt', 'scrbook')):
sections.insert(0, 'chapter')
if self._with_part:
sections.insert(0, 'part')
if (level <= len(sections)):
return sections[(level - 1)]
else:
return sections[(-1)]
|
'Return column specification for longtable.
Assumes reST line length being 80 characters.
Table width is hairy.
ABC DEF
usually gets to narrow, therefore we add 1 (fiddlefactor).'
| def get_colspecs(self):
| width = 80
total_width = 0.0
for node in self._col_specs:
colwidth = (float((node['colwidth'] + 1)) / width)
total_width += colwidth
self._col_width = []
self._rowspan = []
factor = 0.93
if (total_width > 1.0):
factor /= total_width
bar = self.get_vertical_bar()
latex_table_spec = ''
for node in self._col_specs:
colwidth = ((factor * float((node['colwidth'] + 1))) / width)
self._col_width.append((colwidth + 0.005))
self._rowspan.append(0)
latex_table_spec += ('%sp{%.3f\\locallinewidth}' % (bar, (colwidth + 0.005)))
return (latex_table_spec + bar)
|
'return columnwidth for current cell (not multicell)'
| def get_column_width(self):
| return ('%.2f\\locallinewidth' % self._col_width[(self._cell_in_row - 1)])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.