text
stringlengths 0
1.05M
| meta
dict |
---|---|
"""
This file retrieves tasks from an Octopus application
"""
import logging, json, requests, time, sys
import ConfigParser
import splunk.Intersplunk as isp
import octopus_common
# Parse octopus.conf for configuration settings
stanza = octopus_common.getSelfConfStanza("octopus")
protocol = stanza['protocol']
hostname = stanza['hostname']
apikey = stanza['apikey']
# Setup logger object
logger = octopus_common.setup_logging()
logger.info(time.time())
try:
octopus_url = protocol + "://" + hostname + "/api/tasks/"
last_task_id = octopus_common.readCheckPoint("tasks")
while True:
# Setup response object and execute GET request
response = requests.get(
url = octopus_url,
headers = {
"X-Octopus-ApiKey": apikey,
},
)
response.raise_for_status()
# Handle response
json_response = json.loads(response.content)
# Get task ID from first task returned by the API which is the most recent task
try:
if json_response['Links']['Page.Current'].split('=')[1][:1] == '0':
task_id = json_response['Items'][0]['Id'].split('-')[1]
octopus_common.writeCheckPoint("tasks", task_id)
except Exception:
break
# Iterate tasks and print results to Splunk if it hasn't been printed before
for task in json_response['Items']:
# Get task ID
task_id = task['Id'].split('-')[1]
if int(task_id) > int(last_task_id):
print json.dumps(task)
# Try to get next page if available
try:
octopus_url = protocol + "://" + hostname + json_response['Links']['Page.Next']
except Exception:
break
sys.exit(0)
# Catch exceptions if needed
except Exception as e:
logger.exception("Exception: " + str(e))
isp.generateErrorResults(str(e)) | {
"repo_name": "cmeerbeek/splunk-addon-octopus-deploy",
"path": "TA-OctopusNT-Fwd/bin/get_tasks.py",
"copies": "2",
"size": "1896",
"license": "mit",
"hash": -1522295631519764500,
"line_mean": 26.8970588235,
"line_max": 85,
"alpha_frac": 0.6571729958,
"autogenerated": false,
"ratio": 3.4788990825688075,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5136072078368807,
"avg_score": null,
"num_lines": null
} |
"""
This file retrieves users from an Octopus application
"""
import logging, json, requests, time, sys
import ConfigParser
import splunk.Intersplunk as isp
import octopus_common
# Parse octopus.conf for configuration settings
stanza = octopus_common.getSelfConfStanza("octopus")
protocol = stanza['protocol']
hostname = stanza['hostname']
apikey = stanza['apikey']
# Setup logger object
logger = octopus_common.setup_logging()
logger.info(time.time())
try:
octopus_url = protocol + "://" + hostname + "/api/users/all"
# Setup response object and execute GET request
response = requests.get(
url = octopus_url,
headers = {
"X-Octopus-ApiKey": apikey,
},
)
response.raise_for_status()
# Handle response
json_response = json.loads(response.content)
# Iterate users and print results to Splunk
for user in json_response:
print json.dumps(user)
sys.exit(0)
# Catch exceptions if needed
except Exception as e:
logger.exception("Exception: " + str(e))
isp.generateErrorResults(str(e)) | {
"repo_name": "cmeerbeek/splunk-addon-octopus-deploy",
"path": "TA-OctopusNT-Fwd/bin/get_users.py",
"copies": "2",
"size": "1145",
"license": "mit",
"hash": 8334504241456572000,
"line_mean": 22.875,
"line_max": 62,
"alpha_frac": 0.7170305677,
"autogenerated": false,
"ratio": 3.2902298850574714,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.993864273222619,
"avg_score": 0.013723544106256329,
"num_lines": 48
} |
# $Id: gnuplot_Suites.py,v 2.6 2001/04/03 02:42:24 ingraldi Exp $
# This file is provided as part of the Gnuplot.py package for the
# convenience of Mac users. It was generated primarily using gensuitemodule
# with Mac gnuplot 3.7.1a. Thanks to Anthony M. Ingraldi and Noboru Yamamoto
# for helping with this.
# file contains
#
# class gnuplot_Suite
# class odds_and_ends
# class Standard_Suite
# class Miscellaneous_Events
#
"""Suite gnuplot Suite: Events supplied by gnuplot
Level 1, version 1
Generated from Alpha:Desktop Folder:gnuplot.1:gnuplot 3.7.1a
AETE/AEUT resource version 1/0, language 0, script 0
"""
__cvs_version__ = '$Revision: 2.6 $'
import aetools
import MacOS
_code = 'GPSE'
class gnuplot_Suite:
def gnuexec(self, _object=None, _attributes={}, **_arguments):
"""exec: execute a gnuplot command
Required argument: gnuplot command
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'GPSE'
_subcode = 'exec'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
def plot(self, _object=None, _attributes={}, **_arguments):
"""plot: create a 2-D plot
Required argument: data to be plotted
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'GPLT'
_subcode = 'plot'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
def splot(self, _object=None, _attributes={}, **_arguments):
"""splot: create a 3-D plot
Required argument: data to be plotted
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'GPLT'
_subcode = 'splt'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
class graph(aetools.ComponentItem):
"""graph - graph - a subclass of window"""
want = 'cGRF'
class picture(aetools.NProperty):
"""picture - gnuplot graph in "PICT" format"""
which = 'PICT'
want = 'PICT'
graph._propdict = {
'picture' : picture,
}
graph._elemdict = {
}
_Enum_lyty = {
'line' : 'typ1', # line
'points' : 'typ2', # points
'impulses' : 'typ3', # impulses
'linespoints' : 'typ4', # linespoints
'dots' : 'typ5', # dots
'steps' : 'typ6', # steps
'fsteps' : 'typ7', # fsteps
'errorbars' : 'typ8', # errorbars
'xerrorbars' : 'typ9', # xerrorbars
'yerrorbars' : 'ty10', # yerrorbars
'xyerrorbars' : 'ty11', # xyerrorbars
'boxes' : 'ty12', # boxes
'boxerrorbars' : 'ty13', # boxerrorbars
'boxxyerrorbars' : 'ty14', # boxxyerrorbars
'vector' : 'ty19', # vector
}
#
# Indices of types declared in this module
#
_classdeclarations = {
'cGRF' : graph,
}
_propdeclarations = {
'PICT' : picture,
}
_compdeclarations = {
}
_enumdeclarations = {
'lyty' : _Enum_lyty,
}
"""Suite odds and ends: Things that should be in some standard suite, but arenÕt
Level 1, version 1
Generated from Alpha:Desktop Folder:gnuplot.1:gnuplot 3.7.1a
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'Odds'
class odds_and_ends:
def select(self, _object=None, _attributes={}, **_arguments):
"""select: Select the specified object
Required argument: the object to select
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'misc'
_subcode = 'slct'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
#
# Indices of types declared in this module
#
_classdeclarations = {
}
_propdeclarations = {
}
_compdeclarations = {
}
_enumdeclarations = {
}
"""Suite Standard Suite: Common terms for most applications
Level 1, version 1
Generated from Alpha:Desktop Folder:gnuplot.1:gnuplot 3.7.1a
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'CoRe'
class Standard_Suite:
_argmap_close = {
'saving' : 'savo',
'_in' : 'kfil',
}
def close(self, _object, _attributes={}, **_arguments):
"""close: Close an object
Required argument: the objects to close
Keyword argument saving: specifies whether or not changes should be saved before closing
Keyword argument _in: the file in which to save the object
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'core'
_subcode = 'clos'
aetools.keysubst(_arguments, self._argmap_close)
_arguments['----'] = _object
aetools.enumsubst(_arguments, 'savo', _Enum_savo)
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
def data_size(self, _object, _attributes={}, **_arguments):
"""data size: Return the size in bytes of an object
Required argument: the object whose data size is to be returned
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: the size of the object in bytes
"""
_code = 'core'
_subcode = 'dsiz'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
def get(self, _object, _attributes={}, **_arguments):
"""get: Get the data for an object
Required argument: the object whose data is to be returned
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: The data from the object
"""
_code = 'core'
_subcode = 'getd'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
_argmap_make = {
'new' : 'kocl',
'at' : 'insh',
'with_data' : 'data',
'with_properties' : 'prdt',
}
def make(self, _no_object=None, _attributes={}, **_arguments):
"""make: Make a new element
Keyword argument new: the class of the new element
Keyword argument at: the location at which to insert the element
Keyword argument with_data: the initial data for the element
Keyword argument with_properties: the initial values for the properties of the element
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: Object specifier for the new element
"""
_code = 'core'
_subcode = 'crel'
aetools.keysubst(_arguments, self._argmap_make)
if _no_object != None: raise TypeError, 'No direct arg expected'
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
def open(self, _object, _attributes={}, **_arguments):
"""open: Open the specified object(s)
Required argument: Objects to open. Can be a list of files or an object specifier.
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'odoc'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
def _print(self, _object, _attributes={}, **_arguments):
"""print: Print the specified object(s)
Required argument: Objects to print. Can be a list of files or an object specifier.
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
_subcode = 'pdoc'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
_argmap_save = {
'_in' : 'kfil',
'as' : 'fltp',
}
def save(self, _object, _attributes={}, **_arguments):
"""save: save a set of objects
Required argument: Objects to save.
Keyword argument _in: the file in which to save the object(s)
Keyword argument as: the file type of the document in which to save the data
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'core'
_subcode = 'save'
aetools.keysubst(_arguments, self._argmap_save)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
_argmap_set = {
'to' : 'data',
}
def set(self, _object, _attributes={}, **_arguments):
"""set: Set an objectÕs data
Required argument: the object to change
Keyword argument to: the new value
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'core'
_subcode = 'setd'
aetools.keysubst(_arguments, self._argmap_set)
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
class application(aetools.ComponentItem):
"""application - An application program"""
want = 'capp'
# element 'cwin' as ['indx', 'name', 'rele']
# element 'docu' as ['name']
class window(aetools.ComponentItem):
"""window - A Window"""
want = 'cwin'
class bounds(aetools.NProperty):
"""bounds - the boundary rectangle for the window"""
which = 'pbnd'
want = 'qdrt'
class closeable(aetools.NProperty):
"""closeable - Does the window have a close box?"""
which = 'hclb'
want = 'bool'
class titled(aetools.NProperty):
"""titled - Does the window have a title bar?"""
which = 'ptit'
want = 'bool'
class index(aetools.NProperty):
"""index - the number of the window"""
which = 'pidx'
want = 'long'
class floating(aetools.NProperty):
"""floating - Does the window float?"""
which = 'isfl'
want = 'bool'
class modal(aetools.NProperty):
"""modal - Is the window modal?"""
which = 'pmod'
want = 'bool'
class resizable(aetools.NProperty):
"""resizable - Is the window resizable?"""
which = 'prsz'
want = 'bool'
class zoomable(aetools.NProperty):
"""zoomable - Is the window zoomable?"""
which = 'iszm'
want = 'bool'
class zoomed(aetools.NProperty):
"""zoomed - Is the window zoomed?"""
which = 'pzum'
want = 'bool'
class name(aetools.NProperty):
"""name - the title of the window"""
which = 'pnam'
want = 'itxt'
class visible(aetools.NProperty):
"""visible - is the window visible?"""
which = 'pvis'
want = 'bool'
class position(aetools.NProperty):
"""position - upper left coordinates of window"""
which = 'ppos'
want = 'QDpt'
class document(aetools.ComponentItem):
"""document - A Document"""
want = 'docu'
# repeated property name the title of the document
class modified(aetools.NProperty):
"""modified - Has the document been modified since the last save?"""
which = 'imod'
want = 'bool'
application._propdict = {
}
application._elemdict = {
'window' : window,
'document' : document,
}
window._propdict = {
'bounds' : bounds,
'closeable' : closeable,
'titled' : titled,
'index' : index,
'floating' : floating,
'modal' : modal,
'resizable' : resizable,
'zoomable' : zoomable,
'zoomed' : zoomed,
'name' : name,
'visible' : visible,
'position' : position,
}
window._elemdict = {
}
document._propdict = {
'name' : name,
'modified' : modified,
}
document._elemdict = {
}
_Enum_savo = {
'yes' : 'yes ', # Save objects now
'no' : 'no ', # Do not save objects
'ask' : 'ask ', # Ask the user whether to save
}
#
# Indices of types declared in this module
#
_classdeclarations = {
'cwin' : window,
'docu' : document,
'capp' : application,
}
_propdeclarations = {
'ptit' : titled,
'pidx' : index,
'ppos' : position,
'pnam' : name,
'pbnd' : bounds,
'imod' : modified,
'isfl' : floating,
'hclb' : closeable,
'iszm' : zoomable,
'pmod' : modal,
'pzum' : zoomed,
'pvis' : visible,
'prsz' : resizable,
}
_compdeclarations = {
}
_enumdeclarations = {
'savo' : _Enum_savo,
}
"""Suite Miscellaneous Events: Useful events that arenÕt in any other suite
Level 1, version 1
Generated from Alpha:Desktop Folder:gnuplot.1:gnuplot 3.7.1a
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'misc'
class Miscellaneous_Events:
def revert(self, _object, _attributes={}, **_arguments):
"""revert: Revert an object to the most recently saved version
Required argument: object to revert
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'misc'
_subcode = 'rvrt'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
def do_script(self, _object=None, _attributes={}, **_arguments):
"""do script: execute a gnuplot script
Required argument: a gnuplot script
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'misc'
_subcode = 'dosc'
if _arguments: raise TypeError, 'No optional args expected'
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise aetools.Error, aetools.decodeerror(_arguments)
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
#
# Indices of types declared in this module
#
_classdeclarations = {
}
_propdeclarations = {
}
_compdeclarations = {
}
_enumdeclarations = {
}
| {
"repo_name": "pombredanne/ompc",
"path": "ompclib/gplot/gnuplot_Suites.py",
"copies": "1",
"size": "17586",
"license": "bsd-3-clause",
"hash": -3490043900599927000,
"line_mean": 28.1641791045,
"line_max": 96,
"alpha_frac": 0.599283521,
"autogenerated": false,
"ratio": 3.7665452987791816,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9822645848724403,
"avg_score": 0.00863659421095569,
"num_lines": 603
} |
"""A 2D graph widget."""
from pygame import K_PLUS, K_KP_PLUS, K_MINUS, K_KP_MINUS, K_DOWN, K_LEFT
from pygame import K_RIGHT, K_UP
from Diagram import Diagram
from ocempgui.draw import Draw
from Constants import *
import base
class Graph2D (Diagram):
"""Graph2D (width, height) -> Graph2D
A widget displaying graphs on a cartesian coordinate plane.
The Graph2D widget displays function graphs on a cartesian
coordinate plane using two axes.
The axes, scale units and units attributes must have at least two
values on assignment to fit both, the horizontal and vertical axes.
self.axes = 't', 'v' # Set velocity related to time.
self.set_axes ('x', 'y') # The default.
# seconds for the time axis, mph for the velocity axis.
self.scale_units = 's', 'mph'
self.set_scale_units ('-', '-') # The default.
# Each second has a distance of 10px to its neighbours and each mph
# has a distance of 25px to its neighbours.
self.units = 10, 25
self.set_units (10, 10) # The default.
Setting the 'orientation' attribute of the Graph2D widget to
ORIENTATION_VERTICAL will cause it to be rotated clockwise by 90
degrees.
The Graph2D can display the names of the axes and their scale units
next to the related axes. This can be adjusted using the
'show_names' attribute and set_show_names() method:
self.show_names = True # Show the names and scale units.
self.set_show_names (False) # Do not show them.
The axes and graph colors can be set to individual values (e.g. to
outline certain function behaviours) through the 'axis_color' and
'graph_color' attributes and their respective methods
set_axis_color() and set_graph_color().
self.axis_color = (0, 255, 0)
self.set_axiscolor ((255, 255, 0))
self.graph_color = (0, 255, 255)
self.set_graph_color (255, 0, 0)
The 'zoom_factor' attribute and set_zoom_factor() method set the zoom
factor for the graph. Values between 0 and 1 will zoom it out while
values greater than 1 will zoom it out.
Note: The zoom factor directly modifies the 'units' attribute values,
which can lead to rounding errors when using floating point zoom factors.
This usually results in a minor discrepancy, when you try to restore the
original values.
# Zoom the x axis out and the y axis in.
self.zoom_factor = 0.5, 2.0
# Zoom both axis in.
self.set_zoom_factor (3.0, 3.0)
Default action (invoked by activate()):
See the Diagram class.
Mnemonic action (invoked by activate_mnemonic()):
See the Diagram class.
Signals:
SIG_KEYDOWN - Invoked, when a key is pressed while the Graph2D has
the input.
SIG_MOUSEDOWN - Invoked, when a mouse button is pressed on the
Graph2D.
SIG_DOUBLECLICKED - Invoked, when a double-click was emitted on the
Graph2D.
Attributes:
show_names - Indicates, whether the axis names and scale units should
be shown or not.
axis_color - The color for both axes.
graph_color - The color for the displayed graph.
zoom_factor - The zoom factor values for both axes.
"""
def __init__ (self, width, height):
Diagram.__init__ (self)
# Some defaults.
self._zoom_factor = (1, 1)
self._units = (20, 20)
self._scaleunits = ("-", "-")
self._axes = ("x", "y")
self._shownames = True
# Colors.
self._axiscolor = (0, 0, 0)
self._graphcolor = (255, 0, 0)
# Signals.
self._signals[SIG_KEYDOWN] = []
self._signals[SIG_MOUSEDOWN] = []
self._signals[SIG_DOUBLECLICKED] = []
self.minsize = width, height
def get_scale_units (self):
"""G.get_scale_units (...) -> None
Gets the scale units of the axes.
"""
return self._scaleunits
def set_scale_units (self, units):
"""G.set_scale_units (...) -> None
Sets the scale units of the axes.
Raises a TypeError, if the passed argument is not a list or tuple.
Raises a ValueError, if the passed argument values are not strings.
"""
if type (units) not in (list, tuple):
raise TypeError ("units must be a list or tuple")
if len (units) < 2:
raise ValueError ("units must at least contains 2 values")
ov = filter (lambda x: type (x) not in (str, unicode), units)
if len (ov) != 0:
raise ValueError ("values in units must be strings or unicode")
self._scaleunits = units
self.dirty = True
def get_units (self):
"""G.set_units (...) -> None
Gets the pixels per unit for dimensioning.
"""
return self._units
def set_units (self, units):
"""G.set_units (...) -> None
Sets the pixels per unit for dimensioning.
Raises a TypeError, if the passed argument is not a list or tuple.
Raises a ValueError, if the passed argument values are not
integers greater than 0.
"""
if type (units) not in (list, tuple):
raise TypeError ("units must be a list or tuple")
if len (units) < 2:
raise ValueError ("units must at least contains 2 values")
ov = filter (lambda x: (type (x) != int) or (x <= 0), units)
if len (ov) != 0:
raise ValueError ("values in units must be positive integers")
self._units = units
self.dirty = True
def get_axes (self):
"""G.get_axes (...) -> None
Gets the amount and names of the axes.
"""
return self._axes
def set_axes (self, axes):
"""G.set_axes (...) -> None
Sets the amount and names of the axes.
Raises a TypeError, if the passed argument is not a list or tuple.
Raises a ValueError, if the passed argument values are not strings.
"""
if type (axes) not in (list, tuple):
raise TypeError ("axes must be a list or tuple")
if len (axes) < 2:
raise ValueError ("axes must at least contains 2 values")
ov = filter (lambda x: type (x) not in (str, unicode), axes)
if len (ov) != 0:
raise ValueError ("values in axes must be strings or unicode")
self._axes = axes
self.dirty = True
def set_show_names (self, var):
"""G.set_show_names (...) -> None
Sets, whether the axis names and scale units should be shown.
If set to True, the names and scale units of both axes will be
displayed besides and beneath the axes in the form 'name / unit'.
"""
self._shownames = var
self.dirty = True
def set_axis_color (self, var):
"""G.set_axis_color (...) -> None
Sets the color of the axes of the coordinate plane.
"""
self._graphcolor = var
self.dirty = True
def set_graph_color (self, var):
"""G.set_graph_color (...) -> None
Sets the color of the graph to draw.
"""
self._graphcolor = var
self.dirty = True
def set_data (self, data):
"""G.set_data (...) -> None
Sets the data to evaluate.
Raises a TypeError, if the passed argument is not a list or tuple.
Raises a ValueError, if the passed argument values are not
integers or floats.
"""
if data != None:
if type (data) not in (list, tuple):
raise TypeError ("data must be a list, tuple or array")
ov = filter (lambda x: type (x) not in (int, float), data)
if len (ov) != 0:
raise ValueError ("vales in data must be integers or float")
Diagram.set_data (self, data)
def set_zoom_factor (self, x, y):
"""G.set_zoom_factor (...) -> None
Zooms the graph in or out by modifying the pixel per units values.
Zooms the graph in or out by modifying the pixel per units
values. Passing 0 as zoom factor will reset the
Raises a TypeError, if the passed arguments are not floats or
integers.
Raises a ValueError, if the passed arguments are smaller than or
equal to 0.
"""
if (type (x) not in (float, int)) or (type (y) not in (float, int)):
raise TypeError ("x and y must floats or integers")
if (x <= 0) or (y <= 0):
raise ValueError ("x and y must be grater than 0")
ux, uy = 0, 0
oldx, oldy = self._zoom_factor
ux = max (1, int ((self._units[0] / oldx) * x))
uy = max (1, int ((self._units[1] / oldy) * y))
self._zoomfactor = (x, y)
if self.units != (ux, uy):
self.units = ux, uy
def zoom_in (self):
""" G.zoom_in () -> None
Zooms into the graph by factor 2.
"""
x, y = self.zoom_factor
self.set_zoom_factor (x * 2.0, y * 2.0)
def zoom_out (self):
"""G.zoom_out () -> None
Zoom out of the graph by factor 2.
"""
x, y = self.zoom_factor
x /= 2.0
y /= 2.0
if x == 0:
x = self.zoom_factor[0]
if y == 0:
y = self.zoom_factor[1]
self.set_zoom_factor (x, y)
def draw_bg (self):
"""G.draw_bg () -> Surface
Draws the Graph2D background surface and returns it.
Creates the visible background surface of the Graph2D and
returns it to the caller.
"""
return base.GlobalStyle.engine.draw_graph2d (self)
def notify (self, event):
"""G.notify (...) -> None
Notifies the Graph2D about an event.
"""
if not self.sensitive:
return
if event.signal in SIGNALS_MOUSE:
eventarea = self.rect_to_client ()
if (event.signal == SIG_MOUSEDOWN) and \
eventarea.collidepoint (event.data.pos):
if event.data.button == 1:
self.focus = True
# Mouse wheel.
elif event.data.button == 4:
self.zoom_out ()
elif event.data.button == 5:
self.zoom_in ()
self.run_signal_handlers (SIG_MOUSEDOWN, event.data)
event.handled = True
elif (event.signal == SIG_DOUBLECLICKED):
eventarea = self.rect_to_client ()
if eventarea.collidepoint (event.data.pos):
# The y origin starts at the bottom left, thus we have
# to invert the y value by using the height.
self.origin = event.data.pos[0] - eventarea.x, \
self.height - event.data.pos[1] + eventarea.y
self.run_signal_handlers (SIG_DOUBLECLICKED, event.data)
event.handled = True
elif self.focus and (event.signal == SIG_KEYDOWN):
# Zoom in and out.
if event.data.key in (K_PLUS, K_KP_PLUS):
self.zoom_in ()
event.handled = True
elif event.data.key in (K_MINUS, K_KP_MINUS):
self.zoom_out ()
event.handled = True
# Axis movement.
elif event.data.key == K_UP:
self.origin = (self.origin[0], self.origin[1] - 5)
event.handled = True
elif event.data.key == K_DOWN:
self.origin = (self.origin[0], self.origin[1] + 5)
event.handled = True
elif event.data.key == K_LEFT:
self.origin = (self.origin[0] + 5, self.origin[1])
event.handled = True
elif event.data.key == K_RIGHT:
self.origin = (self.origin[0] - 5, self.origin[1])
event.handled = True
Diagram.notify (self, event)
def _draw_axes (self, surface, rect, origin, unitx, unity):
"""G._draw_axes (...) -> None
Draws the coordinate axes on the surface.
"""
style = base.GlobalStyle
cls = self.__class__
if self.orientation == ORIENTATION_VERTICAL:
right = (origin[0], rect.bottom)
left = (origin[0], rect.top)
top = (rect.right, origin[1])
bottom = (rect.left, origin[1])
else:
left = (rect.left, origin[1])
right = (rect.right, origin[1])
top = (origin[0], rect.top)
bottom = (origin[0], rect.bottom)
start = None
end = None
scx = 1
scy = 1
# Draw both, positive and negative axes
if self.negative:
Draw.draw_line (surface, self._axiscolor, left, right, 1)
Draw.draw_line (surface, self._axiscolor, bottom, top, 1)
else:
Draw.draw_line (surface, self._axiscolor, origin, right, 1)
Draw.draw_line (surface, self._axiscolor, origin, top, 1)
# Axis names and units.
if self.show_names:
st = "%s / %s " % (self.axes[0], self.scale_units[0])
surface_x = style.engine.draw_string (st, self.state, cls,
self.style)
st = "%s / %s " % (self.axes[1], self.scale_units[1])
surface_y = style.engine.draw_string (st, self.state, cls,
self.style)
rect_sx = surface_x.get_rect()
rext_sy = surface_y.get_rect()
if self.orientation == ORIENTATION_VERTICAL:
surface.blit (surface_x,
(right[0] - 1 - 2 * scx - rect_sx.width,
right[1] - rect_sx.height))
surface.blit (surface_y, (top[0] - rect_sy.width,
top[1] + 1 + 2 * scy))
else:
surface.blit (surface_x, (right[0] - rect_sx.width,
right[1] + 1 + 2 * scx))
surface.blit (surface_y, (top[0] + 1 + 2 * scy, top[1]))
# Draw the scale unit marks.
# From the origin right and up
y = origin[1]
x = origin[0]
while y > rect.top:
start = (origin[0] - scy, y)
end = (origin[0] + scy, y)
Draw.draw_line (surface, self._axiscolor, start, end, 1)
y -= unity
while x < rect.right:
start = (x, origin[1] - scx)
end = (x, origin[1] + scx)
Draw.draw_line (surface, self._axiscolor, start, end, 1)
x += unitx
# From the origin down and left.
if self.negative:
y = origin[1]
while y < rect.bottom:
start = (origin[0] - scy, y)
end = (origin[0] + scy, y)
Draw.draw_line (surface, self._axiscolor, start, end, 1)
y += unity
x = origin[0]
while x > rect.left:
start = (x, origin[1] - scx)
end = (x, origin[1] + scx)
Draw.draw_line (surface, self._axiscolor, start, end, 1)
x -= unitx
def draw (self):
"""W.draw () -> None
Draws the Graph2D surface.
Creates the visible surface of the Graph2D.
"""
Diagram.draw (self)
surface = self.image
rect = surface.get_rect ()
# Orientation swapped?
swap = self.orientation == ORIENTATION_VERTICAL
# Coordinates.
origin = (rect.left + self.origin[0],
rect.bottom - self.origin[1] - 1)
unitx = 1.0
unity = 1.0
if self.units and (len (self.units) > 1):
if self.orientation == ORIENTATION_VERTICAL:
unitx = self.units[1]
unity = self.units[0]
else:
unitx = self.units[0]
unity = self.units[1]
self._draw_axes (surface, rect, origin, unitx, unity)
data = self.data
values = self.values
if data and values:
# Filter negative values.
if not self.negative:
data = filter (lambda x: x >= 0, data)
values = filter (lambda y: y >= 0, values)
# Create the coordinate tuples and take the unit resolution into
# account.
coords = []
org0 = origin[0]
org1 = origin[1]
if self.orientation == ORIENTATION_VERTICAL:
coords = map (lambda x, y: (int (org1 + (x * unitx)),
int (org0 + (y * unity))),
data, values)
else:
coords = map (lambda x, y: (int (org0 + (x * unitx)),
int (org1 - (y * unity))),
data, values)
# Filter non-visible values.
width = self.width
height = self.height
coords = filter (lambda (x, y): (0 < x < width) and \
(0 < y < width), coords)
# Draw them.
color = self.graph_color
setat = surface.set_at
for xy in coords:
setat (xy, color)
show_names = property (lambda self: self._shownames,
lambda self, var: self.set_show_names (var),
doc = "Indicates, whether the axis names should " \
"be shown.")
axis_color = property (lambda self: self._axiscolor,
lambda self, var: self.set_axis_color (var),
doc = "The color of the axes.")
graph_color = property (lambda self: self._graphcolor,
lambda self, var: self.set_graph_color (var),
doc = "The color of the graph.")
zoom_factor = property (lambda self: self._zoom_factor,
lambda self, (x, y): self.set_zoom_factory (x, y),
doc = "Zoom factor for the axes.")
| {
"repo_name": "prim/ocempgui",
"path": "ocempgui/widgets/Graph2D.py",
"copies": "1",
"size": "19747",
"license": "bsd-2-clause",
"hash": 1048160916091232300,
"line_mean": 35.7728119181,
"line_max": 78,
"alpha_frac": 0.5433230364,
"autogenerated": false,
"ratio": 4.031645569620253,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5074968606020254,
"avg_score": null,
"num_lines": null
} |
# $Id: gre.py 30 2007-01-27 03:10:09Z dugsong $
"""Generic Routing Encapsulation."""
import struct
import dpkt
GRE_CP = 0x8000 # Checksum Present
GRE_RP = 0x4000 # Routing Present
GRE_KP = 0x2000 # Key Present
GRE_SP = 0x1000 # Sequence Present
GRE_SS = 0x0800 # Strict Source Route
GRE_AP = 0x0080 # Acknowledgment Present
GRE_opt_fields = (
(GRE_CP|GRE_RP, 'sum', 'H'), (GRE_CP|GRE_RP, 'off', 'H'),
(GRE_KP, 'key', 'I'), (GRE_SP, 'seq', 'I'), (GRE_AP, 'ack', 'I')
)
class GRE(dpkt.Packet):
__hdr__ = (
('flags', 'H', 0),
('p', 'H', 0x0800), # ETH_TYPE_IP
)
_protosw = {}
sre = ()
def get_v(self):
return self.flags & 0x7
def set_v(self, v):
self.flags = (self.flags & ~0x7) | (v & 0x7)
v = property(get_v, set_v)
def get_recur(self):
return (self.flags >> 5) & 0x7
def set_recur(self, v):
self.flags = (self.flags & ~0xe0) | ((v & 0x7) << 5)
recur = property(get_recur, set_recur)
class SRE(dpkt.Packet):
__hdr__ = [
('family', 'H', 0),
('off', 'B', 0),
('len', 'B', 0)
]
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.data[:self.len]
def opt_fields_fmts(self):
if self.v == 0:
fields, fmts = [], []
opt_fields = GRE_opt_fields
else:
fields, fmts = [ 'len', 'callid' ], [ 'H', 'H' ]
opt_fields = GRE_opt_fields[-2:]
for flags, field, fmt in opt_fields:
if self.flags & flags:
fields.append(field)
fmts.append(fmt)
return fields, fmts
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
fields, fmts = self.opt_fields_fmts()
if fields:
fmt = ''.join(fmts)
fmtlen = struct.calcsize(fmt)
vals = struct.unpack(fmt, self.data[:fmtlen])
self.data = self.data[fmtlen:]
self.__dict__.update(dict(zip(fields, vals)))
if self.flags & GRE_RP:
l = []
while True:
sre = self.SRE(self.data)
l.append(sre)
if not sre.len:
break
self.sre = l
skip = sum(map(len, self.sre))
self.data = self.data[skip:]
self.data = ethernet.Ethernet._typesw[self.p](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
def __len__(self):
opt_fmtlen = struct.calcsize(''.join(self.opt_fields_fmts()[1]))
return self.__hdr_len__ + opt_fmtlen + \
sum(map(len, self.sre)) + len(self.data)
# XXX - need to fix up repr to display optional fields...
def __str__(self):
fields, fmts = self.opt_fields_fmts()
if fields:
vals = []
for f in fields:
vals.append(getattr(self, f))
opt_s = struct.pack(''.join(fmts), *vals)
else:
opt_s = ''
return self.pack_hdr() + opt_s + ''.join(map(str, self.sre)) + \
str(self.data)
# XXX - auto-load GRE dispatch table from Ethernet dispatch table
import ethernet
GRE._protosw.update(ethernet.Ethernet._typesw)
| {
"repo_name": "dragondjf/QMarkdowner",
"path": "dpkt/gre.py",
"copies": "9",
"size": "3301",
"license": "mit",
"hash": 3660970651881698000,
"line_mean": 30.7403846154,
"line_max": 72,
"alpha_frac": 0.5025749773,
"autogenerated": false,
"ratio": 3.186293436293436,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8188868413593436,
"avg_score": null,
"num_lines": null
} |
# $Id: gre.py 342 2006-01-29 14:38:19Z dugsong $
"""Generic Routing Encapsulation."""
import struct
import dpkt
GRE_CP = 0x8000 # Checksum Present
GRE_RP = 0x4000 # Routing Present
GRE_KP = 0x2000 # Key Present
GRE_SP = 0x1000 # Sequence Present
GRE_SS = 0x0800 # Strict Source Route
GRE_AP = 0x0080 # Acknowledgment Present
GRE_opt_fields = (
(GRE_CP|GRE_RP, 'sum', 'H'), (GRE_CP|GRE_RP, 'off', 'H'),
(GRE_KP, 'key', 'I'), (GRE_SP, 'seq', 'I'), (GRE_AP, 'ack', 'I')
)
class GRE(dpkt.Packet):
__hdr__ = (
('flags', 'H', 0),
('p', 'H', 0x0800), # ETH_TYPE_IP
)
_protosw = {}
sre = ()
def get_v(self):
return self.flags & 0x7
def set_v(self, v):
self.flags = (self.flags & ~0x7) | (v & 0x7)
v = property(get_v, set_v)
def get_recur(self):
return (self.flags >> 5) & 0x7
def set_recur(self, v):
self.flags = (self.flags & ~0xe0) | ((v & 0x7) << 5)
recur = property(get_recur, set_recur)
class SRE(dpkt.Packet):
__hdr__ = [
('family', 'H', 0),
('off', 'B', 0),
('len', 'B', 0)
]
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.data[:self.len]
def opt_fields_fmts(self):
if self.v == 0:
fields, fmts = [], []
opt_fields = GRE_opt_fields
else:
fields, fmts = [ 'len', 'callid' ], [ 'H', 'H' ]
opt_fields = GRE_opt_fields[-2:]
for flags, field, fmt in opt_fields:
if self.flags & flags:
fields.append(field)
fmts.append(fmt)
return fields, fmts
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
fields, fmts = self.opt_fields_fmts()
if fields:
fmt = ''.join(fmts)
fmtlen = struct.calcsize(fmt)
vals = struct.unpack(fmt, self.data[:fmtlen])
self.data = self.data[fmtlen:]
self.__dict__.update(dict(zip(fields, vals)))
if self.flags & GRE_RP:
l = []
while True:
sre = SRE(self.data)
l.append(sre)
if not sre.len:
break
self.sre = l
skip = sum(map(len, self.sre))
self.data = self.data[skip:]
self.data = ethernet.Ethernet._typesw[self.p](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
def __len__(self):
opt_fmtlen = struct.calcsize(''.join(self.opt_fields_fmts()[1]))
return self.__hdr_len__ + opt_fmtlen + \
sum(map(len, self.sre)) + len(self.data)
# XXX - need to fix up repr to display optional fields...
def __str__(self):
fields, fmts = self.opt_fields_fmts()
if fields:
vals = []
for f in fields:
vals.append(getattr(self, f))
opt_s = struct.pack(''.join(fmts), *vals)
else:
opt_s = ''
return self.pack_hdr() + opt_s + ''.join(map(str, self.sre)) + \
str(self.data)
# XXX - auto-load GRE dispatch table from Ethernet dispatch table
import ethernet
GRE._protosw.update(ethernet.Ethernet._typesw)
| {
"repo_name": "MercenaryLogic/StompingGround",
"path": "stompingground/dpkt/gre.py",
"copies": "1",
"size": "3297",
"license": "mit",
"hash": 2037120370143332000,
"line_mean": 30.7019230769,
"line_max": 72,
"alpha_frac": 0.5022747953,
"autogenerated": false,
"ratio": 3.1885880077369437,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4190862803036944,
"avg_score": null,
"num_lines": null
} |
# $Id: gre.py 75 2010-08-03 14:42:19Z jon.oberheide $
# -*- coding: utf-8 -*-
"""Generic Routing Encapsulation."""
from __future__ import absolute_import
import struct
import codecs
from . import dpkt
from . import ethernet
from .decorators import deprecated
from .compat import compat_izip
GRE_CP = 0x8000 # Checksum Present
GRE_RP = 0x4000 # Routing Present
GRE_KP = 0x2000 # Key Present
GRE_SP = 0x1000 # Sequence Present
GRE_SS = 0x0800 # Strict Source Route
GRE_AP = 0x0080 # Acknowledgment Present
GRE_opt_fields = (
(GRE_CP | GRE_RP, 'sum', 'H'), (GRE_CP | GRE_RP, 'off', 'H'),
(GRE_KP, 'key', 'I'), (GRE_SP, 'seq', 'I'), (GRE_AP, 'ack', 'I')
)
class GRE(dpkt.Packet):
"""Generic Routing Encapsulation.
TODO: Longer class information....
Attributes:
__hdr__: Header fields of GRE.
TODO.
"""
__hdr__ = (
('flags', 'H', 0),
('p', 'H', 0x0800), # ETH_TYPE_IP
)
sre = ()
@property
def v(self):
return self.flags & 0x7
@v.setter
def v(self, v):
self.flags = (self.flags & ~0x7) | (v & 0x7)
@property
def recur(self):
return (self.flags >> 5) & 0x7
@recur.setter
def recur(self, v):
self.flags = (self.flags & ~0xe0) | ((v & 0x7) << 5)
class SRE(dpkt.Packet):
__hdr__ = [
('family', 'H', 0),
('off', 'B', 0),
('len', 'B', 0)
]
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.data[:self.len]
def opt_fields_fmts(self):
if self.v == 0:
fields, fmts = [], []
opt_fields = GRE_opt_fields
else:
fields, fmts = ['len', 'callid'], ['H', 'H']
opt_fields = GRE_opt_fields[-2:]
for flags, field, fmt in opt_fields:
if self.flags & flags:
fields.append(field)
fmts.append(fmt)
return fields, fmts
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
fields, fmts = self.opt_fields_fmts()
if fields:
fmt = ''.join(fmts)
fmtlen = struct.calcsize(fmt)
vals = struct.unpack("!" + fmt, self.data[:fmtlen])
self.data = self.data[fmtlen:]
self.__dict__.update(dict(compat_izip(fields, vals)))
if self.flags & GRE_RP:
l = []
while True:
sre = self.SRE(self.data)
self.data = self.data[len(sre):]
l.append(sre)
if not sre.len:
break
self.sre = l
try:
self.data = ethernet.Ethernet._typesw[self.p](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
except (KeyError, dpkt.UnpackError):
# data alrady set
pass
def __len__(self):
opt_fmtlen = struct.calcsize(''.join(self.opt_fields_fmts()[1]))
return self.__hdr_len__ + opt_fmtlen + sum(map(len, self.sre)) + len(self.data)
def __bytes__(self):
fields, fmts = self.opt_fields_fmts()
if fields:
vals = []
for f in fields:
vals.append(getattr(self, f))
opt_s = struct.pack(b''.join(fmts), *vals)
else:
opt_s = b''
return self.pack_hdr() + opt_s + b''.join(map(bytes, self.sre)) + bytes(self.data)
def test_gre_v1():
# Runs all the test associated with this class/file
s = codecs.decode("3081880a0067178000068fb100083a76", 'hex') + b"A" * 103
g = GRE(s)
assert g.v == 1
assert g.p == 0x880a
assert g.seq == 430001
assert g.ack == 539254
assert g.callid == 6016
assert g.len == 103
assert g.data == b"A" * 103
assert len(g) == len(s)
s = codecs.decode("3001880a00b2001100083ab8", 'hex') + b"A" * 178
g = GRE(s)
assert g.v == 1
assert g.p == 0x880a
assert g.seq == 539320
assert g.callid == 17
assert g.len == 178
assert g.data == b"A" * 178
assert len(g) == len(s)
def test_gre_len():
gre = GRE()
assert len(gre) == 4
if __name__ == '__main__':
test_gre_v1()
test_gre_len()
| {
"repo_name": "dimagol/trex-core",
"path": "scripts/external_libs/dpkt-1.9.1/dpkt/gre.py",
"copies": "2",
"size": "4221",
"license": "apache-2.0",
"hash": -3013198510865745000,
"line_mean": 26.2322580645,
"line_max": 90,
"alpha_frac": 0.5178867567,
"autogenerated": false,
"ratio": 3.1313056379821957,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9643965902316485,
"avg_score": 0.001045298473142276,
"num_lines": 155
} |
# $Id: gre.py 75 2010-08-03 14:42:19Z jon.oberheide $
# -*- coding: utf-8 -*-
"""Generic Routing Encapsulation."""
import struct
import dpkt
from decorators import deprecated
GRE_CP = 0x8000 # Checksum Present
GRE_RP = 0x4000 # Routing Present
GRE_KP = 0x2000 # Key Present
GRE_SP = 0x1000 # Sequence Present
GRE_SS = 0x0800 # Strict Source Route
GRE_AP = 0x0080 # Acknowledgment Present
GRE_opt_fields = (
(GRE_CP | GRE_RP, 'sum', 'H'), (GRE_CP | GRE_RP, 'off', 'H'),
(GRE_KP, 'key', 'I'), (GRE_SP, 'seq', 'I'), (GRE_AP, 'ack', 'I')
)
class GRE(dpkt.Packet):
__hdr__ = (
('flags', 'H', 0),
('p', 'H', 0x0800), # ETH_TYPE_IP
)
_protosw = {}
sre = ()
@property
def v(self):
return self.flags & 0x7
@v.setter
def v(self, v):
self.flags = (self.flags & ~0x7) | (v & 0x7)
@property
def recur(self):
return (self.flags >> 5) & 0x7
@recur.setter
def recur(self, v):
self.flags = (self.flags & ~0xe0) | ((v & 0x7) << 5)
# Deprecated methods, will be removed in the future
# =================================================
@deprecated('v')
def get_v(self): return self.v
@deprecated('v')
def set_v(self, v): self.v = v
@deprecated('recur')
def get_recur(self): return self.recur
@deprecated('recur')
def set_recur(self, v): self.recur = v
# =================================================
class SRE(dpkt.Packet):
__hdr__ = [
('family', 'H', 0),
('off', 'B', 0),
('len', 'B', 0)
]
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.data[:self.len]
def opt_fields_fmts(self):
if self.v == 0:
fields, fmts = [], []
opt_fields = GRE_opt_fields
else:
fields, fmts = ['len', 'callid'], ['H', 'H']
opt_fields = GRE_opt_fields[-2:]
for flags, field, fmt in opt_fields:
if self.flags & flags:
fields.append(field)
fmts.append(fmt)
return fields, fmts
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
fields, fmts = self.opt_fields_fmts()
if fields:
fmt = ''.join(fmts)
fmtlen = struct.calcsize(fmt)
vals = struct.unpack(fmt, self.data[:fmtlen])
self.data = self.data[fmtlen:]
self.__dict__.update(dict(zip(fields, vals)))
if self.flags & GRE_RP:
l = []
while True:
sre = self.SRE(self.data)
self.data = self.data[len(sre):]
l.append(sre)
if not sre.len:
break
self.sre = l
self.data = ethernet.Ethernet._typesw[self.p](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
def __len__(self):
opt_fmtlen = struct.calcsize(''.join(self.opt_fields_fmts()[1]))
return self.__hdr_len__ + opt_fmtlen + sum(map(len, self.sre)) + len(self.data)
def __str__(self):
fields, fmts = self.opt_fields_fmts()
if fields:
vals = []
for f in fields:
vals.append(getattr(self, f))
opt_s = struct.pack(''.join(fmts), *vals)
else:
opt_s = ''
return self.pack_hdr() + opt_s + ''.join(map(str, self.sre)) + str(self.data)
# XXX - auto-load GRE dispatch table from Ethernet dispatch table
import ethernet
GRE._protosw.update(ethernet.Ethernet._typesw)
| {
"repo_name": "bpanneton/dpkt",
"path": "dpkt/gre.py",
"copies": "6",
"size": "3602",
"license": "bsd-3-clause",
"hash": 6174110543643454000,
"line_mean": 28.0483870968,
"line_max": 87,
"alpha_frac": 0.5024986119,
"autogenerated": false,
"ratio": 3.2775250227479527,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0016179284055463628,
"num_lines": 124
} |
# $Id: gre.py 75 2010-08-03 14:42:19Z jon.oberheide $
"""Generic Routing Encapsulation."""
import struct
import dpkt
GRE_CP = 0x8000 # Checksum Present
GRE_RP = 0x4000 # Routing Present
GRE_KP = 0x2000 # Key Present
GRE_SP = 0x1000 # Sequence Present
GRE_SS = 0x0800 # Strict Source Route
GRE_AP = 0x0080 # Acknowledgment Present
GRE_opt_fields = (
(GRE_CP|GRE_RP, 'sum', 'H'), (GRE_CP|GRE_RP, 'off', 'H'),
(GRE_KP, 'key', 'I'), (GRE_SP, 'seq', 'I'), (GRE_AP, 'ack', 'I')
)
class GRE(dpkt.Packet):
__hdr__ = (
('flags', 'H', 0),
('p', 'H', 0x0800), # ETH_TYPE_IP
)
_protosw = {}
sre = ()
def get_v(self):
return self.flags & 0x7
def set_v(self, v):
self.flags = (self.flags & ~0x7) | (v & 0x7)
v = property(get_v, set_v)
def get_recur(self):
return (self.flags >> 5) & 0x7
def set_recur(self, v):
self.flags = (self.flags & ~0xe0) | ((v & 0x7) << 5)
recur = property(get_recur, set_recur)
class SRE(dpkt.Packet):
__hdr__ = [
('family', 'H', 0),
('off', 'B', 0),
('len', 'B', 0)
]
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.data[:self.len]
def opt_fields_fmts(self):
if self.v == 0:
fields, fmts = [], []
opt_fields = GRE_opt_fields
else:
fields, fmts = [ 'len', 'callid' ], [ 'H', 'H' ]
opt_fields = GRE_opt_fields[-2:]
for flags, field, fmt in opt_fields:
if self.flags & flags:
fields.append(field)
fmts.append(fmt)
return fields, fmts
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
fields, fmts = self.opt_fields_fmts()
if fields:
fmt = ''.join(fmts)
fmtlen = struct.calcsize(fmt)
vals = struct.unpack(fmt, self.data[:fmtlen])
self.data = self.data[fmtlen:]
self.__dict__.update(dict(zip(fields, vals)))
if self.flags & GRE_RP:
l = []
while True:
sre = self.SRE(self.data)
self.data = self.data[len(sre):]
l.append(sre)
if not sre.len:
break
self.sre = l
self.data = ethernet.Ethernet._typesw[self.p](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
def __len__(self):
opt_fmtlen = struct.calcsize(''.join(self.opt_fields_fmts()[1]))
return self.__hdr_len__ + opt_fmtlen + \
sum(map(len, self.sre)) + len(self.data)
# XXX - need to fix up repr to display optional fields...
def __str__(self):
fields, fmts = self.opt_fields_fmts()
if fields:
vals = []
for f in fields:
vals.append(getattr(self, f))
opt_s = struct.pack(''.join(fmts), *vals)
else:
opt_s = ''
return self.pack_hdr() + opt_s + ''.join(map(str, self.sre)) + \
str(self.data)
# XXX - auto-load GRE dispatch table from Ethernet dispatch table
import ethernet
GRE._protosw.update(ethernet.Ethernet._typesw)
| {
"repo_name": "wofanli/trex-core",
"path": "scripts/external_libs/dpkt-1.8.6/dpkt/gre.py",
"copies": "6",
"size": "3272",
"license": "apache-2.0",
"hash": 6212465201164140000,
"line_mean": 30.7669902913,
"line_max": 72,
"alpha_frac": 0.5030562347,
"autogenerated": false,
"ratio": 3.1828793774319064,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6685935612131907,
"avg_score": null,
"num_lines": null
} |
__doc__ = """hashlib module - A common interface to many hash functions.
new(name, string='') - returns a new hash object implementing the
given hash function; initializing the hash
using the given string data.
Named constructor functions are also available, these are much faster
than using new():
md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
More algorithms may be available on your platform but the above are
guaranteed to exist.
Choose your hash function wisely. Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.
Hash objects have these methods:
- update(arg): Update the hash object with the string arg. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments.
- digest(): Return the digest of the strings passed to the update() method
so far. This may contain non-ASCII characters, including
NUL bytes.
- hexdigest(): Like digest() except the digest is returned as a string of
double length, containing only hexadecimal digits.
- copy(): Return a copy (clone) of the hash object. This can be used to
efficiently compute the digests of strings that share a common
initial substring.
For example, to obtain the digest of the string 'Nobody inspects the
spammish repetition':
>>> import hashlib
>>> m = hashlib.md5()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
More condensed:
>>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
"""
def __get_builtin_constructor(name):
if name in ('SHA1', 'sha1'):
import _sha
return _sha.new
elif name in ('MD5', 'md5'):
import _md5
return _md5.new
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
import _sha256
bs = name[3:]
if bs == '256':
return _sha256.sha256
elif bs == '224':
return _sha256.sha224
elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
import _sha512
bs = name[3:]
if bs == '512':
return _sha512.sha512
elif bs == '384':
return _sha512.sha384
raise ValueError, "unsupported hash type"
def __py_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
return __get_builtin_constructor(name)(string)
def __hash_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
try:
return _hashlib.new(name, string)
except ValueError:
# If the _hashlib module (OpenSSL) doesn't support the named
# hash, try using our builtin implementations.
# This allows for SHA224/256 and SHA384/512 support even though
# the OpenSSL library prior to 0.9.8 doesn't provide them.
return __get_builtin_constructor(name)(string)
try:
import _hashlib
# use the wrapper of the C implementation
new = __hash_new
for opensslFuncName in filter(lambda n: n.startswith('openssl_'), dir(_hashlib)):
funcName = opensslFuncName[len('openssl_'):]
try:
# try them all, some may not work due to the OpenSSL
# version not supporting that algorithm.
f = getattr(_hashlib, opensslFuncName)
f()
# Use the C function directly (very fast)
exec funcName + ' = f'
except ValueError:
try:
# Use the builtin implementation directly (fast)
exec funcName + ' = __get_builtin_constructor(funcName)'
except ValueError:
# this one has no builtin implementation, don't define it
pass
# clean up our locals
del f
del opensslFuncName
del funcName
except ImportError:
# We don't have the _hashlib OpenSSL module?
# use the built in legacy interfaces via a wrapper function
new = __py_new
# lookup the C function to use directly for the named constructors
md5 = __get_builtin_constructor('md5')
sha1 = __get_builtin_constructor('sha1')
sha224 = __get_builtin_constructor('sha224')
sha256 = __get_builtin_constructor('sha256')
sha384 = __get_builtin_constructor('sha384')
sha512 = __get_builtin_constructor('sha512')
| {
"repo_name": "TathagataChakraborti/resource-conflicts",
"path": "PLANROB-2015/seq-sat-lama/py2.5/lib/python2.5/hashlib.py",
"copies": "3",
"size": "4887",
"license": "mit",
"hash": 6282126345387432000,
"line_mean": 34.4130434783,
"line_max": 85,
"alpha_frac": 0.6320851238,
"autogenerated": false,
"ratio": 3.979641693811075,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00041229310997270053,
"num_lines": 138
} |
__doc__ = """hashlib module - A common interface to many hash functions.
new(name, string='') - returns a new hash object implementing the
given hash function; initializing the hash
using the given string data.
Named constructor functions are also available, these are much faster
than using new():
md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
More algorithms may be available on your platform but the above are
guaranteed to exist.
Choose your hash function wisely. Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.
Hash objects have these methods:
- update(arg): Update the hash object with the string arg. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments.
- digest(): Return the digest of the strings passed to the update() method
so far. This may contain non-ASCII characters, including
NUL bytes.
- hexdigest(): Like digest() except the digest is returned as a string of
double length, containing only hexadecimal digits.
- copy(): Return a copy (clone) of the hash object. This can be used to
efficiently compute the digests of strings that share a common
initial substring.
For example, to obtain the digest of the string 'Nobody inspects the
spammish repetition':
>>> import hashlib
>>> m = hashlib.md5()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
More condensed:
>>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
"""
def __get_builtin_constructor(name):
if name in ('SHA1', 'sha1'):
import _sha
return _sha.new
elif name in ('MD5', 'md5'):
import _md5
return _md5.new
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
import _sha256
bs = name[3:]
if bs == '256':
return _sha256.sha256
elif bs == '224':
return _sha256.sha224
elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
import _sha512
bs = name[3:]
if bs == '512':
return _sha512.sha512
elif bs == '384':
return _sha512.sha384
raise ValueError, "unsupported hash type"
def __py_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
return __get_builtin_constructor(name)(string)
def __hash_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
try:
return _hashlib.new(name, string)
except ValueError:
# If the _hashlib module (OpenSSL) doesn't support the named
# hash, try using our builtin implementations.
# This allows for SHA224/256 and SHA384/512 support even though
# the OpenSSL library prior to 0.9.8 doesn't provide them.
return __get_builtin_constructor(name)(string)
try:
import _hashlib
# use the wrapper of the C implementation
new = __hash_new
for opensslFuncName in filter(lambda n: n.startswith('openssl_'), dir(_hashlib)):
funcName = opensslFuncName[len('openssl_'):]
try:
# try them all, some may not work due to the OpenSSL
# version not supporting that algorithm.
f = getattr(_hashlib, opensslFuncName)
f()
# Use the C function directly (very fast)
exec funcName + ' = f'
except ValueError:
try:
# Use the builtin implementation directly (fast)
exec funcName + ' = __get_builtin_constructor(funcName)'
except ValueError:
# this one has no builtin implementation, don't define it
pass
# clean up our locals
del f
del opensslFuncName
del funcName
except ImportError:
# We don't have the _hashlib OpenSSL module?
# use the built in legacy interfaces via a wrapper function
new = __py_new
# lookup the C function to use directly for the named constructors
md5 = __get_builtin_constructor('md5')
sha1 = __get_builtin_constructor('sha1')
sha224 = __get_builtin_constructor('sha224')
sha256 = __get_builtin_constructor('sha256')
sha384 = __get_builtin_constructor('sha384')
sha512 = __get_builtin_constructor('sha512')
| {
"repo_name": "ericlink/adms-server",
"path": "playframework-dist/1.1-src/python/Lib/hashlib.py",
"copies": "2",
"size": "5025",
"license": "mit",
"hash": -3396790429005478000,
"line_mean": 34.4130434783,
"line_max": 85,
"alpha_frac": 0.6147263682,
"autogenerated": false,
"ratio": 4.058966074313409,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00040599030849081477,
"num_lines": 138
} |
__doc__ = """hashlib module - A common interface to many hash functions.
new(name, string='') - returns a new hash object implementing the
given hash function; initializing the hash
using the given string data.
Named constructor functions are also available, these are much faster
than using new():
md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
More algorithms may be available on your platform but the above are
guaranteed to exist.
NOTE: If you want the adler32 or crc32 hash functions they are available in
the zlib module.
Choose your hash function wisely. Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.
Hash objects have these methods:
- update(arg): Update the hash object with the string arg. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments.
- digest(): Return the digest of the strings passed to the update() method
so far. This may contain non-ASCII characters, including
NUL bytes.
- hexdigest(): Like digest() except the digest is returned as a string of
double length, containing only hexadecimal digits.
- copy(): Return a copy (clone) of the hash object. This can be used to
efficiently compute the digests of strings that share a common
initial substring.
For example, to obtain the digest of the string 'Nobody inspects the
spammish repetition':
>>> import hashlib
>>> m = hashlib.md5()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
More condensed:
>>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
"""
def __get_builtin_constructor(name):
if name in ('SHA1', 'sha1'):
import _sha
return _sha.new
elif name in ('MD5', 'md5'):
import _md5
return _md5.new
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
import _sha256
bs = name[3:]
if bs == '256':
return _sha256.sha256
elif bs == '224':
return _sha256.sha224
elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
import _sha512
bs = name[3:]
if bs == '512':
return _sha512.sha512
elif bs == '384':
return _sha512.sha384
raise ValueError, "unsupported hash type"
def __py_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
return __get_builtin_constructor(name)(string)
def __hash_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
try:
return _hashlib.new(name, string)
except ValueError:
# If the _hashlib module (OpenSSL) doesn't support the named
# hash, try using our builtin implementations.
# This allows for SHA224/256 and SHA384/512 support even though
# the OpenSSL library prior to 0.9.8 doesn't provide them.
return __get_builtin_constructor(name)(string)
try:
import _hashlib
# use the wrapper of the C implementation
new = __hash_new
for opensslFuncName in filter(lambda n: n.startswith('openssl_'), dir(_hashlib)):
funcName = opensslFuncName[len('openssl_'):]
try:
# try them all, some may not work due to the OpenSSL
# version not supporting that algorithm.
f = getattr(_hashlib, opensslFuncName)
f()
# Use the C function directly (very fast)
exec funcName + ' = f'
except ValueError:
try:
# Use the builtin implementation directly (fast)
exec funcName + ' = __get_builtin_constructor(funcName)'
except ValueError:
# this one has no builtin implementation, don't define it
pass
# clean up our locals
del f
del opensslFuncName
del funcName
except ImportError:
# We don't have the _hashlib OpenSSL module?
# use the built in legacy interfaces via a wrapper function
new = __py_new
# lookup the C function to use directly for the named constructors
md5 = __get_builtin_constructor('md5')
sha1 = __get_builtin_constructor('sha1')
sha224 = __get_builtin_constructor('sha224')
sha256 = __get_builtin_constructor('sha256')
sha384 = __get_builtin_constructor('sha384')
sha512 = __get_builtin_constructor('sha512')
| {
"repo_name": "jeremiahmarks/sl4a",
"path": "python/src/Lib/hashlib.py",
"copies": "95",
"size": "4993",
"license": "apache-2.0",
"hash": 8561263829787504000,
"line_mean": 34.4113475177,
"line_max": 85,
"alpha_frac": 0.6326857601,
"autogenerated": false,
"ratio": 3.981658692185008,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
__doc__ = """hashlib module - A common interface to many hash functions.
new(name, data=b'') - returns a new hash object implementing the
given hash function; initializing the hash
using the given binary data.
Named constructor functions are also available, these are faster
than using new(name):
md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
More algorithms may be available on your platform but the above are
guaranteed to exist.
NOTE: If you want the adler32 or crc32 hash functions they are available in
the zlib module.
Choose your hash function wisely. Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.
Hash objects have these methods:
- update(arg): Update the hash object with the bytes in arg. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments.
- digest(): Return the digest of the bytes passed to the update() method
so far.
- hexdigest(): Like digest() except the digest is returned as a unicode
object of double length, containing only hexadecimal digits.
- copy(): Return a copy (clone) of the hash object. This can be used to
efficiently compute the digests of strings that share a common
initial substring.
For example, to obtain the digest of the string 'Nobody inspects the
spammish repetition':
>>> import hashlib
>>> m = hashlib.md5()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
More condensed:
>>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
"""
def __get_builtin_constructor(name):
if name in ('SHA1', 'sha1'):
import _sha1
return _sha1.sha1
elif name in ('MD5', 'md5'):
import _md5
return _md5.md5
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
import _sha256
bs = name[3:]
if bs == '256':
return _sha256.sha256
elif bs == '224':
return _sha256.sha224
elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
import _sha512
bs = name[3:]
if bs == '512':
return _sha512.sha512
elif bs == '384':
return _sha512.sha384
raise ValueError("unsupported hash type")
def __py_new(name, data=b''):
"""new(name, data=b'') - Return a new hashing object using the named algorithm;
optionally initialized with data (which must be bytes).
"""
return __get_builtin_constructor(name)(data)
def __hash_new(name, data=b''):
"""new(name, data=b'') - Return a new hashing object using the named algorithm;
optionally initialized with data (which must be bytes).
"""
try:
return _hashlib.new(name, data)
except ValueError:
# If the _hashlib module (OpenSSL) doesn't support the named
# hash, try using our builtin implementations.
# This allows for SHA224/256 and SHA384/512 support even though
# the OpenSSL library prior to 0.9.8 doesn't provide them.
return __get_builtin_constructor(name)(data)
try:
import _hashlib
# use the wrapper of the C implementation
new = __hash_new
for opensslFuncName in filter(lambda n: n.startswith('openssl_'), dir(_hashlib)):
funcName = opensslFuncName[len('openssl_'):]
try:
# try them all, some may not work due to the OpenSSL
# version not supporting that algorithm.
f = getattr(_hashlib, opensslFuncName)
f()
# Use the C function directly (very fast)
exec(funcName + ' = f')
except ValueError:
try:
# Use the builtin implementation directly (fast)
exec(funcName + ' = __get_builtin_constructor(funcName)')
except ValueError:
# this one has no builtin implementation, don't define it
pass
# clean up our locals
del f
del opensslFuncName
del funcName
except ImportError:
# We don't have the _hashlib OpenSSL module?
# use the built in legacy interfaces via a wrapper function
new = __py_new
# lookup the C function to use directly for the named constructors
md5 = __get_builtin_constructor('md5')
sha1 = __get_builtin_constructor('sha1')
sha224 = __get_builtin_constructor('sha224')
sha256 = __get_builtin_constructor('sha256')
sha384 = __get_builtin_constructor('sha384')
sha512 = __get_builtin_constructor('sha512')
| {
"repo_name": "MalloyPower/parsing-python",
"path": "front-end/testsuite-python-lib/Python-3.1/Lib/hashlib.py",
"copies": "2",
"size": "4961",
"license": "mit",
"hash": -3130385755183492600,
"line_mean": 34.4357142857,
"line_max": 85,
"alpha_frac": 0.6333400524,
"autogenerated": false,
"ratio": 3.884886452623336,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0002531245056162,
"num_lines": 140
} |
__doc__ = """hashlib module - A common interface to many hash functions.
new(name, string='') - returns a new hash object implementing the
given hash function; initializing the hash
using the given string data.
Named constructor functions are also available, these are much faster
than using new():
md5(), sha1(), sha224(), sha256(), sha384(), and sha512()
More algorithms may be available on your platform but the above are
guaranteed to exist.
Choose your hash function wisely. Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.
Hash objects have these methods:
- update(arg): Update the hash object with the string arg. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments.
- digest(): Return the digest of the strings passed to the update() method
so far. This may contain non-ASCII characters, including
NUL bytes.
- hexdigest(): Like digest() except the digest is returned as a string of
double length, containing only hexadecimal digits.
- copy(): Return a copy (clone) of the hash object. This can be used to
efficiently compute the digests of strings that share a common
initial substring.
For example, to obtain the digest of the string 'Nobody inspects the
spammish repetition':
>>> import hashlib
>>> m = hashlib.md5()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
More condensed:
>>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
"""
def __get_builtin_constructor(name):
if name in ('SHA1', 'sha1'):
import _sha
return _sha.new
elif name in ('MD5', 'md5'):
import _md5
return _md5.new
elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
import _sha256
bs = name[3:]
if bs == '256':
return _sha256.sha256
elif bs == '224':
return _sha256.sha224
elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
import _sha512
bs = name[3:]
if bs == '512':
return _sha512.sha512
elif bs == '384':
return _sha512.sha384
raise ValueError, "unsupported hash type"
def __py_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
return __get_builtin_constructor(name)(string)
def __hash_new(name, string=''):
"""new(name, string='') - Return a new hashing object using the named algorithm;
optionally initialized with a string.
"""
try:
return _hashlib.new(name, string)
except ValueError:
# If the _hashlib module (OpenSSL) doesn't support the named
# hash, try using our builtin implementations.
# This allows for SHA224/256 and SHA384/512 support even though
# the OpenSSL library prior to 0.9.8 doesn't provide them.
return __get_builtin_constructor(name)(string)
try:
import _hashlib
# use the wrapper of the C implementation
new = __hash_new
for opensslFuncName in filter(lambda n: n.startswith('openssl_'), dir(_hashlib)):
funcName = opensslFuncName[len('openssl_'):]
try:
# try them all, some may not work due to the OpenSSL
# version not supporting that algorithm.
f = getattr(_hashlib, opensslFuncName)
f()
# Use the C function directly (very fast)
exec funcName + ' = f'
except ValueError:
try:
# Use the builtin implementation directly (fast)
exec funcName + ' = __get_builtin_constructor(funcName)'
except ValueError:
# this one has no builtin implementation, don't define it
pass
# clean up our locals
del f
del opensslFuncName
del funcName
except ImportError:
# We don't have the _hashlib OpenSSL module?
# use the built in legacy interfaces via a wrapper function
new = __py_new
# lookup the C function to use directly for the named constructors
md5 = __get_builtin_constructor('md5')
sha1 = __get_builtin_constructor('sha1')
sha224 = __get_builtin_constructor('sha224')
sha256 = __get_builtin_constructor('sha256')
sha384 = __get_builtin_constructor('sha384')
sha512 = __get_builtin_constructor('sha512')
| {
"repo_name": "ahb0327/intellij-community",
"path": "python/lib/Lib/hashlib.py",
"copies": "82",
"size": "4905",
"license": "apache-2.0",
"hash": -431001197329141100,
"line_mean": 34.5434782609,
"line_max": 85,
"alpha_frac": 0.6301732926,
"autogenerated": false,
"ratio": 3.9878048780487805,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00041229310997270053,
"num_lines": 138
} |
# $Id: HC.py,v 1.2 2005-07-14 01:36:41 gosselin_a Exp $
# $Log: not supported by cvs2svn $
# Revision 1.1 2004/08/02 15:36:04 gosselin
# Initial revision
#
from . import hdfext as _C
class HC(object):
"""The HC class holds constants defining opening modes and data types.
File opening modes (flags ORed together)
CREATE 4 create file if it does not exist
READ 1 read-only mode
TRUNC 256 truncate if it exists
WRITE 2 read-write mode
Data types
CHAR 4 8-bit char
CHAR8 4 8-bit char
UCHAR 3 unsigned 8-bit integer (0 to 255)
UCHAR8 3 unsigned 8-bit integer (0 to 255)
INT8 20 signed 8-bit integer (-128 to 127)
UINT8 21 unsigned 8-bit integer (0 to 255)
INT16 23 signed 16-bit integer
UINT16 23 unsigned 16-bit integer
INT32 24 signed 32-bit integer
UINT32 25 unsigned 32-bit integer
FLOAT32 5 32-bit floating point
FLOAT64 6 64-bit floating point
Tags
DFTAG_NDG 720 dataset
DFTAG_VH 1962 vdata
DFTAG_VG 1965 vgroup
"""
CREATE = _C.DFACC_CREATE
READ = _C.DFACC_READ
TRUNC = 0x100 # specific to pyhdf
WRITE = _C.DFACC_WRITE
CHAR = _C.DFNT_CHAR8
CHAR8 = _C.DFNT_CHAR8
UCHAR = _C.DFNT_UCHAR8
UCHAR8 = _C.DFNT_UCHAR8
INT8 = _C.DFNT_INT8
UINT8 = _C.DFNT_UINT8
INT16 = _C.DFNT_INT16
UINT16 = _C.DFNT_UINT16
INT32 = _C.DFNT_INT32
UINT32 = _C.DFNT_UINT32
FLOAT32 = _C.DFNT_FLOAT32
FLOAT64 = _C.DFNT_FLOAT64
FULL_INTERLACE = 0
NO_INTERLACE =1
# NOTE:
# INT64 and UINT64 are not yet supported py pyhdf
DFTAG_NDG = _C.DFTAG_NDG
DFTAG_VH = _C.DFTAG_VH
DFTAG_VG = _C.DFTAG_VG
| {
"repo_name": "fhs/pyhdf",
"path": "pyhdf/HC.py",
"copies": "1",
"size": "1928",
"license": "mit",
"hash": 8024798732923601000,
"line_mean": 26.1549295775,
"line_max": 74,
"alpha_frac": 0.5591286307,
"autogenerated": false,
"ratio": 2.984520123839009,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4043648754539009,
"avg_score": null,
"num_lines": null
} |
# $Id: HDF.py,v 1.3 2005-07-14 01:36:41 gosselin_a Exp $
# $Log: not supported by cvs2svn $
# Revision 1.2 2004/08/02 15:36:04 gosselin
# pyhdf-0.7-1
#
# Revision 1.1 2004/08/02 15:22:59 gosselin
# Initial revision
#
# Author: Andre Gosselin
# Maurice-Lamontagne Institute
# gosselina@dfo-mpo.gc.ca
"""
Basic API (:mod:`pyhdf.HDF`)
============================
A module of the pyhdf package implementing the basic API of the
NCSA HDF4 library.
Introduction
------------
The role of the HDF module is to provide support to other modules of the
pyhdf package. It defines constants specifying file opening modes and
various data types, methods for accessing files, plus a few utility
functions to query library version and check if a file is an HDF one.
It should be noted that, among the modules of the pyhdf package, SD is
special in the sense that it is self-contained and does not need support
from the HDF module. For example, SD provides its own file opening and
closing methods, whereas VS uses methods of the HDF.HDF class for that.
Functions and classes summary
-----------------------------
The HDF module provides the following classes.
HC
The HC class holds constants defining opening modes and
various data types.
HDF
The HDF class provides methods to open and close an HDF file,
and return instances of the major HDF APIs (except SD).
To instantiate an HDF class, call the HDF() constructor.
methods:
constructors:
HDF() open an HDF file, creating the file if necessary,
and return an HDF instance
vstart() initialize the VS (Vdata) API over the HDF file and
return a VS instance
vgstart() initialize the V (Vgroup) interface over the HDF file
and return a V instance.
closing file
close() close the HDF file
inquiry
getfileversion() return info about the version of the HDF file
The HDF module also offers the following functions.
inquiry
getlibversion() return info about the version of the library
ishdf() determine whether a file is an HDF file
"""
import os, sys, types
from . import hdfext as _C
from .six.moves import xrange
from .HC import HC
# NOTE: The vstart() and vgstart() modules need to access the
# VS and V modules, resp. We could simply import those
# two modules, but then they would always be loaded and this
# may not be what the user wants. Instead of forcing the
# systematic import, we import the package `pyhdf',
# and access the needed constructors by writing
# 'pyhdf.VS.VS()' and 'pyhdf.V.V()'. Until the VS or
# V modules are imported, those statements will give an
# error (undefined attribute). Once the user has imported
# the modules, the error will disappear.
import pyhdf
from .error import HDF4Error, _checkErr
# List of names we want to be imported by an "from pyhdf.HDF import *"
# statement
__all__ = ['HDF', 'HDF4Error',
'HC',
'getlibversion', 'ishdf']
def getlibversion():
"""Get the library version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlibversion
"""
status, major_v, minor_v, release, info = _C.Hgetlibversion()
_checkErr('getlibversion', status, "cannot get lib version")
return major_v, minor_v, release, info
def ishdf(filename):
"""Determine whether a file is an HDF file.
Args:
filename name of the file to check
Returns:
1 if the file is an HDF file, 0 otherwise
C library equivalent : Hishdf
"""
return _C.Hishdf(filename)
class HDF(object):
"""The HDF class encapsulates the basic HDF functions.
Its main use is to open and close an HDF file, and return
instances of the major HDF APIs (except for SD).
To instantiate an HDF class, call the HDF() constructor. """
def __init__(self, path, mode=HC.READ, nblocks=0):
"""HDF constructor: open an HDF file, creating the file if
necessary.
Args:
path name of the HDF file to open
mode file opening mode; this mode is a set of binary flags
which can be ored together
HC.CREATE combined with HC.WRITE to create file
if it does not exist
HC.READ open file in read-only access (default)
HC.TRUNC if combined with HC.WRITE, overwrite
file if it already exists
HC.WRITE open file in read-write mode; if file
exists it is updated, unless HC.TRUNC is
set, in which case it is erased and
recreated; if file does not exist, an
error is raised unless HC.CREATE is set,
in which case the file is created
Note an important difference in the way CREATE is
handled by the HDF C library and the pyhdf package.
In the C library, CREATE indicates that a new file should
always be created, overwriting an existing one if
any. For pyhdf, CREATE indicates a new file should be
created only if it does not exist, and the overwriting
of an already existing file must be explicitly asked
for by setting the TRUNC flag.
Those differences were introduced so as to harmonize
the way files are opened in the pycdf and pyhdf
packages. Also, this solves a limitation in the
hdf (and netCDF) library, where there is no easy way
to implement the frequent requirement that an existent
file be opened in read-write mode, or created
if it does not exist.
nblocks number of data descriptor blocks in a block wit which
to create the file; the parameter is ignored if the file
is not created; 0 asks to use the default
Returns:
an HDF instance
C library equivalent : Hopen
"""
# Private attributes:
# _id: file id (NOTE: not compatile with the SD file id)
# See if file exists.
exists = os.path.exists(path)
if HC.WRITE & mode:
if exists:
if HC.TRUNC & mode:
try:
os.remove(path)
except Exception as msg:
raise HDF4Error(msg)
mode = HC.CREATE
else:
mode = HC.WRITE
else:
if HC.CREATE & mode:
mode = HC.CREATE
else:
raise HDF4Error("HDF: no such file")
else:
if exists:
if mode & HC.READ:
mode = HC.READ # clean mode
else:
raise HDF4Error("HDF: invalid mode")
else:
raise HDF4Error("HDF: no such file")
id = _C.Hopen(path, mode, nblocks)
_checkErr('HDF', id, "cannot open %s" % path)
self._id = id
def __del__(self):
"""Delete the instance, first calling the end() method
if not already done. """
try:
if self._id:
self.close()
except:
pass
def close(self):
"""Close the HDF file.
Args:
no argument
Returns:
None
C library equivalent : Hclose
"""
_checkErr('close', _C.Hclose(self._id), "cannot close file")
self._id = None
def getfileversion(self):
"""Get file version info.
Args:
no argument
Returns:
4-element tuple with the following components:
-major version number (int)
-minor version number (int)
-complete library version number (int)
-additional information (string)
C library equivalent : Hgetlibversion
"""
status, major_v, minor_v, release, info = _C.Hgetfileversion(self._id)
_checkErr('getfileversion', status, "cannot get file version")
return major_v, minor_v, release, info
def vstart(self):
"""Initialize the VS API over the file and return a VS instance.
Args:
no argument
Returns:
VS instance
C library equivalent : Vstart (in fact: Vinitialize)
"""
# See note at top of file.
return pyhdf.VS.VS(self)
def vgstart(self):
"""Initialize the V API over the file and return a V instance.
Args:
no argument
Returns:
V instance
C library equivalent : Vstart (in fact: Vinitialize)
"""
# See note at top of file.
return pyhdf.V.V(self)
###########################
# Support functions
###########################
def _array_to_ret(buf, nValues):
# Convert array 'buf' to a scalar or a list.
if nValues == 1:
ret = buf[0]
else:
ret = []
for i in xrange(nValues):
ret.append(buf[i])
return ret
def _array_to_str(buf, nValues):
# Convert array of bytes 'buf' to a string.
# Return empty string if there is no value.
if nValues == 0:
return ""
# When there is just one value, _array_to_ret returns a scalar
# over which we cannot iterate.
if nValues == 1:
chrs = [chr(buf[0])]
else:
chrs = [chr(b) for b in _array_to_ret(buf, nValues)]
# Strip NULL at end
if chrs[-1] == '\0':
del chrs[-1]
return ''.join(chrs)
| {
"repo_name": "fhs/python-hdf4",
"path": "pyhdf/HDF.py",
"copies": "1",
"size": "10526",
"license": "mit",
"hash": -8021242355809869000,
"line_mean": 31.487654321,
"line_max": 78,
"alpha_frac": 0.5530115903,
"autogenerated": false,
"ratio": 4.475340136054422,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5528351726354422,
"avg_score": null,
"num_lines": null
} |
'''
Created on 20. okt. 2009
@author: levin
'''
import SEMBA as S
from math import *
Vehicle_Types = {}
def create_vehicle_list():
for k,v in S.H_HDV.items():
k=0
Vehicle_Types[v[0]]= v[2]
def CreateHDV():
S.load_HDV()
create_vehicle_list()
def extractAndCalc(data,Speed):
WarningText=[]
VehicleID = data[0]
VehicleDescription = data[1]
EUROClass = data[2]
Gradient = float(data[3])
Load = float(data[4])
EmissionComponent = data[5]
PythonEquation = data[6]
if data[7] == '':
data[7] = 0
if data[8] == '':
data[8] = 0
if data[9] == '':
data[9] = 0
if data[10] == '':
data[10] = 0
if data[11] == '':
data[11] = 0
if data[12] == '':
data[12] = 0
if data[13] == '':
data[13] = 0
a = float(data[7])
b = float(data[8])
c = float(data[9])
d = float(data[10])
e = float(data[11])
MinSpeed = float(data[12])
MaxSpeed = float(data[13])
Emission = -1
y = -1
if Speed <= MaxSpeed and Speed >= MinSpeed:
x = Speed
if Speed < MinSpeed:
x = MinSpeed
WarningText.append("Speed is below minimum, minimum speed is used ->" + str(MinSpeed))
if Speed > MaxSpeed:
x = MaxSpeed
WarningText.append("Speed is above maximum, maximum speed is used ->" + str(MaxSpeed))
exec PythonEquation
return y,WarningText
def CalculateHDV(HDVID, Component, Speed, Grad, Load):
"""
Calculation of emissions from heavy duty vehicles
UNITS:
Speed km/h
Gradient 6 is 6%
Emission calculated is g/km
CO2 calculated from Fuel consumption
No maximum speed is given for each equation.
"""
Gradient=0.0
WarningText = []
if Grad <= -6 :
Gradient = -6
WarningText.append("Used maximum gradient -6%")
elif Grad > -6 and Grad <= -4:
Gradient = -4
WarningText.append("Used standard gradient -4%")
elif Grad > -4 and Grad <= -2 :
Gradient = -2
WarningText.append("Used standard gradient -2%")
elif Grad > -2 and Grad < 2 :
Gradient = 0
WarningText.append("Used standard gradient 0%")
elif Grad >= 12:
Grad = 12
WarningText.append("Maximum grade 12 % is selected")
#This limits us from using unrealistic grades
CalculateCO2fromFC = False
if Component == "CO2":
Component = "FC"
CalculateCO2fromFC = True
CalculateEnergy = False
if Component == "E":
Component = "FC"
CalculateEnergy = True
if Component == "HC":
Component = "THC"
if Grad <0:
key = str(HDVID) + "_" + Component + "_" + str(int(Gradient)) + "_" + str(int(Load))
data = S.H_HDV[key]
ans=[]
ans=extractAndCalc(data,Speed)
Emission = ans[0]
WarningText.append(ans[1])
else:
X=[]
Y=[]
key = str(HDVID) + "_" + Component + "_" + str(int(0)) + "_" + str(int(Load))
data0 = S.H_HDV[key]
X.append(0)
Y.append(extractAndCalc(data0,Speed)[0])
key = str(HDVID) + "_" + Component + "_" + str(int(2)) + "_" + str(int(Load))
data2 = S.H_HDV[key]
X.append(2)
Y.append(extractAndCalc(data2,Speed)[0])
key = str(HDVID) + "_" + Component + "_" + str(int(4)) + "_" + str(int(Load))
data4 = S.H_HDV[key]
X.append(4)
Y.append(extractAndCalc(data4,Speed)[0])
key = str(HDVID) + "_" + Component + "_" + str(int(6)) + "_" + str(int(Load))
data6 = S.H_HDV[key]
X.append(6)
Y.append(extractAndCalc(data6,Speed)[0])
a,b,rr=S.linreg(X,Y)
#print X
#print Y
#print a,b,rr
Emission = a*Grad + b
if CalculateCO2fromFC:
Emission = Emission * 3.17 # http://www.klif.no/Tema/Klima-og-ozon/Klimagasser/--MENY/Sporsmal-og-svar/
WarningText.append("CO2 emissions calculated from fuel consumption")
if CalculateEnergy:
Emission = Emission * (S.EDensity_Diesel/1000.0)
WarningText.append("Energy calculated from fuel consumption")
if (len(WarningText) == 0):
WarningText.append("No Warnings")
return Emission, "g/km", WarningText
def ListTypes():
"""
Lists all heavy duty vehicles available in the dataset that is loaded.
"""
#Function to sort as integers
def compare(a, b):
return cmp(int(a), int(b)) # compare as integers
keys = Vehicle_Types.keys()
keys.sort(compare)
print "HDV ID ; Description"
for key in keys:
print str(key)+ ' ; '+ Vehicle_Types[key]
###########____Load Data____##################
CreateHDV()
#test segment for debuging purposes
if __name__ == "__main__":
import matplotlib.pyplot as plt
xvar=[]
a = []
b = []
c = []
d = []
e = []
f = []
g = []
h = []
j = []
k = []
l = []
m = []
n = []
for i in range(6, 90):
b.append(i)
#def CalculateHDV(HDVID, Component, Speed, Gradient, Load):
a.append(CalculateHDV(41, 'FC', i, 0.0 , 100)[0])
b.append(CalculateHDV(47, 'FC', i, 0.0 , 100)[0])
c.append(CalculateHDV(53, 'FC', i, 0.0 , 100)[0])
d.append(CalculateHDV(59, 'FC', i, 0.0 , 100)[0])
e.append(CalculateHDV(65, 'FC', i, 0.0 , 100)[0])
f.append(CalculateHDV(71, 'FC', i, 0.0 , 100)[0])
g.append(CalculateHDV(77, 'FC', i, 0.0 , 100)[0])
h.append(CalculateHDV(83, 'FC', i, 0.0 , 100)[0])
j.append(CalculateHDV(89, 'FC', i, 0.0 , 100)[0])
k.append(CalculateHDV(95, 'FC', i, 0.0 , 100)[0])
l.append(CalculateHDV(101, 'FC', i, 0.0 , 100)[0])
m.append(CalculateHDV(107, 'FC', i, 0.0 , 100)[0])
n.append(CalculateHDV(113, 'FC', i, 0.0 , 100)[0])
#a.append(CalculateHDV(91, 'NOx', i, 0.0 , 100)[0])
#c.append(CalculateHDV(92, 'NOx', i, 0.0 , 100)[0])
#d.append(CalculateHDV(93, 'NOx', i, 0.0 , 100)[0])
#e.append(CalculateHDV(94, 'NOx', i, 0.0 , 100)[0])
#f.append(CalculateHDV(95, 'NOx', i, 0.0 , 100)[0])
#g.append(CalculateHDV(96, 'NOx', i, 0.0 , 100)[0])
#h.append(CalculateHDV(95, 'NOx', i, 6.0 , 100)[0])
# plt.plot(b, a,label ='EURO 0')
# plt.plot(b, c,label ='EURO I' )
# plt.plot(b, d,label ='EURO II')
# plt.plot(b, e,label ='EURO III')
# plt.plot(b, f,label ='EURO IV')
# plt.plot(b, g,label ='EURO V')
#plt.plot(b, h,label ='+6 %')
print b
# print a[10]
#print c[10]
#print e[10]
#print d[10]
plt.ylabel('NOx gram/km')
plt.xlabel('Vehicle average speed')
plt.title('SEMBA, EURO IV 34- 40ton truck')
# leg = plt.legend(loc=1,ncol=2)
# for t in leg.get_texts():
# t.set_fontsize('x-small') # the legend text fontsize
plt.show()
#ListTypes()
#CalculateHDV(101, 'NOx', i, 0.0 , 100)[0])
#CalculateHDV(101, 'NOx', i, 0.0 , 100)[0])
#CalculateHDV(101, 'NOx', i, 0.0 , 100)[0]) | {
"repo_name": "tomasle/semba",
"path": "SEMBA/HDV.py",
"copies": "1",
"size": "6578",
"license": "bsd-2-clause",
"hash": 1094339985683117300,
"line_mean": 25.8530612245,
"line_max": 107,
"alpha_frac": 0.5834600182,
"autogenerated": false,
"ratio": 2.7170590665014456,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.38005190847014453,
"avg_score": null,
"num_lines": null
} |
#'$Id: HTMLgen.py,v 1.1 2007/02/22 17:02:49 geoff Exp $'
# COPYRIGHT (C) 1996-9 ROBIN FRIEDRICH email:Robin.Friedrich@pdq.net
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and
# that both that copyright notice and this permission notice appear in
# supporting documentation.
# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""A class library for the generation of HTML documents.
Each HTML tag type has a supporting class which is responsible for
emitting itself as valid HTML formatted text. An attempt is made to
provide classes for newer HTML 3.2 and proposed tag elements. The
definitive reference for HTML tag elements can be found at
[W3C]. Also, I used the HTML book by Musciano and
Kennedy from [O Reilly] (2nd. Ed.) as the guiding reference.
The Document classes are container objects which act as a focal point
to populate all the contents of a particular web page. It also can
enforce consistent document formating according to the guidelines from
the [Yale Web Style Manual].
Features include customization of document template graphics / colors
through use of resource files, minimizing the need for modifying or
subclassing from the module source code. Support for tables, frames,
forms (persistent and otherwise) and client-side imagemaps are included.
A newer implementation for the Table support is now included,
TableLite(). In support of this there are new tag classes TD, TH, TR
and Caption. These class instances can be assembled in any way to
populate the TableLite container object.
.. [W3C] http://www.W3.org/TR/REC-html32.html
.. [O Reilly] http://www.oreilly.com/catalog/html3/index.html
.. [Yale Web Style Manual] http://info.med.yale.edu/caim/manual/contents.html
"""
import string, re, time, os
import UserList, copy
from imgsize import imgsize
__author__ = 'Robin Friedrich friedrich@pythonpros.com'
__version__ = '2.2.2'
StringType = type('s')
IntType = type(3)
ListType = type([1])
TupleType = type((1,2))
InstanceType = type(UserList.UserList())
CONTYPE = 'Content-Type: text/html\n\n'
DOCTYPE = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">\n<HTML>\n'
XHTML_DOCTYPE = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<HTML>\n'
PRINTECHO = 1
#################
# CLASS LIBRARY #
#################
#======= NEW CLASS STRUCTURE ============
# HTMLgen 1 HTMLgen 2
# --------------- ------------------
# Document SeriesDocument
# MinimalDocument SimpleDocument
# BasicDocument (base class)
# TemplateDocument
class BasicDocument:
"""Base class to define an HTML document.
Non-keyword arguments are taken as the initial contents for this object.
Keyword arguments:
title -- HTML TITLE attribute for document
bgcolor -- background color expressed in hex-triplet or names from HTMLcolors.
background -- background image filename
xhtml -- flag to indicate if this is XHTML (1 if it is)
cgi -- flag to indicate if this is used in CGI context (1 if it is)
textcolor -- color to use for normal text
linkcolor -- color to use for hyperlinks
vlinkcolor -- color to use for visited hyperlinks
alinkcolor -- color to use when hyperlink is active
"""
title = ''
cgi = None
xhtml = None
bgcolor = None
background = None
textcolor = None
linkcolor = None
vlinkcolor = None
alinkcolor = None
def __init__(self, *args, **kw):
self.contents = list(args)
for name, value in kw.items():
setattr(self, name, value)
def __str__(self):
s = [ self.get_doc_type() ]
s.append('\n<!-- This file generated using Python HTMLgen module. -->\n')
# build the HEAD and BODY tags
s.append(self.html_head())
s.append(self.html_body_tag())
# DOCUMENT CONTENT SECTION and FOOTER added on
bodystring = '%s\n' * len(self.contents)
s.append((bodystring % tuple(self.contents)))
# CLOSE the document
s.append('\n</BODY> </HTML>\n')
return string.join(s, '')
def get_doc_type(self):
if self.xhtml:
doctype = XHTML_DOCTYPE
else:
doctype = DOCTYPE
if self.cgi:
doctype = CONTYPE + doctype
return doctype
def html_head(self):
"""Generate the HEAD, TITLE and BODY tags.
"""
return '<HEAD>\n <META NAME="GENERATOR" CONTENT="HTMLgen %s">\n\
<TITLE>%s</TITLE> </HEAD>\n' % (__version__, self.title)
def html_body_tag(self):
"""Return BODY tag with attributes.
"""
s = ['<BODY']
if self.bgcolor: s.append(' BGCOLOR="%s"' % self.bgcolor)
if self.background: s.append(' BACKGROUND="%s"' % self.background)
if self.textcolor: s.append(' TEXT="%s"' % self.textcolor)
if self.linkcolor: s.append(' LINK="%s"' % self.linkcolor)
if self.vlinkcolor: s.append(' VLINK="%s"' % self.vlinkcolor)
if self.alinkcolor: s.append(' ALINK="%s"' % self.alinkcolor)
s.append('>\n')
return string.join(s, '')
def append_file(self, filename, marker_function = None):
"""Add the contents of a file to the document.
filename -- the filename of the file to be read [string]
marker_function -- a callable object which the text read from
the file will be passed through before being added to the
document.
"""
f = open(mpath(filename), 'r')
if marker_function:
self.append(marker_function(f.read()))
else:
self.append(f.read())
f.close()
def append(self, *items):
"""Add content to the Document object.
Arg *items* can be plain text or objects; multiple arguments supported.
"""
for item in items:
self.contents.append(item)
def prepend(self, *items):
"""Add content to the beginning of the Document object.
Arg *items* can be plain text or objects; multiple arguments supported.
"""
for item in items:
self.contents.insert(0, item)
def copy(self):
"""Return a complete copy of the current Document object.
"""
return copy.deepcopy(self)
def write(self, filename = None):
"""Emit the Document HTML to a file or standard output.
In Unix you can use environment variables in filenames.
Will print to stdout if no argument.
"""
if filename:
f = open(mpath(filename), 'w')
f.write(str(self))
f.close()
if PRINTECHO: print 'wrote: "'+filename+'"'
else:
import sys
sys.stdout.write(str(self))
class FramesetDocument(BasicDocument):
"""A minimal document suitable for entering Framesets.
Arguments are for contents **NOT** a document resource file.
Keyword Parameters
title -- string to be used as the document title.
base -- object of the Base class
meta -- object of the Meta class
cgi -- if non zero will issue a mime type of text/html
script -- a single or list of Script objects to be included in the <HEAD>
No <body> markup. Instead add Frameset(s) with the constructor or
append method.
"""
base = None
meta = None
cgi = None
script = None
def __str__(self):
s = [ self.get_doc_type() ]
s.append('\n<!-- This file generated using Python HTMLgen module. -->\n')
# build the HEAD tag
s.append(self.html_head())
# DOCUMENT CONTENT SECTION
bodystring = '%s\n' * len(self.contents)
s.append((bodystring % tuple(self.contents)))
# CLOSE the document
s.append('\n</HTML>')
return string.join(s, '')
class SimpleDocument(BasicDocument):
"""Supports all features of a self contained document.
This includes support for CSS1, meta and base tags, and embedded
scripts.
First constructor argument is resource file containing document
attribute settings.
"""
base = None
style = None
stylesheet = None
meta = None
onLoad = None
onUnload = None
script = None
def __init__(self, resource = None, **kw):
self.contents = []
# Read attributes from resource file into instance namespace
if resource: execfile(mpath(resource), self.__dict__)
for name, value in kw.items():
setattr(self, name, value)
def __str__(self):
s = [ self.get_doc_type() ]
s.append('\n<!-- This file generated using Python HTMLgen module. -->\n')
# build the HEAD and BODY tags
s.append(self.html_head())
s.append(self.html_body_tag())
# DOCUMENT CONTENT SECTION and FOOTER added on
bodystring = '%s\n' * len(self.contents)
s.append((bodystring % tuple(self.contents)))
s.append('\n</BODY> </HTML>\n') # CLOSE the document
return string.join(s, '')
def html_head(self):
"""Generate the HEAD TITLE and BODY tags.
"""
s = ['<HEAD>\n <META NAME="GENERATOR" CONTENT="HTMLgen %s">\n\
<TITLE>%s</TITLE>\n' % (__version__, self.title)]
if self.meta: s.append(str(self.meta))
if self.base: s.append(str(self.base))
if self.stylesheet:
s.append('\n <LINK rel=stylesheet href="%s" type=text/css title="%s">\n' \
% (self.stylesheet, self.stylesheet))
if self.style:
s.append('\n<STYLE>\n<!--\n%s\n-->\n</style>\n' % self.style)
if self.script: # for javascripts
if type(self.script) in (TupleType, ListType):
for script in self.script:
s.append(str(script))
else:
s.append(str(self.script))
s.append('</HEAD>\n')
return string.join(s, '')
def html_body_tag(self):
"""Return BODY tag with attributes.
"""
s = ['<BODY']
if self.bgcolor: s.append(' BGCOLOR="%s"' % self.bgcolor)
if self.background: s.append(' BACKGROUND="%s"' % self.background)
if self.textcolor: s.append(' TEXT="%s"' % self.textcolor)
if self.linkcolor: s.append(' LINK="%s"' % self.linkcolor)
if self.vlinkcolor: s.append(' VLINK="%s"' % self.vlinkcolor)
if self.alinkcolor: s.append(' ALINK="%s"' % self.alinkcolor)
if self.onLoad: s.append(' onLoad="%s"' % self.onLoad)
if self.onUnload: s.append(' onUnload="%s"' % self.onUnload)
s.append('>\n')
return string.join(s, '')
class SeriesDocument(SimpleDocument):
"""Primary container class for an HTML document as part of a series.
Formerly known as Document().
Navigation mechanisms are provided.
Single optional string argument for the path to a resource file
used to specify document parameters. This helps minimize the need
for subclassing from this class. Keyword parameters may be used
for any of the following class attributes. See *HTMLtest.py* for
example usage.
Class instance attributes and keyword arguments
base -- object of the Base class
meta -- object of the Meta class
cgi -- if non zero will issue a mime type of text/html
logo -- ('filename', width, height) All images are specified
with a tuple of string, int, int. If the size of the
graphic is unknown, use 0, 0. This one is the little
graphic on the footer of each page.
banner -- ('filename', width, height) Banner graphic at
the top of page. Can also be set to a string filename
or an Image object. Can be autosized if it's a GIF.
title -- string to be used as the document title.
subtitle -- string to be used as the document subtitle.
If non-nil, this string will be used for the doc title
instead of title.
author -- String used in the copyright notice
email -- Email address for feedback mailto: tag
zone -- string used to label the time zone if datetime
is used. By default not used.
bgcolor -- Color string (can use variables from
HTMLcolors.py)
background -- string filename of a graphic used as the
doc background.
textcolor -- Color string used for text. (can use
variables from HTMLcolors.py)
linkcolor -- Color string used for hyperlinked text.
vlinkcolor -- Color string used for visited hypertext.
alinkcolor -- Color string used for active hypertext.
place_nav_buttons -- Flag to enable/disable the use of
navigation buttons.
Default is on. Set to 0 to disable.
blank -- Image tuple for the transparent spacer gif
prev -- Image tuple for the Previous Page button
next -- Image tuple for the Next Page button
top -- Image tuple for the Top of Manual button
home -- Image tuple for the site Home Page button
goprev -- URL string for the prev button
gonext -- URL string for the next button
gotop -- URL string for the top button
gohome -- URL string for the home button
script -- a single or list of Script objects to be included in the <HEAD>
onLoad -- Script, which is executed when the document is loaded
onUnload -- Script, which is executed when the document is unloaded
"""
subtitle = None
banner = ('/image/banner.gif', 472, 30)
logo = ('/image/logo.gif', 36, 35)
author = 'Micky Mouse'
email = 'micky@disney.com'
zone = ' Central US'
place_nav_buttons = 'yes'
blank = ('../image/blank.gif', 71, 19)
prev = ('../image/BTN_PrevPage.gif', 71, 19)
next = ('../image/BTN_NextPage.gif', 71, 19)
top = ('../image/BTN_ManualTop.gif', 74, 19)
home = ('../image/BTN_HomePage.gif', 74, 19)
goprev = None # URLs for above navigation buttons
gonext = None
gotop = None
gohome = None
def __str__(self):
s = [ self.get_doc_type() ]
s.append('\n<!-- This file generated using Python HTMLgen module. -->\n')
# build the HEAD and BODY tags
s.append(self.html_head())
s.append(self.html_body_tag())
# HEADER SECTION
s.append(self.header())
# DOCUMENT CONTENT SECTION and FOOTER added on
bodystring = '%s\n' * len(self.contents)
s.append((bodystring % tuple(self.contents)))
s.append(self.footer())
s.append('\n</BODY> </HTML>\n') # CLOSE the document
return string.join(s, '')
def header(self):
"""Generate the standard header markups.
"""
# HEADER SECTION - overload this if you don't like mine.
s = []
if self.banner:
bannertype = type(self.banner)
if bannertype in (TupleType, StringType):
s.append(str(Image(self.banner, border=0)) + '<BR>\n')
elif bannertype == InstanceType:
s.append(str(self.banner) + '<BR>\n')
else:
raise TypeError, 'banner must be either a tuple, instance, or string.'
if self.place_nav_buttons:
s.append(self.nav_buttons())
s.append(str(Heading(3,self.title)))
if self.subtitle:
s.append('<H2>%s</H2>\n' % self.subtitle)
s.append('<HR>\n\n')
return string.join(s, '')
def nav_buttons(self):
"""Generate hyperlinked navigation buttons.
If a self.go* attribute is null that corresponding button is
replaced with a transparent gif to properly space the remaining
buttons.
"""
s = []
if self.goprev: # place an image button for previous page
btn = Image(self.prev, border=0, alt='Previous')
link = Href(self.goprev, str(btn))
s.append(str(link) + ' \n')
else: # place a blank gif as spacer
#btn = Image(self.blank)
s.append('<span style="width: 60px"></span> \n')
if self.gonext: # place an image button for next page
btn = Image(self.next, border=0, alt='Next')
link = Href(self.gonext, str(btn))
s.append(str(link) + ' \n')
else: # place a blank gif as spacer
btn = Image(self.blank)
s.append(str(btn) + ' \n')
if self.gotop: # place an image button for top of manual page
btn = Image(self.top, border=0, alt='Top of Manual')
link = Href(self.gotop, str(btn))
s.append(str(link) + ' \n')
else: # place a blank gif as spacer
btn = Image(self.blank)
s.append(str(btn) + ' \n')
if self.gohome: # place an image button for site home page
btn = Image(self.home, border=0, alt='Home Page')
link = Href(self.gohome, str(btn))
s.append(str(link) + ' \n')
else: # place a blank gif as spacer
btn = Image(self.blank)
s.append(str(btn) + ' \n')
return string.join(s, '')
def footer(self):
"""Generate the standard footer markups.
"""
# FOOTER SECTION - overload this if you don't like mine.
t = time.localtime(time.time())
#self.datetime = time.strftime("%c %Z", t) #not available in JPython
self.datetime = time.asctime(t)
#self.date = time.strftime("%A %B %d, %Y", t)
x = string.split(self.datetime)
self.date = x[0] + ' ' + x[1] + ' ' + x[2] + ', ' + x[4]
s = ['\n<P><HR>\n']
if self.place_nav_buttons:
s.append(self.nav_buttons())
s.append('<BR>' + str(Image(self.logo, align='bottom')))
s.append('\n<FONT SIZE="-1"><P>Copyright © %s<BR>All Rights Reserved<BR>\n' \
% self.author)
s.append('\nComments to author: ' + str(MailTo(self.email)) )
s.append('<br>\nGenerated: %s <BR>' % self.date) # can use self.datetime here instead
s.append('<hr>\n</FONT>')
return string.join(s, '')
# Aliases for backward compatability with HTMLgen 1.2
Document = SeriesDocument
MinimalDocument = SimpleDocument
class StringTemplate:
"""Generate documents based on a template and a substitution mapping.
Must use Python 1.5 or newer. Uses re and the get method on dictionaries.
Usage:
T = TemplateDocument('Xfile')
T.substitutions = {'month': ObjectY, 'town': 'Scarborough'}
T.write('Maine.html')
A dictionary, or object that behaves like a dictionary, is assigned to the
*substitutions* attribute which has symbols as keys to objects. Upon every
occurance of these symbols surrounded by braces {} in the source template,
the corresponding value is converted to a string and substituted in the output.
For example, source text which looks like:
I lost my heart at {town} Fair.
becomes:
I lost my heart at Scarborough Fair.
Symbols in braces which do not correspond to a key in the dictionary remain
unchanged.
An optional third argument to the class is a list or two strings to be
used as the delimiters instead of { } braces. They must be of the same
length; for example ['##+', '##'] is invalid.
"""
def __init__(self, template, substitutions=None, **kw):
self.delimiters = ['{', '}']
self.__dict__.update(kw)
if len(self.delimiters) != 2:
raise ValueError("delimiter argument must be a pair of strings")
self.delimiter_width = len(self.delimiters[0])
delimiters = map(re.escape, self.delimiters)
self.subpatstr = delimiters[0] + "[\w_]+" + delimiters[1]
self.subpat = re.compile(self.subpatstr)
self.substitutions = substitutions or {}
self.set_template(template)
def set_template(self, template):
self.source = template
def keys(self):
return self.substitutions.keys()
def __setitem__(self, name, value):
self.substitutions[name] = value
def __getitem__(self, name):
return self.substitutions[name]
def __str__(self):
return self._sub(self.source)
def _sub(self, source, subs=None):
"""Perform source text substitutions.
*source* string containing template source text
*subs* mapping of symbols to replacement values
"""
substitutions = subs or self.substitutions
dw = self.delimiter_width
i = 0
output = []
matched = self.subpat.search(source[i:])
while matched:
a, b = matched.span()
output.append(source[i:i+a])
# using the new get method for dicts in 1.5
output.append(str(substitutions.get(
source[i+a+dw:i+b-dw], source[i+a:i+b])))
i = i + b
matched = self.subpat.search(source[i:])
else:
output.append(source[i:])
return string.join(output, '')
def write(self, filename = None):
"""Emit the Document HTML to a file or standard output.
Will not overwrite file is it exists and is textually the same.
In Unix you can use environment variables in filenames.
Will print to stdout if no argument given.
"""
if filename:
filename = mpath(filename)
if os.path.exists(filename):
s = str(self)
if compare_s2f(s, filename):
f = open(filename, 'w')
f.write(str(self))
f.close()
if PRINTECHO: print 'wrote: "'+filename+'"'
else:
if PRINTECHO: print 'file unchanged: "'+filename+'"'
else:
f = open(filename, 'w')
f.write(str(self))
f.close()
if PRINTECHO: print 'wrote: "'+filename+'"'
else:
import sys
sys.stdout.write(str(self))
class TemplateDocument(StringTemplate):
"""Generate documents based on a template and a substitution mapping.
Must use Python 1.5 or newer. Uses re and the get method on dictionaries.
Usage:
T = TemplateDocument('Xfile')
T.substitutions = {'month': ObjectY, 'town': 'Scarborough'}
T.write('Maine.html')
A dictionary, or object that behaves like a dictionary, is assigned to the
*substitutions* attribute which has symbols as keys to objects. Upon every
occurance of these symbols surrounded by braces {} in the source template,
the corresponding value is converted to a string and substituted in the output.
For example, source text which looks like:
I lost my heart at {town} Fair.
becomes:
I lost my heart at Scarborough Fair.
Symbols in braces which do not correspond to a key in the dictionary remain
unchanged.
An optional third argument to the class is a list or two strings to be
used as the delimiters instead of { } braces. They must be of the same
length; for example ['##+', '##'] is invalid.
"""
def set_template(self, template):
f = open(mpath(template))
self.source = f.read()
f.close()
class AutoStringTemplate(StringTemplate):
marker_begin = '<!--{%s}Begin-->'
marker_end = '<!--{%s}End-->'
R = re.compile(r"<!--{(?P<key>[\w_]+)}Begin-->(?P<text>.*?)<!--{\1}End-->", re.S)
def set_template(self, template):
"""Set template string and normalize by extracting comment tokens.
"""
self.source = template
self.extract_template()
def extract_template(self, source=None):
"""Convert comment-marked regions to a regular {tokens}.
Updates the substitution dictionary with the text from the region.
"""
source = source or self.source
a = 0
newsubs = {}
newtemplate = []
d1, d2 = self.delimiters
while 1:
m = self.R.search(source, a)
if m:
start, end = m.span()
newtemplate.append(source[a:start])
a = end
newsubs[m.group('key')] = m.group('text')
newtemplate.append(d1+m.group('key')+d2)
else:
newtemplate.append(source[a:])
break
self.source = string.join(newtemplate, '')
self.substitutions.update(newsubs)
def _sub(self, source, subs=None):
"""Perform source text substitutions.
*source* string containing template source text
*subs* mapping of symbols to replacement values
"""
substitutions = subs or self.substitutions
dw = self.delimiter_width
i = 0
output = []
matched = self.subpat.search(source[i:])
while matched:
a, b = matched.span()
output.append(source[i:i+a])
#implant comments to mark the location of the tokens
output.append(self.marker_begin % source[i+a+dw:i+b-dw])
# using the new get method for dicts in 1.5
output.append(str(substitutions.get(
source[i+a+dw:i+b-dw], source[i+a:i+b])))
output.append(self.marker_end % source[i+a+dw:i+b-dw])
i = i + b
matched = self.subpat.search(source[i:])
else:
output.append(source[i:])
return string.join(output, '')
class AutoTemplateDocument(AutoStringTemplate):
"""Generate documents based on a template and a substitution mapping.
The primary difference between AutoTemplateDocument and TemplateDocument
is that the Auto version can read through an HTML file previously
generated with this class and identify the regions of text that were
substituted. It then extracts that text into the substitution dictionary
and can then be updated. The intent is to eliminate the need to
maintain separate content files for insertion into templates. The HTML
output file can double as a template for future use.
Output from this class have their filled regions marked by comments:
...gets <!--{wz}Begin-->glued,<!--{wz}End--> in place...
Which came from ...gets {wz} in place... in old style template syntax.
AutoTemplateDocument is a functional superset of TemplateDocument and should
be compatible.
Usage:
T = AutoTemplateDocument('Maine.html')
T.substitutions = {'month': ObjectY, 'town': 'Scarborough'}
or
T['month'] = ObjectY ; T['town'] = 'Scarborough'
T.write('Maine.html')
A dictionary, or object that behaves like a dictionary, is assigned to the
*substitutions* attribute which has symbols as keys to objects. Upon every
occurance of these symbols surrounded by braces {} in the source template,
the corresponding value is converted to a string and substituted in the output.
For example, source text which looks like:
I lost my heart at {town} Fair.
becomes:
I lost my heart at Scarborough Fair.
Symbols in braces which do not correspond to a key in the dictionary remain
unchanged.
An optional third argument to the class is a list or two strings to be
used as the delimiters instead of { } braces. They must be of the same
length; for example ['##+', '##'] is invalid.
"""
def set_template(self, template):
f = open(mpath(template))
self.source = f.read()
f.close()
class Container:
"""A holder for a list of HTMLgen objects.
"""
def __init__(self, *args, **kw):
self.contents = list(args)
for name, value in kw.items():
setattr(self, name, value)
def __str__(self):
bodystring = '%s\n' * len(self.contents)
return bodystring % tuple(self.contents)
def __add__(self, other):
new = self.__class__()
new.contents = self.contents + other.contents
return new
def append_file(self, filename, marker_function = None):
"""Add the contents of a file to the document.
filename -- the filename of the file to be read [string]
marker_function -- a callable object which the text read from
the file will be passed through before being added to the
document.
"""
f = open(mpath(filename), 'r')
if marker_function:
self.append(marker_function(f.read()))
else:
self.append(f.read())
f.close()
def append(self, *items):
"""Add content to the Document object.
Arg *items* can be plain text or objects; multiple arguments supported.
"""
for item in items:
self.contents.append(item)
def prepend(self, *items):
"""Add content to the beginning of the Document object.
Arg *items* can be plain text or objects; multiple arguments supported.
"""
li = len(items)
for i in range(li-1, 0, -1):
self.contents.insert(0, items[i])
def copy(self):
"""Return a complete copy of the current Container object.
"""
return copy.deepcopy(self)
#===================
class Meta:
"""Set document Meta-information.
The META element is used within the HEAD element to embed
document meta-information not defined by other HTML elements.
Keywords supported
name -- NAME element attribute (default: 'keywords')
equiv -- will map to the HTTP-EQUIV attribute
content -- mandatory attribute (default: 'python,HTMLgen')
url -- URL naturally
Example:
Meta( name='keywords', content='eggs,spam,beans' )
"""
def __init__(self, **kw):
self.equiv = 'keywords'
self.name = ''
self.content = 'python,HTMLgen'
self.url = ''
for item in kw.keys():
self.__dict__[item] = kw[item]
def __str__(self):
s = ['<META']
if self.equiv: s.append(' HTTP-EQUIV="%s"' % self.equiv)
if self.name: s.append(' NAME="%s"' % self.name)
if self.content: s.append(' CONTENT="%s"' % self.content)
if self.url: s.append(' URL="%s"' % self.url)
s.append('>\n')
return string.join(s, '')
##### Client-side Imagemap Support #####
class Map:
"""Used to name and describe a client-side image map.
The *areas* argument is a list of Area objects.
Keyword arg is supported for *name*, which defines the map name
to be used with the usemap attribute of an Image class instance.
"""
def __init__(self, areas = None, **kw):
self.areas = areas or []
self.name = ''
for item in kw.keys():
self.__dict__[item] = kw[item]
def __str__(self):
s = ['\n<MAP NAME="%s">\n' % self.name]
for area in self.areas:
s.append(str(area))
s.append('</MAP>\n')
return string.join(s, '')
class Href:
"""Generate a hyperlink.
Argument 1 is the URL and argument 2 is the hyperlink text.
Keyword arguments
title -- the title property, usually used for tooltips
target -- is an optional target symbol
onClick -- is the script-code which is executed when link is clicked.
onMouseOver -- the script-code which is executed when the mouse
moves over the link.
onMouseOut -- the script-code which is executed when the mouse
moves off the link.
"""
def __init__(self, url='', text='', **kw):
self.target = None
self.title = None
self.onClick = None
self.onMouseOver = None
self.onMouseOut = None
self.style = None
self.url = url
self.text = text
for item in kw.keys():
if self.__dict__.has_key(item):
self.__dict__[item] = kw[item]
else:
raise KeyError, `item`+' not a valid parameter for this class.'
def __str__(self):
s = ['<A HREF="%s"' % self.url]
if self.target: s.append(' TARGET="%s"' % self.target)
if self.title: s.append(' title="%s"' % self.title)
if self.onClick: s.append(' onClick="%s"' % self.onClick)
if self.onMouseOver: s.append(' onMouseOver="%s"' % self.onMouseOver)
if self.onMouseOut: s.append(' onMouseOut="%s"' % self.onMouseOut)
if self.style: s.append(' style="%s"' % self.style)
s.append('>%s</A>' % self.text)
return string.join(s, '')
def append(self, content):
self.text = self.text + str(content)
A = HREF = Href # alias
class Name(Href):
"""Generate a named anchor.
Arg *url* is a string or URL object,
Arg *text* is optional string or object to be highlighted as the anchor.
"""
def __str__(self):
return '<A NAME="%s">%s</A>' % (self.url, self.text)
NAME = Name # alias
class MailTo:
"""A Mailto href
First argument is an email address, optional second argument is
the text shown as the underlined hyperlink. Default is the email
address. Optional third argument is a Subject: for the email.
"""
def __init__(self, address='', text=None, subject=None):
self.address = address
self.text = text or address
self.subject = subject
def __str__(self):
if self.subject: self.address = "%s?subject=%s" % (self.address, self.subject)
return '<A HREF="mailto:%s">%s</A>' % (self.antispam(self.address), self.text)
def antispam(self, address):
"""Process a string with HTML encodings to defeat address spiders.
"""
from random import choice
buffer = map(None, address)
for i in range(0, len(address), choice((2,3,4))):
buffer[i] = '&#%d;' % ord(buffer[i])
return string.join(buffer,'')
MAILTO = Mailto = MailTo # aliases
class P:
"""Just echo a <P> tag."""
def __str__(self):
return '\n<P>\n'
# List constructs
class List(UserList.UserList):
"""Will generate a bulleted list given a list argument.
Now supports rendering a list into multiple columns by setting the
*columns* attribute to a number greater than one. This is
implemented using tables and you can also set a background color
for the list itself by using the *bgcolor* attribute.
Supports nested lists, i.e. lists of lists. Each time a list is
encountered in a list it will indent those contents w.r.t. the
prior list entry. This can continue indefinitely through nested
lists although there are only three different bullets provided by
the browser (typically).
Optional keyword *indent* can be used to indicate whether you want
the list to start left justified or indented. *indent=0* will make
it left justified. The default is to indent.
Optional keyword *type* can be set to either disk, circle, or
square to specify what kind of symbol is used for each list item's
bullet. (Netscape extension)
Since we inherit from the UserList class any normal list
operations work on instances of this class. Any list contents
will do. Each of the items will be emitted in html if they are
themselves objects from this module.
Aliases: UL, BulletList
"""
I_am_a_list = 1
tagname = 'UL'
attrs = ('type','align','class','id','style')
flags = ('compact',)
columns = 1
bgcolor = ''
pad = ' '
indent = 1
def __init__(self, list = None, **kw):
self.data = []
self.lvl = 0
if list:
if type(list) == type(self.data):
self.data[:] = list
else:
self.data[:] = list.data[:]
for item in kw.keys():
self.__dict__[string.lower(item)] = kw[item]
def __getslice__(self, i, j):
newlist = copy.copy(self)
newlist.data = self.data[i:j]
newlist.columns = 1 # don't forget that the copy will carry
# the old attribute value. set to 1
return newlist
def multi_column_table(self):
"""Return a table containing the list sliced into columns.
"""
slices = self.column_slices(self.columns)
table = TableLite(border=0, cellpadding=3)
if self.bgcolor: table.bgcolor = self.bgcolor
for begin, end in slices:
column = TD(self[begin:end], valign='top', html_escape='no')
table.append(column)
return table
def column_slices(self, columns=1):
"""Calculate a list of index pairs bounding column slices.
"""
list_len = len(self.data)
col_len, remainder = divmod(list_len, columns)
if remainder: col_len = col_len + 1
indexpairs = []
if columns > 1:
for column in range(columns):
col_end = (column+1)*col_len
if col_end < list_len:
indexpairs.append((column*col_len, col_end))
else:
indexpairs.append((column*col_len, list_len))
else:
indexpairs.append((0, list_len))
return indexpairs
def __str__(self):
if self.columns > 1: # go to the new multicolumn feature
return str(self.multi_column_table())
# same as before
self.firstitem = 1
self.s = []
if self.indent:
self.s.append(self.pad*self.lvl + self.start_element())
for item in self.data: #start processing main list
itemtype = type(item)
if itemtype == InstanceType:
try: # in case it's a nested list object
if item.I_am_a_list:
itemtype = ListType
except AttributeError:
pass
if itemtype == ListType: #process the sub list
self.sub_list(item)
else:
self.s.append(self.render_list_item(item))
if self.indent: #close out this level of list
self.s.append(self.pad*self.lvl + self.end_element())
self.lvl = 0
return string.join(self.s, '')
def sub_list(self, list):
"""Recursive method for generating a subordinate list
"""
self.lvl = self.lvl + 1
if type(list) == InstanceType:
try:
if list.I_am_a_list: #render the List object
list.lvl = self.lvl
self.s.append(str(list))
except AttributeError:
pass
else:
self.s.append(self.pad*self.lvl + self.start_element())
for item in list:
itemtype = type(item)
if itemtype == InstanceType:
try: #could be another nested List child object
if item.I_am_a_list:
itemtype = ListType
except AttributeError:
pass
if itemtype == ListType:
self.sub_list(item) #recurse for sub lists
else: # or just render it
self.s.append(self.render_list_item(item))
# close out this list level
self.s.append(self.pad*self.lvl + self.end_element())
self.lvl = self.lvl - 1 #decrement indentation level
def render_list_item(self, item):
"""Renders the individual list items
Overloaded by child classes to represent other list styles.
"""
return '%s<LI>%s\n' % (self.pad*self.lvl, item)
def start_element(self):
"""Generic creator for the HTML element opening tag.
Reads tagname, attrs and flags to return appropriate tag.
"""
s = ['<' + self.tagname]
for attr in self.attrs:
try:
s.append(' %s="%s"' % (attr, getattr(self, attr)))
except AttributeError:
pass
for flag in self.flags:
try:
x = getattr(self, flag)
s.append(' %s' % flag)
except AttributeError:
pass
s.append('>\n')
return string.join(s, '')
def end_element(self):
"""Closes the HTML element
"""
return '</%s>\n' % self.tagname
def append(self, *items):
"""Append entries to the end of the list
"""
for item in items:
self.data.append(item)
UL = BulletList = List #Aliases
class OrderedList(List):
"""Will generate a numbered list given a list arg.
Optional keyword *type* can be used to specify whether you want
the list items marked with: capital letters (type='A'), small
letters (type='a'), large Roman numerals (type='I'), small Roman
numerals (type='i'). The default is arabic numbers. The other
types are HTML3.2 only and may not be supported by browsers yet.
Any list contents will do. Each of the items will be emitted
in HTML if they are themselves objects.
"""
tagname = 'OL'
attrs = ('type','class','id','style')
OL = NumberedList = OrderedList
class DefinitionList(List):
"""Show a series of items and item definitions.
Arg is a list of tuple pairs:
[(string/object,string/object),(,)...] 1st item in each pair is
the word to be defined. It will be rendered in bold. 2nd is the
string which will be indented to it's next-line-right. If the
*compact* flag is set to non-empty, the definition side will be
placed on the same line. Example
DefinitionList([( 4 , 'Number after 3') , ( 1 , 'Unity')] ) will emit:
4
Number after 3
1
Unity
"""
tagname = 'DL'
attrs = ('class','id','style')
flags = ('compact',)
def render_list_item(self, item):
"""Overload method to perform DT/DD markup.
"""
return '%s<DT><B>%s</B><DD>%s\n' % (self.pad*self.lvl, item[0], item[1])
DL = DefinitionList
class ImageBulletList(List):
"""Show a list of images with adjoining text(or object).
Arg is a list of tuple pairs: [(Image_obj, string/object),(,)...]
Generates an inlined image then the text followed by a <BR>
for each element.
"""
tagname = 'UL'
attrs = ()
flags = ()
def render_list_item(self, item):
"""Overload method to take first item from an item tuple and
setting it next to the second item, using BR to separate list items.
"""
return '%s%s %s<BR>\n' % (self.pad*self.lvl, item[0], item[1])
class NonBulletList(List):
"""Generate a raw indented list without bullet symbols.
Arg is a list of python objects:
"""
tagname = 'UL'
attrs = ()
flags = ()
def render_list_item(self, item):
"""Overload method to take first item from an item tuple and
setting it next to the second item, using BR to separate list items.
"""
return '%s%s<BR>\n' % (self.pad*self.lvl, item)
####### FORM TAGS ########
class Form:
"""Define a user filled form. Uses POST method.
*cgi* is the URL to the CGI processing program. Input objects
(any others as well) are appended to this container widget.
Keywords
name -- name of the form
submit -- The Input object to be used as the submit button.
If none specified a Submit button will automatically
be appended to the form. Do not manually append your
submit button. HTMLgen will append it for you.
reset -- Input object to be used as a reset button.
target -- set a TARGET attribute
enctype -- specify an Encoding type.
onSubmit -- script, which is executed, when the form is submitted
"""
def __init__(self, cgi = None, **kw):
self.contents = []
self.cgi = cgi
self.submit = Input(type='submit', name='SubmitButton', value='Send')
self.reset = None
self.target = None
self.enctype = None
self.name = None
self.onSubmit = ''
overlay_values(self, kw)
def append(self, *items):
"""Append any number of items to the form container.
"""
for item in items:
self.contents.append(str(item))
def __str__(self):
s = ['\n<FORM METHOD="POST"']
if self.cgi: s.append(' ACTION="%s"' % self.cgi)
if self.enctype: s.append(' ENCTYPE="%s"' % self.enctype)
if self.target: s.append(' TARGET="%s"' % self.target)
if self.name: s.append(' NAME="%s"' % self.name)
if self.onSubmit: s.append(' onSubmit="%s"' % self.onSubmit)
s.append('>\n')
s = s + self.contents
s.append(str(self.submit))
if self.reset: s.append(str(self.reset))
s.append('\n</FORM>\n')
return string.join(s, '')
def overlay_values(obj, dict):
"""Adds each item from dict to the given object iff there already
exists such a key. Raises KeyError if you try to update the value
of non-existing keys.
"""
for key in dict.keys():
if hasattr(obj, key):
obj.__dict__[key] = dict[key]
else:
raise KeyError(`key` + ' not a keyword for ' + obj.__class__.__name__)
class Input:
"""General Form Input tags.
Keyword Arguments
type -- 'TEXT' (default) Supported types include password, checkbox,
radio, file, submit, reset, hidden.
name -- provides the datum name
value -- the initial value of the input item
checked -- flag indicating if the item is checked initially
size -- size of the widget (e.g. size=10 for a text widget is it's width)
maxlength -- maximum number of characters accepted by the textfield.
border -- border width in pixels for an image type.
align -- top|middle|bottom align w.r.t. adjoining text for image types.
llabel -- an optional string set to the left of the widget
rlabel -- an optional string set to the right of the widget
onBlur -- script, which is executed, when the field loses focus,
useful for the text-type
onChange -- script, which is executed, when the field value changed,
useful for the text-type
onClick -- script, which is executed, when the field in clicked,
useful for the button, checkbox, radio, submit, reset type
onFocus -- script, which is executed, when the field receives focus,
useful for the text-type
onSelect -- script, which is executed, when part of the field
is selected, useful for the text-type
"""
re_type = re.compile('text|password|checkbox|radio|image|button|file|submit|reset|hidden',
re.IGNORECASE)
def __init__(self, **kw):
self.type = 'TEXT'
self.name = 'Default_Name'
self.value = None
self.checked = ''
self.size = 0
self.maxlength = 0
self.llabel = ''
self.rlabel = ''
self.onBlur = ''
self.onChange = ''
self.onClick = ''
self.onFocus = ''
self.onSelect = ''
self.border = None
self.align = ''
for item in kw.keys():
if self.__dict__.has_key(item):
self.__dict__[item] = kw[item]
else:
raise KeyError, `item`+' not a valid parameter of the Input class.'
if Input.re_type.search(self.type) is None:
raise KeyError, `self.type`+' not a valid type of Input class.'
def __str__(self):
s = []
if self.llabel: s.append(str(self.llabel))
s.append('\n<INPUT')
if self.type: s.append(' TYPE="%s"' % self.type)
if self.name: s.append(' NAME="%s"' % self.name)
if self.value is not None: s.append(' VALUE="%s"' % self.value)
if self.checked: s.append(' CHECKED')
if self.size: s.append(' SIZE=%s' % self.size)
if self.maxlength: s.append(' MAXLENGTH=%s' % self.maxlength)
if self.onBlur: s.append(' onBlur="%s"' % self.onBlur)
if self.onChange: s.append(' onChange="%s"' % self.onChange)
if self.onClick: s.append(' onClick="%s"' % self.onClick)
if self.onFocus: s.append(' onFocus="%s"' % self.onFocus)
if self.onSelect: s.append(' onSelect="%s"' % self.onSelect)
if self.border is not None: s.append(' BORDER="%s"' % self.border)
if self.align: s.append(' ALIGN="%s"' % self.align)
s.append('>')
if self.rlabel: s.append(str(self.rlabel))
return string.join(s, '')
class Select(UserList.UserList):
"""Used to define a list widget or option widget.
Pass a list of strings to show a list with those values. Alternatively
can pass a list of tuple pairs. Each pair contains the displayed string
and it's associatated value mapping. If no value mapping is needed just
use something that evaluates to None.
Keyword Arguments:
name -- provides the datum name
size -- the visual size. 1 means use an option popup widget.
>=2 means use a list widget with that many lines.
multiple -- flag to indicate whether multiple selections are supported.
selected -- list of values to be shown as pre-selected.
onBlur -- script, which is executed, when the field loses focus
onChange -- script, which is executed, when the field value changed
onFocus -- script, which is executed, when the field receives focus
"""
def __init__(self, data=None, **kw):
UserList.UserList.__init__(self, data)
self.name = ''
self.size = 1
self.multiple = None
self.selected = []
self.onBlur = ''
self.onChange = ''
self.onFocus = ''
for item in kw.keys():
if self.__dict__.has_key(item):
self.__dict__[item] = kw[item]
else:
raise KeyError, `item`+' not a valid parameter of the Select class.'
def __str__(self):
s = ['<SELECT NAME="%s"' % self.name]
if self.size: s.append(' SIZE=%s' % self.size)
if self.multiple: s.append(' MULTIPLE')
if self.onBlur: s.append(' onBlur="%s"' % self.onBlur)
if self.onChange: s.append(' onChange="%s"' % self.onChange)
if self.onFocus: s.append(' onFocus="%s"' % self.onFocus)
s.append('>\n')
if type(self.data[0]) is TupleType:
for item, value in self.data:
s.append('<OPTION')
if value is not None:
s.append(' Value="%s"' % value)
if value in self.selected:
s.append(' SELECTED')
else:
if item in self.selected:
s.append(' SELECTED')
s.append('>%s\n' % item)
else:
for item in self.data:
if item not in self.selected:
s.append('<OPTION>%s\n' % item)
else:
s.append('<OPTION SELECTED>%s\n' % item)
s.append('</SELECT>\n')
return string.join(s, '')
class Textarea:
"""Used for an entry widget to type multi-line text (for forms).
Keyword Arguments:
rows -- sets the number of text rows. (default=4)
cols -- sets the number of text columns. (default=40)
onBlur -- script, which is executed, when the field loses focus
onChange -- script, which is executed, when the field value changed
onFocus -- script, which is executed, when the field receives focus
onSelect -- script, which is executed, when part of the field
is selected
"""
def __init__(self, text='', **kw):
self.text = text
self.name = 'text_area'
self.rows = 4
self.cols = 40
self.onBlur = ''
self.onChange = ''
self.onFocus = ''
self.onSelect = ''
for item in kw.keys():
if self.__dict__.has_key(item):
self.__dict__[item] = kw[item]
else:
raise KeyError, `item`+' not a valid parameter of the Textarea class.'
def __str__(self):
s = ['<TEXTAREA NAME="%s" ROWS=%s COLS=%s' % (self.name, self.rows, self.cols)]
if self.onBlur: s.append(' onBlur="%s"' % self.onBlur)
if self.onChange: s.append(' onChange="%s"' % self.onChange)
if self.onFocus: s.append(' onFocus="%s"' % self.onFocus)
if self.onSelect: s.append(' onSelect="%s"' % self.onSelect)
s.append('>')
s.append(str(self.text))
s.append('</TEXTAREA>')
return string.join(s, '')
class Script:
"""Construct a Script
Keyword Arguments
Defaults in (parenthesis). Keyword parameters may be set as attributes of
the instantiated script object as well.
language -- specifies the language ('JavaScript')
src -- specifies the location
code -- script code, which is printed in comments, to hide it from non
java-script browsers
"""
def __init__(self, **kw):
# Specify the default values
self.language = 'JavaScript'
self.src = ''
self.code = ''
# Now overlay the keyword arguments from caller
for k in kw.keys():
if self.__dict__.has_key(k):
self.__dict__[k] = kw[k]
else:
print `k`, "isn't a valid parameter for this class."
def __str__(self):
s = ['<SCRIPT LANGUAGE="%s" ' % self.language]
if self.src: s.append('SRC="%s" ' % self.src)
s.append('>')
if self.code: s.append('<!--\n%s\n//-->\n' % self.code)
s.append('</SCRIPT>')
return string.join(s, '')
def append(self, s):
self.code = self.code + s
####################
class Table:
"""Construct a Table with Python lists.
Instantiate with a string argument for the table's name (caption).
Set object.heading to a list of strings representing the column headings.
Set object.body to a list of lists representing rows. **WARNING:** the body
attribute will be edited to conform to html. If you don't want your
data changed make a copy of this list and use that with the table object.
Keyword Parameters
Defaults in (parenthesis). Keyword parameters may be set as attributes of the
instantiated table object as well.
caption_align -- 'top'|'bottom' specifies the location of the table title ('top')
border -- the width in pixels of the bevel effect around the table (2)
cell_padding -- the distance between cell text and the cell boundary (4)
cell_spacing -- the width of the cell borders themselves (1)
width -- the width of the entire table wrt the current window width ('100%')
colspan -- a list specifying the number of columns spanned by that heading
index. e.g. t.colspan = [2,2] will place 2 headings spanning
2 columns each (assuming the body has 4 columns).
heading -- list of strings, the length of which determine the number of
columns. ( [' ']*3 )
heading_align -- 'center'|'left'|'right'
horizontally align text in the header row ('center')
heading_valign -- 'middle' |'top'|'bottom'
vertically align text in the header row ('middle')
body_color -- a list of colors, for each column (None)
heading_color -- a list of color for each column heading (None)
For both these the index used is i%len(..._color) so
the color cycles through the columns
body -- a list of lists in row major order containing strings or objects
to populate the body of the table. ( [[' ']*3] )
column1_align -- 'left'|'right'|'center' text alignment of the first column
cell_align -- 'left'|'right'|'center' text alignment for all other cells
cell_line_breaks -- 1|0 flag to determine if newline char in body text will be
converted to <br> symbols; 1 they will, 0 they won't. (1)
"""
def __init__(self, tabletitle='', **kw):
"""Arg1 is a string title for the table caption, optional keyword
arguments follow.
"""
# Specify the default values
self.tabletitle = tabletitle
self.caption_align = 'top'
self.border = 2
self.cell_padding = 4
self.cell_spacing = 1
self.width = '100%'
self.heading = None
self.heading_align = 'center'
self.heading_valign = 'middle'
self.body = [[' ']*3]
self.column1_align = 'left'
self.cell_align = 'left'
self.cell_line_breaks = 1
self.colspan = None
self.body_color= None
self.heading_color=None
# Now overlay the keyword arguments from caller
for k in kw.keys():
if self.__dict__.has_key(k):
self.__dict__[k] = kw[k]
else:
print `k`, "isn't a valid parameter for this class."
def __str__(self):
"""Generates the html for the entire table.
"""
if self.tabletitle:
s = [str(Name(self.tabletitle)) + '\n<P>']
else:
s = []
s.append('<TABLE border=%s cellpadding=%s cellspacing=%s width="%s">\n' % \
(self.border, self.cell_padding, self.cell_spacing, self.width))
if self.tabletitle:
s.append('<CAPTION align=%s><STRONG>%s</STRONG></CAPTION>\n' % \
(self.caption_align, self.tabletitle))
for i in range(len(self.body)):
for j in range(len(self.body[i])):
if type(self.body[i][j]) == StringType:
#process cell contents to insert breaks for \n char.
if self.cell_line_breaks:
self.body[i][j] = string.replace(self.body[i][j], '\n','<br>')
else:
self.body[i][j] = Text(self.body[i][j])
# Initialize colspan property to 1 for each
# heading column if user doesn't provide it.
if self.heading:
if not self.colspan:
if type(self.heading[0]) == ListType:
self.colspan = [1]*len(self.heading[0])
else:
self.colspan = [1]*len(self.heading)
# Construct heading spec
# can handle multi-row headings. colspan is a list specifying how many
# columns the i-th element should span. Spanning only applies to the first
# or only heading line.
if self.heading:
prefix = '<TR Align=' + self.heading_align + '> '
postfix = '</TR>\n'
middle = ''
if type(self.heading[0]) == ListType:
for i in range(len(self.heading[0])):
middle = middle + '<TH ColSpan=%s%s>' % \
(self.colspan[i], \
self.get_body_color(self.heading_color,i)) \
+ str(self.heading[0][i]) +'</TH>'
s.append(prefix + middle + postfix)
for i in range(len(self.heading[1])):
middle = middle + '<TH>' + str(self.heading[i]) +'</TH>'
for heading_row in self.heading[1:]:
for i in range(len(self.heading[1])):
middle = middle + '<TH>' + heading_row[i] +'</TH>'
s.append(prefix + middle + postfix)
else:
for i in range(len(self.heading)):
middle = middle + '<TH ColSpan=%s%s>' % \
(self.colspan[i], \
self.get_body_color(self.heading_color,i)) \
+ str(self.heading[i]) +'</TH>'
s.append(prefix + middle + postfix)
# construct the rows themselves
stmp = '<TD Align=%s %s>'
for row in self.body:
s.append('<TR>')
for i in range(len(row)):
if i == 0 :
ss1 = self.column1_align
else:
ss1 = self.cell_align
s.append(stmp % (ss1, self.get_body_color(self.body_color,i)))
s.append(str(row[i]))
s.append('</TD>\n')
s.append('</TR>\n')
#close table
s.append('</TABLE><P>\n')
return string.join(s, '')
def get_body_color(self, colors, i):
"""Return bgcolor argument for column number i
"""
if colors is not None:
try:
index = i % len(colors)
return ' bgcolor="%s"' % colors[index]
except:
pass
return ''
#--------------------New stuff--------------------------#
def _make_attr_inits(opts):
"""Construct a format string and dictionary suitable for value
substitution of tag attributes.
"""
a = []
d = {}
for name in opts:
a.append('%('+name+')s')
d[name] = ''
return string.join(a, ''), d
class AbstractTagSingle:
"Abstract base class for all tag markup classes not requiring a closure tag."
tagname = '' # to be provided by derived classes
attrs = () # to be provided by derived classes
attr_template = '' # to be provided by derived classes
attr_dict = {} # to be provided by derived classes
def __init__(self, *args, **kw):
self.__dict__['attr_dict'] = copy.copy(self.__class__.attr_dict)
self.args = args
for name, value in kw.items():
name = string.lower(name)
setattr(self, name, value)
def __str__(self):
"""Generate an HTML formatted string for this object.
"""
return '<%s' % self.tagname + self.attr_template % self.attr_dict + '>'
def __setattr__(self, name, value):
"""Intercept attribute assignments.
If the attribute is a legal HTML tag attribute add it to the
dict used for substitution in __str__, otherwise just set it as
an instance attribute.
"""
name = string.lower(name)
if name in self.attrs:
self.attr_dict[name] = ' %s="%s"' % (name, value)
self.__dict__[name] = value
class Image(AbstractTagSingle):
"""Inlined Image
The *filename* argument is a filename, or URL of a graphic image,
or a triple of ( filename, width, height ) where dimensions are in
pixels. Where the filename is found to be a valid pathname to an
existing graphic file that file will be read to determine its width and
height properties. GIF, JPEG, and PNG files are understood.
Keyword Arguments
width -- (int) Width in pixels
height -- (int) Height in pixels
border -- (int) Border width in pixels
align -- (string) 'top'|'middle'|'bottom'|'right'|'left'
alt -- (string) Text to substitute for the image in nonGUI browsers
usemap -- Imagemap name or Map object
ismap -- Flag (1|0) indicating if a server side imagemap is available.
absolute -- Absolute path to the directory containing the image
prefix -- Relative path or URL to directory containing the image
hspace -- Number of pixels to be added to the left and right of the image.
vspace -- Number of pixels to be added to the top and bottom of the image.
name -- A name for this image to be used by JavaScript
Class -- A CSS class this tag belongs to.
style -- A CSS inline style specification.
"""
tagname = 'IMG'
attrs = ('src', 'height', 'width', 'alt', 'border', 'align', 'class','id',
'hspace','vspace', 'lowsrc', 'name', 'style', 'usemap', 'ismap' )
attr_template , attr_dict = _make_attr_inits(attrs)
def __init__(self, *args, **kw):
apply(AbstractTagSingle.__init__, (self,) + args, kw)
self.prefix = None
self.absolute = None
if self.args:
self.process_arg(self.args[0])
def process_arg(self, arg):
# unpack the tuple if needed
if type(arg) == TupleType:
self.filename = arg[0]
self.width = arg[1]
self.height = arg[2]
else:
self.filename = arg
self.src = self.filename
# if the file is there test it to get size
if not self.attr_dict['width'] and os.path.isfile(self.filename): # assume if the user has set the width property
# she knows the image size already or wants to resize it.
try:
self.width, self.height = imgsize(self.filename)
except IOError:
pass
def calc_rel_path(self, from_dir=None):
"""Calculate the relative path from 'from_dir' to the
absolute location of the image file.
Sets self.prefix.
"""
if not from_dir:
from_dir = os.getcwd()
if self.absolute:
self.prefix = relpath(from_dir, self.absolute)
def __str__(self):
if self.prefix:
self.src = os.path.join(self.prefix, self.filename)
if not self.attr_dict['alt']:
self.alt = os.path.basename(self.filename)
if self.attr_dict['usemap']:
if type(self.attr_dict['usemap']) == InstanceType:
# can use a Map instance for this
try:
self.usemap = '#' + self.usemap.name
except:
pass
return AbstractTagSingle.__str__(self)
IMG = Image # alias
class BR(AbstractTagSingle):
"""Break tag. Argument is an integer integer multiplier. BR(2)=='<BR><BR>'
"""
tagname = 'BR'
attrs = ('clear',)
attr_template , attr_dict = _make_attr_inits(attrs)
def __str__(self):
s = AbstractTagSingle.__str__(self)
if self.args and type(self.args[0]) is IntType:
return s*self.args[0]
else:
return s
class Base(AbstractTagSingle):
"""Specify the base URL for all relative URLs in this document.
One string argument required. It must be a complete file name, and
is usually the original URL of this document. If this file is
moved, having the BASE set to the original URL eliminates the need
to also move all the documents which are identified by relative
URL links in this document.
"""
tagname = 'BASE'
attrs = ('href', 'target')
attr_template , attr_dict = _make_attr_inits(attrs)
class BaseFont(AbstractTagSingle):
"""Specify the font size for subsequent text.
"""
tagname = 'BASEFONT'
attrs = ('color', 'name', 'size')
attr_template , attr_dict = _make_attr_inits(attrs)
class Embed(AbstractTagSingle):
"""Embed an application in this document.
"""
tagname = 'EMBED'
attrs = ('align', 'border', 'height', 'hidden', 'hspace',
'name', 'palette', 'pluginspage', 'src', 'type',
'units', 'vspace', 'width')
attr_template , attr_dict = _make_attr_inits(attrs)
class HR(AbstractTagSingle):
"""Break the current text flow and insert a horizontal rule.
"""
tagname = 'HR'
attrs = ('align', 'class','id', 'color', 'noshade', 'size',
'style', 'width')
attr_template , attr_dict = _make_attr_inits(attrs)
class AbstractTag:
"Abstract base class for all tag markup classes requiring a closure tag."
tagname = '' # to be provided by derived classes
attrs = () # to be provided by derived classes
attr_template = '' # to be provided by derived classes
attr_dict = {} # to be provided by derived classes
html_escape = 'ON'
trailer = '\n'
def __init__(self, *contents, **kw):
self.__dict__['contents'] = []
self.__dict__['attr_dict'] = copy.copy(self.__class__.attr_dict)
for item in contents:
self.contents.append(item)
for name, value in kw.items():
name = string.lower(name)
setattr(self, name, value)
def __str__(self):
"""Generate an HTML formatted string for this object.
"""
s = ['<%s' % self.tagname] # tag opening
s.append(self.attr_template % self.attr_dict + '>') # options
# crunch through the contents
for item in self.contents:
if type(item) is StringType and self.html_escape == 'ON':
s.append(escape(item))
else:
s.append(str(item))
# close out the marked region
s.append( '</%s>' % self.tagname)
return string.join(s, '') + self.trailer
def __setattr__(self, name, value):
"""Intercept attribute assignments.
If the attribute is a legal HTML tag attribute add it to the
dict used for substitution in __str__, otherwise just set it as
an instance attribute.
"""
name = string.lower(name)
if name in self.attrs:
self.attr_dict[name] = ' %s="%s"' % (name, value)
else:
self.__dict__[name] = value
def __call__(self, text):
"""Enable instances to be callable as text processing functions.
For Example:
>>> S = HTMLgen.Strong()
>>> print S('Hi!')
>>> <STRONG>Hi!</STRONG>
"""
self.__dict__['contents'] = [text]
return str(self)
def __add__(self, other):
"""Support self + list
"""
if type(other) is ListType:
self.contents = self.contents + other
return self
else:
raise TypeError, 'can only add lists to this object'
def append(self, *items):
"""Append one or more items to the end of the container.
"""
for item in items:
self.contents.append(item)
def prepend(self, *items):
"""Prepend one or more items to the top of the container.
"""
for item in items:
self.contents.insert(0, item)
def empty(self):
"""Empty the contents of the container.
"""
self.contents = []
def __len__(self):
"""Return the integer length of the container list.
"""
return len(self.contents)
def last(self):
"""Return a reference to the last item in the container.
"""
return self.contents[-1]
def copy(self):
"""Return a full copy of the object.
"""
return copy.deepcopy(self)
def markup(self, rex=None, marker=None, **kw):
"""Markup the contained text matching a regular expression with
a tag class instance or function.
Arguments
rex -- a regular expression object or pattern which will be used
to match all text patterns in the Paragraph body. Must have a single
group defined. Group 1 is the matching text that will be marked.
Default to all parenthetical text.
marker -- an HTMLgen class instance to which the found text will
be sent for wrapping (using its __call__ method). Default is Emphasis.
Keywords
collapse -- When set to 1 removes the non-grouped matching text
from the output. Default 0.
Returns the number of matching text groups.
"""
collapse = 0
if kw.has_key('collapse'): collapse = kw['collapse']
text = string.join(map(str, self.contents))
newtext, count = markup_re(text, rex, marker, collapse)
if count:
self.contents = [newtext]
self.html_escape = 'OFF'
return count
class Area(AbstractTagSingle):
"""Specify a click-sensitive area of an image.
The area is linked to a HREF specified by the *href* attribute.
The *coords* attribute is required and describes the position of
an area (in pixels) of the image in comma-separated x,y
coordinates where the upper-left corner is "0,0". For shape='rect'
(the default), it is "left,top,right,bottom". For shape='circle',
it is "center_x,center_y,radius". For shape='polygon', it is
successive x,y vertices of the polygon. If the first and last
coordinates are not the same, then a segment is inferred to close
the polygon. If no *href* keyword is given a *NOHREF* will be
generated indicating that this region should generate no links.
Keyword Arguments
href -- Typically a reference to an image
coords -- string holding a list of coordinates defining
shape -- 'rect'|'circle'|'polygon'
"""
tagname = 'AREA'
attrs = ('alt','class','coords','href','id','name',
'onmouseout','onmouseover','shape','target')
attr_template, attr_dict = _make_attr_inits(attrs)
attr_dict['href'] = ' nohref'
###### FRAME SUPPORT ######
class Frameset(AbstractTag):
"""Define a Frameset to contain Frames or more Framesets"""
tagname = 'FRAMESET'
attrs = ('border','bordercolor','cols','frameborder','framespacing','onblur',
'onfocus','onload','onunload','rows')
attr_template, attr_dict = _make_attr_inits(attrs)
class NoFrames(AbstractTag):
"""Issue a message on browsers that don't support frames"""
tagname = 'NOFRAMES'
attrs = ()
attr_template, attr_dict = _make_attr_inits(attrs)
def __init__(self, *contents, **kw):
AbstractTag.__init__(self)
for content in contents: self.append(content)
for name, value in kw.items(): self.__setattr__(name,value)
if len(contents) == 0:
self.append(Heading(2,'Frame ALERT!',align='center'),
Para("""This document is designed to be viewed using Netscape's
Frame features. If you are seeing this message, you are using
a frame challenged browser."""),
Para('A ',Strong('Frame-capable'),' browser can be retrieved from',
Href('http://home.netscape.com/','Netscape Communications'),
' or ',
Href('http://www.microsoft.com/','Microsoft')))
class Frame(AbstractTag):
"""Define the characteristics of an individual frame.
Keywords Arguments
src -- is a HREF which points to the initial contents of the frame.
name -- is the window name used by others to direct content into this frame.
marginwidth -- is the number of pixels used to pad the left and right
sides of the frame.
marginheight -- is the number of pixels used to pad the top and bottom
sides of the frame.
scrolling -- is used to indicate scrolling policy set to 'yes'|'no'|'auto'
noresize -- is a flag which instructs the browser to disallow frame resizing.
set to non zero lock size ( noresize=1 ).
"""
tagname = 'FRAME'
attrs = ('align','bordercolor','frameborder','marginheight','marginwidth','name',
'noresize','scrolling','src')
attr_template, attr_dict = _make_attr_inits(attrs)
class Paragraph(AbstractTag):
"""Define a Paragraph.
Takes a single string/object argument and the optional
keyword argument 'align' which may be one of (left, right,
center). As always, Class and style keywords are supported.
**Not to be confused with class P**. That is
just for inserting a para break.
Example:
Paragraph('Some text to center', align='center')
"""
tagname = 'P'
attrs = ('class','id', 'style', 'align')
attr_template , attr_dict = _make_attr_inits(attrs)
Para = Paragraph # Alias
# Headings
class Heading(AbstractTag):
"""Heading markups for H1 - H6
Heading(level, text, **kw)
The *level* arg is an integer for the level of the heading.
Valid levels are 1-6.
The *text* arg is a string (or any object) for the text of the heading.
Keyword arguments are align, Class, and style.
For example:
h = Heading(2, 'Chapter 3', align='center')
"""
tagname = ''
attrs = ('class','id', 'style', 'align')
attr_template , attr_dict = _make_attr_inits(attrs)
def __str__(self):
if not self.tagname:
if self.contents[0] not in (1,2,3,4,5,6):
raise AttributeError, "First arg of Heading must be int from 1 to 6."
self.tagname = 'H%d' % self.contents[0]
del self.contents[0]
return AbstractTag.__str__(self)
H = Head = Header = Heading # Aliases
class Caption(AbstractTag):
"""Define a caption for a table.
"""
tagname = 'CAPTION'
attrs = ('class','id', 'style', 'align', 'valign')
attr_template , attr_dict = _make_attr_inits(attrs)
class TH(AbstractTag):
"""Define a table header cell.
"""
tagname = 'TH'
attrs = ('class','id', 'style', 'nowrap', 'align','valign','rowspan',
'colspan', 'height', 'width', 'bgcolor', 'background',
'bordercolor', 'bordercolordark', 'bordercolorlight')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class TR(AbstractTag):
"""Define a row of cells within a table.
"""
tagname = 'TR'
attrs = ('class','id', 'style', 'align', 'bgcolor', 'bordercolor',
'bordercolordark', 'bordercolorlight', 'nowrap', 'valign')
attr_template , attr_dict = _make_attr_inits(attrs)
class TD(AbstractTag):
"""Define a table data cell.
"""
tagname = 'TD'
attrs = ('class','id', 'style', 'nowrap', 'align','valign', 'background',
'bordercolor', 'bordercolordark', 'bordercolorlight',
'rowspan','colspan','height', 'width','bgcolor', 'title')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class TableLite(AbstractTag):
"""Container class for TH TD TR and Caption objects.
"""
tagname = 'TABLE'
attrs = ('class','id', 'style', 'align', 'background', 'border',
'bordercolor', 'bordercolordark', 'bordercolorlight',
'cols', 'frame', 'cellpadding', 'cellspacing',
'height', 'hspace', 'width', 'bgcolor', 'nowrap',
'rules', 'valign', 'vspace')
attr_template , attr_dict = _make_attr_inits(attrs)
class Pre(AbstractTag):
"""Render the text verbatim honoring line breaks and spacing.
Does not escape special characters. To override this set html_escape
to 'ON'.
"""
tagname = 'PRE'
attrs = ('width',)
attr_template , attr_dict = _make_attr_inits(attrs)
html_escape = 'OFF'
class Strike(AbstractTag):
"""The text is struck trough with a horizontal line.
"""
tagname = 'STRIKE'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Blockquote(AbstractTag):
"""Indent text as a block quotation.
"""
tagname = 'BLOCKQUOTE'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
Indent = Blockquote
class Big(AbstractTag):
"""Format text in a bigger font.
"""
tagname = 'BIG'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Font(AbstractTag):
"""Set the size or color of the text.
"""
tagname = 'FONT'
attrs = ('color', 'face', 'size')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Address(AbstractTag):
"""A mailing address. Not a URL.
"""
tagname = 'ADDRESS'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Emphasis(AbstractTag):
"""Format with additional emphasis. (usually italics)
"""
tagname = 'EM'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Center(AbstractTag):
"""Center the text.
"""
tagname = 'center'
attrs = ()
attr_template , attr_dict = _make_attr_inits(attrs)
class Cite(AbstractTag):
"""A citation.
"""
tagname = 'CITE'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class KBD(AbstractTag):
"""Keyboard-like input.
"""
tagname = 'KBD'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
html_escape = 'OFF'
class Sample(AbstractTag):
"""Sample text. Escaping of special characters is not performed.
To enable escaping set html_escape='ON'.
"""
tagname = 'SAMP'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
html_escape = 'OFF'
class Strong(AbstractTag):
"""Strongly emphasize the text.
"""
tagname = 'STRONG'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Code(AbstractTag):
"""Code sample. Escaping of special characters is not performed.
To enable escaping set html_escape='ON'.
"""
tagname = 'CODE'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
html_escape = 'OFF'
class Define(AbstractTag):
"""Format as definition text.
"""
tagname = 'DFN'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
class Var(AbstractTag):
"""Used for variable names.
"""
tagname = 'VAR'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Div(AbstractTag):
"""Specify a division within a document.
"""
tagname = 'DIV'
attrs = ('class','id', 'style', 'align', 'lang', 'nowrap')
attr_template , attr_dict = _make_attr_inits(attrs)
class TT(AbstractTag):
"""Format teletype style.
"""
tagname = 'TT'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class U(AbstractTag):
"""Underlined text.
"""
tagname = 'U'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Nobr(AbstractTag):
"""Specify non-breaking text.
"""
tagname = 'NOBR'
attrs = ()
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Small(AbstractTag):
"""Render in a smaller font.
"""
tagname = 'SMALL'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Sub(AbstractTag):
"""Render as subscript.
"""
tagname = 'SUB'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Sup(AbstractTag):
"""Render as subscript.
"""
tagname = 'SUP'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
trailer = ''
class Span(AbstractTag):
"""Generic tag to mark text for a style application.
"""
tagname = 'SPAN'
attrs = ('class','id', 'style')
attr_template , attr_dict = _make_attr_inits(attrs)
# Text Formatting Classes
class InitialCaps:
"""Utility class to process text into Initial Upper Case style
using Font specifications. All text is converted to upper case
and the initial characters are altered by the size given by
the optional second argument. The rest of the characters are
altered by the size given in the optional third argument.
For example:
InitialCaps('We the people', '+3', '+1')
"""
def __init__(self, text='', upsize = '+2', downsize = '+1'):
self.hi = Font(size=upsize)
self.lo = Font(size=downsize)
self.text = text
self.upsize = upsize
self.downsize = downsize
def __str__(self):
list = string.split(self.text)
wordlist = []
for word in list:
word = self.hi(string.upper(word[0])) + self.lo(string.upper(word[1:]))
wordlist.append(word)
return string.join(wordlist)
def __call__(self, text):
self.text = text
return self.__str__()
class Text:
"""Class to encapsulate text. Escape special characters for HTML.
"""
def __init__(self, text=''):
if type(text) == StringType:
text = escape(text)
self.text = str(text)
def append(self, text=''):
"""Concatenate text characters onto the end.
Will escape special characters.
"""
if type(text) == StringType:
text = escape(text)
self.text = self.text + ' ' + str(text)
def __str__(self):
return self.text
class RawText:
"""Class to encapsulate raw text. Does **NOT** escape special characters.
"""
def __init__(self, text=''):
self.text = text
def append(self, text):
self.text = self.text + str(text)
def __str__(self):
return self.text
# ALIASES
PRE = Pre
Bold = STRONG = Strong
Italic = EM = Emphasis
Typewriter = TT
class Comment:
"""Place a comment internal to the HTML document.
Will not be visible from the browser.
"""
def __init__(self, text=''):
self.text = text
def __str__(self):
return '\n<!-- %s -->\n' % self.text
def __call__(self, text):
self.text = text
return self.__str__()
###### UTILITIES USED INTERNALLY ########
def escape(text, replace=string.replace):
"""Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
return text
def markup_re(text, rex=None, marker=None, collapse=0):
"""Markup the contained text with a given re pattern/object with
a given tag class instance. Uses re module.
Arguments
text -- string to act on
rex -- a regular expression object or pattern from the re module which will be used
to match all text patterns in the Paragraph body. Must have a single
group defined. Group 1 is the matching text that will be marked.
Defaults to all parenthetical text.
marker -- an HTMLgen class instance to which the found text will
be sent for wrapping (using its __call__ method). Default is Emphasis.
Can be your function as well.
collapse -- Optional flag. When set to 1 removes the non-
grouped matching text from the output. Default 0.
Returns tuple pair of the marked text and the number of matching text groups.
"""
if rex is None: rex = re.compile('\(([^)]*)\)')
if marker is None: marker = Emphasis()
if type(rex) == StringType: rex = re.compile(rex)
endpoints = []
output = []
i = 0
count = 0
while 1:
# build up a list of tuples: ( 'u'|'m', begin, end )
# 'u' indicates unmarked text and 'm' marked text
# begin and end is the range of characters
match = rex.search(text, i)
if match:
if collapse: #skip chars outside group1
endpoints.append( ('u', i, match.start(0)) )
i = match.end(0)
else: #incl chars outside group1
endpoints.append( ('u', i, match.start(1)) )
i = match.end(1)
endpoints.append( ('m', match.start(1), match.end(1)) ) #text2Bmarked
count = count + 1
else:
endpoints.append( ('u', i, len(text) ) ) # tack on an ending slice
break
if count == 0: return text, 0 # didn't find any matches
for (style, begin, end) in endpoints:
if style == 'm':
output.append(marker(text[begin:end]))
else:
output.append(text[begin:end])
return string.join(output, ''), count
class URL:
"""Represent a Universal Resource Locator.
Assumed to be of the form: **http://www.node.edu/directory/file.html**
with *http* being an example protocol, *www.node.edu* being an example
network node, *directory* being the directory path on that node, and
*file.html* being the target filename. The argument string is parsed
into attributes .proto , .node , .dir , .file respectively and may
be altered individually after instantiation. The __str__ method
simply reassembles the components into a full URL string.
"""
def __init__(self, url):
self.url = url
self.parse(url)
def parse(self, url):
import urlparse
self.unparse = urlparse.urlunparse
self.proto, self.node, self.path, self.params, self.query, self.fragment = \
urlparse(url)
self.dir, self.file = self.split(self.path)
def split(self, p):
"""Same as posixpath.split()
Copied here for availability on the Mac.
"""
i = string.rfind(p, '/') + 1
head, tail = p[:i], p[i:]
if head and head != '/'*len(head):
while head[-1] == '/':
head = head[:-1]
return head, tail
def __str__(self):
return self.unparse( (self.proto,
self.node,
self.dir+self.file,
self.params,
self.query, self.fragment) )
def copy(self):
"""No argument. Return a copy of this object.
"""
return copy.deepcopy(self)
def mpath(path):
"""Converts a POSIX path to an equivalent Macintosh path.
Works for ./x ../x /x and bare pathnames.
Won't work for '../../style/paths'.
Also will expand environment variables and Cshell tilde
notation if running on a POSIX platform.
"""
import os
if os.name == 'mac' : #I'm on a Mac
if path[:3] == '../': #parent
mp = '::'
path = path[3:]
elif path[:2] == './': #relative
mp = ':'
path = path[2:]
elif path[0] == '/': #absolute
mp = ''
path = path[1:]
else: # bare relative
mp = ''
pl = string.split(path, '/')
mp = mp + string.join(pl, ':')
return mp
elif os.name == 'posix': # Expand Unix variables
if path[0] == '~' :
path = os.path.expanduser( path )
if '$' in path:
path = os.path.expandvars( path )
return path
else: # needs to take care of dos & nt someday
return path
#_realopen = open #If I do a lot of mpath I can overload 'open'
#def open(filename, mode = 'r', bufsize = -1):
# return _realopen( mpath(filename), mode, bufsize )
def relpath(path1, path2):
"""Return the relative path from directory 'path1' to directory 'path2'
Both arguments are assumed to be directory names as there is no
way to really distinguish a file from a directory by names
alone. To loosen this restriction one can either assume that both
arguments represent files or directories currently extant so that
they can be tested, or add extra arguments to flag the path types
(file or directory).
I chose to impose this restriction because I will use this function
in places where the pathnames are for files yet to be created.
"""
common = os.path.commonprefix([path1, path2])
sliceoff = len(common)
path1 = path1[sliceoff:]
path2 = path2[sliceoff:]
dirs1 = string.split(path1, os.sep) # list of directory components below
# the common path
dirs1 = filter(lambda x: x, dirs1) # filter out empty elements
rel = (os.pardir+os.sep)*len(dirs1) # construct the relative path to the
# common point
return rel+path2
def compare_f2f(f1, f2):
"""Helper to compare two files, return 0 if they are equal."""
BUFSIZE = 8192
fp1 = open(f1)
try:
fp2 = open(f2)
try:
while 1:
b1 = fp1.read(BUFSIZE)
b2 = fp2.read(BUFSIZE)
if not b1 and not b2: return 0
c = cmp(b1, b2)
if c:
return c
finally:
fp2.close()
finally:
fp1.close()
def compare_s2f(s, f2):
"""Helper to compare a string to a file, return 0 if they are equal."""
BUFSIZE = 8192
i = 0
fp2 = open(f2)
try:
while 1:
try:
b1 = s[i: i + BUFSIZE]
i = i + BUFSIZE
except IndexError:
b1 = ''
b2 = fp2.read(BUFSIZE)
if not b1 and not b2: return 0
c = cmp(b1, b2)
if c: return c
finally:
fp2.close()
| {
"repo_name": "emilybache/texttest-runner",
"path": "src/main/python/lib/default/batch/HTMLgen.py",
"copies": "1",
"size": "94192",
"license": "mit",
"hash": -5430824176353145000,
"line_mean": 35.2835130971,
"line_max": 137,
"alpha_frac": 0.5799324783,
"autogenerated": false,
"ratio": 3.9792150732964386,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5059147551596439,
"avg_score": null,
"num_lines": null
} |
"""
Directives for typically HTML-specific constructs.
"""
__docformat__ = 'reStructuredText'
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import states
from docutils.transforms import components
class MetaBody(states.SpecializedBody):
class meta(nodes.Special, nodes.PreBibliographic, nodes.Element):
"""HTML-specific "meta" element."""
pass
def field_marker(self, match, context, next_state):
"""Meta element."""
node, blank_finish = self.parsemeta(match)
self.parent += node
return [], next_state, []
def parsemeta(self, match):
name = self.parse_field_marker(match)
indented, indent, line_offset, blank_finish = \
self.state_machine.get_first_known_indented(match.end())
node = self.meta()
pending = nodes.pending(components.Filter,
{'component': 'writer',
'format': 'html',
'nodes': [node]})
node['content'] = ' '.join(indented)
if not indented:
line = self.state_machine.line
msg = self.reporter.info(
'No content for meta tag "%s".' % name,
nodes.literal_block(line, line),
line=self.state_machine.abs_line_number())
return msg, blank_finish
tokens = name.split()
try:
attname, val = utils.extract_name_value(tokens[0])[0]
node[attname.lower()] = val
except utils.NameValueError:
node['name'] = tokens[0]
for token in tokens[1:]:
try:
attname, val = utils.extract_name_value(token)[0]
node[attname.lower()] = val
except utils.NameValueError, detail:
line = self.state_machine.line
msg = self.reporter.error(
'Error parsing meta tag attribute "%s": %s.'
% (token, detail), nodes.literal_block(line, line),
line=self.state_machine.abs_line_number())
return msg, blank_finish
self.document.note_pending(pending)
return pending, blank_finish
class Meta(Directive):
has_content = True
SMkwargs = {'state_classes': (MetaBody,)}
def run(self):
self.assert_has_content()
node = nodes.Element()
new_line_offset, blank_finish = self.state.nested_list_parse(
self.content, self.content_offset, node,
initial_state='MetaBody', blank_finish=1,
state_machine_kwargs=self.SMkwargs)
if (new_line_offset - self.content_offset) != len(self.content):
# incomplete parse of block?
error = self.state_machine.reporter.error(
'Invalid meta directive.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
node += error
return node.children
| {
"repo_name": "clumsy/intellij-community",
"path": "python/helpers/py2only/docutils/parsers/rst/directives/html.py",
"copies": "5",
"size": "3212",
"license": "apache-2.0",
"hash": -8830700353368594000,
"line_mean": 35.9195402299,
"line_max": 73,
"alpha_frac": 0.5716064757,
"autogenerated": false,
"ratio": 4.1986928104575165,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7270299286157516,
"avg_score": null,
"num_lines": null
} |
"""
Directives for typically HTML-specific constructs.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import states
from docutils.transforms import components
class MetaBody(states.SpecializedBody):
class meta(nodes.Special, nodes.PreBibliographic, nodes.Element):
"""HTML-specific "meta" element."""
pass
def field_marker(self, match, context, next_state):
"""Meta element."""
node, blank_finish = self.parsemeta(match)
self.parent += node
return [], next_state, []
def parsemeta(self, match):
name = self.parse_field_marker(match)
indented, indent, line_offset, blank_finish = \
self.state_machine.get_first_known_indented(match.end())
node = self.meta()
pending = nodes.pending(components.Filter,
{'component': 'writer',
'format': 'html',
'nodes': [node]})
node['content'] = ' '.join(indented)
if not indented:
line = self.state_machine.line
msg = self.reporter.info(
'No content for meta tag "%s".' % name,
nodes.literal_block(line, line),
line=self.state_machine.abs_line_number())
return msg, blank_finish
tokens = name.split()
try:
attname, val = utils.extract_name_value(tokens[0])[0]
node[attname.lower()] = val
except utils.NameValueError:
node['name'] = tokens[0]
for token in tokens[1:]:
try:
attname, val = utils.extract_name_value(token)[0]
node[attname.lower()] = val
except utils.NameValueError, detail:
line = self.state_machine.line
msg = self.reporter.error(
'Error parsing meta tag attribute "%s": %s.'
% (token, detail), nodes.literal_block(line, line),
line=self.state_machine.abs_line_number())
return msg, blank_finish
self.document.note_pending(pending)
return pending, blank_finish
class Meta(Directive):
has_content = True
SMkwargs = {'state_classes': (MetaBody,)}
def run(self):
self.assert_has_content()
node = nodes.Element()
new_line_offset, blank_finish = self.state.nested_list_parse(
self.content, self.content_offset, node,
initial_state='MetaBody', blank_finish=1,
state_machine_kwargs=self.SMkwargs)
if (new_line_offset - self.content_offset) != len(self.content):
# incomplete parse of block?
error = self.state_machine.reporter.error(
'Invalid meta directive.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
node += error
return node.children
| {
"repo_name": "pwoodworth/intellij-community",
"path": "python/helpers/docutils/parsers/rst/directives/html.py",
"copies": "61",
"size": "3223",
"license": "apache-2.0",
"hash": -8302856566071981000,
"line_mean": 35.625,
"line_max": 73,
"alpha_frac": 0.5724480298,
"autogenerated": false,
"ratio": 4.196614583333333,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
Directives for typically HTML-specific constructs.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import states
from docutils.transforms import components
class MetaBody(states.SpecializedBody):
class meta(nodes.Special, nodes.PreBibliographic, nodes.Element):
"""HTML-specific "meta" element."""
pass
def field_marker(self, match, context, next_state):
"""Meta element."""
node, blank_finish = self.parsemeta(match)
self.parent += node
return [], next_state, []
def parsemeta(self, match):
name = self.parse_field_marker(match)
indented, indent, line_offset, blank_finish = \
self.state_machine.get_first_known_indented(match.end())
node = self.meta()
pending = nodes.pending(components.Filter,
{'component': 'writer',
'format': 'html',
'nodes': [node]})
node['content'] = ' '.join(indented)
if not indented:
line = self.state_machine.line
msg = self.reporter.info(
'No content for meta tag "%s".' % name,
nodes.literal_block(line, line),
line=self.state_machine.abs_line_number())
return msg, blank_finish
tokens = name.split()
try:
attname, val = utils.extract_name_value(tokens[0])[0]
node[attname.lower()] = val
except utils.NameValueError:
node['name'] = tokens[0]
for token in tokens[1:]:
try:
attname, val = utils.extract_name_value(token)[0]
node[attname.lower()] = val
except utils.NameValueError, detail:
line = self.state_machine.line
msg = self.reporter.error(
'Error parsing meta tag attribute "%s": %s.'
% (token, detail), nodes.literal_block(line, line),
line=self.state_machine.abs_line_number())
return msg, blank_finish
self.document.note_pending(pending)
return pending, blank_finish
class Meta(Directive):
has_content = True
SMkwargs = {'state_classes': (MetaBody,)}
def run(self):
self.assert_has_content()
node = nodes.Element()
new_line_offset, blank_finish = self.state.nested_list_parse(
self.content, self.content_offset, node,
initial_state='MetaBody', blank_finish=1,
state_machine_kwargs=self.SMkwargs)
if (new_line_offset - self.content_offset) != len(self.content):
# incomplete parse of block?
error = self.state_machine.reporter.error(
'Invalid meta directive.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
node += error
return node.children
| {
"repo_name": "rimbalinux/LMD3",
"path": "docutils/parsers/rst/directives/html.py",
"copies": "2",
"size": "3311",
"license": "bsd-3-clause",
"hash": -2087029132208196000,
"line_mean": 35.625,
"line_max": 73,
"alpha_frac": 0.5572334642,
"autogenerated": false,
"ratio": 4.23943661971831,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5796670083918309,
"avg_score": null,
"num_lines": null
} |
"""
Directives for typically HTML-specific constructs.
"""
__docformat__ = 'reStructuredText'
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import states
from docutils.transforms import components
class MetaBody(states.SpecializedBody):
class meta(nodes.Special, nodes.PreBibliographic, nodes.Element):
"""HTML-specific "meta" element."""
pass
def field_marker(self, match, context, next_state):
"""Meta element."""
node, blank_finish = self.parsemeta(match)
self.parent += node
return [], next_state, []
def parsemeta(self, match):
name = self.parse_field_marker(match)
indented, indent, line_offset, blank_finish = \
self.state_machine.get_first_known_indented(match.end())
node = self.meta()
pending = nodes.pending(components.Filter,
{'component': 'writer',
'format': 'html',
'nodes': [node]})
node['content'] = ' '.join(indented)
if not indented:
line = self.state_machine.line
msg = self.reporter.info(
'No content for meta tag "%s".' % name,
nodes.literal_block(line, line))
return msg, blank_finish
tokens = name.split()
try:
attname, val = utils.extract_name_value(tokens[0])[0]
node[attname.lower()] = val
except utils.NameValueError:
node['name'] = tokens[0]
for token in tokens[1:]:
try:
attname, val = utils.extract_name_value(token)[0]
node[attname.lower()] = val
except utils.NameValueError as detail:
line = self.state_machine.line
msg = self.reporter.error(
'Error parsing meta tag attribute "%s": %s.'
% (token, detail), nodes.literal_block(line, line))
return msg, blank_finish
self.document.note_pending(pending)
return pending, blank_finish
class Meta(Directive):
has_content = True
SMkwargs = {'state_classes': (MetaBody,)}
def run(self):
self.assert_has_content()
node = nodes.Element()
new_line_offset, blank_finish = self.state.nested_list_parse(
self.content, self.content_offset, node,
initial_state='MetaBody', blank_finish=True,
state_machine_kwargs=self.SMkwargs)
if (new_line_offset - self.content_offset) != len(self.content):
# incomplete parse of block?
error = self.state_machine.reporter.error(
'Invalid meta directive.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
node += error
return node.children
| {
"repo_name": "jk1/intellij-community",
"path": "python/helpers/py3only/docutils/parsers/rst/directives/html.py",
"copies": "44",
"size": "3089",
"license": "apache-2.0",
"hash": -7301818432584327000,
"line_mean": 35.3411764706,
"line_max": 73,
"alpha_frac": 0.5739721593,
"autogenerated": false,
"ratio": 4.208446866485014,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00016570008285004143,
"num_lines": 85
} |
"""
Directives for typically HTML-specific constructs.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import states
from docutils.transforms import components
class MetaBody(states.SpecializedBody):
class meta(nodes.Special, nodes.PreBibliographic, nodes.Element):
"""HTML-specific "meta" element."""
pass
def field_marker(self, match, context, next_state):
"""Meta element."""
node, blank_finish = self.parsemeta(match)
self.parent += node
return [], next_state, []
def parsemeta(self, match):
name = self.parse_field_marker(match)
indented, indent, line_offset, blank_finish = \
self.state_machine.get_first_known_indented(match.end())
node = self.meta()
pending = nodes.pending(components.Filter,
{'component': 'writer',
'format': 'html',
'nodes': [node]})
node['content'] = ' '.join(indented)
if not indented:
line = self.state_machine.line
msg = self.reporter.info(
'No content for meta tag "%s".' % name,
nodes.literal_block(line, line))
return msg, blank_finish
tokens = name.split()
try:
attname, val = utils.extract_name_value(tokens[0])[0]
node[attname.lower()] = val
except utils.NameValueError:
node['name'] = tokens[0]
for token in tokens[1:]:
try:
attname, val = utils.extract_name_value(token)[0]
node[attname.lower()] = val
except utils.NameValueError, detail:
line = self.state_machine.line
msg = self.reporter.error(
'Error parsing meta tag attribute "%s": %s.'
% (token, detail), nodes.literal_block(line, line))
return msg, blank_finish
self.document.note_pending(pending)
return pending, blank_finish
class Meta(Directive):
has_content = True
SMkwargs = {'state_classes': (MetaBody,)}
def run(self):
self.assert_has_content()
node = nodes.Element()
new_line_offset, blank_finish = self.state.nested_list_parse(
self.content, self.content_offset, node,
initial_state='MetaBody', blank_finish=True,
state_machine_kwargs=self.SMkwargs)
if (new_line_offset - self.content_offset) != len(self.content):
# incomplete parse of block?
error = self.state_machine.reporter.error(
'Invalid meta directive.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
node += error
return node.children
| {
"repo_name": "marcoantoniooliveira/labweb",
"path": "oscar/lib/python2.7/site-packages/docutils/parsers/rst/directives/html.py",
"copies": "128",
"size": "3098",
"license": "bsd-3-clause",
"hash": -6939121412753285000,
"line_mean": 35.023255814,
"line_max": 73,
"alpha_frac": 0.574564235,
"autogenerated": false,
"ratio": 4.203527815468114,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00016377333770062235,
"num_lines": 86
} |
# $Id: icmp6.py 23 2006-11-08 15:45:33Z dugsong $
# -*- coding: utf-8 -*-
"""Internet Control Message Protocol for IPv6."""
from __future__ import absolute_import
from . import dpkt
ICMP6_DST_UNREACH = 1 # dest unreachable, codes:
ICMP6_PACKET_TOO_BIG = 2 # packet too big
ICMP6_TIME_EXCEEDED = 3 # time exceeded, code:
ICMP6_PARAM_PROB = 4 # ip6 header bad
ICMP6_ECHO_REQUEST = 128 # echo service
ICMP6_ECHO_REPLY = 129 # echo reply
MLD_LISTENER_QUERY = 130 # multicast listener query
MLD_LISTENER_REPORT = 131 # multicast listener report
MLD_LISTENER_DONE = 132 # multicast listener done
# RFC2292 decls
ICMP6_MEMBERSHIP_QUERY = 130 # group membership query
ICMP6_MEMBERSHIP_REPORT = 131 # group membership report
ICMP6_MEMBERSHIP_REDUCTION = 132 # group membership termination
ND_ROUTER_SOLICIT = 133 # router solicitation
ND_ROUTER_ADVERT = 134 # router advertisment
ND_NEIGHBOR_SOLICIT = 135 # neighbor solicitation
ND_NEIGHBOR_ADVERT = 136 # neighbor advertisment
ND_REDIRECT = 137 # redirect
ICMP6_ROUTER_RENUMBERING = 138 # router renumbering
ICMP6_WRUREQUEST = 139 # who are you request
ICMP6_WRUREPLY = 140 # who are you reply
ICMP6_FQDN_QUERY = 139 # FQDN query
ICMP6_FQDN_REPLY = 140 # FQDN reply
ICMP6_NI_QUERY = 139 # node information request
ICMP6_NI_REPLY = 140 # node information reply
ICMP6_MAXTYPE = 201
class ICMP6(dpkt.Packet):
"""Internet Control Message Protocol for IPv6.
TODO: Longer class information....
Attributes:
__hdr__: Header fields of ICMPv6.
TODO.
"""
__hdr__ = (
('type', 'B', 0),
('code', 'B', 0),
('sum', 'H', 0)
)
class Error(dpkt.Packet):
__hdr__ = (('pad', 'I', 0), )
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
from . import ip6
self.data = self.ip6 = ip6.IP6(self.data)
class Unreach(Error): pass
class TooBig(Error):
__hdr__ = (('mtu', 'I', 1232), )
class TimeExceed(Error): pass
class ParamProb(Error):
__hdr__ = (('ptr', 'I', 0), )
class Echo(dpkt.Packet):
__hdr__ = (('id', 'H', 0), ('seq', 'H', 0))
_typesw = {1: Unreach, 2: TooBig, 3: TimeExceed, 4: ParamProb, 128: Echo, 129: Echo}
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
try:
self.data = self._typesw[self.type](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
except (KeyError, dpkt.UnpackError):
pass
| {
"repo_name": "smutt/dpkt",
"path": "dpkt/icmp6.py",
"copies": "3",
"size": "2533",
"license": "bsd-3-clause",
"hash": 3424024409241193500,
"line_mean": 28.1149425287,
"line_max": 88,
"alpha_frac": 0.6253454402,
"autogenerated": false,
"ratio": 3.107975460122699,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.52333209003227,
"avg_score": null,
"num_lines": null
} |
# $Id: icmp6.py 23 2006-11-08 15:45:33Z dugsong $
# -*- coding: utf-8 -*-
"""Internet Control Message Protocol for IPv6."""
import dpkt
import ip6
ICMP6_DST_UNREACH = 1 # dest unreachable, codes:
ICMP6_PACKET_TOO_BIG = 2 # packet too big
ICMP6_TIME_EXCEEDED = 3 # time exceeded, code:
ICMP6_PARAM_PROB = 4 # ip6 header bad
ICMP6_ECHO_REQUEST = 128 # echo service
ICMP6_ECHO_REPLY = 129 # echo reply
MLD_LISTENER_QUERY = 130 # multicast listener query
MLD_LISTENER_REPORT = 131 # multicast listener report
MLD_LISTENER_DONE = 132 # multicast listener done
# RFC2292 decls
ICMP6_MEMBERSHIP_QUERY = 130 # group membership query
ICMP6_MEMBERSHIP_REPORT = 131 # group membership report
ICMP6_MEMBERSHIP_REDUCTION = 132 # group membership termination
ND_ROUTER_SOLICIT = 133 # router solicitation
ND_ROUTER_ADVERT = 134 # router advertisment
ND_NEIGHBOR_SOLICIT = 135 # neighbor solicitation
ND_NEIGHBOR_ADVERT = 136 # neighbor advertisment
ND_REDIRECT = 137 # redirect
ICMP6_ROUTER_RENUMBERING = 138 # router renumbering
ICMP6_WRUREQUEST = 139 # who are you request
ICMP6_WRUREPLY = 140 # who are you reply
ICMP6_FQDN_QUERY = 139 # FQDN query
ICMP6_FQDN_REPLY = 140 # FQDN reply
ICMP6_NI_QUERY = 139 # node information request
ICMP6_NI_REPLY = 140 # node information reply
ICMP6_MAXTYPE = 201
class ICMP6(dpkt.Packet):
__hdr__ = (
('type', 'B', 0),
('code', 'B', 0),
('sum', 'H', 0)
)
class Error(dpkt.Packet):
__hdr__ = (('pad', 'I', 0), )
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.ip6 = ip6.IP6(self.data)
class Unreach(Error): pass
class TooBig(Error):
__hdr__ = (('mtu', 'I', 1232), )
class TimeExceed(Error): pass
class ParamProb(Error):
__hdr__ = (('ptr', 'I', 0), )
class Echo(dpkt.Packet):
__hdr__ = (('id', 'H', 0), ('seq', 'H', 0))
_typesw = {1: Unreach, 2: TooBig, 3: TimeExceed, 4: ParamProb, 128: Echo, 129: Echo}
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
try:
self.data = self._typesw[self.type](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
except (KeyError, dpkt.UnpackError):
pass
| {
"repo_name": "bpanneton/dpkt",
"path": "dpkt/icmp6.py",
"copies": "5",
"size": "2291",
"license": "bsd-3-clause",
"hash": 6795031890748214000,
"line_mean": 28.7532467532,
"line_max": 88,
"alpha_frac": 0.6311654299,
"autogenerated": false,
"ratio": 3.00262123197903,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0009468283672492359,
"num_lines": 77
} |
# $Id: icmp6.py 23 2006-11-08 15:45:33Z dugsong $
"""Internet Control Message Protocol for IPv6."""
import dpkt, ip6
ICMP6_DST_UNREACH = 1 # dest unreachable, codes:
ICMP6_PACKET_TOO_BIG = 2 # packet too big
ICMP6_TIME_EXCEEDED = 3 # time exceeded, code:
ICMP6_PARAM_PROB = 4 # ip6 header bad
ICMP6_ECHO_REQUEST = 128 # echo service
ICMP6_ECHO_REPLY = 129 # echo reply
MLD_LISTENER_QUERY = 130 # multicast listener query
MLD_LISTENER_REPORT = 131 # multicast listener report
MLD_LISTENER_DONE = 132 # multicast listener done
# RFC2292 decls
ICMP6_MEMBERSHIP_QUERY = 130 # group membership query
ICMP6_MEMBERSHIP_REPORT = 131 # group membership report
ICMP6_MEMBERSHIP_REDUCTION = 132 # group membership termination
ND_ROUTER_SOLICIT = 133 # router solicitation
ND_ROUTER_ADVERT = 134 # router advertisment
ND_NEIGHBOR_SOLICIT = 135 # neighbor solicitation
ND_NEIGHBOR_ADVERT = 136 # neighbor advertisment
ND_REDIRECT = 137 # redirect
ICMP6_ROUTER_RENUMBERING = 138 # router renumbering
ICMP6_WRUREQUEST = 139 # who are you request
ICMP6_WRUREPLY = 140 # who are you reply
ICMP6_FQDN_QUERY = 139 # FQDN query
ICMP6_FQDN_REPLY = 140 # FQDN reply
ICMP6_NI_QUERY = 139 # node information request
ICMP6_NI_REPLY = 140 # node information reply
ICMP6_MAXTYPE = 201
class ICMP6(dpkt.Packet):
__hdr__ = (
('type', 'B', 0),
('code', 'B', 0),
('sum', 'H', 0)
)
class Error(dpkt.Packet):
__hdr__ = (('pad', 'I', 0), )
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.ip6 = ip6.IP6(self.data)
class Unreach(Error):
pass
class TooBig(Error):
__hdr__ = (('mtu', 'I', 1232), )
class TimeExceed(Error):
pass
class ParamProb(Error):
__hdr__ = (('ptr', 'I', 0), )
class Echo(dpkt.Packet):
__hdr__ = (('id', 'H', 0), ('seq', 'H', 0))
_typesw = { 1:Unreach, 2:TooBig, 3:TimeExceed, 4:ParamProb,
128:Echo, 129:Echo }
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
try:
self.data = self._typesw[self.type](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
except (KeyError, dpkt.UnpackError):
self.data = buf
| {
"repo_name": "wofanli/trex-core",
"path": "scripts/external_libs/dpkt-1.8.6/dpkt/icmp6.py",
"copies": "15",
"size": "2647",
"license": "apache-2.0",
"hash": -5035956623528712000,
"line_mean": 35.7638888889,
"line_max": 74,
"alpha_frac": 0.5428787306,
"autogenerated": false,
"ratio": 3.367684478371501,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
# $Id: icmp6.py 290 2006-01-22 02:43:28Z dugsong $
"""Internet Control Message Protocol for IPv6."""
import dpkt, ip6
ICMP6_DST_UNREACH = 1 # dest unreachable, codes:
ICMP6_PACKET_TOO_BIG = 2 # packet too big
ICMP6_TIME_EXCEEDED = 3 # time exceeded, code:
ICMP6_PARAM_PROB = 4 # ip6 header bad
ICMP6_ECHO_REQUEST = 128 # echo service
ICMP6_ECHO_REPLY = 129 # echo reply
MLD_LISTENER_QUERY = 130 # multicast listener query
MLD_LISTENER_REPORT = 131 # multicast listener report
MLD_LISTENER_DONE = 132 # multicast listener done
# RFC2292 decls
ICMP6_MEMBERSHIP_QUERY = 130 # group membership query
ICMP6_MEMBERSHIP_REPORT = 131 # group membership report
ICMP6_MEMBERSHIP_REDUCTION = 132 # group membership termination
ND_ROUTER_SOLICIT = 133 # router solicitation
ND_ROUTER_ADVERT = 134 # router advertisment
ND_NEIGHBOR_SOLICIT = 135 # neighbor solicitation
ND_NEIGHBOR_ADVERT = 136 # neighbor advertisment
ND_REDIRECT = 137 # redirect
ICMP6_ROUTER_RENUMBERING = 138 # router renumbering
ICMP6_WRUREQUEST = 139 # who are you request
ICMP6_WRUREPLY = 140 # who are you reply
ICMP6_FQDN_QUERY = 139 # FQDN query
ICMP6_FQDN_REPLY = 140 # FQDN reply
ICMP6_NI_QUERY = 139 # node information request
ICMP6_NI_REPLY = 140 # node information reply
ICMP6_MAXTYPE = 201
class ICMP6(dpkt.Packet):
__hdr__ = (
('type', 'B', 0),
('code', 'B', 0),
('sum', 'H', 0)
)
class Error(dpkt.Packet):
__hdr__ = (('pad', 'I', 0), )
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.ip6 = ip6.IP6(self.data)
class Unreach(Error):
pass
class TooBig(Error):
__hdr__ = (('mtu', 'I', 1232), )
class TimeExceed(Error):
pass
class ParamProb(Error):
__hdr__ = (('ptr', 'I', 0), )
class Echo(dpkt.Packet):
__hdr__ = (('id', 'H', 0), ('seq', 'H', 0))
_typesw = { 1:Unreach, 2:TooBig, 3:TimeExceed, 4:ParamProb,
128:Echo, 129:Echo }
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
try:
self.data = self._typesw[self.type](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
except (KeyError, dpkt.UnpackError):
self.data = buf
| {
"repo_name": "MercenaryLogic/StompingGround",
"path": "stompingground/dpkt/icmp6.py",
"copies": "1",
"size": "2648",
"license": "mit",
"hash": 8512603304475537000,
"line_mean": 35.7777777778,
"line_max": 74,
"alpha_frac": 0.5430513595,
"autogenerated": false,
"ratio": 3.364675984752224,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9317547223083981,
"avg_score": 0.018036024233648723,
"num_lines": 72
} |
# $Id: icmp.py 271 2006-01-11 16:03:33Z dugsong $
"""Internet Control Message Protocol."""
import dpkt, ip
# Types (icmp_type) and codes (icmp_code) -
# http://www.iana.org/assignments/icmp-parameters
ICMP_CODE_NONE = 0 # for types without codes
ICMP_ECHOREPLY = 0 # echo reply
ICMP_UNREACH = 3 # dest unreachable, codes:
ICMP_UNREACH_NET = 0 # bad net
ICMP_UNREACH_HOST = 1 # bad host
ICMP_UNREACH_PROTO = 2 # bad protocol
ICMP_UNREACH_PORT = 3 # bad port
ICMP_UNREACH_NEEDFRAG = 4 # IP_DF caused drop
ICMP_UNREACH_SRCFAIL = 5 # src route failed
ICMP_UNREACH_NET_UNKNOWN = 6 # unknown net
ICMP_UNREACH_HOST_UNKNOWN = 7 # unknown host
ICMP_UNREACH_ISOLATED = 8 # src host isolated
ICMP_UNREACH_NET_PROHIB = 9 # for crypto devs
ICMP_UNREACH_HOST_PROHIB = 10 # ditto
ICMP_UNREACH_TOSNET = 11 # bad tos for net
ICMP_UNREACH_TOSHOST = 12 # bad tos for host
ICMP_UNREACH_FILTER_PROHIB = 13 # prohibited access
ICMP_UNREACH_HOST_PRECEDENCE = 14 # precedence error
ICMP_UNREACH_PRECEDENCE_CUTOFF = 15 # precedence cutoff
ICMP_SRCQUENCH = 4 # packet lost, slow down
ICMP_REDIRECT = 5 # shorter route, codes:
ICMP_REDIRECT_NET = 0 # for network
ICMP_REDIRECT_HOST = 1 # for host
ICMP_REDIRECT_TOSNET = 2 # for tos and net
ICMP_REDIRECT_TOSHOST = 3 # for tos and host
ICMP_ALTHOSTADDR = 6 # alternate host address
ICMP_ECHO = 8 # echo service
ICMP_RTRADVERT = 9 # router advertise, codes:
ICMP_RTRADVERT_NORMAL = 0 # normal
ICMP_RTRADVERT_NOROUTE_COMMON = 16 # selective routing
ICMP_RTRSOLICIT = 10 # router solicitation
ICMP_TIMEXCEED = 11 # time exceeded, code:
ICMP_TIMEXCEED_INTRANS = 0 # ttl==0 in transit
ICMP_TIMEXCEED_REASS = 1 # ttl==0 in reass
ICMP_PARAMPROB = 12 # ip header bad
ICMP_PARAMPROB_ERRATPTR = 0 # req. opt. absent
ICMP_PARAMPROB_OPTABSENT = 1 # req. opt. absent
ICMP_PARAMPROB_LENGTH = 2 # bad length
ICMP_TSTAMP = 13 # timestamp request
ICMP_TSTAMPREPLY = 14 # timestamp reply
ICMP_INFO = 15 # information request
ICMP_INFOREPLY = 16 # information reply
ICMP_MASK = 17 # address mask request
ICMP_MASKREPLY = 18 # address mask reply
ICMP_TRACEROUTE = 30 # traceroute
ICMP_DATACONVERR = 31 # data conversion error
ICMP_MOBILE_REDIRECT = 32 # mobile host redirect
ICMP_IP6_WHEREAREYOU = 33 # IPv6 where-are-you
ICMP_IP6_IAMHERE = 34 # IPv6 i-am-here
ICMP_MOBILE_REG = 35 # mobile registration req
ICMP_MOBILE_REGREPLY = 36 # mobile registration reply
ICMP_DNS = 37 # domain name request
ICMP_DNSREPLY = 38 # domain name reply
ICMP_SKIP = 39 # SKIP
ICMP_PHOTURIS = 40 # Photuris
ICMP_PHOTURIS_UNKNOWN_INDEX = 0 # unknown sec index
ICMP_PHOTURIS_AUTH_FAILED = 1 # auth failed
ICMP_PHOTURIS_DECOMPRESS_FAILED = 2 # decompress failed
ICMP_PHOTURIS_DECRYPT_FAILED = 3 # decrypt failed
ICMP_PHOTURIS_NEED_AUTHN = 4 # no authentication
ICMP_PHOTURIS_NEED_AUTHZ = 5 # no authorization
ICMP_TYPE_MAX = 40
class ICMP(dpkt.Packet):
__hdr__ = (
('type', 'B', 8),
('code', 'B', 0),
('sum', 'H', 0)
)
class Echo(dpkt.Packet):
__hdr__ = (('id', 'H', 0), ('seq', 'H', 0))
class Quote(dpkt.Packet):
__hdr__ = (('pad', 'I', 0),)
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.ip = ip.IP(self.data)
class Unreach(Quote):
__hdr__ = (('pad', 'H', 0), ('mtu', 'H', 0))
class Quench(Quote):
pass
class Redirect(Quote):
__hdr__ = (('gw', 'I', 0),)
class ParamProbe(Quote):
__hdr__ = (('ptr', 'B', 0), ('pad1', 'B', 0), ('pad2', 'H', 0))
class TimeExceed(Quote):
pass
_typesw = { 0:Echo, 3:Unreach, 4:Quench, 5:Redirect, 8:Echo,
11:TimeExceed }
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
try:
self.data = self._typesw[self.type](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
except (KeyError, dpkt.UnpackError):
self.data = buf
def __str__(self):
if not self.sum:
self.sum = dpkt.in_cksum(dpkt.Packet.__str__(self))
return dpkt.Packet.__str__(self)
| {
"repo_name": "MercenaryLogic/StompingGround",
"path": "stompingground/dpkt/icmp.py",
"copies": "1",
"size": "4124",
"license": "mit",
"hash": -1632382164168545800,
"line_mean": 36.1531531532,
"line_max": 74,
"alpha_frac": 0.6503394762,
"autogenerated": false,
"ratio": 2.6848958333333335,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.38352353095333336,
"avg_score": null,
"num_lines": null
} |
# $Id: icmp.py 45 2007-08-03 00:05:22Z jon.oberheide $
# -*- coding: utf-8 -*-
"""Internet Control Message Protocol."""
from __future__ import print_function
from __future__ import absolute_import
from . import dpkt
# Types (icmp_type) and codes (icmp_code) -
# http://www.iana.org/assignments/icmp-parameters
ICMP_CODE_NONE = 0 # for types without codes
ICMP_ECHOREPLY = 0 # echo reply
ICMP_UNREACH = 3 # dest unreachable, codes:
ICMP_UNREACH_NET = 0 # bad net
ICMP_UNREACH_HOST = 1 # bad host
ICMP_UNREACH_PROTO = 2 # bad protocol
ICMP_UNREACH_PORT = 3 # bad port
ICMP_UNREACH_NEEDFRAG = 4 # IP_DF caused drop
ICMP_UNREACH_SRCFAIL = 5 # src route failed
ICMP_UNREACH_NET_UNKNOWN = 6 # unknown net
ICMP_UNREACH_HOST_UNKNOWN = 7 # unknown host
ICMP_UNREACH_ISOLATED = 8 # src host isolated
ICMP_UNREACH_NET_PROHIB = 9 # for crypto devs
ICMP_UNREACH_HOST_PROHIB = 10 # ditto
ICMP_UNREACH_TOSNET = 11 # bad tos for net
ICMP_UNREACH_TOSHOST = 12 # bad tos for host
ICMP_UNREACH_FILTER_PROHIB = 13 # prohibited access
ICMP_UNREACH_HOST_PRECEDENCE = 14 # precedence error
ICMP_UNREACH_PRECEDENCE_CUTOFF = 15 # precedence cutoff
ICMP_SRCQUENCH = 4 # packet lost, slow down
ICMP_REDIRECT = 5 # shorter route, codes:
ICMP_REDIRECT_NET = 0 # for network
ICMP_REDIRECT_HOST = 1 # for host
ICMP_REDIRECT_TOSNET = 2 # for tos and net
ICMP_REDIRECT_TOSHOST = 3 # for tos and host
ICMP_ALTHOSTADDR = 6 # alternate host address
ICMP_ECHO = 8 # echo service
ICMP_RTRADVERT = 9 # router advertise, codes:
ICMP_RTRADVERT_NORMAL = 0 # normal
ICMP_RTRADVERT_NOROUTE_COMMON = 16 # selective routing
ICMP_RTRSOLICIT = 10 # router solicitation
ICMP_TIMEXCEED = 11 # time exceeded, code:
ICMP_TIMEXCEED_INTRANS = 0 # ttl==0 in transit
ICMP_TIMEXCEED_REASS = 1 # ttl==0 in reass
ICMP_PARAMPROB = 12 # ip header bad
ICMP_PARAMPROB_ERRATPTR = 0 # req. opt. absent
ICMP_PARAMPROB_OPTABSENT = 1 # req. opt. absent
ICMP_PARAMPROB_LENGTH = 2 # bad length
ICMP_TSTAMP = 13 # timestamp request
ICMP_TSTAMPREPLY = 14 # timestamp reply
ICMP_INFO = 15 # information request
ICMP_INFOREPLY = 16 # information reply
ICMP_MASK = 17 # address mask request
ICMP_MASKREPLY = 18 # address mask reply
ICMP_TRACEROUTE = 30 # traceroute
ICMP_DATACONVERR = 31 # data conversion error
ICMP_MOBILE_REDIRECT = 32 # mobile host redirect
ICMP_IP6_WHEREAREYOU = 33 # IPv6 where-are-you
ICMP_IP6_IAMHERE = 34 # IPv6 i-am-here
ICMP_MOBILE_REG = 35 # mobile registration req
ICMP_MOBILE_REGREPLY = 36 # mobile registration reply
ICMP_DNS = 37 # domain name request
ICMP_DNSREPLY = 38 # domain name reply
ICMP_SKIP = 39 # SKIP
ICMP_PHOTURIS = 40 # Photuris
ICMP_PHOTURIS_UNKNOWN_INDEX = 0 # unknown sec index
ICMP_PHOTURIS_AUTH_FAILED = 1 # auth failed
ICMP_PHOTURIS_DECOMPRESS_FAILED = 2 # decompress failed
ICMP_PHOTURIS_DECRYPT_FAILED = 3 # decrypt failed
ICMP_PHOTURIS_NEED_AUTHN = 4 # no authentication
ICMP_PHOTURIS_NEED_AUTHZ = 5 # no authorization
ICMP_TYPE_MAX = 40
class ICMP(dpkt.Packet):
"""Internet Control Message Protocol.
TODO: Longer class information....
Attributes:
__hdr__: Header fields of ICMP.
TODO.
"""
__hdr__ = (
('type', 'B', 8),
('code', 'B', 0),
('sum', 'H', 0)
)
class Echo(dpkt.Packet):
__hdr__ = (('id', 'H', 0), ('seq', 'H', 0))
class Quote(dpkt.Packet):
__hdr__ = (('pad', 'I', 0),)
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
from . import ip
self.data = self.ip = ip.IP(self.data)
class Unreach(Quote):
__hdr__ = (('pad', 'H', 0), ('mtu', 'H', 0))
class Quench(Quote):
pass
class Redirect(Quote):
__hdr__ = (('gw', 'I', 0),)
class ParamProbe(Quote):
__hdr__ = (('ptr', 'B', 0), ('pad1', 'B', 0), ('pad2', 'H', 0))
class TimeExceed(Quote):
pass
_typesw = {0: Echo, 3: Unreach, 4: Quench, 5: Redirect, 8: Echo, 11: TimeExceed}
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
try:
self.data = self._typesw[self.type](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
except (KeyError, dpkt.UnpackError):
pass
def __bytes__(self):
if not self.sum:
self.sum = dpkt.in_cksum(dpkt.Packet.__bytes__(self))
return dpkt.Packet.__bytes__(self)
def test_icmp():
s = (
b'\x03\x0a\x6b\x19\x00\x00\x00\x00\x45\x00\x00\x28\x94\x1f\x00\x00\xe3\x06\x99\xb4\x23\x2b'
b'\x24\x00\xde\x8e\x84\x42\xab\xd1\x00\x50\x00\x35\xe1\x29\x20\xd9\x00\x00\x00\x22\x9b\xf0'
b'\xe2\x04\x65\x6b'
)
r = ICMP(s)
assert bytes(r) == s
# construction
s = (
b'\x00\x00\x53\x87\x00\x01\x03\xd6\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e'
b'\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x41\x42\x43\x44\x45\x46\x47\x48\x49'
)
p = ICMP(
type=0,
sum=0x5387,
data=ICMP.Echo(
id=1,
seq=0x03d6,
data=b'ABCDEFGHIJKLMNOPQRSTUVWABCDEFGHI'
)
)
assert bytes(p) == s
# test checksum
p = ICMP(
type=0,
data=ICMP.Echo(
id=1,
seq=0x03d6,
data=b'ABCDEFGHIJKLMNOPQRSTUVWABCDEFGHI'
)
)
assert bytes(p) == s
assert p.sum == 0x5387
if __name__ == '__main__':
test_icmp()
print('Tests Successful...')
| {
"repo_name": "smutt/dpkt",
"path": "dpkt/icmp.py",
"copies": "3",
"size": "5472",
"license": "bsd-3-clause",
"hash": -6734747464662150000,
"line_mean": 30.4482758621,
"line_max": 99,
"alpha_frac": 0.6240862573,
"autogenerated": false,
"ratio": 2.770632911392405,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48947191686924046,
"avg_score": null,
"num_lines": null
} |
# $Id: icmp.py 45 2007-08-03 00:05:22Z jon.oberheide $
# -*- coding: utf-8 -*-
"""Internet Control Message Protocol."""
import dpkt
import ip
# Types (icmp_type) and codes (icmp_code) -
# http://www.iana.org/assignments/icmp-parameters
ICMP_CODE_NONE = 0 # for types without codes
ICMP_ECHOREPLY = 0 # echo reply
ICMP_UNREACH = 3 # dest unreachable, codes:
ICMP_UNREACH_NET = 0 # bad net
ICMP_UNREACH_HOST = 1 # bad host
ICMP_UNREACH_PROTO = 2 # bad protocol
ICMP_UNREACH_PORT = 3 # bad port
ICMP_UNREACH_NEEDFRAG = 4 # IP_DF caused drop
ICMP_UNREACH_SRCFAIL = 5 # src route failed
ICMP_UNREACH_NET_UNKNOWN = 6 # unknown net
ICMP_UNREACH_HOST_UNKNOWN = 7 # unknown host
ICMP_UNREACH_ISOLATED = 8 # src host isolated
ICMP_UNREACH_NET_PROHIB = 9 # for crypto devs
ICMP_UNREACH_HOST_PROHIB = 10 # ditto
ICMP_UNREACH_TOSNET = 11 # bad tos for net
ICMP_UNREACH_TOSHOST = 12 # bad tos for host
ICMP_UNREACH_FILTER_PROHIB = 13 # prohibited access
ICMP_UNREACH_HOST_PRECEDENCE = 14 # precedence error
ICMP_UNREACH_PRECEDENCE_CUTOFF = 15 # precedence cutoff
ICMP_SRCQUENCH = 4 # packet lost, slow down
ICMP_REDIRECT = 5 # shorter route, codes:
ICMP_REDIRECT_NET = 0 # for network
ICMP_REDIRECT_HOST = 1 # for host
ICMP_REDIRECT_TOSNET = 2 # for tos and net
ICMP_REDIRECT_TOSHOST = 3 # for tos and host
ICMP_ALTHOSTADDR = 6 # alternate host address
ICMP_ECHO = 8 # echo service
ICMP_RTRADVERT = 9 # router advertise, codes:
ICMP_RTRADVERT_NORMAL = 0 # normal
ICMP_RTRADVERT_NOROUTE_COMMON = 16 # selective routing
ICMP_RTRSOLICIT = 10 # router solicitation
ICMP_TIMEXCEED = 11 # time exceeded, code:
ICMP_TIMEXCEED_INTRANS = 0 # ttl==0 in transit
ICMP_TIMEXCEED_REASS = 1 # ttl==0 in reass
ICMP_PARAMPROB = 12 # ip header bad
ICMP_PARAMPROB_ERRATPTR = 0 # req. opt. absent
ICMP_PARAMPROB_OPTABSENT = 1 # req. opt. absent
ICMP_PARAMPROB_LENGTH = 2 # bad length
ICMP_TSTAMP = 13 # timestamp request
ICMP_TSTAMPREPLY = 14 # timestamp reply
ICMP_INFO = 15 # information request
ICMP_INFOREPLY = 16 # information reply
ICMP_MASK = 17 # address mask request
ICMP_MASKREPLY = 18 # address mask reply
ICMP_TRACEROUTE = 30 # traceroute
ICMP_DATACONVERR = 31 # data conversion error
ICMP_MOBILE_REDIRECT = 32 # mobile host redirect
ICMP_IP6_WHEREAREYOU = 33 # IPv6 where-are-you
ICMP_IP6_IAMHERE = 34 # IPv6 i-am-here
ICMP_MOBILE_REG = 35 # mobile registration req
ICMP_MOBILE_REGREPLY = 36 # mobile registration reply
ICMP_DNS = 37 # domain name request
ICMP_DNSREPLY = 38 # domain name reply
ICMP_SKIP = 39 # SKIP
ICMP_PHOTURIS = 40 # Photuris
ICMP_PHOTURIS_UNKNOWN_INDEX = 0 # unknown sec index
ICMP_PHOTURIS_AUTH_FAILED = 1 # auth failed
ICMP_PHOTURIS_DECOMPRESS_FAILED = 2 # decompress failed
ICMP_PHOTURIS_DECRYPT_FAILED = 3 # decrypt failed
ICMP_PHOTURIS_NEED_AUTHN = 4 # no authentication
ICMP_PHOTURIS_NEED_AUTHZ = 5 # no authorization
ICMP_TYPE_MAX = 40
class ICMP(dpkt.Packet):
__hdr__ = (
('type', 'B', 8),
('code', 'B', 0),
('sum', 'H', 0)
)
class Echo(dpkt.Packet):
__hdr__ = (('id', 'H', 0), ('seq', 'H', 0))
class Quote(dpkt.Packet):
__hdr__ = (('pad', 'I', 0),)
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
self.data = self.ip = ip.IP(self.data)
class Unreach(Quote):
__hdr__ = (('pad', 'H', 0), ('mtu', 'H', 0))
class Quench(Quote): pass
class Redirect(Quote):
__hdr__ = (('gw', 'I', 0),)
class ParamProbe(Quote):
__hdr__ = (('ptr', 'B', 0), ('pad1', 'B', 0), ('pad2', 'H', 0))
class TimeExceed(Quote): pass
_typesw = {0: Echo, 3: Unreach, 4: Quench, 5: Redirect, 8: Echo, 11: TimeExceed}
def unpack(self, buf):
dpkt.Packet.unpack(self, buf)
try:
self.data = self._typesw[self.type](self.data)
setattr(self, self.data.__class__.__name__.lower(), self.data)
except (KeyError, dpkt.UnpackError):
pass
def __str__(self):
if not self.sum:
self.sum = dpkt.in_cksum(dpkt.Packet.__str__(self))
return dpkt.Packet.__str__(self)
def test_icmp():
s = '\x03\x0a\x6b\x19\x00\x00\x00\x00\x45\x00\x00\x28\x94\x1f\x00\x00\xe3\x06\x99\xb4\x23\x2b\x24\x00\xde\x8e\x84\x42\xab\xd1\x00\x50\x00\x35\xe1\x29\x20\xd9\x00\x00\x00\x22\x9b\xf0\xe2\x04\x65\x6b'
assert (str(ICMP(s)) == s)
if __name__ == '__main__':
test_icmp()
print 'Tests Successful...'
| {
"repo_name": "jack8daniels2/dpkt",
"path": "dpkt/icmp.py",
"copies": "6",
"size": "4464",
"license": "bsd-3-clause",
"hash": 1177008489762563600,
"line_mean": 34.1496062992,
"line_max": 202,
"alpha_frac": 0.6505376344,
"autogenerated": false,
"ratio": 2.7369711833231145,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6387508817723114,
"avg_score": null,
"num_lines": null
} |
"""Image constants for the widgets module.
The image constants defined here include different image filenames and
file paths to images included in the ocempgui library. All of the
following image files are 16 pixels wide and high and several are using
alpha transparency.
File related icons
------------------
FOLDER - Open folder icon.
FILE - Blank file sheet icon.
FILE_SOCKET - Like FILE, but with additional red and green arrows on the left.
FILE_CHAR - Like FILE, but covered with binary code.
FILE_LINK - Two overlaid, linked FILE like icons.
"""
FOLDER = "folder.png"
FILE = "file_normal.png"
FILE_SOCKET = "file_socket.png"
FILE_CHAR = "file_char.png"
FILE_LINK = "file_link.png"
| {
"repo_name": "prim/ocempgui",
"path": "ocempgui/widgets/images/Icons16x16.py",
"copies": "1",
"size": "2136",
"license": "bsd-2-clause",
"hash": -7166344321987698000,
"line_mean": 45.4347826087,
"line_max": 78,
"alpha_frac": 0.7551498127,
"autogenerated": false,
"ratio": 4.099808061420346,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5354957874120345,
"avg_score": null,
"num_lines": null
} |
"""A button widget, which can display an image."""
from pygame import Surface
from ocempgui.draw import Image
from ButtonBase import ButtonBase
from Label import Label
from Constants import *
from StyleInformation import StyleInformation
import base
class ImageButton (ButtonBase):
"""ImageButton (image) -> ImageButton
A button widget class which can display an image.
The ImageButton widget is able to display nearly any kind of
image, while providing all the features of the Button widget.
The image to display can be set with the 'picture' attribute or
set_picture() method. The image can be either a file name from which
the image should be loaded or a pygame.Surface object to display.
button.picture = './image.png'
button.set_picture (image_surface)
If the displayed image is loaded from a file, its file path will be
saved in the 'path' attribute. This also can be used to determine,
whether the image was loaded from a file ('path' contains a file
path) or not ('path' is None).
The ImageButton supports different border types by setting its
'border' attribute to a valid value of the BORDER_TYPES constants.
button.border = BORDER_SUNKEN
button.set_border (BORDER_SUNKEN)
Default action (invoked by activate()):
See the ButtonBase class.
Mnemonic action (invoked by activate_mnemonic()):
See the ButtonBase class.
Attributes:
text - The text to display on the ImageButton.
picture - A pygame.Surface of the set image.
path - The path of the set image (if it is loaded from a file).
border - The border style to set for the ImageButton.
"""
def __init__ (self, image=None):
ButtonBase.__init__ (self)
self._border = BORDER_RAISED
self._picture = None
self._path = None
self.set_picture (image)
def set_border (self, border):
"""I.set_border (...) -> None
Sets the border type to be used by the ImageButton.
Raises a ValueError, if the passed argument is not a value from
BORDER_TYPES
"""
if border not in BORDER_TYPES:
raise ValueError ("border must be a value from BORDER_TYPES")
self._border = border
self.dirty = True
def set_picture (self, image):
"""I.set_picture (...) -> None
Sets the image to be displayed on the ImageButton.
The image can be either a valid pygame.Surface object or the
path to an image file. If the argument is a file, the 'path'
attribute will be set to the file path, otherwise it will be
None.
Raises a TypeError, if the passed argument is not a string,
unicode or pygame.Surface.
"""
if image:
if type (image) in (str, unicode):
self._path = image
self._picture = Image.load_image (image)
elif isinstance (image, Surface):
self._path = None
self._picture = image
else:
raise TypeError ("image must be a string, unicode or a " \
"pygame.Surface")
else:
self._path = None
self._picture = None
self.dirty = True
def set_text (self, text=None):
"""I.set_text (...) -> None
Sets the text to display on the ImageButton by referring to the
'text' attribute of its child Label.
"""
if text != None:
if self.child:
self.child.set_text (text)
else:
self.child = Label (text)
else:
self.child = None
def get_text (self):
"""I.get_text () -> string
Returns the set text of the ImageButton.
Returns the text set on the Label of the ImageButton.
"""
if self.child:
return self.child.text
return ""
def set_child (self, child=None):
"""I.set_child (...) -> None
Sets the Label to display on the ImageButton.
Creates a parent-child relationship from the ImageButton to a
Label and causes the Label to set its mnemonic widget to the
ImageButton.
Raises a TypeError, if the passed argument does not inherit
from the Label class.
"""
self.lock ()
if child and not isinstance (child, Label):
raise TypeError ("child must inherit from Label")
ButtonBase.set_child (self, child)
if child:
child.set_widget (self)
if not child.style:
child.style = self.style or \
base.GlobalStyle.get_style (self.__class__)
self.unlock ()
def set_state (self, state):
"""I.set_state (...) -> None
Sets the state of the ImageButton.
Sets the state of the ImageButton and causes its child to set
its state to the same value.
"""
if self.state == state:
return
self.lock ()
if self.child:
self.child.state = state
ButtonBase.set_state (self, state)
self.unlock ()
def draw_bg (self):
"""I.draw_bg () -> Surface
Draws the background surface of the ImageButton and returns it.
Creates the visible surface of the image button and returns it
to the caller.
"""
return base.GlobalStyle.engine.draw_imagebutton (self)
def draw (self):
"""I.draw () -> None
Draws the ImageButton surface and places its picture and Label on it.
"""
ButtonBase.draw (self)
spacing = StyleInformation.get ("IMAGEBUTTON_SPACING")
rect_img = None
rect_child = None
rect = self.image.get_rect ()
if self.picture:
rect_img = self.picture.get_rect ()
rect_img.center = rect.center
if self.child:
rect_img.right -= (self.child.width / 2 + spacing)
rect_img.centery = rect.centery
self.image.blit (self.picture, rect_img)
if self.child:
self.child.center = rect.center
if self.picture:
self.child.left = rect_img.right + spacing
rect_child = self.child.rect
self.image.blit (self.child.image, rect_child)
text = property (lambda self: self.get_text (),
lambda self, var: self.set_text (var),
doc = "The text of the ImageButton.")
path = property (lambda self: self._path,
doc = "The file path of the image.")
picture = property (lambda self: self._picture,
lambda self, var: self.set_picture (var),
doc = "The image to display on the ImageButton.")
border = property (lambda self: self._border,
lambda self, var: self.set_border (var),
doc = "The border style to set for the ImageButton.")
| {
"repo_name": "prim/ocempgui",
"path": "ocempgui/widgets/ImageButton.py",
"copies": "1",
"size": "8485",
"license": "bsd-2-clause",
"hash": -146452398116285700,
"line_mean": 35.2606837607,
"line_max": 78,
"alpha_frac": 0.6161461402,
"autogenerated": false,
"ratio": 4.4400837257980115,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.009053796373224324,
"num_lines": 234
} |
"""A simple widget, which can display text."""
from pygame import Surface
from ocempgui.draw import Image
from BaseWidget import BaseWidget
from Constants import *
import base
class ImageLabel (BaseWidget):
"""ImageLabel (image) -> ImageLabel
A simple widget class, which can display an image.
The ImageLabel widget is able to display nearly any kind of image
and serves as a placeholder widget for simple image displaying.
The image to display can be set with the 'picture' attribute or
set_picture() method. The image can be either a file name from which
the image should be loaded or a pygame.Surface object to display.
label.picture = './image.png'
label.set_picture (image_surface)
If the displayed image is loaded from a file, its file path will be
saved in the 'path' attribute. This also can be used to determine,
whether the image was loaded from a file ('path' contains a file
path) or not ('path' is None).
The ImageLabel supports different border types by setting its
'border' attribute to a valid value of the BORDER_TYPES constants.
label.border = BORDER_SUNKEN
label.set_border (BORDER_SUNKEN)
The 'padding' attribute and set_padding() method are used to place a
certain amount of pixels between the text and the outer edges of the
Label.
label.padding = 10
label.set_padding (10)
Default action (invoked by activate()):
None
Mnemonic action (invoked by activate_mnemonic()):
None
Attributes:
padding - Additional padding between text and borders. Default is 2.
picture - A pygame.Surface of the set image.
path - The path of the set image (if it is loaded from a file).
border - The border style to set for the ImageLabel.
"""
def __init__ (self, image):
BaseWidget.__init__ (self)
self._padding = 2
self._border = BORDER_NONE
self._picture = None
self._path = None
self.set_picture (image)
def set_padding (self, padding):
"""I.set_padding (...) -> None
Sets the padding between the edges and image of the ImageLabel.
The padding value is the amount of pixels to place between the
edges of the Label and the displayed text.
Raises a TypeError, if the passed argument is not a positive
integer.
Note: If the 'size' attribute is set, it can influence the
visible space between the text and the edges. That does not
mean, that any padding is set.
"""
if (type (padding) != int) or (padding < 0):
raise TypeError ("padding must be a positive integer")
self._padding = padding
self.dirty = True
def set_border (self, border):
"""I.set_border (...) -> None
Sets the border type to be used by the ImageLabel.
Raises a ValueError, if the passed argument is not a value from
BORDER_TYPES
"""
if border not in BORDER_TYPES:
raise ValueError ("border must be a value from BORDER_TYPES")
self._border = border
self.dirty = True
def set_picture (self, image):
"""I.set_picture (...) -> None
Sets the image to be displayed on the ImageLabel.
The image can be either a valid pygame.Surface object or the
path to an image file. If the argument is a file, the 'path'
attribute will be set to the file path, otherwise it will be
None.
Raises a TypeError, if the passed argument is not a string,
unicode or pygame.Surface.
"""
if image:
if type (image) in (str, unicode):
self._path = image
self._picture = Image.load_image (image)
elif isinstance (image, Surface):
self._path = None
self._picture = image
else:
raise TypeError ("image must be a string, unicode or a " \
"pygame.Surface")
else:
self._path = None
self._picture = None
self.dirty = True
def set_focus (self, focus=True):
"""I.set_focus (...) -> bool
Overrides the default widget input focus.
ImageLabels cannot be focused by default, thus this method
always returns False and does not do anything.
"""
return False
def draw_bg (self):
"""I.draw_bg () -> Surface
Draws the ImageLabel background surface and returns it.
Creates the visible background surface of the ImageLabel and
returns it to the caller.
"""
return base.GlobalStyle.engine.draw_imagelabel (self)
def draw (self):
"""I.draw () -> None
Draws the ImageLabel surface and places its picture on it.
"""
BaseWidget.draw (self)
rect_img = None
rect_child = None
rect = self.image.get_rect ()
rect_img = self.picture.get_rect ()
rect_img.center = rect.center
rect_img.centery = rect.centery
self.image.blit (self.picture, rect_img)
padding = property (lambda self: self._padding,
lambda self, var: self.set_padding (var),
doc = "Additional padding between image and borders.")
path = property (lambda self: self._path,
doc = "The file path of the image.")
picture = property (lambda self: self._picture,
lambda self, var: self.set_picture (var),
doc = "The image to display on the ImageLabel.")
border = property (lambda self: self._border,
lambda self, var: self.set_border (var),
doc = "The border style to set for the ImageLabel.")
| {
"repo_name": "prim/ocempgui",
"path": "ocempgui/widgets/ImageLabel.py",
"copies": "1",
"size": "7259",
"license": "bsd-2-clause",
"hash": 5576008350929140000,
"line_mean": 36.2256410256,
"line_max": 78,
"alpha_frac": 0.6408596225,
"autogenerated": false,
"ratio": 4.478099938309685,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5618959560809685,
"avg_score": null,
"num_lines": null
} |
"""A widget, which can display images and reacts upon mouse events."""
from pygame import Surface, Rect
from ocempgui.draw import Image
from BaseWidget import BaseWidget
from Constants import *
from StyleInformation import StyleInformation
import base
class ImageMap (BaseWidget):
"""ImageMap (image) -> ImageMap
A widget class, which displays images and acts upon mouse events.
The ImageMap widget can - as the ImageButton - load and display
images, but additionally keeps track of mouse events and their
relative position on the widget.
The image to display can be set with the 'picture' attribute or
set_picture() method. The image can be either a file name from which
the image should be loaded or a pygame.Surface object to display.
imagemap.image = './image.png'
imagemap.set_image (image_surface)
If the displayed image is loaded from a file, its file path will be
saved in the 'path' attribute. This also can be used to determine,
whether the image was loaded from a file ('path' contains a file
path) or not ('path' is None).
To keep track of mouse events, the ImageMap stores the last event,
which occured on it in the 'last_event' attribute.
if imagemap.last_event.signal == SIG_MOUSEDOWN:
...
To allow easy acces of the real coordinates on the displayed image,
the ImageMap contains a 'relative_position' attribute, which returns
the absolute position of the mouse on the ImageMap widget.
if imagemap.relative_position == (10, 40):
...
Default action (invoked by activate()):
None
Mnemonic action (invoked by activate_mnemonic()):
None
Signals:
SIG_MOUSEDOWN - Invoked, when a mouse button is pressed on the
ImageMap.
SIG_MOUSEUP - Invoked, when a mouse button is released on the
ImageMap.
SIG_MOUSEMOVE - Invoked, when the mouse moves over the ImageMap.
SIG_CLICKED - Invoked, when the left mouse button is pressed AND
released over the ImageMap.
Attributes:
image - A pygame.Surface of the set image.
path - The path of the set image (if it is loaded from a
file).
last_event - The last event, which occured on the ImageMap.
relative_position - The last relative position of the event on the
ImageMap.
"""
def __init__ (self, image):
BaseWidget.__init__ (self)
self._picture = None
self._path = None
self.__click = False
self._lastevent = None
self._signals[SIG_MOUSEDOWN] = []
self._signals[SIG_MOUSEUP] = []
self._signals[SIG_CLICKED] = []
self._signals[SIG_MOUSEMOVE] = []
self.set_picture (image)
def set_picture (self, image):
"""I.set_picture (...) -> None
Sets the image to be displayed on the ImageMap.
The image can be either a valid pygame.Surface object or the
path to an image file. If the argument is a file, the 'path'
attribute will be set to the file path, otherwise it will be
None.
Raises a TypeError, if the passed argument is not a string,
unicode or pygame.Surface.
"""
if image:
if type (image) in (str, unicode):
self._path = image
self._picture = Image.load_image (image)
elif isinstance (image, Surface):
self._path = None
self._picture = image
else:
raise TypeError ("image must be a string, unicode or a " \
"pygame.Surface")
else:
self._path = None
self._picture = None
self.dirty = True
def _get_relative_position (self):
"""I._get_relative_position () -> int, int
Gets the last relative position of the mouse on the ImageMap
(absolute position on it).
If the last position could not be determined -1, -1 will be
returned instead.
"""
if self.last_event:
border = base.GlobalStyle.get_border_size \
(self.__class__, self.style,
StyleInformation.get ("IMAGEMAP_BORDER"))
area = self.rect_to_client ()
return self.last_event.data.pos[0] - border - area.x, \
self.last_event.data.pos[1] - border - area.y
return -1, -1
def invalidate (self, rect):
"""I.invalidate (...) -> None
Invalidates a rectangular portion of the ImageMap its picture.
Invalidates a rectangular portion of the shown image of the
ImageMap and causes the rendering mechanisms to update that
region.
The set IMAGEMAP_BORDER of the StyleInformation settings will be
taken into account automatically and added to the rect offsets.
Raises a TypeError, if the passed argument is not a pygame.Rect.
"""
if type (rect) != Rect:
raise TypeError ("rect must be a pygame.Rect")
self._lock += 1
border = base.GlobalStyle.get_border_size \
(self.__class__, self.style,
StyleInformation.get ("IMAGEMAP_BORDER"))
x, y = rect.x + border, rect.y + border
self._image.blit (self.picture, (x, y), rect)
self._image.set_alpha (self.opacity)
if self.parent:
rect.x = x + self.x
rect.y = y + self.y
self.parent.update (children={ self : rect }, resize=False)
self._lock -= 1
def notify (self, event):
"""I.notify (...) -> None
Notifies the ImageMap about an event.
"""
if not self.sensitive:
return
if event.signal in SIGNALS_MOUSE:
eventarea = self.rect_to_client ()
if event.signal == SIG_MOUSEDOWN:
if eventarea.collidepoint (event.data.pos):
self._lastevent = event
if event.data.button == 1:
self.state = STATE_ACTIVE
self.__click = True
self.run_signal_handlers (SIG_MOUSEDOWN, event.data)
event.handled = True
elif event.signal == SIG_MOUSEUP:
if eventarea.collidepoint (event.data.pos):
self._lastevent = event
self.run_signal_handlers (SIG_MOUSEUP, event.data)
if event.data.button == 1:
if self.state == STATE_ACTIVE:
self.state = STATE_ENTERED
else:
self.state = STATE_NORMAL
if self.__click:
self.__click = False
self.run_signal_handlers (SIG_CLICKED)
event.handled = True
elif (event.data.button == 1) and (self.state == STATE_ACTIVE):
self.__click = False
self.state = STATE_NORMAL
elif event.signal == SIG_MOUSEMOVE:
if eventarea.collidepoint (event.data.pos):
self._lastevent = event
if self.state == STATE_NORMAL:
self.state = STATE_ENTERED
self.run_signal_handlers (SIG_MOUSEMOVE, event.data)
event.handled = True
elif self.state == STATE_ENTERED:
self.state = STATE_NORMAL
BaseWidget.notify (self, event)
def draw_bg (self):
"""I.draw_bg () -> Surface
Draws the background surface of the ImageMap and returns it.
Creates the visible surface of the ImageMap and returns it to
the caller.
"""
return base.GlobalStyle.engine.draw_imagemap (self)
def draw (self):
"""I.draw () -> None
Draws the ImageMap surface and places its picture on it.
"""
BaseWidget.draw (self)
rect = self.picture.get_rect ()
rect.center = self.image.get_rect ().center
self.image.blit (self.picture, rect)
path = property (lambda self: self._path,
doc = "The file path of the image.")
picture = property (lambda self: self._picture,
lambda self, var: self.set_picture (var),
doc = "The image to display on the ImageMap.")
last_event = property (lambda self: self._lastevent,
doc = "The last event occured on the ImageMap.")
relative_position = property (lambda self: self._get_relative_position (),
doc = "The last relative position of the " \
"mouse.")
| {
"repo_name": "prim/ocempgui",
"path": "ocempgui/widgets/ImageMap.py",
"copies": "1",
"size": "10329",
"license": "bsd-2-clause",
"hash": 5286390188493134000,
"line_mean": 38.4236641221,
"line_max": 79,
"alpha_frac": 0.5909574983,
"autogenerated": false,
"ratio": 4.494778067885117,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5585735566185117,
"avg_score": null,
"num_lines": null
} |
"""$Id: image.py 699 2006-09-25 02:01:18Z rubys $"""
__author__ = "Sam Ruby <http://intertwingly.net/> and Mark Pilgrim <http://diveintomark.org/>"
__version__ = "$Revision: 699 $"
__date__ = "$Date: 2006-09-25 02:01:18 +0000 (Mon, 25 Sep 2006) $"
__copyright__ = "Copyright (c) 2002 Sam Ruby and Mark Pilgrim"
from base import validatorBase
from validators import *
from extension import extension_everywhere
#
# image element.
#
class image(validatorBase, extension_everywhere):
def getExpectedAttrNames(self):
return [(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#', u'resource'),
(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#', u'about'),
(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#', u'parseType')]
def validate(self):
if self.value.strip():
self.log(UnexpectedText({"parent":self.parent.name, "element":"image"}))
if self.attrs.has_key((rdfNS,"resource")):
return # looks like an RSS 1.0 feed
if not "title" in self.children:
self.log(MissingTitle({"parent":self.name, "element":"title"}))
if not "url" in self.children:
self.log(MissingElement({"parent":self.name, "element":"url"}))
if self.attrs.has_key((rdfNS,"parseType")):
return # looks like an RSS 1.1 feed
if not "link" in self.children:
self.log(MissingLink({"parent":self.name, "element":"link"}))
def do_title(self):
return title(), noduplicates()
def do_link(self):
return link(), noduplicates()
def do_url(self):
return url(), noduplicates()
def do_width(self):
return width(), noduplicates()
def do_height(self):
return height(), noduplicates()
def do_description(self):
return nonhtml(), noduplicates()
def do_dc_creator(self):
return text()
def do_dc_subject(self):
return text() # duplicates allowed
def do_dc_date(self):
return w3cdtf(), noduplicates()
def do_cc_license(self):
return eater()
class link(rfc2396_full):
def validate(self):
rfc2396_full.validate(self)
if self.parent.parent.link and self.parent.parent.link != self.value:
self.log(ImageLinkDoesntMatch({"parent":self.parent.name, "element":self.name}))
class url(rfc2396_full):
def validate(self):
rfc2396_full.validate(self)
import re
ext = self.value.split('.')[-1].lower()
if re.match("^\w+$", ext) and ext not in ['jpg','jpeg','gif','png']:
self.log(ImageUrlFormat({"parent":self.parent.name, "element":self.name}))
class title(nonhtml, noduplicates):
def validate(self):
if not self.value.strip():
self.log(NotBlank({"parent":self.parent.name, "element":self.name}))
else:
self.log(ValidTitle({"parent":self.parent.name, "element":self.name}))
nonhtml.validate(self)
class width(text, noduplicates):
def validate(self):
try:
w = int(self.value)
if (w <= 0) or (w > 144):
self.log(InvalidWidth({"parent":self.parent.name, "element":self.name, "value":self.value}))
else:
self.log(ValidWidth({"parent":self.parent.name, "element":self.name}))
except ValueError:
self.log(InvalidWidth({"parent":self.parent.name, "element":self.name, "value":self.value}))
class height(text, noduplicates):
def validate(self):
try:
h = int(self.value)
if (h <= 0) or (h > 400):
self.log(InvalidHeight({"parent":self.parent.name, "element":self.name, "value":self.value}))
else:
self.log(ValidHeight({"parent":self.parent.name, "element":self.name}))
except ValueError:
self.log(InvalidHeight({"parent":self.parent.name, "element":self.name, "value":self.value}))
| {
"repo_name": "slava-sh/NewsBlur",
"path": "vendor/feedvalidator/image.py",
"copies": "16",
"size": "3634",
"license": "mit",
"hash": 3305537281029260000,
"line_mean": 33.2830188679,
"line_max": 101,
"alpha_frac": 0.6474958723,
"autogenerated": false,
"ratio": 3.2330960854092528,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
from docutils import nodes
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.parsers.rst.roles import set_classes
try:
import Image as PIL # PIL
except ImportError:
PIL = None
class Image(Directive):
align_h_values = ('left', 'center', 'right')
align_v_values = ('top', 'middle', 'bottom')
align_values = align_v_values + align_h_values
def align(argument):
# This is not callable as self.align. We cannot make it a
# staticmethod because we're saving an unbound method in
# option_spec below.
return directives.choice(argument, Image.align_values)
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.percentage,
'align': align,
'target': directives.unchanged_required,
'class': directives.class_option}
def run(self):
if 'align' in self.options:
if isinstance(self.state, states.SubstitutionDef):
# Check for align_v_values.
if self.options['align'] not in self.align_v_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value '
'for the "align" option within a substitution '
'definition. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_v_values)))
elif self.options['align'] not in self.align_h_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value for '
'the "align" option. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_h_values)))
messages = []
reference = directives.uri(self.arguments[0])
self.options['uri'] = reference
reference_node = None
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
block = [line for line in block]
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
reference_node = nodes.reference(refuri=data)
elif target_type == 'refname':
reference_node = nodes.reference(
refname=fully_normalize_name(data),
name=whitespace_normalize_name(data))
reference_node.indirect_reference_name = data
self.state.document.note_refname(reference_node)
else: # malformed target
messages.append(data) # data is a system message
del self.options['target']
set_classes(self.options)
image_node = nodes.image(self.block_text, **self.options)
if reference_node:
reference_node += image_node
return messages + [reference_node]
else:
return messages + [image_node]
class Figure(Image):
def align(argument):
return directives.choice(argument, Figure.align_h_values)
def figwidth_value(argument):
if argument.lower() == 'image':
return 'image'
else:
return directives.length_or_percentage_or_unitless(argument, 'px')
option_spec = Image.option_spec.copy()
option_spec['figwidth'] = figwidth_value
option_spec['figclass'] = directives.class_option
option_spec['align'] = align
has_content = True
def run(self):
figwidth = self.options.pop('figwidth', None)
figclasses = self.options.pop('figclass', None)
align = self.options.pop('align', None)
(image_node,) = Image.run(self)
if isinstance(image_node, nodes.system_message):
return [image_node]
figure_node = nodes.figure('', image_node)
if figwidth == 'image':
if PIL and self.state.document.settings.file_insertion_enabled:
# PIL doesn't like Unicode paths:
try:
i = PIL.open(str(image_node['uri']))
except (IOError, UnicodeError):
pass
else:
self.state.document.settings.record_dependencies.add(
image_node['uri'])
figure_node['width'] = i.size[0]
elif figwidth is not None:
figure_node['width'] = figwidth
if figclasses:
figure_node['classes'] += figclasses
if align:
figure_node['align'] = align
if self.content:
node = nodes.Element() # anonymous container for parsing
self.state.nested_parse(self.content, self.content_offset, node)
first_node = node[0]
if isinstance(first_node, nodes.paragraph):
caption = nodes.caption(first_node.rawsource, '',
*first_node.children)
figure_node += caption
elif not (isinstance(first_node, nodes.comment)
and len(first_node) == 0):
error = self.state_machine.reporter.error(
'Figure caption must be a paragraph or empty comment.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
return [figure_node, error]
if len(node) > 1:
figure_node += nodes.legend('', *node[1:])
return [figure_node]
| {
"repo_name": "MichaelNedzelsky/intellij-community",
"path": "python/helpers/py2only/docutils/parsers/rst/directives/images.py",
"copies": "5",
"size": "6329",
"license": "apache-2.0",
"hash": -7632111782579808000,
"line_mean": 40.6381578947,
"line_max": 78,
"alpha_frac": 0.5561700111,
"autogenerated": false,
"ratio": 4.355815554026153,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7411985565126152,
"avg_score": null,
"num_lines": null
} |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst.roles import set_classes
try:
import Image as PIL # PIL
except ImportError:
PIL = None
class Image(Directive):
align_h_values = ('left', 'center', 'right')
align_v_values = ('top', 'middle', 'bottom')
align_values = align_v_values + align_h_values
def align(argument):
# This is not callable as self.align. We cannot make it a
# staticmethod because we're saving an unbound method in
# option_spec below.
return directives.choice(argument, Image.align_values)
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.percentage,
'align': align,
'target': directives.unchanged_required,
'class': directives.class_option}
def run(self):
if 'align' in self.options:
if isinstance(self.state, states.SubstitutionDef):
# Check for align_v_values.
if self.options['align'] not in self.align_v_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value '
'for the "align" option within a substitution '
'definition. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_v_values)))
elif self.options['align'] not in self.align_h_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value for '
'the "align" option. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_h_values)))
messages = []
reference = directives.uri(self.arguments[0])
self.options['uri'] = reference
reference_node = None
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
block = [line for line in block]
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
reference_node = nodes.reference(refuri=data)
elif target_type == 'refname':
reference_node = nodes.reference(
refname=fully_normalize_name(data),
name=whitespace_normalize_name(data))
reference_node.indirect_reference_name = data
self.state.document.note_refname(reference_node)
else: # malformed target
messages.append(data) # data is a system message
del self.options['target']
set_classes(self.options)
image_node = nodes.image(self.block_text, **self.options)
if reference_node:
reference_node += image_node
return messages + [reference_node]
else:
return messages + [image_node]
class Figure(Image):
def align(argument):
return directives.choice(argument, Figure.align_h_values)
def figwidth_value(argument):
if argument.lower() == 'image':
return 'image'
else:
return directives.length_or_percentage_or_unitless(argument, 'px')
option_spec = Image.option_spec.copy()
option_spec['figwidth'] = figwidth_value
option_spec['figclass'] = directives.class_option
option_spec['align'] = align
has_content = True
def run(self):
figwidth = self.options.pop('figwidth', None)
figclasses = self.options.pop('figclass', None)
align = self.options.pop('align', None)
(image_node,) = Image.run(self)
if isinstance(image_node, nodes.system_message):
return [image_node]
figure_node = nodes.figure('', image_node)
if figwidth == 'image':
if PIL and self.state.document.settings.file_insertion_enabled:
# PIL doesn't like Unicode paths:
try:
i = PIL.open(str(image_node['uri']))
except (IOError, UnicodeError):
pass
else:
self.state.document.settings.record_dependencies.add(
image_node['uri'])
figure_node['width'] = i.size[0]
elif figwidth is not None:
figure_node['width'] = figwidth
if figclasses:
figure_node['classes'] += figclasses
if align:
figure_node['align'] = align
if self.content:
node = nodes.Element() # anonymous container for parsing
self.state.nested_parse(self.content, self.content_offset, node)
first_node = node[0]
if isinstance(first_node, nodes.paragraph):
caption = nodes.caption(first_node.rawsource, '',
*first_node.children)
figure_node += caption
elif not (isinstance(first_node, nodes.comment)
and len(first_node) == 0):
error = self.state_machine.reporter.error(
'Figure caption must be a paragraph or empty comment.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
return [figure_node, error]
if len(node) > 1:
figure_node += nodes.legend('', *node[1:])
return [figure_node]
| {
"repo_name": "ahb0327/intellij-community",
"path": "python/helpers/docutils/parsers/rst/directives/images.py",
"copies": "51",
"size": "6348",
"license": "apache-2.0",
"hash": -7813138445835482000,
"line_mean": 40.2207792208,
"line_max": 78,
"alpha_frac": 0.556710775,
"autogenerated": false,
"ratio": 4.3539094650205765,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst.roles import set_classes
try:
import Image as PIL # PIL
except ImportError:
PIL = None
class Image(Directive):
align_h_values = ('left', 'center', 'right')
align_v_values = ('top', 'middle', 'bottom')
align_values = align_v_values + align_h_values
def align(argument):
# This is not callable as self.align. We cannot make it a
# staticmethod because we're saving an unbound method in
# option_spec below.
return directives.choice(argument, Image.align_values)
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.percentage,
'align': align,
'target': directives.unchanged_required,
'class': directives.class_option}
def run(self):
if 'align' in self.options:
if isinstance(self.state, states.SubstitutionDef):
# Check for align_v_values.
if self.options['align'] not in self.align_v_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value '
'for the "align" option within a substitution '
'definition. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_v_values)))
elif self.options['align'] not in self.align_h_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value for '
'the "align" option. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_h_values)))
messages = []
reference = directives.uri(self.arguments[0])
self.options['uri'] = reference
reference_node = None
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
block = [line for line in block]
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
reference_node = nodes.reference(refuri=data)
elif target_type == 'refname':
reference_node = nodes.reference(
refname=fully_normalize_name(data),
name=whitespace_normalize_name(data))
reference_node.indirect_reference_name = data
self.state.document.note_refname(reference_node)
else: # malformed target
messages.append(data) # data is a system message
del self.options['target']
set_classes(self.options)
image_node = nodes.image(self.block_text, **self.options)
if reference_node:
reference_node += image_node
return messages + [reference_node]
else:
return messages + [image_node]
class Figure(Image):
def align(argument):
return directives.choice(argument, Figure.align_h_values)
def figwidth_value(argument):
if argument.lower() == 'image':
return 'image'
else:
return directives.length_or_percentage_or_unitless(argument, 'px')
option_spec = Image.option_spec.copy()
option_spec['figwidth'] = figwidth_value
option_spec['figclass'] = directives.class_option
option_spec['align'] = align
has_content = True
def run(self):
figwidth = self.options.pop('figwidth', None)
figclasses = self.options.pop('figclass', None)
align = self.options.pop('align', None)
(image_node,) = Image.run(self)
if isinstance(image_node, nodes.system_message):
return [image_node]
figure_node = nodes.figure('', image_node)
if figwidth == 'image':
if PIL and self.state.document.settings.file_insertion_enabled:
# PIL doesn't like Unicode paths:
try:
i = PIL.open(str(image_node['uri']))
except (IOError, UnicodeError):
pass
else:
self.state.document.settings.record_dependencies.add(
image_node['uri'])
figure_node['width'] = i.size[0]
elif figwidth is not None:
figure_node['width'] = figwidth
if figclasses:
figure_node['classes'] += figclasses
if align:
figure_node['align'] = align
if self.content:
node = nodes.Element() # anonymous container for parsing
self.state.nested_parse(self.content, self.content_offset, node)
first_node = node[0]
if isinstance(first_node, nodes.paragraph):
caption = nodes.caption(first_node.rawsource, '',
*first_node.children)
figure_node += caption
elif not (isinstance(first_node, nodes.comment)
and len(first_node) == 0):
error = self.state_machine.reporter.error(
'Figure caption must be a paragraph or empty comment.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
return [figure_node, error]
if len(node) > 1:
figure_node += nodes.legend('', *node[1:])
return [figure_node]
| {
"repo_name": "rimbalinux/LMD3",
"path": "docutils/parsers/rst/directives/images.py",
"copies": "2",
"size": "6502",
"license": "bsd-3-clause",
"hash": 2854151722713147000,
"line_mean": 40.2207792208,
"line_max": 78,
"alpha_frac": 0.5435250692,
"autogenerated": false,
"ratio": 4.390276839972991,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 154
} |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst.roles import set_classes
try:
import Image as PIL # PIL
except ImportError:
PIL = None
class Image(Directive):
align_h_values = ('left', 'center', 'right')
align_v_values = ('top', 'middle', 'bottom')
align_values = align_v_values + align_h_values
def align(argument):
# This is not callable as self.align. We cannot make it a
# staticmethod because we're saving an unbound method in
# option_spec below.
return directives.choice(argument, Image.align_values)
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.percentage,
'align': align,
'name': directives.unchanged,
'target': directives.unchanged_required,
'class': directives.class_option}
def run(self):
if 'align' in self.options:
if isinstance(self.state, states.SubstitutionDef):
# Check for align_v_values.
if self.options['align'] not in self.align_v_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value '
'for the "align" option within a substitution '
'definition. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_v_values)))
elif self.options['align'] not in self.align_h_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value for '
'the "align" option. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_h_values)))
messages = []
reference = directives.uri(self.arguments[0])
self.options['uri'] = reference
reference_node = None
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
block = [line for line in block]
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
reference_node = nodes.reference(refuri=data)
elif target_type == 'refname':
reference_node = nodes.reference(
refname=fully_normalize_name(data),
name=whitespace_normalize_name(data))
reference_node.indirect_reference_name = data
self.state.document.note_refname(reference_node)
else: # malformed target
messages.append(data) # data is a system message
del self.options['target']
set_classes(self.options)
image_node = nodes.image(self.block_text, **self.options)
self.add_name(image_node)
if reference_node:
reference_node += image_node
return messages + [reference_node]
else:
return messages + [image_node]
class Figure(Image):
def align(argument):
return directives.choice(argument, Figure.align_h_values)
def figwidth_value(argument):
if argument.lower() == 'image':
return 'image'
else:
return directives.length_or_percentage_or_unitless(argument, 'px')
option_spec = Image.option_spec.copy()
option_spec['figwidth'] = figwidth_value
option_spec['figclass'] = directives.class_option
option_spec['align'] = align
has_content = True
def run(self):
figwidth = self.options.pop('figwidth', None)
figclasses = self.options.pop('figclass', None)
align = self.options.pop('align', None)
(image_node,) = Image.run(self)
if isinstance(image_node, nodes.system_message):
return [image_node]
figure_node = nodes.figure('', image_node)
if figwidth == 'image':
if PIL and self.state.document.settings.file_insertion_enabled:
# PIL doesn't like Unicode paths:
try:
i = PIL.open(str(image_node['uri']))
except (IOError, UnicodeError):
pass
else:
self.state.document.settings.record_dependencies.add(
image_node['uri'])
figure_node['width'] = i.size[0]
elif figwidth is not None:
figure_node['width'] = figwidth
if figclasses:
figure_node['classes'] += figclasses
if align:
figure_node['align'] = align
if self.content:
node = nodes.Element() # anonymous container for parsing
self.state.nested_parse(self.content, self.content_offset, node)
first_node = node[0]
if isinstance(first_node, nodes.paragraph):
caption = nodes.caption(first_node.rawsource, '',
*first_node.children)
figure_node += caption
elif not (isinstance(first_node, nodes.comment)
and len(first_node) == 0):
error = self.state_machine.reporter.error(
'Figure caption must be a paragraph or empty comment.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
return [figure_node, error]
if len(node) > 1:
figure_node += nodes.legend('', *node[1:])
return [figure_node]
| {
"repo_name": "paaschpa/badcomputering",
"path": "docutils/parsers/rst/directives/images.py",
"copies": "6",
"size": "6431",
"license": "bsd-3-clause",
"hash": -6009653844886542000,
"line_mean": 40.2243589744,
"line_max": 78,
"alpha_frac": 0.5562120977,
"autogenerated": false,
"ratio": 4.354096140825999,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 156
} |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst.roles import set_classes
try:
import Image as PIL # PIL
except ImportError:
PIL = None
class Image(Directive):
align_h_values = ('left', 'center', 'right')
align_v_values = ('top', 'middle', 'bottom')
align_values = align_v_values + align_h_values
def align(argument):
# This is not callable as self.align. We cannot make it a
# staticmethod because we're saving an unbound method in
# option_spec below.
return directives.choice(argument, Image.align_values)
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.percentage,
'align': align,
'name': directives.unchanged,
'target': directives.unchanged_required,
'class': directives.class_option}
def run(self):
if 'align' in self.options:
if isinstance(self.state, states.SubstitutionDef):
# Check for align_v_values.
if self.options['align'] not in self.align_v_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value '
'for the "align" option within a substitution '
'definition. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_v_values)))
elif self.options['align'] not in self.align_h_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value for '
'the "align" option. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_h_values)))
messages = []
reference = directives.uri(self.arguments[0])
self.options['uri'] = reference
reference_node = None
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
block = [line for line in block]
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
reference_node = nodes.reference(refuri=data)
elif target_type == 'refname':
reference_node = nodes.reference(
refname=fully_normalize_name(data),
name=whitespace_normalize_name(data))
reference_node.indirect_reference_name = data
self.state.document.note_refname(reference_node)
else: # malformed target
messages.append(data) # data is a system message
del self.options['target']
set_classes(self.options)
image_node = nodes.image(self.block_text, **self.options)
self.add_name(image_node)
if reference_node:
reference_node += image_node
return messages + [reference_node]
else:
return messages + [image_node]
class Figure(Image):
def align(argument):
return directives.choice(argument, Figure.align_h_values)
def figwidth_value(argument):
if argument.lower() == 'image':
return 'image'
else:
return directives.length_or_percentage_or_unitless(argument, 'px')
option_spec = Image.option_spec.copy()
option_spec['figwidth'] = figwidth_value
option_spec['figclass'] = directives.class_option
option_spec['align'] = align
has_content = True
def run(self):
figwidth = self.options.pop('figwidth', None)
figclasses = self.options.pop('figclass', None)
align = self.options.pop('align', None)
(image_node,) = Image.run(self)
if isinstance(image_node, nodes.system_message):
return [image_node]
figure_node = nodes.figure('', image_node)
if figwidth == 'image':
if PIL and self.state.document.settings.file_insertion_enabled:
# PIL doesn't like Unicode paths:
try:
i = PIL.open(str(image_node['uri']))
except (IOError, UnicodeError):
pass
else:
self.state.document.settings.record_dependencies.add(
image_node['uri'])
figure_node['width'] = i.size[0]
elif figwidth is not None:
figure_node['width'] = figwidth
if figclasses:
figure_node['classes'] += figclasses
if align:
figure_node['align'] = align
if self.content:
node = nodes.Element() # anonymous container for parsing
self.state.nested_parse(self.content, self.content_offset, node)
first_node = node[0]
if isinstance(first_node, nodes.paragraph):
caption = nodes.caption(first_node.rawsource, '',
*first_node.children)
figure_node += caption
elif not (isinstance(first_node, nodes.comment)
and len(first_node) == 0):
error = self.state_machine.reporter.error(
'Figure caption must be a paragraph or empty comment.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
return [figure_node, error]
if len(node) > 1:
figure_node += nodes.legend('', *node[1:])
return [figure_node]
| {
"repo_name": "ajaxsys/dict-admin",
"path": "docutils/parsers/rst/directives/images.py",
"copies": "2",
"size": "6587",
"license": "bsd-3-clause",
"hash": 9082078375678682000,
"line_mean": 40.2243589744,
"line_max": 78,
"alpha_frac": 0.5430393199,
"autogenerated": false,
"ratio": 4.388407728181212,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5931447048081213,
"avg_score": null,
"num_lines": null
} |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
import sys
import urllib
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst.roles import set_classes
try: # check for the Python Imaging Library
import PIL
except ImportError:
try: # sometimes PIL modules are put in PYTHONPATH's root
import Image
class PIL(object): pass # dummy wrapper
PIL.Image = Image
except ImportError:
PIL = None
class Image(Directive):
align_h_values = ('left', 'center', 'right')
align_v_values = ('top', 'middle', 'bottom')
align_values = align_v_values + align_h_values
def align(argument):
# This is not callable as self.align. We cannot make it a
# staticmethod because we're saving an unbound method in
# option_spec below.
return directives.choice(argument, Image.align_values)
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.percentage,
'align': align,
'name': directives.unchanged,
'target': directives.unchanged_required,
'class': directives.class_option}
def run(self):
if 'align' in self.options:
if isinstance(self.state, states.SubstitutionDef):
# Check for align_v_values.
if self.options['align'] not in self.align_v_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value '
'for the "align" option within a substitution '
'definition. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_v_values)))
elif self.options['align'] not in self.align_h_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value for '
'the "align" option. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_h_values)))
messages = []
reference = directives.uri(self.arguments[0])
self.options['uri'] = reference
reference_node = None
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
block = [line for line in block]
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
reference_node = nodes.reference(refuri=data)
elif target_type == 'refname':
reference_node = nodes.reference(
refname=fully_normalize_name(data),
name=whitespace_normalize_name(data))
reference_node.indirect_reference_name = data
self.state.document.note_refname(reference_node)
else: # malformed target
messages.append(data) # data is a system message
del self.options['target']
set_classes(self.options)
image_node = nodes.image(self.block_text, **self.options)
self.add_name(image_node)
if reference_node:
reference_node += image_node
return messages + [reference_node]
else:
return messages + [image_node]
class Figure(Image):
def align(argument):
return directives.choice(argument, Figure.align_h_values)
def figwidth_value(argument):
if argument.lower() == 'image':
return 'image'
else:
return directives.length_or_percentage_or_unitless(argument, 'px')
option_spec = Image.option_spec.copy()
option_spec['figwidth'] = figwidth_value
option_spec['figclass'] = directives.class_option
option_spec['align'] = align
has_content = True
def run(self):
figwidth = self.options.pop('figwidth', None)
figclasses = self.options.pop('figclass', None)
align = self.options.pop('align', None)
(image_node,) = Image.run(self)
if isinstance(image_node, nodes.system_message):
return [image_node]
figure_node = nodes.figure('', image_node)
if figwidth == 'image':
if PIL and self.state.document.settings.file_insertion_enabled:
imagepath = urllib.url2pathname(image_node['uri'])
try:
img = PIL.Image.open(
imagepath.encode(sys.getfilesystemencoding()))
except (IOError, UnicodeEncodeError):
pass # TODO: warn?
else:
self.state.document.settings.record_dependencies.add(
imagepath.replace('\\', '/'))
figure_node['width'] = img.size[0]
del img
elif figwidth is not None:
figure_node['width'] = figwidth
if figclasses:
figure_node['classes'] += figclasses
if align:
figure_node['align'] = align
if self.content:
node = nodes.Element() # anonymous container for parsing
self.state.nested_parse(self.content, self.content_offset, node)
first_node = node[0]
if isinstance(first_node, nodes.paragraph):
caption = nodes.caption(first_node.rawsource, '',
*first_node.children)
figure_node += caption
elif not (isinstance(first_node, nodes.comment)
and len(first_node) == 0):
error = self.state_machine.reporter.error(
'Figure caption must be a paragraph or empty comment.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
return [figure_node, error]
if len(node) > 1:
figure_node += nodes.legend('', *node[1:])
return [figure_node]
| {
"repo_name": "ddd332/presto",
"path": "presto-docs/target/sphinx/docutils/parsers/rst/directives/images.py",
"copies": "4",
"size": "6769",
"license": "apache-2.0",
"hash": 277430974279927140,
"line_mean": 40.7839506173,
"line_max": 78,
"alpha_frac": 0.5609395775,
"autogenerated": false,
"ratio": 4.389753566796369,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6950693144296369,
"avg_score": null,
"num_lines": null
} |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
import sys
import urllib.error
import urllib.parse
import urllib.request
from docutils import nodes
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.parsers.rst.roles import set_classes
try: # check for the Python Imaging Library
import PIL.Image
except ImportError:
try: # sometimes PIL modules are put in PYTHONPATH's root
import Image
class PIL(object): pass # dummy wrapper
PIL.Image = Image
except ImportError:
PIL = None
class Image(Directive):
align_h_values = ('left', 'center', 'right')
align_v_values = ('top', 'middle', 'bottom')
align_values = align_v_values + align_h_values
def align(argument):
# This is not callable as self.align. We cannot make it a
# staticmethod because we're saving an unbound method in
# option_spec below.
return directives.choice(argument, Image.align_values)
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.percentage,
'align': align,
'name': directives.unchanged,
'target': directives.unchanged_required,
'class': directives.class_option}
def run(self):
if 'align' in self.options:
if isinstance(self.state, states.SubstitutionDef):
# Check for align_v_values.
if self.options['align'] not in self.align_v_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value '
'for the "align" option within a substitution '
'definition. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_v_values)))
elif self.options['align'] not in self.align_h_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value for '
'the "align" option. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_h_values)))
messages = []
reference = directives.uri(self.arguments[0])
self.options['uri'] = reference
reference_node = None
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
block = [line for line in block]
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
reference_node = nodes.reference(refuri=data)
elif target_type == 'refname':
reference_node = nodes.reference(
refname=fully_normalize_name(data),
name=whitespace_normalize_name(data))
reference_node.indirect_reference_name = data
self.state.document.note_refname(reference_node)
else: # malformed target
messages.append(data) # data is a system message
del self.options['target']
set_classes(self.options)
image_node = nodes.image(self.block_text, **self.options)
self.add_name(image_node)
if reference_node:
reference_node += image_node
return messages + [reference_node]
else:
return messages + [image_node]
class Figure(Image):
def align(argument):
return directives.choice(argument, Figure.align_h_values)
def figwidth_value(argument):
if argument.lower() == 'image':
return 'image'
else:
return directives.length_or_percentage_or_unitless(argument, 'px')
option_spec = Image.option_spec.copy()
option_spec['figwidth'] = figwidth_value
option_spec['figclass'] = directives.class_option
option_spec['align'] = align
has_content = True
def run(self):
figwidth = self.options.pop('figwidth', None)
figclasses = self.options.pop('figclass', None)
align = self.options.pop('align', None)
(image_node,) = Image.run(self)
if isinstance(image_node, nodes.system_message):
return [image_node]
figure_node = nodes.figure('', image_node)
if figwidth == 'image':
if PIL and self.state.document.settings.file_insertion_enabled:
imagepath = urllib.request.url2pathname(image_node['uri'])
try:
img = PIL.Image.open(
imagepath.encode(sys.getfilesystemencoding()))
except (IOError, UnicodeEncodeError):
pass # TODO: warn?
else:
self.state.document.settings.record_dependencies.add(
imagepath.replace('\\', '/'))
figure_node['width'] = '%dpx' % img.size[0]
del img
elif figwidth is not None:
figure_node['width'] = figwidth
if figclasses:
figure_node['classes'] += figclasses
if align:
figure_node['align'] = align
if self.content:
node = nodes.Element() # anonymous container for parsing
self.state.nested_parse(self.content, self.content_offset, node)
first_node = node[0]
if isinstance(first_node, nodes.paragraph):
caption = nodes.caption(first_node.rawsource, '',
*first_node.children)
caption.source = first_node.source
caption.line = first_node.line
figure_node += caption
elif not (isinstance(first_node, nodes.comment)
and len(first_node) == 0):
error = self.state_machine.reporter.error(
'Figure caption must be a paragraph or empty comment.',
nodes.literal_block(self.block_text, self.block_text),
line=self.lineno)
return [figure_node, error]
if len(node) > 1:
figure_node += nodes.legend('', *node[1:])
return [figure_node]
| {
"repo_name": "dahlstrom-g/intellij-community",
"path": "python/helpers/py3only/docutils/parsers/rst/directives/images.py",
"copies": "44",
"size": "6933",
"license": "apache-2.0",
"hash": -935192787127929100,
"line_mean": 40.2678571429,
"line_max": 78,
"alpha_frac": 0.5625270446,
"autogenerated": false,
"ratio": 4.3768939393939394,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""$Id: index.py 133 2009-03-26 15:31:38Z thomas.figg $"""
import os
import base64
import hashlib
import datetime
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import memcache
from google.appengine.api import users
class LogoProgram(db.Model):
code = db.TextProperty()
img = db.BlobProperty()
date = db.DateTimeProperty(auto_now_add=True)
hash = db.StringProperty()
class Moderate(webapp.RequestHandler):
def get(self):
login_url = users.create_login_url("/moderate")
values = dict(login_url=login_url)
if users.is_current_user_admin():
values["items"] = db.GqlQuery("SELECT * FROM LogoProgram WHERE img = null").fetch(10000)
fstring = self.request.get("filter_string", None)
if fstring:
values["items"] = filter(lambda x: fstring in x.code, values["items"])
if int(self.request.get("delete", 0)):
for item in values["items"]:
try:
item.delete()
except db.InternalError:
pass
else:
values["items"] = ["please log in as an admin"]
page = os.path.join(os.path.dirname(__file__), 'moderate.html.tmpl')
self.response.out.write(template.render(page, values))
application = webapp.WSGIApplication([('/moderate', Moderate)],debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
| {
"repo_name": "elliotlaster/papert",
"path": "moderate.py",
"copies": "1",
"size": "1678",
"license": "mit",
"hash": 9123307837129872000,
"line_mean": 30.6603773585,
"line_max": 100,
"alpha_frac": 0.6269368296,
"autogenerated": false,
"ratio": 3.8310502283105023,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9908754760523353,
"avg_score": 0.009846459477429806,
"num_lines": 53
} |
import os
import socket
import sys
def chop(s, extras=[]):
"""Remove \\r, \\n and all characters in the extras list from
the end of string s and return """
_ch = ['\r','\n']
_ch.extend(extras)
while s[-1] in _ch:
s = s[:-1]
return s
def getClassFromString(clazz, reload=False):
""" Performn an import given an absolute class reference as a string; returns
the class object. If 'reload' is set True sys.modules will be cleaned prior
to import thus hopefuly effecting a reload."""
packageTree = clazz.split('.')
cls = packageTree[-1]
packageTree = packageTree[:-1]
if reload:
currentKey = ''
loadedModules = sys.modules.keys()
for pkg in packageTree:
currentKey = ".".join([i for i in [currentKey, pkg] if i])
if currentKey in loadedModules:
del(sys.modules[currentKey])
print("Purging %s " % currentKey)
try:
mdle = __import__(".".join(packageTree),{},{},".".join(packageTree[:-1]))
handler = getattr(mdle, cls)
if callable(handler):
return handler
else:
raise Exception("Class %s is not valid" % clazz)
except Exception,ex:
raise Exception("Could not find class %s (error: %s)" %(clazz, str(ex)))
def getExternalIPAddress():
""" Bit of a cheap way of working out what the IP address
of the external interface on this machine is; if we've got
configuration saying to connect to 0.0.0.0 that's fine, but we
will still need to know what address to tell other nodes to
contact this node on. As a result, something like this is handy."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('1.2.3.4', 56))
ip = s.getsockname()[0]
s.close()
except:
ip = socket.gethostbyname(socket.gethostname())
return ip
def deCompound(l):
""" Takes l which is likely from configuration parsing and will be
a list of strings, some of which may be comma delimited. Expands the
comma delimited lists and returns a single, separated list. Thus,
a list transforms as follows::
["a", "b", "c,d,e", "f"] --> ["a","b","c","d","e","f"]
"""
out = []
for i in l:
out.extend(i.split(','))
return out | {
"repo_name": "aquamatt/Peloton",
"path": "src/peloton/utils/__init__.py",
"copies": "1",
"size": "2477",
"license": "bsd-3-clause",
"hash": -2623132613159616500,
"line_mean": 32.4864864865,
"line_max": 81,
"alpha_frac": 0.6156641098,
"autogenerated": false,
"ratio": 3.69150521609538,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9701714994941534,
"avg_score": 0.021090866190769143,
"num_lines": 74
} |
""" Provides logging facilities to peloton. Allows
centralised setup of logging and the option to switch
logging back-ends.
"""
DEBUG, INFO, WARN, WARNING, ERROR, CRITICAL, FATAL = (10,20,30,30,40,50,50)
__LOGGER__ = None
_DEFAULT_FORMAT__ = "[%(levelname)s]\t %(asctime)-4s %(name)s\t : %(message)s"
def initLogging(backend='PYTHON', defaultFormat=None,
rootLoggerName='PSC', logLevel=ERROR,
logdir='', logfile='', logToConsole=True):
""" Initialise the Peloton logger with the specified backend,
either PYTHON (default) or TWISTED.
You may optionaly set the default log entry format here."""
global __LOGGER__, _DEFAULT_FORMAT__
if backend == 'PYTHON':
import peloton.utils.logging.python_logger as _logger
elif backend == 'TWISTED':
import peloton.utils.logging.twisted_logger as _logger
else:
raise Exception("Logger backend '%s' not known!" % backend)
if defaultFormat != None:
_DEFAULT_FORMAT__ = defaultFormat
__LOGGER__ = _logger
__LOGGER__.initialise(rootLoggerName, logLevel, logdir, logfile, logToConsole)
getLogger().info("SET DEFAULT LOG LEVEL FROM OPTIONS: self.profile.loglevel")
def closeHandlers():
""" Close all log handlers cleanly. """
if __LOGGER__:
__LOGGER__.closeHandlers()
def getLogger(name=''):
""" Return the root logger or the named logger
if specified. """
if __LOGGER__ == None:
initLogging()
__LOGGER__.getLogger().info("Logger initialised with defaults!")
return __LOGGER__.getLogger(name)
def setAdditionalLoggers(kernel):
__LOGGER__.BusLogHandler(kernel)
#class BasePelotonLogger(object):
# """ Base class for all Peloton logger systems """
# _LOG_LEVEL__ = ERROR
#
# def debug(self, msg):
# raise NotImplementedError()
#
# def info(self, msg):
# raise NotImplementedError()
#
# def warn(self, msg):
# raise NotImplementedError()
#
# def warning(self, msg):
# self.warn(msg)
#
# def error(self, msg):
# raise NotImplementedError()
#
# def critical(self, msg):
# raise NotImplementedError()
#
# def fatal(self, msg):
# raise NotImplementedError()
#
# def exception(self, msg):
# raise NotImplementedError()
#
# def setLevel(level=ERROR):
# """ Set the log level to level (constants defined in
#logging are:
#
# - DEBUG
# - INFO
# - WARN
# - WARNING
# - ERROR
# - CRITICAL
# - FATAL
#
#When the level is set all messages at that level or higher (later in the
#list) are output; all others are ignored. For example, if loglevel==WARN
#then WARN[ING], ERROR, CRITICAL and FATAL messages will be output whilst
#INFO and DEBUG messages will silently be dropped.
#"""
# pass
| {
"repo_name": "aquamatt/Peloton",
"path": "src/peloton/utils/logging/__init__.py",
"copies": "1",
"size": "3007",
"license": "bsd-3-clause",
"hash": -4632251970301909000,
"line_mean": 29.3737373737,
"line_max": 82,
"alpha_frac": 0.638510143,
"autogenerated": false,
"ratio": 3.6185318892900122,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4757042032290012,
"avg_score": null,
"num_lines": null
} |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""matplotlib_kit package driver file.
Inserts the following modules in sys.modules: matplotlib, pylab.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
import types
# you have to define this
VERSION = ''
def init(theModuleManager, pre_import=True):
if hasattr(sys, 'frozen') and sys.frozen:
# matplotlib supports py2exe by checking for matplotlibdata in the appdir
# but this is only done on windows (and therefore works for our windows
# installer builds). On non-windows, we have to stick it in the env
# to make sure that MPL finds its datadir (only if we're frozen)
mpldir = os.path.join(theModuleManager.get_appdir(), 'matplotlibdata')
os.environ['MATPLOTLIBDATA'] = mpldir
# import the main module itself
# this doesn't import numerix yet...
global matplotlib
import matplotlib
# use WX + Agg backend (slower, but nicer that WX)
matplotlib.use('WXAgg')
# interactive mode: user can use pylab commands from any introspection
# interface, changes will be made immediately and matplotlib cooperates
# nicely with main WX event loop
matplotlib.interactive(True)
# with matplotlib 1.0.1 we can't do this anymore.
# makes sure we use the numpy backend
#from matplotlib import rcParams
#rcParams['numerix'] = 'numpy'
theModuleManager.setProgress(25, 'Initialising matplotlib_kit: config')
# @PATCH:
# this is for the combination numpy 1.0.4 and matplotlib 0.91.2
# matplotlib/numerix/ma/__init__.py:
# . normal installation fails on "from numpy.ma import *", so "from
# numpy.core.ma import *" is done, thus bringing in e.g. getmask
# . pyinstaller binaries for some or other reason succeed on
# "from numpy.ma import *" (no exception raised), therefore do
# not do "from numpy.core.ma import *", and therefore things like
# getmask are not imported.
# solution:
# we make sure that "from numpy.ma import *" actually brings in
# numpy.core.ma by importing that and associating the module
# binding to the global numpy.ma.
#if hasattr(sys, 'frozen') and sys.frozen:
# import numpy.core.ma
# sys.modules['numpy.ma'] = sys.modules['numpy.core.ma']
# import the pylab interface, make sure it's available from this namespace
global pylab
import pylab
theModuleManager.setProgress(90, 'Initialising matplotlib_kit: pylab')
# build up VERSION
global VERSION
VERSION = '%s' % (matplotlib.__version__,)
theModuleManager.setProgress(100, 'Initialising matplotlib_kit: complete')
| {
"repo_name": "zhangfangyan/devide",
"path": "module_kits/matplotlib_kit/__init__.py",
"copies": "7",
"size": "2895",
"license": "bsd-3-clause",
"hash": -4838247926058217000,
"line_mean": 34.3048780488,
"line_max": 81,
"alpha_frac": 0.6911917098,
"autogenerated": false,
"ratio": 3.9121621621621623,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8103353871962161,
"avg_score": null,
"num_lines": null
} |
"""
PEP HTML Writer.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import codecs
import docutils
from docutils import frontend, nodes, utils, writers
from docutils.writers import html4css1
class Writer(html4css1.Writer):
default_stylesheet = 'pep.css'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = html4css1.Writer.settings_spec + (
'PEP/HTML-Specific Options',
'For the PEP/HTML writer, the default value for the --stylesheet-path '
'option is "%s", and the default value for --template is "%s". '
'See HTML-Specific Options above.'
% (default_stylesheet_path, default_template_path),
(('Python\'s home URL. Default is "http://www.python.org".',
['--python-home'],
{'default': 'http://www.python.org', 'metavar': '<URL>'}),
('Home URL prefix for PEPs. Default is "." (current directory).',
['--pep-home'],
{'default': '.', 'metavar': '<URL>'}),
# For testing.
(frontend.SUPPRESS_HELP,
['--no-random'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),))
settings_default_overrides = {'stylesheet_path': default_stylesheet_path,
'template': default_template_path,}
relative_path_settings = (html4css1.Writer.relative_path_settings
+ ('template',))
config_section = 'pep_html writer'
config_section_dependencies = ('writers', 'html4css1 writer')
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = HTMLTranslator
def interpolation_dict(self):
subs = html4css1.Writer.interpolation_dict(self)
settings = self.document.settings
pyhome = settings.python_home
subs['pyhome'] = pyhome
subs['pephome'] = settings.pep_home
if pyhome == '..':
subs['pepindex'] = '.'
else:
subs['pepindex'] = pyhome + '/dev/peps'
index = self.document.first_child_matching_class(nodes.field_list)
header = self.document[index]
self.pepnum = header[0][1].astext()
subs['pep'] = self.pepnum
if settings.no_random:
subs['banner'] = 0
else:
import random
subs['banner'] = random.randrange(64)
try:
subs['pepnum'] = '%04i' % int(self.pepnum)
except ValueError:
subs['pepnum'] = pepnum
self.title = header[1][1].astext()
subs['title'] = self.title
subs['body'] = ''.join(
self.body_pre_docinfo + self.docinfo + self.body)
return subs
def assemble_parts(self):
html4css1.Writer.assemble_parts(self)
self.parts['title'] = [self.title]
self.parts['pepnum'] = self.pepnum
class HTMLTranslator(html4css1.HTMLTranslator):
def depart_field_list(self, node):
html4css1.HTMLTranslator.depart_field_list(self, node)
if 'rfc2822' in node['classes']:
self.body.append('<hr />\n')
| {
"repo_name": "umitproject/tease-o-matic",
"path": "docutils/writers/pep_html/__init__.py",
"copies": "10",
"size": "3578",
"license": "bsd-3-clause",
"hash": 332049363251966460,
"line_mean": 33.0761904762,
"line_max": 79,
"alpha_frac": 0.5944661822,
"autogenerated": false,
"ratio": 3.7902542372881354,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9384720419488135,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils parser modules.
"""
__docformat__ = 'reStructuredText'
from docutils import Component
class Parser(Component):
component_type = 'parser'
config_section = 'parsers'
def parse(self, inputstring, document):
"""Override to parse `inputstring` into document tree `document`."""
raise NotImplementedError('subclass must override this method')
def setup_parse(self, inputstring, document):
"""Initial parse setup. Call at start of `self.parse()`."""
self.inputstring = inputstring
self.document = document
document.reporter.attach_observer(document.note_parse_message)
def finish_parse(self):
"""Finalize parse details. Call at end of `self.parse()`."""
self.document.reporter.detach_observer(
self.document.note_parse_message)
_parser_aliases = {
'restructuredtext': 'rst',
'rest': 'rst',
'restx': 'rst',
'rtxt': 'rst',}
def get_parser_class(parser_name):
"""Return the Parser class from the `parser_name` module."""
parser_name = parser_name.lower()
if _parser_aliases.has_key(parser_name):
parser_name = _parser_aliases[parser_name]
module = __import__(parser_name, globals(), locals())
return module.Parser
| {
"repo_name": "PatrickKennedy/Sybil",
"path": "docutils/parsers/__init__.py",
"copies": "2",
"size": "1464",
"license": "bsd-2-clause",
"hash": 3270042501447439400,
"line_mean": 30.1489361702,
"line_max": 76,
"alpha_frac": 0.6584699454,
"autogenerated": false,
"ratio": 3.8526315789473684,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0020478339627275797,
"num_lines": 47
} |
"""
PEP HTML Writer.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import codecs
import docutils
from docutils import frontend, nodes, utils, writers
from docutils.writers import html4css1
class Writer(html4css1.Writer):
default_stylesheet = 'pep.css'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = html4css1.Writer.settings_spec + (
'PEP/HTML-Specific Options',
'For the PEP/HTML writer, the default value for the --stylesheet-path '
'option is "%s", and the default value for --template is "%s". '
'See HTML-Specific Options above.'
% (default_stylesheet_path, default_template_path),
(('Python\'s home URL. Default is "http://www.python.org".',
['--python-home'],
{'default': 'http://www.python.org', 'metavar': '<URL>'}),
('Home URL prefix for PEPs. Default is "." (current directory).',
['--pep-home'],
{'default': '.', 'metavar': '<URL>'}),
# For testing.
(frontend.SUPPRESS_HELP,
['--no-random'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),))
settings_default_overrides = {'stylesheet_path': default_stylesheet_path,
'template': default_template_path,}
relative_path_settings = (html4css1.Writer.relative_path_settings
+ ('template',))
config_section = 'pep_html writer'
config_section_dependencies = ('writers', 'html4css1 writer')
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = HTMLTranslator
def interpolation_dict(self):
subs = html4css1.Writer.interpolation_dict(self)
settings = self.document.settings
pyhome = settings.python_home
subs['pyhome'] = pyhome
subs['pephome'] = settings.pep_home
if pyhome == '..':
subs['pepindex'] = '.'
else:
subs['pepindex'] = pyhome + '/dev/peps'
index = self.document.first_child_matching_class(nodes.field_list)
header = self.document[index]
self.pepnum = header[0][1].astext()
subs['pep'] = self.pepnum
if settings.no_random:
subs['banner'] = 0
else:
import random
subs['banner'] = random.randrange(64)
try:
subs['pepnum'] = '%04i' % int(self.pepnum)
except ValueError:
subs['pepnum'] = pepnum
self.title = header[1][1].astext()
subs['title'] = self.title
subs['body'] = ''.join(
self.body_pre_docinfo + self.docinfo + self.body)
return subs
def assemble_parts(self):
html4css1.Writer.assemble_parts(self)
self.parts['title'] = [self.title]
self.parts['pepnum'] = self.pepnum
class HTMLTranslator(html4css1.HTMLTranslator):
def depart_field_list(self, node):
html4css1.HTMLTranslator.depart_field_list(self, node)
if 'rfc2822' in node['classes']:
self.body.append('<hr />\n')
| {
"repo_name": "rimbalinux/LMD3",
"path": "docutils/writers/pep_html/__init__.py",
"copies": "2",
"size": "3683",
"license": "bsd-3-clause",
"hash": -944172263727621900,
"line_mean": 33.0761904762,
"line_max": 79,
"alpha_frac": 0.5775183275,
"autogenerated": false,
"ratio": 3.852510460251046,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5430028787751046,
"avg_score": null,
"num_lines": null
} |
"""
This package contains directive implementation modules.
"""
__docformat__ = 'reStructuredText'
import re
import codecs
from docutils import nodes
from docutils.parsers.rst.languages import en as _fallback_language_module
_directive_registry = {
'attention': ('admonitions', 'Attention'),
'caution': ('admonitions', 'Caution'),
'danger': ('admonitions', 'Danger'),
'error': ('admonitions', 'Error'),
'important': ('admonitions', 'Important'),
'note': ('admonitions', 'Note'),
'tip': ('admonitions', 'Tip'),
'hint': ('admonitions', 'Hint'),
'warning': ('admonitions', 'Warning'),
'admonition': ('admonitions', 'Admonition'),
'sidebar': ('body', 'Sidebar'),
'topic': ('body', 'Topic'),
'line-block': ('body', 'LineBlock'),
'parsed-literal': ('body', 'ParsedLiteral'),
'rubric': ('body', 'Rubric'),
'epigraph': ('body', 'Epigraph'),
'highlights': ('body', 'Highlights'),
'pull-quote': ('body', 'PullQuote'),
'compound': ('body', 'Compound'),
'container': ('body', 'Container'),
#'questions': ('body', 'question_list'),
'table': ('tables', 'RSTTable'),
'csv-table': ('tables', 'CSVTable'),
'list-table': ('tables', 'ListTable'),
'image': ('images', 'Image'),
'figure': ('images', 'Figure'),
'contents': ('parts', 'Contents'),
'sectnum': ('parts', 'Sectnum'),
'header': ('parts', 'Header'),
'footer': ('parts', 'Footer'),
#'footnotes': ('parts', 'footnotes'),
#'citations': ('parts', 'citations'),
'target-notes': ('references', 'TargetNotes'),
'meta': ('html', 'Meta'),
#'imagemap': ('html', 'imagemap'),
'raw': ('misc', 'Raw'),
'include': ('misc', 'Include'),
'replace': ('misc', 'Replace'),
'unicode': ('misc', 'Unicode'),
'class': ('misc', 'Class'),
'role': ('misc', 'Role'),
'default-role': ('misc', 'DefaultRole'),
'title': ('misc', 'Title'),
'date': ('misc', 'Date'),
'restructuredtext-test-directive': ('misc', 'TestDirective'),}
"""Mapping of directive name to (module name, class name). The
directive name is canonical & must be lowercase. Language-dependent
names are defined in the ``language`` subpackage."""
_directives = {}
"""Cache of imported directives."""
def directive(directive_name, language_module, document):
"""
Locate and return a directive function from its language-dependent name.
If not found in the current language, check English. Return None if the
named directive cannot be found.
"""
normname = directive_name.lower()
messages = []
msg_text = []
if _directives.has_key(normname):
return _directives[normname], messages
canonicalname = None
try:
canonicalname = language_module.directives[normname]
except AttributeError, error:
msg_text.append('Problem retrieving directive entry from language '
'module %r: %s.' % (language_module, error))
except KeyError:
msg_text.append('No directive entry for "%s" in module "%s".'
% (directive_name, language_module.__name__))
if not canonicalname:
try:
canonicalname = _fallback_language_module.directives[normname]
msg_text.append('Using English fallback for directive "%s".'
% directive_name)
except KeyError:
msg_text.append('Trying "%s" as canonical directive name.'
% directive_name)
# The canonical name should be an English name, but just in case:
canonicalname = normname
if msg_text:
message = document.reporter.info(
'\n'.join(msg_text), line=document.current_line)
messages.append(message)
try:
modulename, classname = _directive_registry[canonicalname]
except KeyError:
# Error handling done by caller.
return None, messages
try:
module = __import__(modulename, globals(), locals())
except ImportError, detail:
messages.append(document.reporter.error(
'Error importing directive module "%s" (directive "%s"):\n%s'
% (modulename, directive_name, detail),
line=document.current_line))
return None, messages
try:
directive = getattr(module, classname)
_directives[normname] = directive
except AttributeError:
messages.append(document.reporter.error(
'No directive class "%s" in module "%s" (directive "%s").'
% (classname, modulename, directive_name),
line=document.current_line))
return None, messages
return directive, messages
def register_directive(name, directive):
"""
Register a nonstandard application-defined directive function.
Language lookups are not needed for such functions.
"""
_directives[name] = directive
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
else:
return None
def unchanged_required(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
return argument # unchanged!
def unchanged(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
No argument implies empty string ("").
"""
if argument is None:
return u''
else:
return argument # unchanged!
def path(argument):
"""
Return the path argument unwrapped (with newlines removed).
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
path = ''.join([s.strip() for s in argument.splitlines()])
return path
def uri(argument):
"""
Return the URI argument with whitespace removed.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
uri = ''.join(argument.split())
return uri
def nonnegative_int(argument):
"""
Check for a nonnegative integer argument; raise ``ValueError`` if not.
(Directive option conversion function.)
"""
value = int(argument)
if value < 0:
raise ValueError('negative value; must be positive or zero')
return value
length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc']
def get_measure(argument, units):
"""
Check for a positive argument of one of the units and return a
normalized string of the form "<value><unit>" (without space in
between).
To be called from directive option conversion functions.
"""
match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument)
try:
assert match is not None
float(match.group(1))
except (AssertionError, ValueError):
raise ValueError(
'not a positive measure of one of the following units:\n%s'
% ' '.join(['"%s"' % i for i in units]))
return match.group(1) + match.group(2)
def length_or_unitless(argument):
return get_measure(argument, length_units + [''])
def length_or_percentage_or_unitless(argument):
return get_measure(argument, length_units + ['%', ''])
def class_option(argument):
"""
Convert the argument into a list of ID-compatible strings and return it.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
names = argument.split()
class_names = []
for name in names:
class_name = nodes.make_id(name)
if not class_name:
raise ValueError('cannot make "%s" into a class name' % name)
class_names.append(class_name)
return class_names
unicode_pattern = re.compile(
r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE)
def unicode_code(code):
r"""
Convert a Unicode character code to a Unicode character.
(Directive option conversion function.)
Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``,
``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style
numeric character entities (e.g. ``☮``). Other text remains as-is.
Raise ValueError for illegal Unicode code values.
"""
try:
if code.isdigit(): # decimal number
return unichr(int(code))
else:
match = unicode_pattern.match(code)
if match: # hex number
value = match.group(1) or match.group(2)
return unichr(int(value, 16))
else: # other text
return code
except OverflowError, detail:
raise ValueError('code too large (%s)' % detail)
def single_char_or_unicode(argument):
"""
A single character is returned as-is. Unicode characters codes are
converted as in `unicode_code`. (Directive option conversion function.)
"""
char = unicode_code(argument)
if len(char) > 1:
raise ValueError('%r invalid; must be a single character or '
'a Unicode code' % char)
return char
def single_char_or_whitespace_or_unicode(argument):
"""
As with `single_char_or_unicode`, but "tab" and "space" are also supported.
(Directive option conversion function.)
"""
if argument == 'tab':
char = '\t'
elif argument == 'space':
char = ' '
else:
char = single_char_or_unicode(argument)
return char
def positive_int(argument):
"""
Converts the argument into an integer. Raises ValueError for negative,
zero, or non-integer values. (Directive option conversion function.)
"""
value = int(argument)
if value < 1:
raise ValueError('negative or zero value; must be positive')
return value
def positive_int_list(argument):
"""
Converts a space- or comma-separated list of values into a Python list
of integers.
(Directive option conversion function.)
Raises ValueError for non-positive-integer values.
"""
if ',' in argument:
entries = argument.split(',')
else:
entries = argument.split()
return [positive_int(entry) for entry in entries]
def encoding(argument):
"""
Verfies the encoding argument by lookup.
(Directive option conversion function.)
Raises ValueError for unknown encodings.
"""
try:
codecs.lookup(argument)
except LookupError:
raise ValueError('unknown encoding: "%s"' % argument)
return argument
def choice(argument, values):
"""
Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
example::
from docutils.parsers.rst import directives
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
Raise ``ValueError`` if no argument is found or if the argument's value is
not valid (not an entry in the supplied list).
"""
try:
value = argument.lower().strip()
except AttributeError:
raise ValueError('must supply an argument; choose from %s'
% format_values(values))
if value in values:
return value
else:
raise ValueError('"%s" unknown; choose from %s'
% (argument, format_values(values)))
def format_values(values):
return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]),
values[-1])
| {
"repo_name": "PatrickKennedy/Sybil",
"path": "docutils/parsers/rst/directives/__init__.py",
"copies": "2",
"size": "12516",
"license": "bsd-2-clause",
"hash": 2120916281707862300,
"line_mean": 33.1035422343,
"line_max": 79,
"alpha_frac": 0.606583573,
"autogenerated": false,
"ratio": 4.190157348510211,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002881362451768098,
"num_lines": 367
} |
"""
This package contains the Python Source Reader modules.
"""
__docformat__ = 'reStructuredText'
import sys
import docutils.readers
from docutils.readers.python import moduleparser
from docutils import parsers
from docutils import nodes
from docutils.readers.python import pynodes
from docutils import readers
class Reader(docutils.readers.Reader):
config_section = 'python reader'
config_section_dependencies = ('readers',)
default_parser = 'restructuredtext'
def parse(self):
"""Parse `self.input` into a document tree."""
self.document = document = self.new_document()
module_section = moduleparser.parse_module(self.input,
self.source.source_path)
module_section.walk(DocformatVisitor(self.document))
visitor = DocstringFormattingVisitor(
document=document,
default_parser=self.default_parser)
module_section.walk(visitor)
self.document.append(module_section)
class DocformatVisitor(nodes.SparseNodeVisitor):
"""
This sets docformat attributes in a module. Wherever an assignment
to __docformat__ is found, we look for the enclosing scope -- a class,
a module, or a function -- and set the docformat attribute there.
We can't do this during the DocstringFormattingVisitor walking,
because __docformat__ may appear below a docstring in that format
(typically below the module docstring).
"""
def visit_attribute(self, node):
assert isinstance(node[0], pynodes.object_name)
name = node[0][0].data
if name != '__docformat__':
return
value = None
for child in children:
if isinstance(child, pynodes.expression_value):
value = child[0].data
break
assert value.startswith("'") or value.startswith('"'), "__docformat__ must be assigned a string literal (not %s); line: %s" % (value, node['lineno'])
name = name[1:-1]
looking_in = node.parent
while not isinstance(looking_in, (pynodes.module_section,
pynodes.function_section,
pynodes.class_section)):
looking_in = looking_in.parent
looking_in['docformat'] = name
class DocstringFormattingVisitor(nodes.SparseNodeVisitor):
def __init__(self, document, default_parser):
self.document = document
self.default_parser = default_parser
self.parsers = {}
def visit_docstring(self, node):
text = node[0].data
docformat = self.find_docformat(node)
del node[0]
node['docformat'] = docformat
parser = self.get_parser(docformat)
parser.parse(text, self.document)
for child in self.document.children:
node.append(child)
self.document.current_source = self.document.current_line = None
del self.document[:]
def get_parser(self, parser_name):
"""
Get a parser based on its name. We reuse parsers during this
visitation, so parser instances are cached.
"""
parser_name = parsers._parser_aliases.get(parser_name, parser_name)
if not self.parsers.has_key(parser_name):
cls = parsers.get_parser_class(parser_name)
self.parsers[parser_name] = cls()
return self.parsers[parser_name]
def find_docformat(self, node):
"""
Find the __docformat__ closest to this node (i.e., look in the
class or module)
"""
while node:
if node.get('docformat'):
return node['docformat']
node = node.parent
return self.default_parser
if __name__ == '__main__':
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates pseudo-XML from Python modules '
'(for testing purposes). ' + default_description)
publish_cmdline(description=description,
reader=Reader())
| {
"repo_name": "PatrickKennedy/Sybil",
"path": "docutils/readers/python/__init__.py",
"copies": "2",
"size": "4345",
"license": "bsd-2-clause",
"hash": -7246210186595545000,
"line_mean": 33.2125984252,
"line_max": 157,
"alpha_frac": 0.6204833142,
"autogenerated": false,
"ratio": 4.375629405840886,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5996112720040886,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils Reader modules.
"""
__docformat__ = 'reStructuredText'
from docutils import utils, parsers, Component
from docutils.transforms import universal
class Reader(Component):
"""
Abstract base class for docutils Readers.
Each reader module or package must export a subclass also called 'Reader'.
The two steps of a Reader's responsibility are `scan()` and
`parse()`. Call `read()` to process a document.
"""
component_type = 'reader'
config_section = 'readers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Decorations,
universal.ExposeInternals,
universal.StripComments,]
def __init__(self, parser=None, parser_name=None):
"""
Initialize the Reader instance.
Several instance attributes are defined with dummy initial values.
Subclasses may use these attributes as they wish.
"""
self.parser = parser
"""A `parsers.Parser` instance shared by all doctrees. May be left
unspecified if the document source determines the parser."""
if parser is None and parser_name:
self.set_parser(parser_name)
self.source = None
"""`docutils.io` IO object, source of input data."""
self.input = None
"""Raw text input; either a single string or, for more complex cases,
a collection of strings."""
def set_parser(self, parser_name):
"""Set `self.parser` by name."""
parser_class = parsers.get_parser_class(parser_name)
self.parser = parser_class()
def read(self, source, parser, settings):
self.source = source
if not self.parser:
self.parser = parser
self.settings = settings
self.input = self.source.read()
self.parse()
return self.document
def parse(self):
"""Parse `self.input` into a document tree."""
self.document = document = self.new_document()
self.parser.parse(self.input, document)
document.current_source = document.current_line = None
def new_document(self):
"""Create and return a new empty document tree (root node)."""
document = utils.new_document(self.source.source_path, self.settings)
return document
class ReReader(Reader):
"""
A reader which rereads an existing document tree (e.g. a
deserializer).
Often used in conjunction with `writers.UnfilteredWriter`.
"""
def get_transforms(self):
# Do not add any transforms. They have already been applied
# by the reader which originally created the document.
return Component.get_transforms(self)
_reader_aliases = {}
def get_reader_class(reader_name):
"""Return the Reader class from the `reader_name` module."""
reader_name = reader_name.lower()
if _reader_aliases.has_key(reader_name):
reader_name = _reader_aliases[reader_name]
module = __import__(reader_name, globals(), locals())
return module.Reader
| {
"repo_name": "PatrickKennedy/Sybil",
"path": "docutils/readers/__init__.py",
"copies": "2",
"size": "3272",
"license": "bsd-2-clause",
"hash": -2028978134836391400,
"line_mean": 29.5794392523,
"line_max": 78,
"alpha_frac": 0.6460880196,
"autogenerated": false,
"ratio": 4.205655526992288,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007206489744610748,
"num_lines": 107
} |
"""
This package contains modules for standard tree transforms available
to Docutils components. Tree transforms serve a variety of purposes:
- To tie up certain syntax-specific "loose ends" that remain after the
initial parsing of the input plaintext. These transforms are used to
supplement a limited syntax.
- To automate the internal linking of the document tree (hyperlink
references, footnote references, etc.).
- To extract useful information from the document tree. These
transforms may be used to construct (for centralfitestoque) indexes and tables
of contents.
Each transform is an optional step that a Docutils component may
choose to perform on the parsed document.
"""
__docformat__ = 'reStructuredText'
from docutils import languages, ApplicationError, TransformSpec
class TransformError(ApplicationError): pass
class Transform:
"""
Docutils transform component abstract base class.
"""
default_priority = None
"""Numerical priority of this transform, 0 through 999 (override)."""
def __init__(self, document, startnode=None):
"""
Initial setup for in-place document transforms.
"""
self.document = document
"""The document tree to transform."""
self.startnode = startnode
"""Node from which to begin the transform. For many transforms which
apply to the document as a whole, `startnode` is not set (i.e. its
value is `None`)."""
self.language = languages.get_language(
document.settings.language_code)
"""Language module local to this document."""
def apply(self, **kwargs):
"""Override to apply the transform to the document tree."""
raise NotImplementedError('subclass must override this method')
class Transformer(TransformSpec):
"""
Stores transforms (`Transform` classes) and applies them to document
trees. Also keeps track of components by component type name.
"""
def __init__(self, document):
self.transforms = []
"""List of transforms to apply. Each item is a 3-tuple:
``(priority string, transform class, pending node or None)``."""
self.unknown_reference_resolvers = []
"""List of hook functions which assist in resolving references"""
self.document = document
"""The `nodes.document` object this Transformer is attached to."""
self.applied = []
"""Transforms already applied, in order."""
self.sorted = 0
"""Boolean: is `self.tranforms` sorted?"""
self.components = {}
"""Mapping of component type name to component object. Set by
`self.populate_from_components()`."""
self.serialno = 0
"""Internal serial number to keep track of the add order of
transforms."""
def add_transform(self, transform_class, priority=None, **kwargs):
"""
Store a single transform. Use `priority` to override the default.
`kwargs` is a dictionary whose contents are passed as keyword
arguments to the `apply` method of the transform. This can be used to
pass application-specific data to the transform instance.
"""
if priority is None:
priority = transform_class.default_priority
priority_string = self.get_priority_string(priority)
self.transforms.append(
(priority_string, transform_class, None, kwargs))
self.sorted = 0
def add_transforms(self, transform_list):
"""Store multiple transforms, with default priorities."""
for transform_class in transform_list:
priority_string = self.get_priority_string(
transform_class.default_priority)
self.transforms.append(
(priority_string, transform_class, None, {}))
self.sorted = 0
def add_pending(self, pending, priority=None):
"""Store a transform with an associated `pending` node."""
transform_class = pending.transform
if priority is None:
priority = transform_class.default_priority
priority_string = self.get_priority_string(priority)
self.transforms.append(
(priority_string, transform_class, pending, {}))
self.sorted = 0
def get_priority_string(self, priority):
"""
Return a string, `priority` combined with `self.serialno`.
This ensures FIFO order on transforms with identical priority.
"""
self.serialno += 1
return '%03d-%03d' % (priority, self.serialno)
def populate_from_components(self, components):
"""
Store each component's default transforms, with default priorities.
Also, store components by type name in a mapping for later lookup.
"""
for component in components:
if component is None:
continue
self.add_transforms(component.get_transforms())
self.components[component.component_type] = component
self.sorted = 0
# Set up all of the reference resolvers for this transformer. Each
# component of this transformer is able to register its own helper
# functions to help resolve references.
unknown_reference_resolvers = []
for i in components:
unknown_reference_resolvers.extend(i.unknown_reference_resolvers)
decorated_list = [(f.priority, f) for f in unknown_reference_resolvers]
decorated_list.sort()
self.unknown_reference_resolvers.extend([f[1] for f in decorated_list])
def apply_transforms(self):
"""Apply all of the stored transforms, in priority order."""
self.document.reporter.attach_observer(
self.document.note_transform_message)
while self.transforms:
if not self.sorted:
# Unsorted initially, and whenever a transform is added.
self.transforms.sort()
self.transforms.reverse()
self.sorted = 1
priority, transform_class, pending, kwargs = self.transforms.pop()
transform = transform_class(self.document, startnode=pending)
transform.apply(**kwargs)
self.applied.append((priority, transform_class, pending, kwargs))
| {
"repo_name": "akiokio/centralfitestoque",
"path": "src/.pycharm_helpers/docutils/transforms/__init__.py",
"copies": "1",
"size": "6498",
"license": "bsd-2-clause",
"hash": -2888573276523362000,
"line_mean": 36.7790697674,
"line_max": 80,
"alpha_frac": 0.6506617421,
"autogenerated": false,
"ratio": 4.658064516129032,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5808726258229033,
"avg_score": null,
"num_lines": null
} |
"""
This package contains modules for standard tree transforms available
to Docutils components. Tree transforms serve a variety of purposes:
- To tie up certain syntax-specific "loose ends" that remain after the
initial parsing of the input plaintext. These transforms are used to
supplement a limited syntax.
- To automate the internal linking of the document tree (hyperlink
references, footnote references, etc.).
- To extract useful information from the document tree. These
transforms may be used to construct (for example) indexes and tables
of contents.
Each transform is an optional step that a Docutils component may
choose to perform on the parsed document.
"""
__docformat__ = 'reStructuredText'
from docutils import languages, ApplicationError, TransformSpec
class TransformError(ApplicationError): pass
class Transform:
"""
Docutils transform component abstract base class.
"""
default_priority = None
"""Numerical priority of this transform, 0 through 999 (override)."""
def __init__(self, document, startnode=None):
"""
Initial setup for in-place document transforms.
"""
self.document = document
"""The document tree to transform."""
self.startnode = startnode
"""Node from which to begin the transform. For many transforms which
apply to the document as a whole, `startnode` is not set (i.e. its
value is `None`)."""
self.language = languages.get_language(
document.settings.language_code)
"""Language module local to this document."""
def apply(self, **kwargs):
"""Override to apply the transform to the document tree."""
raise NotImplementedError('subclass must override this method')
class Transformer(TransformSpec):
"""
Stores transforms (`Transform` classes) and applies them to document
trees. Also keeps track of components by component type name.
"""
def __init__(self, document):
self.transforms = []
"""List of transforms to apply. Each item is a 3-tuple:
``(priority string, transform class, pending node or None)``."""
self.unknown_reference_resolvers = []
"""List of hook functions which assist in resolving references"""
self.document = document
"""The `nodes.document` object this Transformer is attached to."""
self.applied = []
"""Transforms already applied, in order."""
self.sorted = 0
"""Boolean: is `self.tranforms` sorted?"""
self.components = {}
"""Mapping of component type name to component object. Set by
`self.populate_from_components()`."""
self.serialno = 0
"""Internal serial number to keep track of the add order of
transforms."""
def add_transform(self, transform_class, priority=None, **kwargs):
"""
Store a single transform. Use `priority` to override the default.
`kwargs` is a dictionary whose contents are passed as keyword
arguments to the `apply` method of the transform. This can be used to
pass application-specific data to the transform instance.
"""
if priority is None:
priority = transform_class.default_priority
priority_string = self.get_priority_string(priority)
self.transforms.append(
(priority_string, transform_class, None, kwargs))
self.sorted = 0
def add_transforms(self, transform_list):
"""Store multiple transforms, with default priorities."""
for transform_class in transform_list:
priority_string = self.get_priority_string(
transform_class.default_priority)
self.transforms.append(
(priority_string, transform_class, None, {}))
self.sorted = 0
def add_pending(self, pending, priority=None):
"""Store a transform with an associated `pending` node."""
transform_class = pending.transform
if priority is None:
priority = transform_class.default_priority
priority_string = self.get_priority_string(priority)
self.transforms.append(
(priority_string, transform_class, pending, {}))
self.sorted = 0
def get_priority_string(self, priority):
"""
Return a string, `priority` combined with `self.serialno`.
This ensures FIFO order on transforms with identical priority.
"""
self.serialno += 1
return '%03d-%03d' % (priority, self.serialno)
def populate_from_components(self, components):
"""
Store each component's default transforms, with default priorities.
Also, store components by type name in a mapping for later lookup.
"""
for component in components:
if component is None:
continue
self.add_transforms(component.get_transforms())
self.components[component.component_type] = component
self.sorted = 0
# Set up all of the reference resolvers for this transformer. Each
# component of this transformer is able to register its own helper
# functions to help resolve references.
unknown_reference_resolvers = []
for i in components:
unknown_reference_resolvers.extend(i.unknown_reference_resolvers)
decorated_list = [(f.priority, f) for f in unknown_reference_resolvers]
decorated_list.sort()
self.unknown_reference_resolvers.extend([f[1] for f in decorated_list])
def apply_transforms(self):
"""Apply all of the stored transforms, in priority order."""
self.document.reporter.attach_observer(
self.document.note_transform_message)
while self.transforms:
if not self.sorted:
# Unsorted initially, and whenever a transform is added.
self.transforms.sort()
self.transforms.reverse()
self.sorted = 1
priority, transform_class, pending, kwargs = self.transforms.pop()
transform = transform_class(self.document, startnode=pending)
transform.apply(**kwargs)
self.applied.append((priority, transform_class, pending, kwargs))
| {
"repo_name": "rimbalinux/MSISDNArea",
"path": "docutils/transforms/__init__.py",
"copies": "2",
"size": "6660",
"license": "bsd-3-clause",
"hash": 3014064064606079500,
"line_mean": 36.7209302326,
"line_max": 79,
"alpha_frac": 0.6333333333,
"autogenerated": false,
"ratio": 4.774193548387097,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6407526881687097,
"avg_score": null,
"num_lines": null
} |
"""
This is the Docutils (Python Documentation Utilities) package.
Package Structure
=================
Modules:
- __init__.py: Contains component base classes, exception classes, and
Docutils version information.
- core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience
functions.
- frontend.py: Runtime settings (command-line interface, configuration files)
processing, for Docutils front-ends.
- io.py: Provides a uniform API for low-level input and output.
- nodes.py: Docutils document tree (doctree) node class library.
- statemachine.py: A finite state machine specialized for
regular-expression-based text filters.
- urischemes.py: Contains a complete mapping of known URI addressing
scheme names to descriptions.
- utils.py: Contains the ``Reporter`` system warning class and miscellaneous
utilities.
Subpackages:
- languages: Language-specific mappings of terms.
- parsers: Syntax-specific input parser modules or packages.
- readers: Context-specific input handlers which understand the data
source and manage a parser.
- transforms: Modules used by readers and writers to modify DPS
doctrees.
- writers: Format-specific output translators.
"""
__docformat__ = 'reStructuredText'
__version__ = '0.6'
"""``major.minor.micro`` version number. The micro number is bumped for API
changes, for new functionality, and for interim project releases. The minor
number is bumped whenever there is a significant project release. The major
number will be bumped when the project is feature-complete, and perhaps if
there is a major change in the design."""
__version_details__ = 'snapshot 2009-08-18, r6081'
"""Extra version details (e.g. 'snapshot 2005-05-29, r3410', 'repository',
'release'), modified automatically & manually."""
class ApplicationError(StandardError): pass
class DataError(ApplicationError): pass
class SettingsSpec:
"""
Runtime setting specification base class.
SettingsSpec subclass objects used by `docutils.frontend.OptionParser`.
"""
settings_spec = ()
"""Runtime settings specification. Override in subclasses.
Defines runtime settings and associated command-line options, as used by
`docutils.frontend.OptionParser`. This is a tuple of:
- Option group title (string or `None` which implies no group, just a list
of single options).
- Description (string or `None`).
- A sequence of option tuples. Each consists of:
- Help text (string)
- List of option strings (e.g. ``['-Q', '--quux']``).
- Dictionary of keyword arguments sent to the OptionParser/OptionGroup
``add_option`` method.
Runtime setting names are derived implicitly from long option names
('--a-setting' becomes ``settings.a_setting``) or explicitly from the
'dest' keyword argument.
Most settings will also have a 'validator' keyword & function. The
validator function validates setting values (from configuration files
and command-line option arguments) and converts them to appropriate
types. For example, the ``docutils.frontend.validate_boolean``
function, **required by all boolean settings**, converts true values
('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off',
'no', 'false', and '') to 0. Validators need only be set once per
setting. See the `docutils.frontend.validate_*` functions.
See the optparse docs for more details.
- More triples of group title, description, options, as many times as
needed. Thus, `settings_spec` tuples can be simply concatenated.
"""
settings_defaults = None
"""A dictionary of defaults for settings not in `settings_spec` (internal
settings, intended to be inaccessible by command-line and config file).
Override in subclasses."""
settings_default_overrides = None
"""A dictionary of auxiliary defaults, to override defaults for settings
defined in other components. Override in subclasses."""
relative_path_settings = ()
"""Settings containing filesystem paths. Override in subclasses.
Settings listed here are to be interpreted relative to the current working
directory."""
config_section = None
"""The name of the config file section specific to this component
(lowercase, no brackets). Override in subclasses."""
config_section_dependencies = None
"""A list of names of config file sections that are to be applied before
`config_section`, in order (from general to specific). In other words,
the settings in `config_section` are to be overlaid on top of the settings
from these sections. The "general" section is assumed implicitly.
Override in subclasses."""
class TransformSpec:
"""
Runtime transform specification base class.
TransformSpec subclass objects used by `docutils.transforms.Transformer`.
"""
def get_transforms(self):
"""Transforms required by this class. Override in subclasses."""
if self.default_transforms != ():
import warnings
warnings.warn('default_transforms attribute deprecated.\n'
'Use get_transforms() method instead.',
DeprecationWarning)
return list(self.default_transforms)
return []
# Deprecated; for compatibility.
default_transforms = ()
unknown_reference_resolvers = ()
"""List of functions to try to resolve unknown references. Unknown
references have a 'refname' attribute which doesn't correspond to any
target in the document. Called when the transforms in
`docutils.tranforms.references` are unable to find a correct target. The
list should contain functions which will try to resolve unknown
references, with the following signature::
def reference_resolver(node):
'''Returns boolean: true if resolved, false if not.'''
If the function is able to resolve the reference, it should also remove
the 'refname' attribute and mark the node as resolved::
del node['refname']
node.resolved = 1
Each function must have a "priority" attribute which will affect the order
the unknown_reference_resolvers are run::
reference_resolver.priority = 100
Override in subclasses."""
class Component(SettingsSpec, TransformSpec):
"""Base class for Docutils components."""
component_type = None
"""Name of the component type ('reader', 'parser', 'writer'). Override in
subclasses."""
supported = ()
"""Names for this component. Override in subclasses."""
def supports(self, format):
"""
Is `format` supported by this component?
To be used by transforms to ask the dependent component if it supports
a certain input context or output format.
"""
return format in self.supported
| {
"repo_name": "spreeker/democracygame",
"path": "external_apps/docutils-snapshot/docutils/__init__.py",
"copies": "2",
"size": "7102",
"license": "bsd-3-clause",
"hash": 2733173340557853700,
"line_mean": 33.8137254902,
"line_max": 78,
"alpha_frac": 0.6971275697,
"autogenerated": false,
"ratio": 4.56426735218509,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0003453654188948307,
"num_lines": 204
} |
"""
This package contains Docutils parser modules.
"""
__docformat__ = 'reStructuredText'
from docutils import Component
class Parser(Component):
component_type = 'parser'
config_section = 'parsers'
def parse(self, inputstring, document):
"""Override to parse `inputstring` into document tree `document`."""
raise NotImplementedError('subclass must override this method')
def setup_parse(self, inputstring, document):
"""Initial parse setup. Call at start of `self.parse()`."""
self.inputstring = inputstring
self.document = document
document.reporter.attach_observer(document.note_parse_message)
def finish_parse(self):
"""Finalize parse details. Call at end of `self.parse()`."""
self.document.reporter.detach_observer(
self.document.note_parse_message)
_parser_aliases = {
'restructuredtext': 'rst',
'rest': 'rst',
'restx': 'rst',
'rtxt': 'rst',}
def get_parser_class(parser_name):
"""Return the Parser class from the `parser_name` module."""
parser_name = parser_name.lower()
if parser_name in _parser_aliases:
parser_name = _parser_aliases[parser_name]
module = __import__(parser_name, globals(), locals())
return module.Parser
| {
"repo_name": "bobthecow/ManipulateCoda",
"path": "src/Support/Library/docutils/parsers/__init__.py",
"copies": "70",
"size": "1457",
"license": "mit",
"hash": 8248649748395490000,
"line_mean": 30,
"line_max": 76,
"alpha_frac": 0.6582017845,
"autogenerated": false,
"ratio": 3.8853333333333335,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils Writer modules.
"""
__docformat__ = 'reStructuredText'
import os.path
import docutils
from docutils import languages, Component
from docutils.transforms import universal
class Writer(Component):
"""
Abstract base class for docutils Writers.
Each writer module or package must export a subclass also called 'Writer'.
Each writer must support all standard node types listed in
`docutils.nodes.node_class_names`.
The `write()` method is the main entry point.
"""
component_type = 'writer'
config_section = 'writers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Messages,
universal.FilterMessages,
universal.StripClassesAndElements,]
document = None
"""The document to write (Docutils doctree); set by `write`."""
output = None
"""Final translated form of `document` (Unicode string for text, binary
string for other forms); set by `translate`."""
language = None
"""Language module for the document; set by `write`."""
destination = None
"""`docutils.io` Output object; where to write the document.
Set by `write`."""
def __init__(self):
# Currently only used by HTML writer for output fragments:
self.parts = {}
"""Mapping of document part names to fragments of `self.output`.
Values are Unicode strings; encoding is up to the client. The 'whole'
key should contain the entire document output.
"""
def write(self, document, destination):
"""
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.
"""
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
def translate(self):
"""
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.
"""
raise NotImplementedError('subclass must override this method')
def assemble_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses."""
self.parts['whole'] = self.output
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
class UnfilteredWriter(Writer):
"""
A writer that passes the document tree on unchanged (e.g. a
serializer.)
Documents written by UnfilteredWriters are typically reused at a
later date using a subclass of `readers.ReReader`.
"""
def get_transforms(self):
# Do not add any transforms. When the document is reused
# later, the then-used writer will add the appropriate
# transforms.
return Component.get_transforms(self)
_writer_aliases = {
'html': 'html4css1',
'latex': 'latex2e',
'pprint': 'pseudoxml',
'pformat': 'pseudoxml',
'pdf': 'rlpdf',
'xml': 'docutils_xml',
's5': 's5_html'}
def get_writer_class(writer_name):
"""Return the Writer class from the `writer_name` module."""
writer_name = writer_name.lower()
if writer_name in _writer_aliases:
writer_name = _writer_aliases[writer_name]
module = __import__(writer_name, globals(), locals())
return module.Writer
| {
"repo_name": "spreeker/democracygame",
"path": "external_apps/docutils-snapshot/docutils/writers/__init__.py",
"copies": "2",
"size": "4258",
"license": "bsd-3-clause",
"hash": 2298143483927577900,
"line_mean": 31.015037594,
"line_max": 78,
"alpha_frac": 0.6510098638,
"autogenerated": false,
"ratio": 4.349336057201226,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6000345921001227,
"avg_score": null,
"num_lines": null
} |
"""
This package contains the Python Source Reader modules.
"""
__docformat__ = 'reStructuredText'
import docutils.readers
from docutils import nodes
from docutils import parsers
from docutils.readers.python import moduleparser
from docutils.readers.python import pynodes
class Reader(docutils.readers.Reader):
config_section = 'python reader'
config_section_dependencies = ('readers',)
default_parser = 'restructuredtext'
def parse(self):
"""Parse `self.input` into a document tree."""
self.document = document = self.new_document()
module_section = moduleparser.parse_module(self.input,
self.source.source_path)
module_section.walk(DocformatVisitor(self.document))
visitor = DocstringFormattingVisitor(
document=document,
default_parser=self.default_parser)
module_section.walk(visitor)
self.document.append(module_section)
class DocformatVisitor(nodes.SparseNodeVisitor):
"""
This sets docformat attributes in a module. Wherever an assignment
to __docformat__ is found, we look for the enclosing scope -- a class,
a module, or a function -- and set the docformat attribute there.
We can't do this during the DocstringFormattingVisitor walking,
because __docformat__ may appear below a docstring in that format
(typically below the module docstring).
"""
def visit_attribute(self, node):
assert isinstance(node[0], pynodes.object_name)
name = node[0][0].data
if name != '__docformat__':
return
value = None
for child in children:
if isinstance(child, pynodes.expression_value):
value = child[0].data
break
assert value.startswith("'") or value.startswith('"'), "__docformat__ must be assigned a string literal (not %s); line: %s" % (value, node['lineno'])
name = name[1:-1]
looking_in = node.parent
while not isinstance(looking_in, (pynodes.module_section,
pynodes.function_section,
pynodes.class_section)):
looking_in = looking_in.parent
looking_in['docformat'] = name
class DocstringFormattingVisitor(nodes.SparseNodeVisitor):
def __init__(self, document, default_parser):
self.document = document
self.default_parser = default_parser
self.parsers = {}
def visit_docstring(self, node):
text = node[0].data
docformat = self.find_docformat(node)
del node[0]
node['docformat'] = docformat
parser = self.get_parser(docformat)
parser.parse(text, self.document)
for child in self.document.children:
node.append(child)
self.document.current_source = self.document.current_line = None
del self.document[:]
def get_parser(self, parser_name):
"""
Get a parser based on its name. We reuse parsers during this
visitation, so parser instances are cached.
"""
parser_name = parsers._parser_aliases.get(parser_name, parser_name)
if parser_name not in self.parsers:
cls = parsers.get_parser_class(parser_name)
self.parsers[parser_name] = cls()
return self.parsers[parser_name]
def find_docformat(self, node):
"""
Find the __docformat__ closest to this node (i.e., look in the
class or module)
"""
while node:
if node.get('docformat'):
return node['docformat']
node = node.parent
return self.default_parser
if __name__ == '__main__':
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates pseudo-XML from Python modules '
'(for testing purposes). ' + default_description)
publish_cmdline(description=description,
reader=Reader())
| {
"repo_name": "MichaelNedzelsky/intellij-community",
"path": "python/helpers/py2only/docutils/readers/python/__init__.py",
"copies": "5",
"size": "4298",
"license": "apache-2.0",
"hash": -3960341462280866300,
"line_mean": 33.384,
"line_max": 157,
"alpha_frac": 0.6181945091,
"autogenerated": false,
"ratio": 4.390194075587334,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007172995780590718,
"num_lines": 125
} |
"""
This package contains the Python Source Reader modules.
"""
__docformat__ = 'reStructuredText'
import sys
import docutils.readers
from docutils.readers.python import moduleparser
from docutils import parsers
from docutils import nodes
from docutils.readers.python import pynodes
from docutils import readers
class Reader(docutils.readers.Reader):
config_section = 'python reader'
config_section_dependencies = ('readers',)
default_parser = 'restructuredtext'
def parse(self):
"""Parse `self.input` into a document tree."""
self.document = document = self.new_document()
module_section = moduleparser.parse_module(self.input,
self.source.source_path)
module_section.walk(DocformatVisitor(self.document))
visitor = DocstringFormattingVisitor(
document=document,
default_parser=self.default_parser)
module_section.walk(visitor)
self.document.append(module_section)
class DocformatVisitor(nodes.SparseNodeVisitor):
"""
This sets docformat attributes in a module. Wherever an assignment
to __docformat__ is found, we look for the enclosing scope -- a class,
a module, or a function -- and set the docformat attribute there.
We can't do this during the DocstringFormattingVisitor walking,
because __docformat__ may appear below a docstring in that format
(typically below the module docstring).
"""
def visit_attribute(self, node):
assert isinstance(node[0], pynodes.object_name)
name = node[0][0].data
if name != '__docformat__':
return
value = None
for child in children:
if isinstance(child, pynodes.expression_value):
value = child[0].data
break
assert value.startswith("'") or value.startswith('"'), "__docformat__ must be assigned a string literal (not %s); line: %s" % (value, node['lineno'])
name = name[1:-1]
looking_in = node.parent
while not isinstance(looking_in, (pynodes.module_section,
pynodes.function_section,
pynodes.class_section)):
looking_in = looking_in.parent
looking_in['docformat'] = name
class DocstringFormattingVisitor(nodes.SparseNodeVisitor):
def __init__(self, document, default_parser):
self.document = document
self.default_parser = default_parser
self.parsers = {}
def visit_docstring(self, node):
text = node[0].data
docformat = self.find_docformat(node)
del node[0]
node['docformat'] = docformat
parser = self.get_parser(docformat)
parser.parse(text, self.document)
for child in self.document.children:
node.append(child)
self.document.current_source = self.document.current_line = None
del self.document[:]
def get_parser(self, parser_name):
"""
Get a parser based on its name. We reuse parsers during this
visitation, so parser instances are cached.
"""
parser_name = parsers._parser_aliases.get(parser_name, parser_name)
if parser_name not in self.parsers:
cls = parsers.get_parser_class(parser_name)
self.parsers[parser_name] = cls()
return self.parsers[parser_name]
def find_docformat(self, node):
"""
Find the __docformat__ closest to this node (i.e., look in the
class or module)
"""
while node:
if node.get('docformat'):
return node['docformat']
node = node.parent
return self.default_parser
if __name__ == '__main__':
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates pseudo-XML from Python modules '
'(for testing purposes). ' + default_description)
publish_cmdline(description=description,
reader=Reader())
| {
"repo_name": "holmes/intellij-community",
"path": "python/helpers/docutils/readers/python/__init__.py",
"copies": "51",
"size": "4338",
"license": "apache-2.0",
"hash": -5402625147479237000,
"line_mean": 33.157480315,
"line_max": 157,
"alpha_frac": 0.6203319502,
"autogenerated": false,
"ratio": 4.390688259109312,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0009079013614048001,
"num_lines": 127
} |
"""
This package contains Docutils Reader modules.
"""
__docformat__ = 'reStructuredText'
from docutils import utils, parsers, Component
from docutils.transforms import universal
class Reader(Component):
"""
Abstract base class for docutils Readers.
Each reader module or package must export a subclass also called 'Reader'.
The two steps of a Reader's responsibility are `scan()` and
`parse()`. Call `read()` to process a document.
"""
component_type = 'reader'
config_section = 'readers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Decorations,
universal.ExposeInternals,
universal.StripComments,]
def __init__(self, parser=None, parser_name=None):
"""
Initialize the Reader instance.
Several instance attributes are defined with dummy initial values.
Subclasses may use these attributes as they wish.
"""
self.parser = parser
"""A `parsers.Parser` instance shared by all doctrees. May be left
unspecified if the document source determines the parser."""
if parser is None and parser_name:
self.set_parser(parser_name)
self.source = None
"""`docutils.io` IO object, source of input data."""
self.input = None
"""Raw text input; either a single string or, for more complex cases,
a collection of strings."""
def set_parser(self, parser_name):
"""Set `self.parser` by name."""
parser_class = parsers.get_parser_class(parser_name)
self.parser = parser_class()
def read(self, source, parser, settings):
self.source = source
if not self.parser:
self.parser = parser
self.settings = settings
self.input = self.source.read()
self.parse()
return self.document
def parse(self):
"""Parse `self.input` into a document tree."""
self.document = document = self.new_document()
self.parser.parse(self.input, document)
document.current_source = document.current_line = None
def new_document(self):
"""Create and return a new empty document tree (root node)."""
document = utils.new_document(self.source.source_path, self.settings)
return document
class ReReader(Reader):
"""
A reader which rereads an existing document tree (e.g. a
deserializer).
Often used in conjunction with `writers.UnfilteredWriter`.
"""
def get_transforms(self):
# Do not add any transforms. They have already been applied
# by the reader which originally created the document.
return Component.get_transforms(self)
_reader_aliases = {}
def get_reader_class(reader_name):
"""Return the Reader class from the `reader_name` module."""
reader_name = reader_name.lower()
if reader_name in _reader_aliases:
reader_name = _reader_aliases[reader_name]
module = __import__(reader_name, globals(), locals())
return module.Reader
| {
"repo_name": "MER-GROUP/intellij-community",
"path": "python/helpers/py2only/docutils/readers/__init__.py",
"copies": "70",
"size": "3265",
"license": "apache-2.0",
"hash": -8559807576995436000,
"line_mean": 29.5140186916,
"line_max": 78,
"alpha_frac": 0.645941807,
"autogenerated": false,
"ratio": 4.223803363518758,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils parser modules.
"""
__docformat__ = 'reStructuredText'
from docutils import Component
class Parser(Component):
component_type = 'parser'
config_section = 'parsers'
def parse(self, inputstring, document):
"""Override to parse `inputstring` into document tree `document`."""
raise NotImplementedError('subclass must override this method')
def setup_parse(self, inputstring, document):
"""Initial parse setup. Call at start of `self.parse()`."""
self.inputstring = inputstring
self.document = document
document.reporter.attach_observer(document.note_parse_message)
def finish_parse(self):
"""Finalize parse details. Call at end of `self.parse()`."""
self.document.reporter.detach_observer(
self.document.note_parse_message)
_parser_aliases = {
'restructuredtext': 'rst',
'rest': 'rst',
'restx': 'rst',
'rtxt': 'rst',}
def get_parser_class(parser_name):
"""Return the Parser class from the `parser_name` module."""
parser_name = parser_name.lower()
if parser_name in _parser_aliases:
parser_name = _parser_aliases[parser_name]
module = __import__(parser_name, globals(), locals())
return module.Parser
| {
"repo_name": "rimbalinux/LMD3",
"path": "docutils/parsers/__init__.py",
"copies": "2",
"size": "1504",
"license": "bsd-3-clause",
"hash": 8253345689400622000,
"line_mean": 30,
"line_max": 76,
"alpha_frac": 0.6376329787,
"autogenerated": false,
"ratio": 3.9683377308707124,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5605970709570712,
"avg_score": null,
"num_lines": null
} |
"""
This package contains the Python Source Reader modules.
"""
__docformat__ = 'reStructuredText'
import sys
import docutils.readers
from docutils.readers.python import moduleparser
from docutils import parsers
from docutils import nodes
from docutils.readers.python import pynodes
from docutils import readers
class Reader(docutils.readers.Reader):
config_section = 'python reader'
config_section_dependencies = ('readers',)
default_parser = 'restructuredtext'
def parse(self):
"""Parse `self.input` into a document tree."""
self.document = document = self.new_document()
module_section = moduleparser.parse_module(self.input,
self.source.source_path)
module_section.walk(DocformatVisitor(self.document))
visitor = DocstringFormattingVisitor(
document=document,
default_parser=self.default_parser)
module_section.walk(visitor)
self.document.append(module_section)
class DocformatVisitor(nodes.SparseNodeVisitor):
"""
This sets docformat attributes in a module. Wherever an assignment
to __docformat__ is found, we look for the enclosing scope -- a class,
a module, or a function -- and set the docformat attribute there.
We can't do this during the DocstringFormattingVisitor walking,
because __docformat__ may appear below a docstring in that format
(typically below the module docstring).
"""
def visit_attribute(self, node):
assert isinstance(node[0], pynodes.object_name)
name = node[0][0].data
if name != '__docformat__':
return
value = None
for child in children:
if isinstance(child, pynodes.expression_value):
value = child[0].data
break
assert value.startswith("'") or value.startswith('"'), "__docformat__ must be assigned a string literal (not %s); line: %s" % (value, node['lineno'])
name = name[1:-1]
looking_in = node.parent
while not isinstance(looking_in, (pynodes.module_section,
pynodes.function_section,
pynodes.class_section)):
looking_in = looking_in.parent
looking_in['docformat'] = name
class DocstringFormattingVisitor(nodes.SparseNodeVisitor):
def __init__(self, document, default_parser):
self.document = document
self.default_parser = default_parser
self.parsers = {}
def visit_docstring(self, node):
text = node[0].data
docformat = self.find_docformat(node)
del node[0]
node['docformat'] = docformat
parser = self.get_parser(docformat)
parser.parse(text, self.document)
for child in self.document.children:
node.append(child)
self.document.current_source = self.document.current_line = None
del self.document[:]
def get_parser(self, parser_name):
"""
Get a parser based on its name. We reuse parsers during this
visitation, so parser instances are cached.
"""
parser_name = parsers._parser_aliases.get(parser_name, parser_name)
if parser_name not in self.parsers:
cls = parsers.get_parser_class(parser_name)
self.parsers[parser_name] = cls()
return self.parsers[parser_name]
def find_docformat(self, node):
"""
Find the __docformat__ closest to this node (i.e., look in the
class or module)
"""
while node:
if node.get('docformat'):
return node['docformat']
node = node.parent
return self.default_parser
if __name__ == '__main__':
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default_description
description = ('Generates pseudo-XML from Python modules '
'(for testing purposes). ' + default_description)
publish_cmdline(description=description,
reader=Reader())
| {
"repo_name": "rimbalinux/MSISDNArea",
"path": "docutils/readers/python/__init__.py",
"copies": "2",
"size": "4465",
"license": "bsd-3-clause",
"hash": 7555743668727895000,
"line_mean": 33.157480315,
"line_max": 157,
"alpha_frac": 0.60268757,
"autogenerated": false,
"ratio": 4.456087824351298,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6058775394351298,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils Reader modules.
"""
__docformat__ = 'reStructuredText'
from docutils import utils, parsers, Component
from docutils.transforms import universal
class Reader(Component):
"""
Abstract base class for docutils Readers.
Each reader module or package must export a subclass also called 'Reader'.
The two steps of a Reader's responsibility are `scan()` and
`parse()`. Call `read()` to process a document.
"""
component_type = 'reader'
config_section = 'readers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Decorations,
universal.ExposeInternals,
universal.StripComments,]
def __init__(self, parser=None, parser_name=None):
"""
Initialize the Reader instance.
Several instance attributes are defined with dummy initial values.
Subclasses may use these attributes as they wish.
"""
self.parser = parser
"""A `parsers.Parser` instance shared by all doctrees. May be left
unspecified if the document source determines the parser."""
if parser is None and parser_name:
self.set_parser(parser_name)
self.source = None
"""`docutils.io` IO object, source of input data."""
self.input = None
"""Raw text input; either a single string or, for more complex cases,
a collection of strings."""
def set_parser(self, parser_name):
"""Set `self.parser` by name."""
parser_class = parsers.get_parser_class(parser_name)
self.parser = parser_class()
def read(self, source, parser, settings):
self.source = source
if not self.parser:
self.parser = parser
self.settings = settings
self.input = self.source.read()
self.parse()
return self.document
def parse(self):
"""Parse `self.input` into a document tree."""
self.document = document = self.new_document()
self.parser.parse(self.input, document)
document.current_source = document.current_line = None
def new_document(self):
"""Create and return a new empty document tree (root node)."""
document = utils.new_document(self.source.source_path, self.settings)
return document
class ReReader(Reader):
"""
A reader which rereads an existing document tree (e.g. a
deserializer).
Often used in conjunction with `writers.UnfilteredWriter`.
"""
def get_transforms(self):
# Do not add any transforms. They have already been applied
# by the reader which originally created the document.
return Component.get_transforms(self)
_reader_aliases = {}
def get_reader_class(reader_name):
"""Return the Reader class from the `reader_name` module."""
reader_name = reader_name.lower()
if reader_name in _reader_aliases:
reader_name = _reader_aliases[reader_name]
module = __import__(reader_name, globals(), locals())
return module.Reader
| {
"repo_name": "rimbalinux/MSISDNArea",
"path": "docutils/readers/__init__.py",
"copies": "2",
"size": "3372",
"license": "bsd-3-clause",
"hash": -6854236395513899000,
"line_mean": 29.5140186916,
"line_max": 78,
"alpha_frac": 0.6254448399,
"autogenerated": false,
"ratio": 4.334190231362468,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5959635071262468,
"avg_score": null,
"num_lines": null
} |
"""
LaTeX2e document tree Writer.
"""
# Thanks to Engelbert Gruber and various contributors for the original
# LaTeX writer, some code and many ideas of which have been used for
# this writer.
__docformat__ = 'reStructuredText'
import os.path
import re
import docutils
from docutils import nodes, writers, utils
from docutils.transforms import writer_aux
from docutils.writers.newlatex2e import unicode_map
class Writer(writers.Writer):
supported = ('newlatex', 'newlatex2e')
"""Formats this writer supports."""
default_stylesheet = 'base.tex'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
settings_spec = (
'LaTeX-Specific Options',
'Note that this LaTeX writer is still EXPERIMENTAL and not '
'feature-complete. ',
(('Specify a stylesheet file. The path is used verbatim to include '
'the file. Overrides --stylesheet-path.',
['--stylesheet'],
{'default': '', 'metavar': '<file>',
'overrides': 'stylesheet_path'}),
('Specify a stylesheet file, relative to the current working '
'directory. Overrides --stylesheet. Default: "%s"'
% default_stylesheet_path,
['--stylesheet-path'],
{'metavar': '<file>', 'overrides': 'stylesheet',
'default': default_stylesheet_path}),
('Specify a user stylesheet file. See --stylesheet.',
['--user-stylesheet'],
{'default': '', 'metavar': '<file>',
'overrides': 'user_stylesheet_path'}),
('Specify a user stylesheet file. See --stylesheet-path.',
['--user-stylesheet-path'],
{'metavar': '<file>', 'overrides': 'user_stylesheet'})
),)
settings_defaults = {
# Many Unicode characters are provided by unicode_map.py, so
# we can default to latin-1.
'output_encoding': 'latin-1',
'output_encoding_error_handler': 'strict',
# Since we are using superscript footnotes, it is necessary to
# trim whitespace in front of footnote references.
'trim_footnote_reference_space': 1,
# Currently unsupported:
'docinfo_xform': 0,
# During development:
'traceback': 1
}
relative_path_settings = ('stylesheet_path', 'user_stylesheet_path')
config_section = 'newlatex2e writer'
config_section_dependencies = ('writers',)
output = None
"""Final translated form of `document`."""
def get_transforms(self):
return writers.Writer.get_transforms(self) + [
writer_aux.Compound, writer_aux.Admonitions]
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = LaTeXTranslator
def translate(self):
visitor = self.translator_class(self.document)
self.document.walkabout(visitor)
assert not visitor.context, 'context not empty: %s' % visitor.context
self.output = visitor.astext()
self.head = visitor.header
self.body = visitor.body
class LaTeXException(Exception):
"""
Exception base class to for exceptions which influence the
automatic generation of LaTeX code.
"""
class SkipAttrParentLaTeX(LaTeXException):
"""
Do not generate ``\DECattr`` and ``\renewcommand{\DEVparent}{...}`` for this
node.
To be raised from ``before_...`` methods.
"""
class SkipParentLaTeX(LaTeXException):
"""
Do not generate ``\renewcommand{\DEVparent}{...}`` for this node.
To be raised from ``before_...`` methods.
"""
class LaTeXTranslator(nodes.SparseNodeVisitor):
# Country code by a.schlock.
# Partly manually converted from iso and babel stuff.
iso639_to_babel = {
'no': 'norsk', # added by hand
'gd': 'scottish', # added by hand
'sl': 'slovenian',
'af': 'afrikaans',
'bg': 'bulgarian',
'br': 'breton',
'ca': 'catalan',
'cs': 'czech',
'cy': 'welsh',
'da': 'danish',
'fr': 'french',
# french, francais, canadien, acadian
'de': 'ngerman',
# ngerman, naustrian, german, germanb, austrian
'el': 'greek',
'en': 'english',
# english, USenglish, american, UKenglish, british, canadian
'eo': 'esperanto',
'es': 'spanish',
'et': 'estonian',
'eu': 'basque',
'fi': 'finnish',
'ga': 'irish',
'gl': 'galician',
'he': 'hebrew',
'hr': 'croatian',
'hu': 'hungarian',
'is': 'icelandic',
'it': 'italian',
'la': 'latin',
'nl': 'dutch',
'pl': 'polish',
'pt': 'portuguese',
'ro': 'romanian',
'ru': 'russian',
'sk': 'slovak',
'sr': 'serbian',
'sv': 'swedish',
'tr': 'turkish',
'uk': 'ukrainian'
}
# Start with left double quote.
left_quote = 1
def __init__(self, document):
nodes.NodeVisitor.__init__(self, document)
self.settings = document.settings
self.header = []
self.body = []
self.context = []
self.stylesheet_path = utils.get_stylesheet_reference(
self.settings, os.path.join(os.getcwd(), 'dummy'))
if self.stylesheet_path:
self.settings.record_dependencies.add(self.stylesheet_path)
# This ugly hack will be cleaned up when refactoring the
# stylesheet mess.
self.settings.stylesheet = self.settings.user_stylesheet
self.settings.stylesheet_path = self.settings.user_stylesheet_path
self.user_stylesheet_path = utils.get_stylesheet_reference(
self.settings, os.path.join(os.getcwd(), 'dummy'))
if self.user_stylesheet_path:
self.settings.record_dependencies.add(self.user_stylesheet_path)
lang = self.settings.language_code or ''
if lang.startswith('de'):
self.double_quote_replacment = "{\\dq}"
elif lang.startswith('it'):
self.double_quote_replacment = r'{\char`\"}'
else:
self.double_quote_replacment = None
self.write_header()
def write_header(self):
a = self.header.append
a('%% Generated by Docutils %s <http://docutils.sourceforge.net>.'
% docutils.__version__)
a('')
a('% Docutils settings:')
lang = self.settings.language_code or ''
a(r'\providecommand{\DEVlanguageiso}{%s}' % lang)
a(r'\providecommand{\DEVlanguagebabel}{%s}' % self.iso639_to_babel.get(
lang, self.iso639_to_babel.get(lang.split('_')[0], '')))
a('')
if self.user_stylesheet_path:
a('% User stylesheet:')
a(r'\input{%s}' % self.user_stylesheet_path)
a('% Docutils stylesheet:')
a(r'\input{%s}' % self.stylesheet_path)
a('')
a('% Default definitions for Docutils nodes:')
for node_name in nodes.node_class_names:
a(r'\providecommand{\DN%s}[1]{#1}' % node_name.replace('_', ''))
a('')
a('% Auxiliary definitions:')
for attr in (r'\DEVparent \DEVattrlen \DEVtitleastext '
r'\DEVsinglebackref \DEVmultiplebackrefs'
).split():
# Later set using \renewcommand.
a(r'\providecommand{%s}{DOCUTILSUNINITIALIZEDVARIABLE}' % attr)
for attr in (r'\DEVparagraphindented \DEVhassubtitle').split():
# Initialize as boolean variables.
a(r'\providecommand{%s}{false}' % attr)
a('\n\n')
unicode_map = unicode_map.unicode_map # comprehensive Unicode map
# Fix problems with unimap.py.
unicode_map.update({
# We have AE or T1 encoding, so "``" etc. work. The macros
# from unimap.py may *not* work.
u'\u201C': '{``}',
u'\u201D': "{''}",
u'\u201E': '{,,}',
})
character_map = {
'\\': r'{\textbackslash}',
'{': r'{\{}',
'}': r'{\}}',
'$': r'{\$}',
'&': r'{\&}',
'%': r'{\%}',
'#': r'{\#}',
'[': r'{[}',
']': r'{]}',
'-': r'{-}',
'`': r'{`}',
"'": r"{'}",
',': r'{,}',
'"': r'{"}',
'|': r'{\textbar}',
'<': r'{\textless}',
'>': r'{\textgreater}',
'^': r'{\textasciicircum}',
'~': r'{\textasciitilde}',
'_': r'{\DECtextunderscore}',
}
character_map.update(unicode_map)
#character_map.update(special_map)
# `att_map` is for encoding attributes. According to
# <http://www-h.eng.cam.ac.uk/help/tpl/textprocessing/teTeX/latex/latex2e-html/ltx-164.html>,
# the following characters are special: # $ % & ~ _ ^ \ { }
# These work without special treatment in macro parameters:
# $, &, ~, _, ^
att_map = {'#': '\\#',
'%': '\\%',
# We cannot do anything about backslashes.
'\\': '',
'{': '\\{',
'}': '\\}',
# The quotation mark may be redefined by babel.
'"': '"{}',
}
att_map.update(unicode_map)
def encode(self, text, attval=None):
"""
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.
"""
if attval in ('width', 'height'):
match = re.match(r'([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 = r'\DECrelativeunit'
elif unit in ('', 'px'):
# If \DECpixelunit is "pt", this gives the same notion
# of pixels as graphicx. This is a bit of a hack.
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:
# NB: We can have inline literals within literal blocks.
# Shrink '\r\n'.
text = text.replace('\r\n', '\n')
# Convert space. If "{ }~~~~~" is wrapped (at the
# brace-enclosed space "{ }"), the following non-breaking
# spaces ("~~~~") do *not* wind up at the beginning of the
# next line. Also note that no hyphenation is done if the
# breaking space ("{ }") comes *after* the non-breaking
# spaces.
if self.literal_block:
# Replace newlines with real newlines.
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(r'\s+', replace_fn, text)
# Protect hyphens; if we don't, line breaks will be
# possible at the hyphens and even the \textnhtt macro
# from the hyphenat package won't change that.
text = text.replace('-', r'\mbox{-}')
text = text.replace("'", r'{\DECtextliteralsinglequote}')
if self.double_quote_replacment is not None:
text = text.replace('"', self.double_quote_replacment)
return text
else:
if not attval:
# Replace space with single protected space.
text = re.sub(r'\s+', '{ }', text)
# Replace double quotes with macro calls.
L = []
for part in text.split(self.character_map['"']):
if L:
# Insert quote.
L.append(self.left_quote and r'{\DECtextleftdblquote}'
or r'{\DECtextrightdblquote}')
self.left_quote = not self.left_quote
L.append(part)
return ''.join(L)
else:
return text
def encode_replace_for_literal_block_spaces(self, match):
return '~' * len(match.group())
def encode_replace_for_inline_literal_spaces(self, match):
return '{ }' + '~' * (len(match.group()) - 1)
def astext(self):
return '\n'.join(self.header) + (''.join(self.body))
def append(self, text, newline='%\n'):
"""
Append text, stripping newlines, producing nice LaTeX code.
"""
lines = [' ' * self.indentation_level + line + newline
for line in text.splitlines(0)]
self.body.append(''.join(lines))
def visit_Text(self, node):
self.append(self.encode(node.astext()))
def depart_Text(self, node):
pass
def is_indented(self, paragraph):
"""Return true if `paragraph` should be first-line-indented."""
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
# Indent all but the first paragraphs.
return index > 0
def before_paragraph(self, node):
self.append(r'\renewcommand{\DEVparagraphindented}{%s}'
% (self.is_indented(node) and 'true' or 'false'))
def before_title(self, node):
self.append(r'\renewcommand{\DEVtitleastext}{%s}'
% self.encode(node.astext()))
self.append(r'\renewcommand{\DEVhassubtitle}{%s}'
% ((len(node.parent) > 2 and
isinstance(node.parent[1], nodes.subtitle))
and 'true' or 'false'))
def before_generated(self, node):
if 'sectnum' in node['classes']:
node[0] = node[0].strip()
literal_block = 0
def visit_literal_block(self, node):
self.literal_block = 1
def depart_literal_block(self, node):
self.literal_block = 0
visit_doctest_block = visit_literal_block
depart_doctest_block = depart_literal_block
inline_literal = 0
def visit_literal(self, node):
self.inline_literal += 1
def depart_literal(self, node):
self.inline_literal -= 1
def _make_encodable(self, text):
"""
Return text (a unicode object) with all unencodable characters
replaced with '?'.
Thus, the returned unicode string is guaranteed to be encodable.
"""
encoding = self.settings.output_encoding
return text.encode(encoding, 'replace').decode(encoding)
def visit_comment(self, node):
"""
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.)
"""
self.append('\n'.join(['% ' + self._make_encodable(line) for line
in node.astext().splitlines(0)]), newline='\n')
raise nodes.SkipChildren
def before_topic(self, node):
if 'contents' in node['classes']:
for bullet_list in list(node.traverse(nodes.bullet_list)):
p = bullet_list.parent
if isinstance(p, nodes.list_item):
p.parent.insert(p.parent.index(p) + 1, bullet_list)
del p[1]
for paragraph in node.traverse(nodes.paragraph):
paragraph.attributes.update(paragraph[0].attributes)
paragraph[:] = paragraph[0]
paragraph.parent['tocrefid'] = paragraph['refid']
node['contents'] = 1
else:
node['contents'] = 0
bullet_list_level = 0
def visit_bullet_list(self, node):
self.append(r'\DECsetbullet{\labelitem%s}' %
['i', 'ii', 'iii', 'iv'][min(self.bullet_list_level, 3)])
self.bullet_list_level += 1
def depart_bullet_list(self, node):
self.bullet_list_level -= 1
enum_styles = {'arabic': 'arabic', 'loweralpha': 'alph', 'upperalpha':
'Alph', 'lowerroman': 'roman', 'upperroman': 'Roman'}
enum_counter = 0
def visit_enumerated_list(self, node):
# We create our own enumeration list environment. This allows
# to set the style and starting value and unlimited nesting.
# Maybe the actual creation (\DEC) can be moved to the
# stylesheet?
self.enum_counter += 1
enum_prefix = self.encode(node['prefix'])
enum_suffix = self.encode(node['suffix'])
enum_type = '\\' + self.enum_styles.get(node['enumtype'], r'arabic')
start = node.get('start', 1) - 1
counter = 'Denumcounter%d' % self.enum_counter
self.append(r'\DECmakeenumeratedlist{%s}{%s}{%s}{%s}{%s}{'
% (enum_prefix, enum_type, enum_suffix, counter, start))
# for Emacs: }
def depart_enumerated_list(self, node):
self.append('}') # for Emacs: {
def before_list_item(self, node):
# XXX needs cleanup.
if (len(node) and (isinstance(node[-1], nodes.TextElement) or
isinstance(node[-1], nodes.Text)) and
node.parent.index(node) == len(node.parent) - 1):
node['lastitem'] = 'true'
before_line = before_list_item
def before_raw(self, node):
if 'latex' in node.get('format', '').split():
# We're inserting the text in before_raw and thus outside
# of \DN... and \DECattr in order to make grouping with
# curly brackets work.
self.append(node.astext())
raise nodes.SkipChildren
def process_backlinks(self, node, type):
"""
Add LaTeX handling code for backlinks of footnote or citation
node `node`. `type` is either 'footnote' or 'citation'.
"""
self.append(r'\renewcommand{\DEVsinglebackref}{}')
self.append(r'\renewcommand{\DEVmultiplebackrefs}{}')
if len(node['backrefs']) > 1:
refs = []
for i in range(len(node['backrefs'])):
# \DECmulticitationbacklink or \DECmultifootnotebacklink.
refs.append(r'\DECmulti%sbacklink{%s}{%s}'
% (type, node['backrefs'][i], i + 1))
self.append(r'\renewcommand{\DEVmultiplebackrefs}{(%s){ }}'
% ', '.join(refs))
elif len(node['backrefs']) == 1:
self.append(r'\renewcommand{\DEVsinglebackref}{%s}'
% node['backrefs'][0])
def visit_footnote(self, node):
self.process_backlinks(node, 'footnote')
def visit_citation(self, node):
self.process_backlinks(node, 'citation')
def before_table(self, node):
# A table contains exactly one tgroup. See before_tgroup.
pass
def before_tgroup(self, node):
widths = []
total_width = 0
for i in range(int(node['cols'])):
assert isinstance(node[i], nodes.colspec)
widths.append(int(node[i]['colwidth']) + 1)
total_width += widths[-1]
del node[:len(widths)]
tablespec = '|'
for w in widths:
# 0.93 is probably wrong in many cases. XXX Find a
# solution which works *always*.
tablespec += r'p{%s\textwidth}|' % (0.93 * w /
max(total_width, 60))
self.append(r'\DECmaketable{%s}{' % tablespec)
self.context.append('}')
raise SkipAttrParentLaTeX
def depart_tgroup(self, node):
self.append(self.context.pop())
def before_row(self, node):
raise SkipAttrParentLaTeX
def before_thead(self, node):
raise SkipAttrParentLaTeX
def before_tbody(self, node):
raise SkipAttrParentLaTeX
def is_simply_entry(self, node):
return (len(node) == 1 and isinstance(node[0], nodes.paragraph) or
len(node) == 0)
def before_entry(self, node):
is_leftmost = 0
if node.hasattr('morerows'):
self.document.reporter.severe('Rowspans are not supported.')
# Todo: Add empty cells below rowspanning cell and issue
# warning instead of severe.
if node.hasattr('morecols'):
# The author got a headache trying to implement
# multicolumn support.
if not self.is_simply_entry(node):
self.document.reporter.severe(
'Colspanning table cells may only contain one paragraph.')
# Todo: Same as above.
# The number of columns this entry spans (as a string).
colspan = int(node['morecols']) + 1
del node['morecols']
else:
colspan = 1
# Macro to call -- \DECcolspan or \DECcolspanleft.
macro_name = r'\DECcolspan'
if node.parent.index(node) == 0:
# Leftmost column.
macro_name += 'left'
is_leftmost = 1
if colspan > 1:
self.append('%s{%s}{' % (macro_name, colspan))
self.context.append('}')
else:
# Do not add a multicolumn with colspan 1 beacuse we need
# at least one non-multicolumn cell per column to get the
# desired column widths, and we can only do colspans with
# cells consisting of only one paragraph.
if not is_leftmost:
self.append(r'\DECsubsequententry{')
self.context.append('}')
else:
self.context.append('')
if isinstance(node.parent.parent, nodes.thead):
node['tableheaderentry'] = 'true'
# Don't add \renewcommand{\DEVparent}{...} because there must
# not be any non-expandable commands in front of \multicolumn.
raise SkipParentLaTeX
def depart_entry(self, node):
self.append(self.context.pop())
def before_substitution_definition(self, node):
raise nodes.SkipNode
indentation_level = 0
def node_name(self, node):
return node.__class__.__name__.replace('_', '')
# Attribute propagation order.
attribute_order = ['align', 'classes', 'ids']
def attribute_cmp(self, a1, a2):
"""
Compare attribute names `a1` and `a2`. Used in
propagate_attributes to determine propagation order.
See built-in function `cmp` for return value.
"""
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):
# Attributes not in self.attribute_order come last.
return a1 in self.attribute_order and -1 or 1
else:
return cmp(a1, a2)
def propagate_attributes(self, node):
# Propagate attributes using \DECattr macros.
node_name = self.node_name(node)
attlist = []
if isinstance(node, nodes.Element):
attlist = node.attlist()
attlist.sort(lambda pair1, pair2: self.attribute_cmp(pair1[0],
pair2[0]))
# `numatts` may be greater than len(attlist) due to list
# attributes.
numatts = 0
pass_contents = self.pass_contents(node)
for key, value in attlist:
if isinstance(value, list):
self.append(r'\renewcommand{\DEVattrlen}{%s}' % len(value))
for i in range(len(value)):
self.append(r'\DECattr{%s}{%s}{%s}{%s}{' %
(i+1, key, self.encode(value[i], attval=key),
node_name))
if not pass_contents:
self.append('}')
numatts += len(value)
else:
self.append(r'\DECattr{}{%s}{%s}{%s}{' %
(key, self.encode(unicode(value), attval=key),
node_name))
if not pass_contents:
self.append('}')
numatts += 1
if pass_contents:
self.context.append('}' * numatts) # for Emacs: {
else:
self.context.append('')
def visit_docinfo(self, node):
raise NotImplementedError('Docinfo not yet implemented.')
def visit_document(self, node):
document = node
# Move IDs into TextElements. This won't work for images.
# Need to review this.
for node in document.traverse(nodes.Element):
if 'ids' in node and not isinstance(node,
nodes.TextElement):
next_text_element = node.next_node(nodes.TextElement)
if next_text_element:
next_text_element['ids'].extend(node['ids'])
node['ids'] = []
def pass_contents(self, node):
r"""
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.
"""
# Passing the whole document or whole sections as parameters
# to \DN... or \DECattr causes LaTeX to run out of memory.
return not isinstance(node, (nodes.document, nodes.section))
def dispatch_visit(self, node):
skip_attr = skip_parent = 0
# TreePruningException to be propagated.
tree_pruning_exception = None
if hasattr(self, 'before_' + node.__class__.__name__):
try:
getattr(self, 'before_' + node.__class__.__name__)(node)
except SkipParentLaTeX:
skip_parent = 1
except SkipAttrParentLaTeX:
skip_attr = 1
skip_parent = 1
except nodes.SkipNode:
raise
except (nodes.SkipChildren, nodes.SkipSiblings), instance:
tree_pruning_exception = instance
except nodes.SkipDeparture:
raise NotImplementedError(
'SkipDeparture not usable in LaTeX writer')
if not isinstance(node, nodes.Text):
node_name = self.node_name(node)
# attribute_deleters will be appended to self.context.
attribute_deleters = []
if not skip_parent and not isinstance(node, nodes.document):
self.append(r'\renewcommand{\DEVparent}{%s}'
% self.node_name(node.parent))
for name, value in node.attlist():
if not isinstance(value, list) and not ':' in name:
# For non-list and non-special (like
# 'xml:preserve') attributes, set
# \DEVcurrentN<nodename>A<attribute> to the
# attribute value, so that the value of the
# attribute is available in the node handler
# and all children.
macro = r'\DEVcurrentN%sA%s' % (node_name, name)
self.append(r'\def%s{%s}' % (
macro, self.encode(unicode(value), attval=name)))
# Make the attribute undefined afterwards.
attribute_deleters.append(r'\let%s=\relax' % macro)
self.context.append('\n'.join(attribute_deleters))
if self.pass_contents(node):
# Call \DN<nodename>{<contents>}.
self.append(r'\DN%s{' % node_name)
self.context.append('}')
else:
# Call \DECvisit<nodename> <contents>
# \DECdepart<nodename>. (Maybe we should use LaTeX
# environments for this?)
self.append(r'\DECvisit%s' % node_name)
self.context.append(r'\DECdepart%s' % node_name)
self.indentation_level += 1
if not skip_attr:
self.propagate_attributes(node)
else:
self.context.append('')
if (isinstance(node, nodes.TextElement) and
not isinstance(node.parent, nodes.TextElement)):
# Reset current quote to left.
self.left_quote = 1
# Call visit_... method.
try:
nodes.SparseNodeVisitor.dispatch_visit(self, node)
except LaTeXException:
raise NotImplementedError(
'visit_... methods must not raise LaTeXExceptions')
if tree_pruning_exception:
# Propagate TreePruningException raised in before_... method.
raise tree_pruning_exception
def is_invisible(self, node):
# Return true if node is invisible or moved away in the LaTeX
# rendering.
return (not isinstance(node, nodes.Text) and
(isinstance(node, nodes.Invisible) or
isinstance(node, nodes.footnote) or
isinstance(node, nodes.citation) or
# Assume raw nodes to be invisible.
isinstance(node, nodes.raw) or
# Floating image or figure.
node.get('align') in ('left', 'right')))
def is_visible(self, node):
return not self.is_invisible(node)
def needs_space(self, node):
"""Two nodes for which `needs_space` is true need auxiliary space."""
# Return true if node is a visible block-level element.
return ((isinstance(node, nodes.Body) or
isinstance(node, nodes.topic)) and
not (self.is_invisible(node) or
isinstance(node.parent, nodes.TextElement)))
def always_needs_space(self, node):
"""
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.)
"""
return isinstance(node, nodes.transition)
def dispatch_departure(self, node):
# Call departure method.
nodes.SparseNodeVisitor.dispatch_departure(self, node)
if not isinstance(node, nodes.Text):
# Close attribute and node handler call (\DN...{...}).
self.indentation_level -= 1
self.append(self.context.pop() + self.context.pop())
# Delete \DECcurrentN... attribute macros.
self.append(self.context.pop())
# Get next sibling.
next_node = node.next_node(
ascend=0, siblings=1, descend=0,
condition=self.is_visible)
# Insert space if necessary.
if (self.needs_space(node) and self.needs_space(next_node) or
self.always_needs_space(node) or
self.always_needs_space(next_node)):
if isinstance(node, nodes.paragraph) and isinstance(next_node, nodes.paragraph):
# Space between paragraphs.
self.append(r'\DECparagraphspace')
else:
# One of the elements is not a paragraph.
self.append(r'\DECauxiliaryspace')
| {
"repo_name": "MER-GROUP/intellij-community",
"path": "python/helpers/py2only/docutils/writers/newlatex2e/__init__.py",
"copies": "5",
"size": "32261",
"license": "apache-2.0",
"hash": -8346162357209320000,
"line_mean": 37.6359281437,
"line_max": 97,
"alpha_frac": 0.5456123493,
"autogenerated": false,
"ratio": 4.054927099044746,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005498640499502119,
"num_lines": 835
} |
"""
LaTeX2e document tree Writer.
"""
# Thanks to Engelbert Gruber and various contributors for the original
# LaTeX writer, some code and many ideas of which have been used for
# this writer.
__docformat__ = 'reStructuredText'
import re
import os.path
import docutils
from docutils import nodes, writers, utils
from docutils.writers.newlatex2e import unicode_map
from docutils.transforms import writer_aux
class Writer(writers.Writer):
supported = ('newlatex', 'newlatex2e')
"""Formats this writer supports."""
default_stylesheet = 'base.tex'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
settings_spec = (
'LaTeX-Specific Options',
'Note that this LaTeX writer is still EXPERIMENTAL and not '
'feature-complete. ',
(('Specify a stylesheet file. The path is used verbatim to include '
'the file. Overrides --stylesheet-path.',
['--stylesheet'],
{'default': '', 'metavar': '<file>',
'overrides': 'stylesheet_path'}),
('Specify a stylesheet file, relative to the current working '
'directory. Overrides --stylesheet. Default: "%s"'
% default_stylesheet_path,
['--stylesheet-path'],
{'metavar': '<file>', 'overrides': 'stylesheet',
'default': default_stylesheet_path}),
('Specify a user stylesheet file. See --stylesheet.',
['--user-stylesheet'],
{'default': '', 'metavar': '<file>',
'overrides': 'user_stylesheet_path'}),
('Specify a user stylesheet file. See --stylesheet-path.',
['--user-stylesheet-path'],
{'metavar': '<file>', 'overrides': 'user_stylesheet'})
),)
settings_defaults = {
# Many Unicode characters are provided by unicode_map.py, so
# we can default to latin-1.
'output_encoding': 'latin-1',
'output_encoding_error_handler': 'strict',
# Since we are using superscript footnotes, it is necessary to
# trim whitespace in front of footnote references.
'trim_footnote_reference_space': 1,
# Currently unsupported:
'docinfo_xform': 0,
# During development:
'traceback': 1
}
relative_path_settings = ('stylesheet_path', 'user_stylesheet_path')
config_section = 'newlatex2e writer'
config_section_dependencies = ('writers',)
output = None
"""Final translated form of `document`."""
def get_transforms(self):
return writers.Writer.get_transforms(self) + [
writer_aux.Compound, writer_aux.Admonitions]
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = LaTeXTranslator
def translate(self):
visitor = self.translator_class(self.document)
self.document.walkabout(visitor)
assert not visitor.context, 'context not empty: %s' % visitor.context
self.output = visitor.astext()
self.head = visitor.header
self.body = visitor.body
class LaTeXException(Exception):
"""
Exception base class to for exceptions which influence the
automatic generation of LaTeX code.
"""
class SkipAttrParentLaTeX(LaTeXException):
"""
Do not generate ``\DECattr`` and ``\renewcommand{\DEVparent}{...}`` for this
node.
To be raised from ``before_...`` methods.
"""
class SkipParentLaTeX(LaTeXException):
"""
Do not generate ``\renewcommand{\DEVparent}{...}`` for this node.
To be raised from ``before_...`` methods.
"""
class LaTeXTranslator(nodes.SparseNodeVisitor):
# Country code by a.schlock.
# Partly manually converted from iso and babel stuff.
iso639_to_babel = {
'no': 'norsk', # added by hand
'gd': 'scottish', # added by hand
'sl': 'slovenian',
'af': 'afrikaans',
'bg': 'bulgarian',
'br': 'breton',
'ca': 'catalan',
'cs': 'czech',
'cy': 'welsh',
'da': 'danish',
'fr': 'french',
# french, francais, canadien, acadian
'de': 'ngerman',
# ngerman, naustrian, german, germanb, austrian
'el': 'greek',
'en': 'english',
# english, USenglish, american, UKenglish, british, canadian
'eo': 'esperanto',
'es': 'spanish',
'et': 'estonian',
'eu': 'basque',
'fi': 'finnish',
'ga': 'irish',
'gl': 'galician',
'he': 'hebrew',
'hr': 'croatian',
'hu': 'hungarian',
'is': 'icelandic',
'it': 'italian',
'la': 'latin',
'nl': 'dutch',
'pl': 'polish',
'pt': 'portuguese',
'ro': 'romanian',
'ru': 'russian',
'sk': 'slovak',
'sr': 'serbian',
'sv': 'swedish',
'tr': 'turkish',
'uk': 'ukrainian'
}
# Start with left double quote.
left_quote = 1
def __init__(self, document):
nodes.NodeVisitor.__init__(self, document)
self.settings = document.settings
self.header = []
self.body = []
self.context = []
self.stylesheet_path = utils.get_stylesheet_reference(
self.settings, os.path.join(os.getcwd(), 'dummy'))
if self.stylesheet_path:
self.settings.record_dependencies.add(self.stylesheet_path)
# This ugly hack will be cleaned up when refactoring the
# stylesheet mess.
self.settings.stylesheet = self.settings.user_stylesheet
self.settings.stylesheet_path = self.settings.user_stylesheet_path
self.user_stylesheet_path = utils.get_stylesheet_reference(
self.settings, os.path.join(os.getcwd(), 'dummy'))
if self.user_stylesheet_path:
self.settings.record_dependencies.add(self.user_stylesheet_path)
lang = self.settings.language_code or ''
if lang.startswith('de'):
self.double_quote_replacment = "{\\dq}"
elif lang.startswith('it'):
self.double_quote_replacment = r'{\char`\"}'
else:
self.double_quote_replacment = None
self.write_header()
def write_header(self):
a = self.header.append
a('%% Generated by Docutils %s <http://docutils.sourceforge.net>.'
% docutils.__version__)
a('')
a('% Docutils settings:')
lang = self.settings.language_code or ''
a(r'\providecommand{\DEVlanguageiso}{%s}' % lang)
a(r'\providecommand{\DEVlanguagebabel}{%s}' % self.iso639_to_babel.get(
lang, self.iso639_to_babel.get(lang.split('_')[0], '')))
a('')
if self.user_stylesheet_path:
a('% User stylesheet:')
a(r'\input{%s}' % self.user_stylesheet_path)
a('% Docutils stylesheet:')
a(r'\input{%s}' % self.stylesheet_path)
a('')
a('% Default definitions for Docutils nodes:')
for node_name in nodes.node_class_names:
a(r'\providecommand{\DN%s}[1]{#1}' % node_name.replace('_', ''))
a('')
a('% Auxiliary definitions:')
for attr in (r'\DEVparent \DEVattrlen \DEVtitleastext '
r'\DEVsinglebackref \DEVmultiplebackrefs'
).split():
# Later set using \renewcommand.
a(r'\providecommand{%s}{DOCUTILSUNINITIALIZEDVARIABLE}' % attr)
for attr in (r'\DEVparagraphindented \DEVhassubtitle').split():
# Initialize as boolean variables.
a(r'\providecommand{%s}{false}' % attr)
a('\n\n')
unicode_map = unicode_map.unicode_map # comprehensive Unicode map
# Fix problems with unimap.py.
unicode_map.update({
# We have AE or T1 encoding, so "``" etc. work. The macros
# from unimap.py may *not* work.
u'\u201C': '{``}',
u'\u201D': "{''}",
u'\u201E': '{,,}',
})
character_map = {
'\\': r'{\textbackslash}',
'{': r'{\{}',
'}': r'{\}}',
'$': r'{\$}',
'&': r'{\&}',
'%': r'{\%}',
'#': r'{\#}',
'[': r'{[}',
']': r'{]}',
'-': r'{-}',
'`': r'{`}',
"'": r"{'}",
',': r'{,}',
'"': r'{"}',
'|': r'{\textbar}',
'<': r'{\textless}',
'>': r'{\textgreater}',
'^': r'{\textasciicircum}',
'~': r'{\textasciitilde}',
'_': r'{\DECtextunderscore}',
}
character_map.update(unicode_map)
#character_map.update(special_map)
# `att_map` is for encoding attributes. According to
# <http://www-h.eng.cam.ac.uk/help/tpl/textprocessing/teTeX/latex/latex2e-html/ltx-164.html>,
# the following characters are special: # $ % & ~ _ ^ \ { }
# These work without special treatment in macro parameters:
# $, &, ~, _, ^
att_map = {'#': '\\#',
'%': '\\%',
# We cannot do anything about backslashes.
'\\': '',
'{': '\\{',
'}': '\\}',
# The quotation mark may be redefined by babel.
'"': '"{}',
}
att_map.update(unicode_map)
def encode(self, text, attval=None):
"""
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.
"""
if attval in ('width', 'height'):
match = re.match(r'([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 = r'\DECrelativeunit'
elif unit in ('', 'px'):
# If \DECpixelunit is "pt", this gives the same notion
# of pixels as graphicx. This is a bit of a hack.
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:
# NB: We can have inline literals within literal blocks.
# Shrink '\r\n'.
text = text.replace('\r\n', '\n')
# Convert space. If "{ }~~~~~" is wrapped (at the
# brace-enclosed space "{ }"), the following non-breaking
# spaces ("~~~~") do *not* wind up at the beginning of the
# next line. Also note that no hyphenation is done if the
# breaking space ("{ }") comes *after* the non-breaking
# spaces.
if self.literal_block:
# Replace newlines with real newlines.
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(r'\s+', replace_fn, text)
# Protect hyphens; if we don't, line breaks will be
# possible at the hyphens and even the \textnhtt macro
# from the hyphenat package won't change that.
text = text.replace('-', r'\mbox{-}')
text = text.replace("'", r'{\DECtextliteralsinglequote}')
if self.double_quote_replacment is not None:
text = text.replace('"', self.double_quote_replacment)
return text
else:
if not attval:
# Replace space with single protected space.
text = re.sub(r'\s+', '{ }', text)
# Replace double quotes with macro calls.
L = []
for part in text.split(self.character_map['"']):
if L:
# Insert quote.
L.append(self.left_quote and r'{\DECtextleftdblquote}'
or r'{\DECtextrightdblquote}')
self.left_quote = not self.left_quote
L.append(part)
return ''.join(L)
else:
return text
def encode_replace_for_literal_block_spaces(self, match):
return '~' * len(match.group())
def encode_replace_for_inline_literal_spaces(self, match):
return '{ }' + '~' * (len(match.group()) - 1)
def astext(self):
return '\n'.join(self.header) + (''.join(self.body))
def append(self, text, newline='%\n'):
"""
Append text, stripping newlines, producing nice LaTeX code.
"""
lines = [' ' * self.indentation_level + line + newline
for line in text.splitlines(0)]
self.body.append(''.join(lines))
def visit_Text(self, node):
self.append(self.encode(node.astext()))
def depart_Text(self, node):
pass
def is_indented(self, paragraph):
"""Return true if `paragraph` should be first-line-indented."""
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
# Indent all but the first paragraphs.
return index > 0
def before_paragraph(self, node):
self.append(r'\renewcommand{\DEVparagraphindented}{%s}'
% (self.is_indented(node) and 'true' or 'false'))
def before_title(self, node):
self.append(r'\renewcommand{\DEVtitleastext}{%s}'
% self.encode(node.astext()))
self.append(r'\renewcommand{\DEVhassubtitle}{%s}'
% ((len(node.parent) > 2 and
isinstance(node.parent[1], nodes.subtitle))
and 'true' or 'false'))
def before_generated(self, node):
if 'sectnum' in node['classes']:
node[0] = node[0].strip()
literal_block = 0
def visit_literal_block(self, node):
self.literal_block = 1
def depart_literal_block(self, node):
self.literal_block = 0
visit_doctest_block = visit_literal_block
depart_doctest_block = depart_literal_block
inline_literal = 0
def visit_literal(self, node):
self.inline_literal += 1
def depart_literal(self, node):
self.inline_literal -= 1
def _make_encodable(self, text):
"""
Return text (a unicode object) with all unencodable characters
replaced with '?'.
Thus, the returned unicode string is guaranteed to be encodable.
"""
encoding = self.settings.output_encoding
return text.encode(encoding, 'replace').decode(encoding)
def visit_comment(self, node):
"""
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.)
"""
self.append('\n'.join(['% ' + self._make_encodable(line) for line
in node.astext().splitlines(0)]), newline='\n')
raise nodes.SkipChildren
def before_topic(self, node):
if 'contents' in node['classes']:
for bullet_list in list(node.traverse(nodes.bullet_list)):
p = bullet_list.parent
if isinstance(p, nodes.list_item):
p.parent.insert(p.parent.index(p) + 1, bullet_list)
del p[1]
for paragraph in node.traverse(nodes.paragraph):
paragraph.attributes.update(paragraph[0].attributes)
paragraph[:] = paragraph[0]
paragraph.parent['tocrefid'] = paragraph['refid']
node['contents'] = 1
else:
node['contents'] = 0
bullet_list_level = 0
def visit_bullet_list(self, node):
self.append(r'\DECsetbullet{\labelitem%s}' %
['i', 'ii', 'iii', 'iv'][min(self.bullet_list_level, 3)])
self.bullet_list_level += 1
def depart_bullet_list(self, node):
self.bullet_list_level -= 1
enum_styles = {'arabic': 'arabic', 'loweralpha': 'alph', 'upperalpha':
'Alph', 'lowerroman': 'roman', 'upperroman': 'Roman'}
enum_counter = 0
def visit_enumerated_list(self, node):
# We create our own enumeration list environment. This allows
# to set the style and starting value and unlimited nesting.
# Maybe the actual creation (\DEC) can be moved to the
# stylesheet?
self.enum_counter += 1
enum_prefix = self.encode(node['prefix'])
enum_suffix = self.encode(node['suffix'])
enum_type = '\\' + self.enum_styles.get(node['enumtype'], r'arabic')
start = node.get('start', 1) - 1
counter = 'Denumcounter%d' % self.enum_counter
self.append(r'\DECmakeenumeratedlist{%s}{%s}{%s}{%s}{%s}{'
% (enum_prefix, enum_type, enum_suffix, counter, start))
# for Emacs: }
def depart_enumerated_list(self, node):
self.append('}') # for Emacs: {
def before_list_item(self, node):
# XXX needs cleanup.
if (len(node) and (isinstance(node[-1], nodes.TextElement) or
isinstance(node[-1], nodes.Text)) and
node.parent.index(node) == len(node.parent) - 1):
node['lastitem'] = 'true'
before_line = before_list_item
def before_raw(self, node):
if 'latex' in node.get('format', '').split():
# We're inserting the text in before_raw and thus outside
# of \DN... and \DECattr in order to make grouping with
# curly brackets work.
self.append(node.astext())
raise nodes.SkipChildren
def process_backlinks(self, node, type):
"""
Add LaTeX handling code for backlinks of footnote or citation
node `node`. `type` is either 'footnote' or 'citation'.
"""
self.append(r'\renewcommand{\DEVsinglebackref}{}')
self.append(r'\renewcommand{\DEVmultiplebackrefs}{}')
if len(node['backrefs']) > 1:
refs = []
for i in range(len(node['backrefs'])):
# \DECmulticitationbacklink or \DECmultifootnotebacklink.
refs.append(r'\DECmulti%sbacklink{%s}{%s}'
% (type, node['backrefs'][i], i + 1))
self.append(r'\renewcommand{\DEVmultiplebackrefs}{(%s){ }}'
% ', '.join(refs))
elif len(node['backrefs']) == 1:
self.append(r'\renewcommand{\DEVsinglebackref}{%s}'
% node['backrefs'][0])
def visit_footnote(self, node):
self.process_backlinks(node, 'footnote')
def visit_citation(self, node):
self.process_backlinks(node, 'citation')
def before_table(self, node):
# A table contains exactly one tgroup. See before_tgroup.
pass
def before_tgroup(self, node):
widths = []
total_width = 0
for i in range(int(node['cols'])):
assert isinstance(node[i], nodes.colspec)
widths.append(int(node[i]['colwidth']) + 1)
total_width += widths[-1]
del node[:len(widths)]
tablespec = '|'
for w in widths:
# 0.93 is probably wrong in many cases. XXX Find a
# solution which works *always*.
tablespec += r'p{%s\textwidth}|' % (0.93 * w /
max(total_width, 60))
self.append(r'\DECmaketable{%s}{' % tablespec)
self.context.append('}')
raise SkipAttrParentLaTeX
def depart_tgroup(self, node):
self.append(self.context.pop())
def before_row(self, node):
raise SkipAttrParentLaTeX
def before_thead(self, node):
raise SkipAttrParentLaTeX
def before_tbody(self, node):
raise SkipAttrParentLaTeX
def is_simply_entry(self, node):
return (len(node) == 1 and isinstance(node[0], nodes.paragraph) or
len(node) == 0)
def before_entry(self, node):
is_leftmost = 0
if node.hasattr('morerows'):
self.document.reporter.severe('Rowspans are not supported.')
# Todo: Add empty cells below rowspanning cell and issue
# warning instead of severe.
if node.hasattr('morecols'):
# The author got a headache trying to implement
# multicolumn support.
if not self.is_simply_entry(node):
self.document.reporter.severe(
'Colspanning table cells may only contain one paragraph.')
# Todo: Same as above.
# The number of columns this entry spans (as a string).
colspan = int(node['morecols']) + 1
del node['morecols']
else:
colspan = 1
# Macro to call -- \DECcolspan or \DECcolspanleft.
macro_name = r'\DECcolspan'
if node.parent.index(node) == 0:
# Leftmost column.
macro_name += 'left'
is_leftmost = 1
if colspan > 1:
self.append('%s{%s}{' % (macro_name, colspan))
self.context.append('}')
else:
# Do not add a multicolumn with colspan 1 beacuse we need
# at least one non-multicolumn cell per column to get the
# desired column widths, and we can only do colspans with
# cells consisting of only one paragraph.
if not is_leftmost:
self.append(r'\DECsubsequententry{')
self.context.append('}')
else:
self.context.append('')
if isinstance(node.parent.parent, nodes.thead):
node['tableheaderentry'] = 'true'
# Don't add \renewcommand{\DEVparent}{...} because there must
# not be any non-expandable commands in front of \multicolumn.
raise SkipParentLaTeX
def depart_entry(self, node):
self.append(self.context.pop())
def before_substitution_definition(self, node):
raise nodes.SkipNode
indentation_level = 0
def node_name(self, node):
return node.__class__.__name__.replace('_', '')
# Attribute propagation order.
attribute_order = ['align', 'classes', 'ids']
def attribute_cmp(self, a1, a2):
"""
Compare attribute names `a1` and `a2`. Used in
propagate_attributes to determine propagation order.
See built-in function `cmp` for return value.
"""
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):
# Attributes not in self.attribute_order come last.
return a1 in self.attribute_order and -1 or 1
else:
return cmp(a1, a2)
def propagate_attributes(self, node):
# Propagate attributes using \DECattr macros.
node_name = self.node_name(node)
attlist = []
if isinstance(node, nodes.Element):
attlist = node.attlist()
attlist.sort(lambda pair1, pair2: self.attribute_cmp(pair1[0],
pair2[0]))
# `numatts` may be greater than len(attlist) due to list
# attributes.
numatts = 0
pass_contents = self.pass_contents(node)
for key, value in attlist:
if isinstance(value, list):
self.append(r'\renewcommand{\DEVattrlen}{%s}' % len(value))
for i in range(len(value)):
self.append(r'\DECattr{%s}{%s}{%s}{%s}{' %
(i+1, key, self.encode(value[i], attval=key),
node_name))
if not pass_contents:
self.append('}')
numatts += len(value)
else:
self.append(r'\DECattr{}{%s}{%s}{%s}{' %
(key, self.encode(unicode(value), attval=key),
node_name))
if not pass_contents:
self.append('}')
numatts += 1
if pass_contents:
self.context.append('}' * numatts) # for Emacs: {
else:
self.context.append('')
def visit_docinfo(self, node):
raise NotImplementedError('Docinfo not yet implemented.')
def visit_document(self, node):
document = node
# Move IDs into TextElements. This won't work for images.
# Need to review this.
for node in document.traverse(nodes.Element):
if 'ids' in node and not isinstance(node,
nodes.TextElement):
next_text_element = node.next_node(nodes.TextElement)
if next_text_element:
next_text_element['ids'].extend(node['ids'])
node['ids'] = []
def pass_contents(self, node):
r"""
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.
"""
# Passing the whole document or whole sections as parameters
# to \DN... or \DECattr causes LaTeX to run out of memory.
return not isinstance(node, (nodes.document, nodes.section))
def dispatch_visit(self, node):
skip_attr = skip_parent = 0
# TreePruningException to be propagated.
tree_pruning_exception = None
if hasattr(self, 'before_' + node.__class__.__name__):
try:
getattr(self, 'before_' + node.__class__.__name__)(node)
except SkipParentLaTeX:
skip_parent = 1
except SkipAttrParentLaTeX:
skip_attr = 1
skip_parent = 1
except nodes.SkipNode:
raise
except (nodes.SkipChildren, nodes.SkipSiblings), instance:
tree_pruning_exception = instance
except nodes.SkipDeparture:
raise NotImplementedError(
'SkipDeparture not usable in LaTeX writer')
if not isinstance(node, nodes.Text):
node_name = self.node_name(node)
# attribute_deleters will be appended to self.context.
attribute_deleters = []
if not skip_parent and not isinstance(node, nodes.document):
self.append(r'\renewcommand{\DEVparent}{%s}'
% self.node_name(node.parent))
for name, value in node.attlist():
if not isinstance(value, list) and not ':' in name:
# For non-list and non-special (like
# 'xml:preserve') attributes, set
# \DEVcurrentN<nodename>A<attribute> to the
# attribute value, so that the value of the
# attribute is available in the node handler
# and all children.
macro = r'\DEVcurrentN%sA%s' % (node_name, name)
self.append(r'\def%s{%s}' % (
macro, self.encode(unicode(value), attval=name)))
# Make the attribute undefined afterwards.
attribute_deleters.append(r'\let%s=\relax' % macro)
self.context.append('\n'.join(attribute_deleters))
if self.pass_contents(node):
# Call \DN<nodename>{<contents>}.
self.append(r'\DN%s{' % node_name)
self.context.append('}')
else:
# Call \DECvisit<nodename> <contents>
# \DECdepart<nodename>. (Maybe we should use LaTeX
# environments for this?)
self.append(r'\DECvisit%s' % node_name)
self.context.append(r'\DECdepart%s' % node_name)
self.indentation_level += 1
if not skip_attr:
self.propagate_attributes(node)
else:
self.context.append('')
if (isinstance(node, nodes.TextElement) and
not isinstance(node.parent, nodes.TextElement)):
# Reset current quote to left.
self.left_quote = 1
# Call visit_... method.
try:
nodes.SparseNodeVisitor.dispatch_visit(self, node)
except LaTeXException:
raise NotImplementedError(
'visit_... methods must not raise LaTeXExceptions')
if tree_pruning_exception:
# Propagate TreePruningException raised in before_... method.
raise tree_pruning_exception
def is_invisible(self, node):
# Return true if node is invisible or moved away in the LaTeX
# rendering.
return (not isinstance(node, nodes.Text) and
(isinstance(node, nodes.Invisible) or
isinstance(node, nodes.footnote) or
isinstance(node, nodes.citation) or
# Assume raw nodes to be invisible.
isinstance(node, nodes.raw) or
# Floating image or figure.
node.get('align') in ('left', 'right')))
def is_visible(self, node):
return not self.is_invisible(node)
def needs_space(self, node):
"""Two nodes for which `needs_space` is true need auxiliary space."""
# Return true if node is a visible block-level element.
return ((isinstance(node, nodes.Body) or
isinstance(node, nodes.topic)) and
not (self.is_invisible(node) or
isinstance(node.parent, nodes.TextElement)))
def always_needs_space(self, node):
"""
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.)
"""
return isinstance(node, nodes.transition)
def dispatch_departure(self, node):
# Call departure method.
nodes.SparseNodeVisitor.dispatch_departure(self, node)
if not isinstance(node, nodes.Text):
# Close attribute and node handler call (\DN...{...}).
self.indentation_level -= 1
self.append(self.context.pop() + self.context.pop())
# Delete \DECcurrentN... attribute macros.
self.append(self.context.pop())
# Get next sibling.
next_node = node.next_node(
ascend=0, siblings=1, descend=0,
condition=self.is_visible)
# Insert space if necessary.
if (self.needs_space(node) and self.needs_space(next_node) or
self.always_needs_space(node) or
self.always_needs_space(next_node)):
if isinstance(node, nodes.paragraph) and isinstance(next_node, nodes.paragraph):
# Space between paragraphs.
self.append(r'\DECparagraphspace')
else:
# One of the elements is not a paragraph.
self.append(r'\DECauxiliaryspace')
| {
"repo_name": "rimbalinux/LMD3",
"path": "docutils/writers/newlatex2e/__init__.py",
"copies": "2",
"size": "33098",
"license": "bsd-3-clause",
"hash": -6612387738607564000,
"line_mean": 37.5909090909,
"line_max": 97,
"alpha_frac": 0.5318146112,
"autogenerated": false,
"ratio": 4.149178889306757,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5680993500506757,
"avg_score": null,
"num_lines": null
} |
"""
S5/HTML Slideshow Writer.
"""
__docformat__ = 'reStructuredText'
import os
import re
import sys
import docutils
from docutils import frontend, nodes, utils
from docutils._compat import b
from docutils.writers import html4css1
themes_dir_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), 'themes'))
def find_theme(name):
# Where else to look for a theme?
# Check working dir? Destination dir? Config dir? Plugins dir?
path = os.path.join(themes_dir_path, name)
if not os.path.isdir(path):
raise docutils.ApplicationError(
'Theme directory not found: %r (path: %r)' % (name, path))
return path
class Writer(html4css1.Writer):
settings_spec = html4css1.Writer.settings_spec + (
'S5 Slideshow Specific Options',
'For the S5/HTML writer, the --no-toc-backlinks option '
'(defined in General Docutils Options above) is the default, '
'and should not be changed.',
(('Specify an installed S5 theme by name. Overrides --theme-url. '
'The default theme name is "default". The theme files will be '
'copied into a "ui/<theme>" directory, in the same directory as the '
'destination file (output HTML). Note that existing theme files '
'will not be overwritten (unless --overwrite-theme-files is used).',
['--theme'],
{'default': 'default', 'metavar': '<name>',
'overrides': 'theme_url'}),
('Specify an S5 theme URL. The destination file (output HTML) will '
'link to this theme; nothing will be copied. Overrides --theme.',
['--theme-url'],
{'metavar': '<URL>', 'overrides': 'theme'}),
('Allow existing theme files in the ``ui/<theme>`` directory to be '
'overwritten. The default is not to overwrite theme files.',
['--overwrite-theme-files'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Keep existing theme files in the ``ui/<theme>`` directory; do not '
'overwrite any. This is the default.',
['--keep-theme-files'],
{'dest': 'overwrite_theme_files', 'action': 'store_false'}),
('Set the initial view mode to "slideshow" [default] or "outline".',
['--view-mode'],
{'choices': ['slideshow', 'outline'], 'default': 'slideshow',
'metavar': '<mode>'}),
('Normally hide the presentation controls in slideshow mode. '
'This is the default.',
['--hidden-controls'],
{'action': 'store_true', 'default': True,
'validator': frontend.validate_boolean}),
('Always show the presentation controls in slideshow mode. '
'The default is to hide the controls.',
['--visible-controls'],
{'dest': 'hidden_controls', 'action': 'store_false'}),
('Enable the current slide indicator ("1 / 15"). '
'The default is to disable it.',
['--current-slide'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Disable the current slide indicator. This is the default.',
['--no-current-slide'],
{'dest': 'current_slide', 'action': 'store_false'}),))
settings_default_overrides = {'toc_backlinks': 0}
config_section = 's5_html writer'
config_section_dependencies = ('writers', 'html4css1 writer')
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = S5HTMLTranslator
class S5HTMLTranslator(html4css1.HTMLTranslator):
s5_stylesheet_template = """\
<!-- configuration parameters -->
<meta name="defaultView" content="%(view_mode)s" />
<meta name="controlVis" content="%(control_visibility)s" />
<!-- style sheet links -->
<script src="%(path)s/slides.js" type="text/javascript"></script>
<link rel="stylesheet" href="%(path)s/slides.css"
type="text/css" media="projection" id="slideProj" />
<link rel="stylesheet" href="%(path)s/outline.css"
type="text/css" media="screen" id="outlineStyle" />
<link rel="stylesheet" href="%(path)s/print.css"
type="text/css" media="print" id="slidePrint" />
<link rel="stylesheet" href="%(path)s/opera.css"
type="text/css" media="projection" id="operaFix" />\n"""
# The script element must go in front of the link elements to
# avoid a flash of unstyled content (FOUC), reproducible with
# Firefox.
disable_current_slide = """
<style type="text/css">
#currentSlide {display: none;}
</style>\n"""
layout_template = """\
<div class="layout">
<div id="controls"></div>
<div id="currentSlide"></div>
<div id="header">
%(header)s
</div>
<div id="footer">
%(title)s%(footer)s
</div>
</div>\n"""
# <div class="topleft"></div>
# <div class="topright"></div>
# <div class="bottomleft"></div>
# <div class="bottomright"></div>
default_theme = 'default'
"""Name of the default theme."""
base_theme_file = '__base__'
"""Name of the file containing the name of the base theme."""
direct_theme_files = (
'slides.css', 'outline.css', 'print.css', 'opera.css', 'slides.js')
"""Names of theme files directly linked to in the output HTML"""
indirect_theme_files = (
's5-core.css', 'framing.css', 'pretty.css', 'blank.gif', 'iepngfix.htc')
"""Names of files used indirectly; imported or used by files in
`direct_theme_files`."""
required_theme_files = indirect_theme_files + direct_theme_files
"""Names of mandatory theme files."""
def __init__(self, *args):
html4css1.HTMLTranslator.__init__(self, *args)
#insert S5-specific stylesheet and script stuff:
self.theme_file_path = None
self.setup_theme()
view_mode = self.document.settings.view_mode
control_visibility = ('visible', 'hidden')[self.document.settings
.hidden_controls]
self.stylesheet.append(self.s5_stylesheet_template
% {'path': self.theme_file_path,
'view_mode': view_mode,
'control_visibility': control_visibility})
if not self.document.settings.current_slide:
self.stylesheet.append(self.disable_current_slide)
self.add_meta('<meta name="version" content="S5 1.1" />\n')
self.s5_footer = []
self.s5_header = []
self.section_count = 0
self.theme_files_copied = None
def setup_theme(self):
if self.document.settings.theme:
self.copy_theme()
elif self.document.settings.theme_url:
self.theme_file_path = self.document.settings.theme_url
else:
raise docutils.ApplicationError(
'No theme specified for S5/HTML writer.')
def copy_theme(self):
"""
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'.
"""
settings = self.document.settings
path = find_theme(settings.theme)
theme_paths = [path]
self.theme_files_copied = {}
required_files_copied = {}
# This is a link (URL) in HTML, so we use "/", not os.sep:
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:
# no destination, so we can't copy the theme
return
default = 0
while path:
for f in os.listdir(path): # copy all files from each theme
if f == self.base_theme_file:
continue # ... except the "__base__" file
if ( self.copy_file(f, path, dest)
and f in self.required_theme_files):
required_files_copied[f] = 1
if default:
break # "default" theme has no base theme
# Find the "__base__" file in theme directory:
base_theme_file = os.path.join(path, self.base_theme_file)
# If it exists, read it and record the theme path:
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: # check for duplicates (cycles)
path = None # if found, use default base
else:
theme_paths.append(path)
break
else: # no theme name found
path = None # use default base
else: # no base theme file found
path = None # use default base
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):
# Some required files weren't found & couldn't be copied.
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]))
files_to_skip_pattern = re.compile(r'~$|\.bak$|#$|\.cvsignore$')
def copy_file(self, name, source_dir, dest_dir):
"""
Copy file `name` from `source_dir` to `dest_dir`.
Return 1 if the file exists in either `source_dir` or `dest_dir`.
"""
source = os.path.join(source_dir, name)
dest = os.path.join(dest_dir, name)
if dest in self.theme_files_copied:
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(
b('ui/default'),
dest_dir[dest_dir.rfind('ui/'):].encode(
sys.getfilesystemencoding())))
dest_file.close()
settings.record_dependencies.add(source)
return 1
if os.path.isfile(dest):
return 1
def depart_document(self, node):
header = ''.join(self.s5_header)
footer = ''.join(self.s5_footer)
title = ''.join(self.html_title).replace('<h1 class="title">', '<h1>')
layout = self.layout_template % {'header': header,
'title': title,
'footer': footer}
self.fragment.extend(self.body)
self.body_prefix.extend(layout)
self.body_prefix.append('<div class="presentation">\n')
self.body_prefix.append(
self.starttag({'classes': ['slide'], 'ids': ['slide0']}, 'div'))
if not self.section_count:
self.body.append('</div>\n')
self.body_suffix.insert(0, '</div>\n')
# skip content-type meta tag with interpolated charset value:
self.html_head.extend(self.head[1:])
self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
+ self.docinfo + self.body
+ self.body_suffix[:-1])
def depart_footer(self, node):
start = self.context.pop()
self.s5_footer.append('<h2>')
self.s5_footer.extend(self.body[start:])
self.s5_footer.append('</h2>')
del self.body[start:]
def depart_header(self, node):
start = self.context.pop()
header = ['<div id="header">\n']
header.extend(self.body[start:])
header.append('\n</div>\n')
del self.body[start:]
self.s5_header.extend(header)
def visit_section(self, node):
if not self.section_count:
self.body.append('\n</div>\n')
self.section_count += 1
self.section_level += 1
if self.section_level > 1:
# dummy for matching div's
self.body.append(self.starttag(node, 'div', CLASS='section'))
else:
self.body.append(self.starttag(node, 'div', CLASS='slide'))
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.section):
level = self.section_level + self.initial_header_level - 1
if level == 1:
level = 2
tag = 'h%s' % level
self.body.append(self.starttag(node, tag, ''))
self.context.append('</%s>\n' % tag)
else:
html4css1.HTMLTranslator.visit_subtitle(self, node)
def visit_title(self, node):
html4css1.HTMLTranslator.visit_title(self, node)
| {
"repo_name": "clumsy/intellij-community",
"path": "python/helpers/py2only/docutils/writers/s5_html/__init__.py",
"copies": "5",
"size": "13959",
"license": "apache-2.0",
"hash": 5248223182164354000,
"line_mean": 40.1769911504,
"line_max": 80,
"alpha_frac": 0.5602836879,
"autogenerated": false,
"ratio": 3.967879476975554,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0003748075822729314,
"num_lines": 339
} |
"""
S5/HTML Slideshow Writer.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import re
import docutils
from docutils import frontend, nodes, utils
from docutils.writers import html4css1
from docutils.parsers.rst import directives
from docutils._compat import b
themes_dir_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), 'themes'))
def find_theme(name):
# Where else to look for a theme?
# Check working dir? Destination dir? Config dir? Plugins dir?
path = os.path.join(themes_dir_path, name)
if not os.path.isdir(path):
raise docutils.ApplicationError(
'Theme directory not found: %r (path: %r)' % (name, path))
return path
class Writer(html4css1.Writer):
settings_spec = html4css1.Writer.settings_spec + (
'S5 Slideshow Specific Options',
'For the S5/HTML writer, the --no-toc-backlinks option '
'(defined in General Docutils Options above) is the default, '
'and should not be changed.',
(('Specify an installed S5 theme by name. Overrides --theme-url. '
'The default theme name is "default". The theme files will be '
'copied into a "ui/<theme>" directory, in the same directory as the '
'destination file (output HTML). Note that existing theme files '
'will not be overwritten (unless --overwrite-theme-files is used).',
['--theme'],
{'default': 'default', 'metavar': '<name>',
'overrides': 'theme_url'}),
('Specify an S5 theme URL. The destination file (output HTML) will '
'link to this theme; nothing will be copied. Overrides --theme.',
['--theme-url'],
{'metavar': '<URL>', 'overrides': 'theme'}),
('Allow existing theme files in the ``ui/<theme>`` directory to be '
'overwritten. The default is not to overwrite theme files.',
['--overwrite-theme-files'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Keep existing theme files in the ``ui/<theme>`` directory; do not '
'overwrite any. This is the default.',
['--keep-theme-files'],
{'dest': 'overwrite_theme_files', 'action': 'store_false'}),
('Set the initial view mode to "slideshow" [default] or "outline".',
['--view-mode'],
{'choices': ['slideshow', 'outline'], 'default': 'slideshow',
'metavar': '<mode>'}),
('Normally hide the presentation controls in slideshow mode. '
'This is the default.',
['--hidden-controls'],
{'action': 'store_true', 'default': True,
'validator': frontend.validate_boolean}),
('Always show the presentation controls in slideshow mode. '
'The default is to hide the controls.',
['--visible-controls'],
{'dest': 'hidden_controls', 'action': 'store_false'}),
('Enable the current slide indicator ("1 / 15"). '
'The default is to disable it.',
['--current-slide'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Disable the current slide indicator. This is the default.',
['--no-current-slide'],
{'dest': 'current_slide', 'action': 'store_false'}),))
settings_default_overrides = {'toc_backlinks': 0}
config_section = 's5_html writer'
config_section_dependencies = ('writers', 'html4css1 writer')
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = S5HTMLTranslator
class S5HTMLTranslator(html4css1.HTMLTranslator):
s5_stylesheet_template = """\
<!-- configuration parameters -->
<meta name="defaultView" content="%(view_mode)s" />
<meta name="controlVis" content="%(control_visibility)s" />
<!-- style sheet links -->
<script src="%(path)s/slides.js" type="text/javascript"></script>
<link rel="stylesheet" href="%(path)s/slides.css"
type="text/css" media="projection" id="slideProj" />
<link rel="stylesheet" href="%(path)s/outline.css"
type="text/css" media="screen" id="outlineStyle" />
<link rel="stylesheet" href="%(path)s/print.css"
type="text/css" media="print" id="slidePrint" />
<link rel="stylesheet" href="%(path)s/opera.css"
type="text/css" media="projection" id="operaFix" />\n"""
# The script element must go in front of the link elements to
# avoid a flash of unstyled content (FOUC), reproducible with
# Firefox.
disable_current_slide = """
<style type="text/css">
#currentSlide {display: none;}
</style>\n"""
layout_template = """\
<div class="layout">
<div id="controls"></div>
<div id="currentSlide"></div>
<div id="header">
%(header)s
</div>
<div id="footer">
%(title)s%(footer)s
</div>
</div>\n"""
# <div class="topleft"></div>
# <div class="topright"></div>
# <div class="bottomleft"></div>
# <div class="bottomright"></div>
default_theme = 'default'
"""Name of the default theme."""
base_theme_file = '__base__'
"""Name of the file containing the name of the base theme."""
direct_theme_files = (
'slides.css', 'outline.css', 'print.css', 'opera.css', 'slides.js')
"""Names of theme files directly linked to in the output HTML"""
indirect_theme_files = (
's5-core.css', 'framing.css', 'pretty.css', 'blank.gif', 'iepngfix.htc')
"""Names of files used indirectly; imported or used by files in
`direct_theme_files`."""
required_theme_files = indirect_theme_files + direct_theme_files
"""Names of mandatory theme files."""
def __init__(self, *args):
html4css1.HTMLTranslator.__init__(self, *args)
#insert S5-specific stylesheet and script stuff:
self.theme_file_path = None
self.setup_theme()
view_mode = self.document.settings.view_mode
control_visibility = ('visible', 'hidden')[self.document.settings
.hidden_controls]
self.stylesheet.append(self.s5_stylesheet_template
% {'path': self.theme_file_path,
'view_mode': view_mode,
'control_visibility': control_visibility})
if not self.document.settings.current_slide:
self.stylesheet.append(self.disable_current_slide)
self.add_meta('<meta name="version" content="S5 1.1" />\n')
self.s5_footer = []
self.s5_header = []
self.section_count = 0
self.theme_files_copied = None
def setup_theme(self):
if self.document.settings.theme:
self.copy_theme()
elif self.document.settings.theme_url:
self.theme_file_path = self.document.settings.theme_url
else:
raise docutils.ApplicationError(
'No theme specified for S5/HTML writer.')
def copy_theme(self):
"""
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'.
"""
settings = self.document.settings
path = find_theme(settings.theme)
theme_paths = [path]
self.theme_files_copied = {}
required_files_copied = {}
# This is a link (URL) in HTML, so we use "/", not os.sep:
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:
# no destination, so we can't copy the theme
return
default = 0
while path:
for f in os.listdir(path): # copy all files from each theme
if f == self.base_theme_file:
continue # ... except the "__base__" file
if ( self.copy_file(f, path, dest)
and f in self.required_theme_files):
required_files_copied[f] = 1
if default:
break # "default" theme has no base theme
# Find the "__base__" file in theme directory:
base_theme_file = os.path.join(path, self.base_theme_file)
# If it exists, read it and record the theme path:
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: # check for duplicates (cycles)
path = None # if found, use default base
else:
theme_paths.append(path)
break
else: # no theme name found
path = None # use default base
else: # no base theme file found
path = None # use default base
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):
# Some required files weren't found & couldn't be copied.
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]))
files_to_skip_pattern = re.compile(r'~$|\.bak$|#$|\.cvsignore$')
def copy_file(self, name, source_dir, dest_dir):
"""
Copy file `name` from `source_dir` to `dest_dir`.
Return 1 if the file exists in either `source_dir` or `dest_dir`.
"""
source = os.path.join(source_dir, name)
dest = os.path.join(dest_dir, name)
if dest in self.theme_files_copied:
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(
b('ui/default'),
dest_dir[dest_dir.rfind('ui/'):].encode(
sys.getfilesystemencoding())))
dest_file.close()
settings.record_dependencies.add(source)
return 1
if os.path.isfile(dest):
return 1
def depart_document(self, node):
header = ''.join(self.s5_header)
footer = ''.join(self.s5_footer)
title = ''.join(self.html_title).replace('<h1 class="title">', '<h1>')
layout = self.layout_template % {'header': header,
'title': title,
'footer': footer}
self.fragment.extend(self.body)
self.body_prefix.extend(layout)
self.body_prefix.append('<div class="presentation">\n')
self.body_prefix.append(
self.starttag({'classes': ['slide'], 'ids': ['slide0']}, 'div'))
if not self.section_count:
self.body.append('</div>\n')
self.body_suffix.insert(0, '</div>\n')
# skip content-type meta tag with interpolated charset value:
self.html_head.extend(self.head[1:])
self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
+ self.docinfo + self.body
+ self.body_suffix[:-1])
def depart_footer(self, node):
start = self.context.pop()
self.s5_footer.append('<h2>')
self.s5_footer.extend(self.body[start:])
self.s5_footer.append('</h2>')
del self.body[start:]
def depart_header(self, node):
start = self.context.pop()
header = ['<div id="header">\n']
header.extend(self.body[start:])
header.append('\n</div>\n')
del self.body[start:]
self.s5_header.extend(header)
def visit_section(self, node):
if not self.section_count:
self.body.append('\n</div>\n')
self.section_count += 1
self.section_level += 1
if self.section_level > 1:
# dummy for matching div's
self.body.append(self.starttag(node, 'div', CLASS='section'))
else:
self.body.append(self.starttag(node, 'div', CLASS='slide'))
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.section):
level = self.section_level + self.initial_header_level - 1
if level == 1:
level = 2
tag = 'h%s' % level
self.body.append(self.starttag(node, tag, ''))
self.context.append('</%s>\n' % tag)
else:
html4css1.HTMLTranslator.visit_subtitle(self, node)
def visit_title(self, node):
html4css1.HTMLTranslator.visit_title(self, node)
| {
"repo_name": "umitproject/tease-o-matic",
"path": "docutils/writers/s5_html/__init__.py",
"copies": "51",
"size": "14003",
"license": "bsd-3-clause",
"hash": 9143433466077451000,
"line_mean": 40.1852941176,
"line_max": 80,
"alpha_frac": 0.5612368778,
"autogenerated": false,
"ratio": 3.971355643788996,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
S5/HTML Slideshow Writer.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import re
import docutils
from docutils import frontend, nodes, utils
from docutils.writers import html4css1
from docutils.parsers.rst import directives
from docutils._compat import b
themes_dir_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), 'themes'))
def find_theme(name):
# Where else to look for a theme?
# Check working dir? Destination dir? Config dir? Plugins dir?
path = os.path.join(themes_dir_path, name)
if not os.path.isdir(path):
raise docutils.ApplicationError(
'Theme directory not found: %r (path: %r)' % (name, path))
return path
class Writer(html4css1.Writer):
settings_spec = html4css1.Writer.settings_spec + (
'S5 Slideshow Specific Options',
'For the S5/HTML writer, the --no-toc-backlinks option '
'(defined in General Docutils Options above) is the default, '
'and should not be changed.',
(('Specify an installed S5 theme by name. Overrides --theme-url. '
'The default theme name is "default". The theme files will be '
'copied into a "ui/<theme>" directory, in the same directory as the '
'destination file (output HTML). Note that existing theme files '
'will not be overwritten (unless --overwrite-theme-files is used).',
['--theme'],
{'default': 'default', 'metavar': '<name>',
'overrides': 'theme_url'}),
('Specify an S5 theme URL. The destination file (output HTML) will '
'link to this theme; nothing will be copied. Overrides --theme.',
['--theme-url'],
{'metavar': '<URL>', 'overrides': 'theme'}),
('Allow existing theme files in the ``ui/<theme>`` directory to be '
'overwritten. The default is not to overwrite theme files.',
['--overwrite-theme-files'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Keep existing theme files in the ``ui/<theme>`` directory; do not '
'overwrite any. This is the default.',
['--keep-theme-files'],
{'dest': 'overwrite_theme_files', 'action': 'store_false'}),
('Set the initial view mode to "slideshow" [default] or "outline".',
['--view-mode'],
{'choices': ['slideshow', 'outline'], 'default': 'slideshow',
'metavar': '<mode>'}),
('Normally hide the presentation controls in slideshow mode. '
'This is the default.',
['--hidden-controls'],
{'action': 'store_true', 'default': True,
'validator': frontend.validate_boolean}),
('Always show the presentation controls in slideshow mode. '
'The default is to hide the controls.',
['--visible-controls'],
{'dest': 'hidden_controls', 'action': 'store_false'}),
('Enable the current slide indicator ("1 / 15"). '
'The default is to disable it.',
['--current-slide'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Disable the current slide indicator. This is the default.',
['--no-current-slide'],
{'dest': 'current_slide', 'action': 'store_false'}),))
settings_default_overrides = {'toc_backlinks': 0}
config_section = 's5_html writer'
config_section_dependencies = ('writers', 'html4css1 writer')
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = S5HTMLTranslator
class S5HTMLTranslator(html4css1.HTMLTranslator):
s5_stylesheet_template = """\
<!-- configuration parameters -->
<meta name="defaultView" content="%(view_mode)s" />
<meta name="controlVis" content="%(control_visibility)s" />
<!-- style sheet links -->
<script src="%(path)s/slides.js" type="text/javascript"></script>
<link rel="stylesheet" href="%(path)s/slides.css"
type="text/css" media="projection" id="slideProj" />
<link rel="stylesheet" href="%(path)s/outline.css"
type="text/css" media="screen" id="outlineStyle" />
<link rel="stylesheet" href="%(path)s/print.css"
type="text/css" media="print" id="slidePrint" />
<link rel="stylesheet" href="%(path)s/opera.css"
type="text/css" media="projection" id="operaFix" />\n"""
# The script element must go in front of the link elements to
# avoid a flash of unstyled content (FOUC), reproducible with
# Firefox.
disable_current_slide = """
<style type="text/css">
#currentSlide {display: none;}
</style>\n"""
layout_template = """\
<div class="layout">
<div id="controls"></div>
<div id="currentSlide"></div>
<div id="header">
%(header)s
</div>
<div id="footer">
%(title)s%(footer)s
</div>
</div>\n"""
# <div class="topleft"></div>
# <div class="topright"></div>
# <div class="bottomleft"></div>
# <div class="bottomright"></div>
default_theme = 'default'
"""Name of the default theme."""
base_theme_file = '__base__'
"""Name of the file containing the name of the base theme."""
direct_theme_files = (
'slides.css', 'outline.css', 'print.css', 'opera.css', 'slides.js')
"""Names of theme files directly linked to in the output HTML"""
indirect_theme_files = (
's5-core.css', 'framing.css', 'pretty.css', 'blank.gif', 'iepngfix.htc')
"""Names of files used indirectly; imported or used by files in
`direct_theme_files`."""
required_theme_files = indirect_theme_files + direct_theme_files
"""Names of mandatory theme files."""
def __init__(self, *args):
html4css1.HTMLTranslator.__init__(self, *args)
#insert S5-specific stylesheet and script stuff:
self.theme_file_path = None
self.setup_theme()
view_mode = self.document.settings.view_mode
control_visibility = ('visible', 'hidden')[self.document.settings
.hidden_controls]
self.stylesheet.append(self.s5_stylesheet_template
% {'path': self.theme_file_path,
'view_mode': view_mode,
'control_visibility': control_visibility})
if not self.document.settings.current_slide:
self.stylesheet.append(self.disable_current_slide)
self.add_meta('<meta name="version" content="S5 1.1" />\n')
self.s5_footer = []
self.s5_header = []
self.section_count = 0
self.theme_files_copied = None
def setup_theme(self):
if self.document.settings.theme:
self.copy_theme()
elif self.document.settings.theme_url:
self.theme_file_path = self.document.settings.theme_url
else:
raise docutils.ApplicationError(
'No theme specified for S5/HTML writer.')
def copy_theme(self):
"""
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'.
"""
settings = self.document.settings
path = find_theme(settings.theme)
theme_paths = [path]
self.theme_files_copied = {}
required_files_copied = {}
# This is a link (URL) in HTML, so we use "/", not os.sep:
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:
# no destination, so we can't copy the theme
return
default = 0
while path:
for f in os.listdir(path): # copy all files from each theme
if f == self.base_theme_file:
continue # ... except the "__base__" file
if ( self.copy_file(f, path, dest)
and f in self.required_theme_files):
required_files_copied[f] = 1
if default:
break # "default" theme has no base theme
# Find the "__base__" file in theme directory:
base_theme_file = os.path.join(path, self.base_theme_file)
# If it exists, read it and record the theme path:
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: # check for duplicates (cycles)
path = None # if found, use default base
else:
theme_paths.append(path)
break
else: # no theme name found
path = None # use default base
else: # no base theme file found
path = None # use default base
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):
# Some required files weren't found & couldn't be copied.
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]))
files_to_skip_pattern = re.compile(r'~$|\.bak$|#$|\.cvsignore$')
def copy_file(self, name, source_dir, dest_dir):
"""
Copy file `name` from `source_dir` to `dest_dir`.
Return 1 if the file exists in either `source_dir` or `dest_dir`.
"""
source = os.path.join(source_dir, name)
dest = os.path.join(dest_dir, name)
if dest in self.theme_files_copied:
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(
b('ui/default'),
dest_dir[dest_dir.rfind('ui/'):].encode(
sys.getfilesystemencoding())))
dest_file.close()
settings.record_dependencies.add(source)
return 1
if os.path.isfile(dest):
return 1
def depart_document(self, node):
header = ''.join(self.s5_header)
footer = ''.join(self.s5_footer)
title = ''.join(self.html_title).replace('<h1 class="title">', '<h1>')
layout = self.layout_template % {'header': header,
'title': title,
'footer': footer}
self.fragment.extend(self.body)
self.body_prefix.extend(layout)
self.body_prefix.append('<div class="presentation">\n')
self.body_prefix.append(
self.starttag({'classes': ['slide'], 'ids': ['slide0']}, 'div'))
if not self.section_count:
self.body.append('</div>\n')
self.body_suffix.insert(0, '</div>\n')
# skip content-type meta tag with interpolated charset value:
self.html_head.extend(self.head[1:])
self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
+ self.docinfo + self.body
+ self.body_suffix[:-1])
def depart_footer(self, node):
start = self.context.pop()
self.s5_footer.append('<h2>')
self.s5_footer.extend(self.body[start:])
self.s5_footer.append('</h2>')
del self.body[start:]
def depart_header(self, node):
start = self.context.pop()
header = ['<div id="header">\n']
header.extend(self.body[start:])
header.append('\n</div>\n')
del self.body[start:]
self.s5_header.extend(header)
def visit_section(self, node):
if not self.section_count:
self.body.append('\n</div>\n')
self.section_count += 1
self.section_level += 1
if self.section_level > 1:
# dummy for matching div's
self.body.append(self.starttag(node, 'div', CLASS='section'))
else:
self.body.append(self.starttag(node, 'div', CLASS='slide'))
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.section):
level = self.section_level + self.initial_header_level - 1
if level == 1:
level = 2
tag = 'h%s' % level
self.body.append(self.starttag(node, tag, ''))
self.context.append('</%s>\n' % tag)
else:
html4css1.HTMLTranslator.visit_subtitle(self, node)
def visit_title(self, node):
html4css1.HTMLTranslator.visit_title(self, node)
| {
"repo_name": "rimbalinux/MSISDNArea",
"path": "docutils/writers/s5_html/__init__.py",
"copies": "2",
"size": "14343",
"license": "bsd-3-clause",
"hash": 8433276496553163000,
"line_mean": 40.1852941176,
"line_max": 80,
"alpha_frac": 0.5479327895,
"autogenerated": false,
"ratio": 4.015397536394177,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005529638055609647,
"num_lines": 340
} |
"""
Simple HyperText Markup Language document tree Writer.
The output conforms to the XHTML version 1.0 Transitional DTD
(*almost* strict). The output contains a minimum of formatting
information. The cascading style sheet "html4css1.css" is required
for proper viewing with a modern graphical browser.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import time
import re
try:
import Image # check for the Python Imaging Library
except ImportError:
Image = None
import docutils
from docutils import frontend, nodes, utils, writers, languages
from docutils.transforms import writer_aux
class Writer(writers.Writer):
supported = ('html', 'html4css1', 'xhtml')
"""Formats this writer supports."""
default_stylesheet = 'html4css1.css'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = (
'HTML-Specific Options',
None,
(('Specify the template file (UTF-8 encoded). Default is "%s".'
% default_template_path,
['--template'],
{'default': default_template_path, 'metavar': '<file>'}),
('Specify comma separated list of stylesheet URLs. '
'Overrides previous --stylesheet and --stylesheet-path settings.',
['--stylesheet'],
{'metavar': '<URL>', 'overrides': 'stylesheet_path'}),
('Like --stylesheet, '
'but a relative path is converted from relative to the current '
'working directory to relative to the output HTML file. '
'Default: "%s"' % default_stylesheet_path,
['--stylesheet-path'],
{'metavar': '<file>', 'overrides': 'stylesheet',
'default': default_stylesheet_path}),
('Embed the stylesheet(s) in the output HTML file. The stylesheet '
'files must be accessible during processing (--stylesheet-path is '
'recommended). This is the default.',
['--embed-stylesheet'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Link to the stylesheet(s) in the output HTML file. '
'Default: embed stylesheets.',
['--link-stylesheet'],
{'dest': 'embed_stylesheet', 'action': 'store_false'}),
('Specify the initial header level. Default is 1 for "<h1>". '
'Does not affect document title & subtitle (see --no-doc-title).',
['--initial-header-level'],
{'choices': '1 2 3 4 5 6'.split(), 'default': '1',
'metavar': '<level>'}),
('Specify the maximum width (in characters) for one-column field '
'names. Longer field names will span an entire row of the table '
'used to render the field list. Default is 14 characters. '
'Use 0 for "no limit".',
['--field-name-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
('Specify the maximum width (in characters) for options in option '
'lists. Longer options will span an entire row of the table used '
'to render the option list. Default is 14 characters. '
'Use 0 for "no limit".',
['--option-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
('Format for footnote references: one of "superscript" or '
'"brackets". Default is "brackets".',
['--footnote-references'],
{'choices': ['superscript', 'brackets'], 'default': 'brackets',
'metavar': '<format>',
'overrides': 'trim_footnote_reference_space'}),
('Format for block quote attributions: one of "dash" (em-dash '
'prefix), "parentheses"/"parens", or "none". Default is "dash".',
['--attribution'],
{'choices': ['dash', 'parentheses', 'parens', 'none'],
'default': 'dash', 'metavar': '<format>'}),
('Remove extra vertical whitespace between items of "simple" bullet '
'lists and enumerated lists. Default: enabled.',
['--compact-lists'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compact simple bullet and enumerated lists.',
['--no-compact-lists'],
{'dest': 'compact_lists', 'action': 'store_false'}),
('Remove extra vertical whitespace between items of simple field '
'lists. Default: enabled.',
['--compact-field-lists'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compact simple field lists.',
['--no-compact-field-lists'],
{'dest': 'compact_field_lists', 'action': 'store_false'}),
('Omit the XML declaration. Use with caution.',
['--no-xml-declaration'],
{'dest': 'xml_declaration', 'default': 1, 'action': 'store_false',
'validator': frontend.validate_boolean}),
('Obfuscate email addresses to confuse harvesters while still '
'keeping email links usable with standards-compliant browsers.',
['--cloak-email-addresses'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),))
settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'}
relative_path_settings = ('stylesheet_path',)
config_section = 'html4css1 writer'
config_section_dependencies = ('writers',)
visitor_attributes = (
'head_prefix', 'head', 'stylesheet', 'body_prefix',
'body_pre_docinfo', 'docinfo', 'body', 'body_suffix',
'title', 'subtitle', 'header', 'footer', 'meta', 'fragment',
'html_prolog', 'html_head', 'html_title', 'html_subtitle',
'html_body')
def get_transforms(self):
return writers.Writer.get_transforms(self) + [writer_aux.Admonitions]
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = HTMLTranslator
def translate(self):
self.visitor = visitor = self.translator_class(self.document)
self.document.walkabout(visitor)
for attr in self.visitor_attributes:
setattr(self, attr, getattr(visitor, attr))
self.output = self.apply_template()
def apply_template(self):
template_file = open(self.document.settings.template, 'rb')
template = unicode(template_file.read(), 'utf-8')
template_file.close()
subs = self.interpolation_dict()
return template % subs
def interpolation_dict(self):
subs = {}
settings = self.document.settings
for attr in self.visitor_attributes:
subs[attr] = ''.join(getattr(self, attr)).rstrip('\n')
subs['encoding'] = settings.output_encoding
subs['version'] = docutils.__version__
return subs
def assemble_parts(self):
writers.Writer.assemble_parts(self)
for part in self.visitor_attributes:
self.parts[part] = ''.join(getattr(self, part))
class HTMLTranslator(nodes.NodeVisitor):
"""
This HTML writer has been optimized to produce visually compact
lists (less vertical whitespace). HTML's mixed content models
allow list items to contain "<li><p>body elements</p></li>" or
"<li>just text</li>" or even "<li>text<p>and body
elements</p>combined</li>", each with different effects. It would
be best to stick with strict body elements in list items, but they
affect vertical spacing in browsers (although they really
shouldn't).
Here is an outline of the optimization:
- Check for and omit <p> tags in "simple" lists: list items
contain either a single paragraph, a nested simple list, or a
paragraph followed by a nested simple list. This means that
this list can be compact:
- Item 1.
- Item 2.
But this list cannot be compact:
- Item 1.
This second paragraph forces space between list items.
- Item 2.
- In non-list contexts, omit <p> tags on a paragraph if that
paragraph is the only child of its parent (footnotes & citations
are allowed a label first).
- Regardless of the above, in definitions, table cells, field bodies,
option descriptions, and list items, mark the first child with
'class="first"' and the last child with 'class="last"'. The stylesheet
sets the margins (top & bottom respectively) to 0 for these elements.
The ``no_compact_lists`` setting (``--no-compact-lists`` command-line
option) disables list whitespace optimization.
"""
xml_declaration = '<?xml version="1.0" encoding="%s" ?>\n'
doctype = (
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
head_prefix_template = ('<html xmlns="http://www.w3.org/1999/xhtml"'
' xml:lang="%s" lang="%s">\n<head>\n')
content_type = ('<meta http-equiv="Content-Type"'
' content="text/html; charset=%s" />\n')
generator = ('<meta name="generator" content="Docutils %s: '
'http://docutils.sourceforge.net/" />\n')
stylesheet_link = '<link rel="stylesheet" href="%s" type="text/css" />\n'
embedded_stylesheet = '<style type="text/css">\n\n%s\n</style>\n'
words_and_spaces = re.compile(r'\S+| +|\n')
def __init__(self, document):
nodes.NodeVisitor.__init__(self, document)
self.settings = settings = document.settings
lcode = settings.language_code
self.language = languages.get_language(lcode)
self.meta = [self.content_type % settings.output_encoding,
self.generator % docutils.__version__]
self.head_prefix = []
self.html_prolog = []
if settings.xml_declaration:
self.head_prefix.append(self.xml_declaration
% settings.output_encoding)
# encoding not interpolated:
self.html_prolog.append(self.xml_declaration)
self.head_prefix.extend([self.doctype,
self.head_prefix_template % (lcode, lcode)])
self.html_prolog.append(self.doctype)
self.head = self.meta[:]
# stylesheets
styles = utils.get_stylesheet_list(settings)
if settings.stylesheet_path and not(settings.embed_stylesheet):
styles = [utils.relative_path(settings._destination, sheet)
for sheet in styles]
if settings.embed_stylesheet:
settings.record_dependencies.add(*styles)
self.stylesheet = [self.embedded_stylesheet % open(sheet).read()
for sheet in styles]
else: # link to stylesheets
self.stylesheet = [self.stylesheet_link % self.encode(stylesheet)
for stylesheet in styles]
self.body_prefix = ['</head>\n<body>\n']
# document title, subtitle display
self.body_pre_docinfo = []
# author, date, etc.
self.docinfo = []
self.body = []
self.fragment = []
self.body_suffix = ['</body>\n</html>\n']
self.section_level = 0
self.initial_header_level = int(settings.initial_header_level)
# A heterogenous stack used in conjunction with the tree traversal.
# Make sure that the pops correspond to the pushes:
self.context = []
self.topic_classes = []
self.colspecs = []
self.compact_p = 1
self.compact_simple = None
self.compact_field_list = None
self.in_docinfo = None
self.in_sidebar = None
self.title = []
self.subtitle = []
self.header = []
self.footer = []
self.html_head = [self.content_type] # charset not interpolated
self.html_title = []
self.html_subtitle = []
self.html_body = []
self.in_document_title = 0
self.in_mailto = 0
self.author_in_authors = None
def astext(self):
return ''.join(self.head_prefix + self.head
+ self.stylesheet + self.body_prefix
+ self.body_pre_docinfo + self.docinfo
+ self.body + self.body_suffix)
def encode(self, text):
"""Encode special characters in `text` & return."""
# @@@ A codec to do these and all other HTML entities would be nice.
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace('"', """)
text = text.replace(">", ">")
text = text.replace("@", "@") # may thwart some address harvesters
# Replace the non-breaking space character with the HTML entity:
text = text.replace(u'\u00a0', " ")
return text
def cloak_mailto(self, uri):
"""Try to hide a mailto: URL from harvesters."""
# Encode "@" using a URL octet reference (see RFC 1738).
# Further cloaking with HTML entities will be done in the
# `attval` function.
return uri.replace('@', '%40')
def cloak_email(self, addr):
"""Try to hide the link text of a email link from harversters."""
# Surround at-signs and periods with <span> tags. ("@" has
# already been encoded to "@" by the `encode` method.)
addr = addr.replace('@', '<span>@</span>')
addr = addr.replace('.', '<span>.</span>')
return addr
def attval(self, text,
whitespace=re.compile('[\n\r\t\v\f]')):
"""Cleanse, HTML encode, and return attribute value text."""
encoded = self.encode(whitespace.sub(' ', text))
if self.in_mailto and self.settings.cloak_email_addresses:
# Cloak at-signs ("%40") and periods with HTML entities.
encoded = encoded.replace('%40', '%40')
encoded = encoded.replace('.', '.')
return encoded
def starttag(self, node, tagname, suffix='\n', empty=0, **attributes):
"""
Construct and return a start tag given a node (id & class attributes
are extracted), tag name, and optional attributes.
"""
tagname = tagname.lower()
prefix = []
atts = {}
ids = []
for (name, value) in attributes.items():
atts[name.lower()] = value
classes = node.get('classes', [])
if 'class' in atts:
classes.append(atts['class'])
if classes:
atts['class'] = ' '.join(classes)
assert 'id' not in atts
ids.extend(node.get('ids', []))
if 'ids' in atts:
ids.extend(atts['ids'])
del atts['ids']
if ids:
atts['id'] = ids[0]
for id in ids[1:]:
# Add empty "span" elements for additional IDs. Note
# that we cannot use empty "a" elements because there
# may be targets inside of references, but nested "a"
# elements aren't allowed in XHTML (even if they do
# not all have a "href" attribute).
if empty:
# Empty tag. Insert target right in front of element.
prefix.append('<span id="%s"></span>' % id)
else:
# Non-empty tag. Place the auxiliary <span> tag
# *inside* the element, as the first child.
suffix += '<span id="%s"></span>' % id
attlist = atts.items()
attlist.sort()
parts = [tagname]
for name, value in attlist:
# value=None was used for boolean attributes without
# value, but this isn't supported by XHTML.
assert value is not None
if isinstance(value, list):
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
def emptytag(self, node, tagname, suffix='\n', **attributes):
"""Construct and return an XML-compatible empty tag."""
return self.starttag(node, tagname, suffix, empty=1, **attributes)
def set_class_on_child(self, node, class_, index=0):
"""
Set class `class_` on the visible child no. index of `node`.
Do nothing if node has fewer children than `index`.
"""
children = [n for n in node if not isinstance(n, nodes.Invisible)]
try:
child = children[index]
except IndexError:
return
child['classes'].append(class_)
def set_first_last(self, node):
self.set_class_on_child(node, 'first', 0)
self.set_class_on_child(node, 'last', -1)
def visit_Text(self, node):
text = node.astext()
encoded = self.encode(text)
if self.in_mailto and self.settings.cloak_email_addresses:
encoded = self.cloak_email(encoded)
self.body.append(encoded)
def depart_Text(self, node):
pass
def visit_abbreviation(self, node):
# @@@ implementation incomplete ("title" attribute)
self.body.append(self.starttag(node, 'abbr', ''))
def depart_abbreviation(self, node):
self.body.append('</abbr>')
def visit_acronym(self, node):
# @@@ implementation incomplete ("title" attribute)
self.body.append(self.starttag(node, 'acronym', ''))
def depart_acronym(self, node):
self.body.append('</acronym>')
def visit_address(self, node):
self.visit_docinfo_item(node, 'address', meta=None)
self.body.append(self.starttag(node, 'pre', CLASS='address'))
def depart_address(self, node):
self.body.append('\n</pre>\n')
self.depart_docinfo_item()
def visit_admonition(self, node):
self.body.append(self.starttag(node, 'div'))
self.set_first_last(node)
def depart_admonition(self, node=None):
self.body.append('</div>\n')
attribution_formats = {'dash': ('—', ''),
'parentheses': ('(', ')'),
'parens': ('(', ')'),
'none': ('', '')}
def visit_attribution(self, node):
prefix, suffix = self.attribution_formats[self.settings.attribution]
self.context.append(suffix)
self.body.append(
self.starttag(node, 'p', prefix, CLASS='attribution'))
def depart_attribution(self, node):
self.body.append(self.context.pop() + '</p>\n')
def visit_author(self, node):
if isinstance(node.parent, nodes.authors):
if self.author_in_authors:
self.body.append('\n<br />')
else:
self.visit_docinfo_item(node, 'author')
def depart_author(self, node):
if isinstance(node.parent, nodes.authors):
self.author_in_authors += 1
else:
self.depart_docinfo_item()
def visit_authors(self, node):
self.visit_docinfo_item(node, 'authors')
self.author_in_authors = 0 # initialize counter
def depart_authors(self, node):
self.depart_docinfo_item()
self.author_in_authors = None
def visit_block_quote(self, node):
self.body.append(self.starttag(node, 'blockquote'))
def depart_block_quote(self, node):
self.body.append('</blockquote>\n')
def check_simple_list(self, node):
"""Check for a simple list that can be rendered compactly."""
visitor = SimpleListChecker(self.document)
try:
node.walk(visitor)
except nodes.NodeFound:
return None
else:
return 1
def is_compactable(self, node):
return ('compact' in node['classes']
or (self.settings.compact_lists
and 'open' not in node['classes']
and (self.compact_simple
or self.topic_classes == ['contents']
or self.check_simple_list(node))))
def visit_bullet_list(self, node):
atts = {}
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'] = 'simple'
self.body.append(self.starttag(node, 'ul', **atts))
def depart_bullet_list(self, node):
self.compact_simple, self.compact_p = self.context.pop()
self.body.append('</ul>\n')
def visit_caption(self, node):
self.body.append(self.starttag(node, 'p', '', CLASS='caption'))
def depart_caption(self, node):
self.body.append('</p>\n')
def visit_citation(self, node):
self.body.append(self.starttag(node, 'table',
CLASS='docutils citation',
frame="void", rules="none"))
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n'
'<tbody valign="top">\n'
'<tr>')
self.footnote_backrefs(node)
def depart_citation(self, node):
self.body.append('</td></tr>\n'
'</tbody>\n</table>\n')
def visit_citation_reference(self, node):
href = '#' + node['refid']
self.body.append(self.starttag(
node, 'a', '[', CLASS='citation-reference', href=href))
def depart_citation_reference(self, node):
self.body.append(']</a>')
def visit_classifier(self, node):
self.body.append(' <span class="classifier-delimiter">:</span> ')
self.body.append(self.starttag(node, 'span', '', CLASS='classifier'))
def depart_classifier(self, node):
self.body.append('</span>')
def visit_colspec(self, node):
self.colspecs.append(node)
# "stubs" list is an attribute of the tgroup element:
node.parent.stubs.append(node.attributes.get('stub'))
def depart_colspec(self, node):
pass
def write_colspecs(self):
width = 0
for node in self.colspecs:
width += node['colwidth']
for node in self.colspecs:
colwidth = int(node['colwidth'] * 100.0 / width + 0.5)
self.body.append(self.emptytag(node, 'col',
width='%i%%' % colwidth))
self.colspecs = []
def visit_comment(self, node,
sub=re.compile('-(?=-)').sub):
"""Escape double-dashes in comment text."""
self.body.append('<!-- %s -->\n' % sub('- ', node.astext()))
# Content already processed:
raise nodes.SkipNode
def visit_compound(self, node):
self.body.append(self.starttag(node, 'div', CLASS='compound'))
if len(node) > 1:
node[0]['classes'].append('compound-first')
node[-1]['classes'].append('compound-last')
for child in node[1:-1]:
child['classes'].append('compound-middle')
def depart_compound(self, node):
self.body.append('</div>\n')
def visit_container(self, node):
self.body.append(self.starttag(node, 'div', CLASS='container'))
def depart_container(self, node):
self.body.append('</div>\n')
def visit_contact(self, node):
self.visit_docinfo_item(node, 'contact', meta=None)
def depart_contact(self, node):
self.depart_docinfo_item()
def visit_copyright(self, node):
self.visit_docinfo_item(node, 'copyright')
def depart_copyright(self, node):
self.depart_docinfo_item()
def visit_date(self, node):
self.visit_docinfo_item(node, 'date')
def depart_date(self, node):
self.depart_docinfo_item()
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
self.body.append('</dt>\n')
self.body.append(self.starttag(node, 'dd', ''))
self.set_first_last(node)
def depart_definition(self, node):
self.body.append('</dd>\n')
def visit_definition_list(self, node):
self.body.append(self.starttag(node, 'dl', CLASS='docutils'))
def depart_definition_list(self, node):
self.body.append('</dl>\n')
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_description(self, node):
self.body.append(self.starttag(node, 'td', ''))
self.set_first_last(node)
def depart_description(self, node):
self.body.append('</td>')
def visit_docinfo(self, node):
self.context.append(len(self.body))
self.body.append(self.starttag(node, 'table',
CLASS='docinfo',
frame="void", rules="none"))
self.body.append('<col class="docinfo-name" />\n'
'<col class="docinfo-content" />\n'
'<tbody valign="top">\n')
self.in_docinfo = 1
def depart_docinfo(self, node):
self.body.append('</tbody>\n</table>\n')
self.in_docinfo = None
start = self.context.pop()
self.docinfo = self.body[start:]
self.body = []
def visit_docinfo_item(self, node, name, meta=1):
if meta:
meta_tag = '<meta name="%s" content="%s" />\n' \
% (name, self.attval(node.astext()))
self.add_meta(meta_tag)
self.body.append(self.starttag(node, 'tr', ''))
self.body.append('<th class="docinfo-name">%s:</th>\n<td>'
% self.language.labels[name])
if len(node):
if isinstance(node[0], nodes.Element):
node[0]['classes'].append('first')
if isinstance(node[-1], nodes.Element):
node[-1]['classes'].append('last')
def depart_docinfo_item(self):
self.body.append('</td></tr>\n')
def visit_doctest_block(self, node):
self.body.append(self.starttag(node, 'pre', CLASS='doctest-block'))
def depart_doctest_block(self, node):
self.body.append('\n</pre>\n')
def visit_document(self, node):
self.head.append('<title>%s</title>\n'
% self.encode(node.get('title', '')))
def depart_document(self, node):
self.fragment.extend(self.body)
self.body_prefix.append(self.starttag(node, 'div', CLASS='document'))
self.body_suffix.insert(0, '</div>\n')
# skip content-type meta tag with interpolated charset value:
self.html_head.extend(self.head[1:])
self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
+ self.docinfo + self.body
+ self.body_suffix[:-1])
assert not self.context, 'len(context) = %s' % len(self.context)
def visit_emphasis(self, node):
self.body.append(self.starttag(node, 'em', ''))
def depart_emphasis(self, node):
self.body.append('</em>')
def visit_entry(self, node):
atts = {'class': []}
if isinstance(node.parent.parent, nodes.thead):
atts['class'].append('head')
if node.parent.parent.parent.stubs[node.parent.column]:
# "stubs" list is an attribute of the tgroup element
atts['class'].append('stub')
if atts['class']:
tagname = 'th'
atts['class'] = ' '.join(atts['class'])
else:
tagname = 'td'
del atts['class']
node.parent.column += 1
if 'morerows' in node:
atts['rowspan'] = node['morerows'] + 1
if 'morecols' in node:
atts['colspan'] = node['morecols'] + 1
node.parent.column += node['morecols']
self.body.append(self.starttag(node, tagname, '', **atts))
self.context.append('</%s>\n' % tagname.lower())
if len(node) == 0: # empty cell
self.body.append(' ')
self.set_first_last(node)
def depart_entry(self, node):
self.body.append(self.context.pop())
def visit_enumerated_list(self, node):
"""
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.
"""
atts = {}
if 'start' in node:
atts['start'] = node['start']
if 'enumtype' in node:
atts['class'] = node['enumtype']
# @@@ To do: prefix, suffix. How? Change prefix/suffix to a
# single "format" attribute? Use CSS2?
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))
def depart_enumerated_list(self, node):
self.compact_simple, self.compact_p = self.context.pop()
self.body.append('</ol>\n')
def visit_field(self, node):
self.body.append(self.starttag(node, 'tr', '', CLASS='field'))
def depart_field(self, node):
self.body.append('</tr>\n')
def visit_field_body(self, node):
self.body.append(self.starttag(node, 'td', '', CLASS='field-body'))
self.set_class_on_child(node, 'first', 0)
field = node.parent
if (self.compact_field_list or
isinstance(field.parent, nodes.docinfo) or
field.parent.index(field) == len(field.parent) - 1):
# If we are in a compact list, the docinfo, or if this is
# the last field of the field list, do not add vertical
# space after last element.
self.set_class_on_child(node, 'last', -1)
def depart_field_body(self, node):
self.body.append('</td>\n')
def visit_field_list(self, node):
self.context.append((self.compact_field_list, self.compact_p))
self.compact_p = None
if 'compact' in node['classes']:
self.compact_field_list = 1
elif (self.settings.compact_field_lists
and 'open' not in node['classes']):
self.compact_field_list = 1
if self.compact_field_list:
for field in node:
field_body = field[-1]
assert isinstance(field_body, nodes.field_body)
children = [n for n in field_body
if not isinstance(n, nodes.Invisible)]
if not (len(children) == 0 or
len(children) == 1 and
isinstance(children[0],
(nodes.paragraph, nodes.line_block))):
self.compact_field_list = 0
break
self.body.append(self.starttag(node, 'table', frame='void',
rules='none',
CLASS='docutils field-list'))
self.body.append('<col class="field-name" />\n'
'<col class="field-body" />\n'
'<tbody valign="top">\n')
def depart_field_list(self, node):
self.body.append('</tbody>\n</table>\n')
self.compact_field_list, self.compact_p = self.context.pop()
def visit_field_name(self, node):
atts = {}
if self.in_docinfo:
atts['class'] = 'docinfo-name'
else:
atts['class'] = 'field-name'
if ( self.settings.field_name_limit
and len(node.astext()) > self.settings.field_name_limit):
atts['colspan'] = 2
self.context.append('</tr>\n<tr><td> </td>')
else:
self.context.append('')
self.body.append(self.starttag(node, 'th', '', **atts))
def depart_field_name(self, node):
self.body.append(':</th>')
self.body.append(self.context.pop())
def visit_figure(self, node):
atts = {'class': 'figure'}
if node.get('width'):
atts['style'] = 'width: %s' % node['width']
if node.get('align'):
atts['class'] += " align-" + node['align']
self.body.append(self.starttag(node, 'div', **atts))
def depart_figure(self, node):
self.body.append('</div>\n')
def visit_footer(self, node):
self.context.append(len(self.body))
def depart_footer(self, node):
start = self.context.pop()
footer = [self.starttag(node, 'div', CLASS='footer'),
'<hr class="footer" />\n']
footer.extend(self.body[start:])
footer.append('\n</div>\n')
self.footer.extend(footer)
self.body_suffix[:0] = footer
del self.body[start:]
def visit_footnote(self, node):
self.body.append(self.starttag(node, 'table',
CLASS='docutils footnote',
frame="void", rules="none"))
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n'
'<tbody valign="top">\n'
'<tr>')
self.footnote_backrefs(node)
def footnote_backrefs(self, node):
backlinks = []
backrefs = node['backrefs']
if self.settings.footnote_backlinks and backrefs:
if len(backrefs) == 1:
self.context.append('')
self.context.append('</a>')
self.context.append('<a class="fn-backref" href="#%s">'
% backrefs[0])
else:
i = 1
for backref in backrefs:
backlinks.append('<a class="fn-backref" href="#%s">%s</a>'
% (backref, i))
i += 1
self.context.append('<em>(%s)</em> ' % ', '.join(backlinks))
self.context += ['', '']
else:
self.context.append('')
self.context += ['', '']
# If the node does not only consist of a label.
if len(node) > 1:
# If there are preceding backlinks, we do not set class
# 'first', because we need to retain the top-margin.
if not backlinks:
node[1]['classes'].append('first')
node[-1]['classes'].append('last')
def depart_footnote(self, node):
self.body.append('</td></tr>\n'
'</tbody>\n</table>\n')
def visit_footnote_reference(self, node):
href = '#' + node['refid']
format = self.settings.footnote_references
if format == 'brackets':
suffix = '['
self.context.append(']')
else:
assert format == 'superscript'
suffix = '<sup>'
self.context.append('</sup>')
self.body.append(self.starttag(node, 'a', suffix,
CLASS='footnote-reference', href=href))
def depart_footnote_reference(self, node):
self.body.append(self.context.pop() + '</a>')
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def visit_header(self, node):
self.context.append(len(self.body))
def depart_header(self, node):
start = self.context.pop()
header = [self.starttag(node, 'div', CLASS='header')]
header.extend(self.body[start:])
header.append('\n<hr class="header"/>\n</div>\n')
self.body_prefix.extend(header)
self.header.extend(header)
del self.body[start:]
def visit_image(self, node):
atts = {}
atts['src'] = node['uri']
if 'width' in node:
atts['width'] = node['width']
if 'height' in node:
atts['height'] = node['height']
if 'scale' in node:
if Image and not ('width' in node
and 'height' in node):
try:
im = Image.open(str(atts['src']))
except (IOError, # Source image can't be found or opened
UnicodeError): # PIL doesn't like Unicode paths.
pass
else:
if 'width' not in atts:
atts['width'] = str(im.size[0])
if 'height' not in atts:
atts['height'] = str(im.size[1])
del im
for att_name in 'width', 'height':
if att_name in atts:
match = re.match(r'([0-9.]+)(\S*)$', atts[att_name])
assert match
atts[att_name] = '%s%s' % (
float(match.group(1)) * (float(node['scale']) / 100),
match.group(2))
style = []
for att_name in 'width', 'height':
if att_name in atts:
if re.match(r'^[0-9.]+$', atts[att_name]):
# Interpret unitless values as pixels.
atts[att_name] += 'px'
style.append('%s: %s;' % (att_name, atts[att_name]))
del atts[att_name]
if style:
atts['style'] = ' '.join(style)
atts['alt'] = node.get('alt', atts['src'])
if (isinstance(node.parent, nodes.TextElement) or
(isinstance(node.parent, nodes.reference) and
not isinstance(node.parent.parent, nodes.TextElement))):
# Inline context or surrounded by <a>...</a>.
suffix = ''
else:
suffix = '\n'
if 'classes' in node and 'align-center' in node['classes']:
node['align'] = 'center'
if 'align' in node:
if node['align'] == 'center':
# "align" attribute is set in surrounding "div" element.
self.body.append('<div align="center" class="align-center">')
self.context.append('</div>\n')
suffix = ''
else:
# "align" attribute is set in "img" element.
atts['align'] = node['align']
self.context.append('')
atts['class'] = 'align-%s' % node['align']
else:
self.context.append('')
self.body.append(self.emptytag(node, 'img', suffix, **atts))
def depart_image(self, node):
self.body.append(self.context.pop())
def visit_inline(self, node):
self.body.append(self.starttag(node, 'span', ''))
def depart_inline(self, node):
self.body.append('</span>')
def visit_label(self, node):
# Context added in footnote_backrefs.
self.body.append(self.starttag(node, 'td', '%s[' % self.context.pop(),
CLASS='label'))
def depart_label(self, node):
# Context added in footnote_backrefs.
self.body.append(']%s</td><td>%s' % (self.context.pop(), self.context.pop()))
def visit_legend(self, node):
self.body.append(self.starttag(node, 'div', CLASS='legend'))
def depart_legend(self, node):
self.body.append('</div>\n')
def visit_line(self, node):
self.body.append(self.starttag(node, 'div', suffix='', CLASS='line'))
if not len(node):
self.body.append('<br />')
def depart_line(self, node):
self.body.append('</div>\n')
def visit_line_block(self, node):
self.body.append(self.starttag(node, 'div', CLASS='line-block'))
def depart_line_block(self, node):
self.body.append('</div>\n')
def visit_list_item(self, node):
self.body.append(self.starttag(node, 'li', ''))
if len(node):
node[0]['classes'].append('first')
def depart_list_item(self, node):
self.body.append('</li>\n')
def visit_literal(self, node):
"""Process text to prevent tokens from wrapping."""
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():
# Protect text like "--an-option" from bad line wrapping:
self.body.append('<span class="pre">%s</span>'
% self.encode(token))
elif token in ('\n', ' '):
# Allow breaks at whitespace:
self.body.append(token)
else:
# Protect runs of multiple spaces; the last space can wrap:
self.body.append(' ' * (len(token) - 1) + ' ')
self.body.append('</tt>')
# Content already processed:
raise nodes.SkipNode
def visit_literal_block(self, node):
self.body.append(self.starttag(node, 'pre', CLASS='literal-block'))
def depart_literal_block(self, node):
self.body.append('\n</pre>\n')
def visit_meta(self, node):
meta = self.emptytag(node, 'meta', **node.non_default_attributes())
self.add_meta(meta)
def depart_meta(self, node):
pass
def add_meta(self, tag):
self.meta.append(tag)
self.head.append(tag)
def visit_option(self, node):
if self.context[-1]:
self.body.append(', ')
self.body.append(self.starttag(node, 'span', '', CLASS='option'))
def depart_option(self, node):
self.body.append('</span>')
self.context[-1] += 1
def visit_option_argument(self, node):
self.body.append(node.get('delimiter', ' '))
self.body.append(self.starttag(node, 'var', ''))
def depart_option_argument(self, node):
self.body.append('</var>')
def visit_option_group(self, node):
atts = {}
if ( self.settings.option_limit
and len(node.astext()) > self.settings.option_limit):
atts['colspan'] = 2
self.context.append('</tr>\n<tr><td> </td>')
else:
self.context.append('')
self.body.append(
self.starttag(node, 'td', CLASS='option-group', **atts))
self.body.append('<kbd>')
self.context.append(0) # count number of options
def depart_option_group(self, node):
self.context.pop()
self.body.append('</kbd></td>\n')
self.body.append(self.context.pop())
def visit_option_list(self, node):
self.body.append(
self.starttag(node, 'table', CLASS='docutils option-list',
frame="void", rules="none"))
self.body.append('<col class="option" />\n'
'<col class="description" />\n'
'<tbody valign="top">\n')
def depart_option_list(self, node):
self.body.append('</tbody>\n</table>\n')
def visit_option_list_item(self, node):
self.body.append(self.starttag(node, 'tr', ''))
def depart_option_list_item(self, node):
self.body.append('</tr>\n')
def visit_option_string(self, node):
pass
def depart_option_string(self, node):
pass
def visit_organization(self, node):
self.visit_docinfo_item(node, 'organization')
def depart_organization(self, node):
self.depart_docinfo_item()
def should_be_compact_paragraph(self, node):
"""
Determine if the <p> tags around paragraph ``node`` can be omitted.
"""
if (isinstance(node.parent, nodes.document) or
isinstance(node.parent, nodes.compound)):
# Never compact paragraphs in document or 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']))):
# Attribute which needs to survive.
return 0
first = isinstance(node.parent[0], nodes.label) # skip label
for child in node.parent.children[first:]:
# only first paragraph can be compact
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
def visit_paragraph(self, node):
if self.should_be_compact_paragraph(node):
self.context.append('')
else:
self.body.append(self.starttag(node, 'p', ''))
self.context.append('</p>\n')
def depart_paragraph(self, node):
self.body.append(self.context.pop())
def visit_problematic(self, node):
if node.hasattr('refid'):
self.body.append('<a href="#%s">' % node['refid'])
self.context.append('</a>')
else:
self.context.append('')
self.body.append(self.starttag(node, 'span', '', CLASS='problematic'))
def depart_problematic(self, node):
self.body.append('</span>')
self.body.append(self.context.pop())
def visit_raw(self, node):
if 'html' in node.get('format', '').split():
t = isinstance(node.parent, nodes.TextElement) and 'span' or 'div'
if node['classes']:
self.body.append(self.starttag(node, t, suffix=''))
self.body.append(node.astext())
if node['classes']:
self.body.append('</%s>' % t)
# Keep non-HTML raw text out of output:
raise nodes.SkipNode
def visit_reference(self, node):
atts = {'class': 'reference'}
if 'refuri' in node:
atts['href'] = node['refuri']
if ( self.settings.cloak_email_addresses
and atts['href'].startswith('mailto:')):
atts['href'] = self.cloak_mailto(atts['href'])
self.in_mailto = 1
atts['class'] += ' external'
else:
assert 'refid' in node, \
'References must have "refuri" or "refid" attribute.'
atts['href'] = '#' + node['refid']
atts['class'] += ' internal'
if not isinstance(node.parent, nodes.TextElement):
assert len(node) == 1 and isinstance(node[0], nodes.image)
atts['class'] += ' image-reference'
self.body.append(self.starttag(node, 'a', '', **atts))
def depart_reference(self, node):
self.body.append('</a>')
if not isinstance(node.parent, nodes.TextElement):
self.body.append('\n')
self.in_mailto = 0
def visit_revision(self, node):
self.visit_docinfo_item(node, 'revision', meta=None)
def depart_revision(self, node):
self.depart_docinfo_item()
def visit_row(self, node):
self.body.append(self.starttag(node, 'tr', ''))
node.column = 0
def depart_row(self, node):
self.body.append('</tr>\n')
def visit_rubric(self, node):
self.body.append(self.starttag(node, 'p', '', CLASS='rubric'))
def depart_rubric(self, node):
self.body.append('</p>\n')
def visit_section(self, node):
self.section_level += 1
self.body.append(
self.starttag(node, 'div', CLASS='section'))
def depart_section(self, node):
self.section_level -= 1
self.body.append('</div>\n')
def visit_sidebar(self, node):
self.body.append(
self.starttag(node, 'div', CLASS='sidebar'))
self.set_first_last(node)
self.in_sidebar = 1
def depart_sidebar(self, node):
self.body.append('</div>\n')
self.in_sidebar = None
def visit_status(self, node):
self.visit_docinfo_item(node, 'status', meta=None)
def depart_status(self, node):
self.depart_docinfo_item()
def visit_strong(self, node):
self.body.append(self.starttag(node, 'strong', ''))
def depart_strong(self, node):
self.body.append('</strong>')
def visit_subscript(self, node):
self.body.append(self.starttag(node, 'sub', ''))
def depart_subscript(self, node):
self.body.append('</sub>')
def visit_substitution_definition(self, node):
"""Internal only."""
raise nodes.SkipNode
def visit_substitution_reference(self, node):
self.unimplemented_visit(node)
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.sidebar):
self.body.append(self.starttag(node, 'p', '',
CLASS='sidebar-subtitle'))
self.context.append('</p>\n')
elif isinstance(node.parent, nodes.document):
self.body.append(self.starttag(node, 'h2', '', CLASS='subtitle'))
self.context.append('</h2>\n')
self.in_document_title = len(self.body)
elif isinstance(node.parent, nodes.section):
tag = 'h%s' % (self.section_level + self.initial_header_level - 1)
self.body.append(
self.starttag(node, tag, '', CLASS='section-subtitle') +
self.starttag({}, 'span', '', CLASS='section-subtitle'))
self.context.append('</span></%s>\n' % tag)
def depart_subtitle(self, node):
self.body.append(self.context.pop())
if self.in_document_title:
self.subtitle = self.body[self.in_document_title:-1]
self.in_document_title = 0
self.body_pre_docinfo.extend(self.body)
self.html_subtitle.extend(self.body)
del self.body[:]
def visit_superscript(self, node):
self.body.append(self.starttag(node, 'sup', ''))
def depart_superscript(self, node):
self.body.append('</sup>')
def visit_system_message(self, node):
self.body.append(self.starttag(node, 'div', CLASS='system-message'))
self.body.append('<p class="system-message-title">')
backref_text = ''
if len(node['backrefs']):
backrefs = node['backrefs']
if len(backrefs) == 1:
backref_text = ('; <em><a href="#%s">backlink</a></em>'
% backrefs[0])
else:
i = 1
backlinks = []
for backref in backrefs:
backlinks.append('<a href="#%s">%s</a>' % (backref, i))
i += 1
backref_text = ('; <em>backlinks: %s</em>'
% ', '.join(backlinks))
if node.hasattr('line'):
line = ', line %s' % node['line']
else:
line = ''
self.body.append('System Message: %s/%s '
'(<tt class="docutils">%s</tt>%s)%s</p>\n'
% (node['type'], node['level'],
self.encode(node['source']), line, backref_text))
def depart_system_message(self, node):
self.body.append('</div>\n')
def visit_table(self, node):
self.body.append(
self.starttag(node, 'table', CLASS='docutils', border="1"))
def depart_table(self, node):
self.body.append('</table>\n')
def visit_target(self, node):
if not ('refuri' in node or 'refid' in node
or 'refname' in node):
self.body.append(self.starttag(node, 'span', '', CLASS='target'))
self.context.append('</span>')
else:
self.context.append('')
def depart_target(self, node):
self.body.append(self.context.pop())
def visit_tbody(self, node):
self.write_colspecs()
self.body.append(self.context.pop()) # '</colgroup>\n' or ''
self.body.append(self.starttag(node, 'tbody', valign='top'))
def depart_tbody(self, node):
self.body.append('</tbody>\n')
def visit_term(self, node):
self.body.append(self.starttag(node, 'dt', ''))
def depart_term(self, node):
"""
Leave the end tag to `self.visit_definition()`, in case there's a
classifier.
"""
pass
def visit_tgroup(self, node):
# Mozilla needs <colgroup>:
self.body.append(self.starttag(node, 'colgroup'))
# Appended by thead or tbody:
self.context.append('</colgroup>\n')
node.stubs = []
def depart_tgroup(self, node):
pass
def visit_thead(self, node):
self.write_colspecs()
self.body.append(self.context.pop()) # '</colgroup>\n'
# There may or may not be a <thead>; this is for <tbody> to use:
self.context.append('')
self.body.append(self.starttag(node, 'thead', valign='bottom'))
def depart_thead(self, node):
self.body.append('</thead>\n')
def visit_title(self, node):
"""Only 6 section levels are supported by HTML."""
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)
def depart_title(self, node):
self.body.append(self.context.pop())
if self.in_document_title:
self.title = self.body[self.in_document_title:-1]
self.in_document_title = 0
self.body_pre_docinfo.extend(self.body)
self.html_title.extend(self.body)
del self.body[:]
def visit_title_reference(self, node):
self.body.append(self.starttag(node, 'cite', ''))
def depart_title_reference(self, node):
self.body.append('</cite>')
def visit_topic(self, node):
self.body.append(self.starttag(node, 'div', CLASS='topic'))
self.topic_classes = node['classes']
def depart_topic(self, node):
self.body.append('</div>\n')
self.topic_classes = []
def visit_transition(self, node):
self.body.append(self.emptytag(node, 'hr', CLASS='docutils'))
def depart_transition(self, node):
pass
def visit_version(self, node):
self.visit_docinfo_item(node, 'version', meta=None)
def depart_version(self, node):
self.depart_docinfo_item()
def unimplemented_visit(self, node):
raise NotImplementedError('visiting unimplemented node type: %s'
% node.__class__.__name__)
class SimpleListChecker(nodes.GenericNodeVisitor):
"""
Raise `nodes.NodeFound` if non-simple list item is encountered.
Here "simple" means a list item containing nothing other than a single
paragraph, a simple list, or a paragraph followed by a simple list.
"""
def default_visit(self, node):
raise nodes.NodeFound
def visit_bullet_list(self, node):
pass
def visit_enumerated_list(self, node):
pass
def visit_list_item(self, node):
children = []
for child in node.children:
if not isinstance(child, nodes.Invisible):
children.append(child)
if (children and isinstance(children[0], nodes.paragraph)
and (isinstance(children[-1], nodes.bullet_list)
or isinstance(children[-1], nodes.enumerated_list))):
children.pop()
if len(children) <= 1:
return
else:
raise nodes.NodeFound
def visit_paragraph(self, node):
raise nodes.SkipNode
def invisible_visit(self, node):
"""Invisible nodes should be ignored."""
raise nodes.SkipNode
visit_comment = invisible_visit
visit_substitution_definition = invisible_visit
visit_target = invisible_visit
visit_pending = invisible_visit
| {
"repo_name": "spreeker/democracygame",
"path": "external_apps/docutils-snapshot/build/lib/docutils/writers/html4css1/__init__.py",
"copies": "2",
"size": "58584",
"license": "bsd-3-clause",
"hash": 340714269464389400,
"line_mean": 37.0415584416,
"line_max": 85,
"alpha_frac": 0.5500477946,
"autogenerated": false,
"ratio": 3.968299126193863,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5518346920793863,
"avg_score": null,
"num_lines": null
} |
"""
This package contains directive implementation modules.
"""
__docformat__ = 'reStructuredText'
import codecs
import re
from docutils import nodes
from docutils.parsers.rst.languages import en as _fallback_language_module
_directive_registry = {
'attention': ('admonitions', 'Attention'),
'caution': ('admonitions', 'Caution'),
'danger': ('admonitions', 'Danger'),
'error': ('admonitions', 'Error'),
'important': ('admonitions', 'Important'),
'note': ('admonitions', 'Note'),
'tip': ('admonitions', 'Tip'),
'hint': ('admonitions', 'Hint'),
'warning': ('admonitions', 'Warning'),
'admonition': ('admonitions', 'Admonition'),
'sidebar': ('body', 'Sidebar'),
'topic': ('body', 'Topic'),
'line-block': ('body', 'LineBlock'),
'parsed-literal': ('body', 'ParsedLiteral'),
'rubric': ('body', 'Rubric'),
'epigraph': ('body', 'Epigraph'),
'highlights': ('body', 'Highlights'),
'pull-quote': ('body', 'PullQuote'),
'compound': ('body', 'Compound'),
'container': ('body', 'Container'),
#'questions': ('body', 'question_list'),
'table': ('tables', 'RSTTable'),
'csv-table': ('tables', 'CSVTable'),
'list-table': ('tables', 'ListTable'),
'image': ('images', 'Image'),
'figure': ('images', 'Figure'),
'contents': ('parts', 'Contents'),
'sectnum': ('parts', 'Sectnum'),
'header': ('parts', 'Header'),
'footer': ('parts', 'Footer'),
#'footnotes': ('parts', 'footnotes'),
#'citations': ('parts', 'citations'),
'target-notes': ('references', 'TargetNotes'),
'meta': ('html', 'Meta'),
#'imagemap': ('html', 'imagemap'),
'raw': ('misc', 'Raw'),
'include': ('misc', 'Include'),
'replace': ('misc', 'Replace'),
'unicode': ('misc', 'Unicode'),
'class': ('misc', 'Class'),
'role': ('misc', 'Role'),
'default-role': ('misc', 'DefaultRole'),
'title': ('misc', 'Title'),
'date': ('misc', 'Date'),
'restructuredtext-test-directive': ('misc', 'TestDirective'),}
"""Mapping of directive name to (module name, class name). The
directive name is canonical & must be lowercase. Language-dependent
names are defined in the ``language`` subpackage."""
_directives = {}
"""Cache of imported directives."""
def directive(directive_name, language_module, document):
"""
Locate and return a directive function from its language-dependent name.
If not found in the current language, check English. Return None if the
named directive cannot be found.
"""
normname = directive_name.lower()
messages = []
msg_text = []
if normname in _directives:
return _directives[normname], messages
canonicalname = None
try:
canonicalname = language_module.directives[normname]
except AttributeError, error:
msg_text.append('Problem retrieving directive entry from language '
'module %r: %s.' % (language_module, error))
except KeyError:
msg_text.append('No directive entry for "%s" in module "%s".'
% (directive_name, language_module.__name__))
if not canonicalname:
try:
canonicalname = _fallback_language_module.directives[normname]
msg_text.append('Using English fallback for directive "%s".'
% directive_name)
except KeyError:
msg_text.append('Trying "%s" as canonical directive name.'
% directive_name)
# The canonical name should be an English name, but just in case:
canonicalname = normname
if msg_text:
message = document.reporter.info(
'\n'.join(msg_text), line=document.current_line)
messages.append(message)
try:
modulename, classname = _directive_registry[canonicalname]
except KeyError:
# Error handling done by caller.
return None, messages
try:
module = __import__(modulename, globals(), locals())
except ImportError, detail:
messages.append(document.reporter.error(
'Error importing directive module "%s" (directive "%s"):\n%s'
% (modulename, directive_name, detail),
line=document.current_line))
return None, messages
try:
directive = getattr(module, classname)
_directives[normname] = directive
except AttributeError:
messages.append(document.reporter.error(
'No directive class "%s" in module "%s" (directive "%s").'
% (classname, modulename, directive_name),
line=document.current_line))
return None, messages
return directive, messages
def register_directive(name, directive):
"""
Register a nonstandard application-defined directive function.
Language lookups are not needed for such functions.
"""
_directives[name] = directive
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
else:
return None
def unchanged_required(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
return argument # unchanged!
def unchanged(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
No argument implies empty string ("").
"""
if argument is None:
return u''
else:
return argument # unchanged!
def path(argument):
"""
Return the path argument unwrapped (with newlines removed).
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
path = ''.join([s.strip() for s in argument.splitlines()])
return path
def uri(argument):
"""
Return the URI argument with whitespace removed.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
uri = ''.join(argument.split())
return uri
def nonnegative_int(argument):
"""
Check for a nonnegative integer argument; raise ``ValueError`` if not.
(Directive option conversion function.)
"""
value = int(argument)
if value < 0:
raise ValueError('negative value; must be positive or zero')
return value
def percentage(argument):
"""
Check for an integer percentage value with optional percent sign.
"""
try:
argument = argument.rstrip(' %')
except AttributeError:
pass
return nonnegative_int(argument)
length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc']
def get_measure(argument, units):
"""
Check for a positive argument of one of the units and return a
normalized string of the form "<value><unit>" (without space in
between).
To be called from directive option conversion functions.
"""
match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument)
try:
assert match is not None
float(match.group(1))
except (AssertionError, ValueError):
raise ValueError(
'not a positive measure of one of the following units:\n%s'
% ' '.join(['"%s"' % i for i in units]))
return match.group(1) + match.group(2)
def length_or_unitless(argument):
return get_measure(argument, length_units + [''])
def length_or_percentage_or_unitless(argument, default=''):
"""
Return normalized string of a length or percentage unit.
Add <default> if there is no unit. Raise ValueError if the argument is not
a positive measure of one of the valid CSS units (or without unit).
>>> length_or_percentage_or_unitless('3 pt')
'3pt'
>>> length_or_percentage_or_unitless('3%', 'em')
'3%'
>>> length_or_percentage_or_unitless('3')
'3'
>>> length_or_percentage_or_unitless('3', 'px')
'3px'
"""
try:
return get_measure(argument, length_units + ['%'])
except ValueError:
return get_measure(argument, ['']) + default
def class_option(argument):
"""
Convert the argument into a list of ID-compatible strings and return it.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
names = argument.split()
class_names = []
for name in names:
class_name = nodes.make_id(name)
if not class_name:
raise ValueError('cannot make "%s" into a class name' % name)
class_names.append(class_name)
return class_names
unicode_pattern = re.compile(
r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE)
def unicode_code(code):
r"""
Convert a Unicode character code to a Unicode character.
(Directive option conversion function.)
Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``,
``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style
numeric character entities (e.g. ``☮``). Other text remains as-is.
Raise ValueError for illegal Unicode code values.
"""
try:
if code.isdigit(): # decimal number
return unichr(int(code))
else:
match = unicode_pattern.match(code)
if match: # hex number
value = match.group(1) or match.group(2)
return unichr(int(value, 16))
else: # other text
return code
except OverflowError, detail:
raise ValueError('code too large (%s)' % detail)
def single_char_or_unicode(argument):
"""
A single character is returned as-is. Unicode characters codes are
converted as in `unicode_code`. (Directive option conversion function.)
"""
char = unicode_code(argument)
if len(char) > 1:
raise ValueError('%r invalid; must be a single character or '
'a Unicode code' % char)
return char
def single_char_or_whitespace_or_unicode(argument):
"""
As with `single_char_or_unicode`, but "tab" and "space" are also supported.
(Directive option conversion function.)
"""
if argument == 'tab':
char = '\t'
elif argument == 'space':
char = ' '
else:
char = single_char_or_unicode(argument)
return char
def positive_int(argument):
"""
Converts the argument into an integer. Raises ValueError for negative,
zero, or non-integer values. (Directive option conversion function.)
"""
value = int(argument)
if value < 1:
raise ValueError('negative or zero value; must be positive')
return value
def positive_int_list(argument):
"""
Converts a space- or comma-separated list of values into a Python list
of integers.
(Directive option conversion function.)
Raises ValueError for non-positive-integer values.
"""
if ',' in argument:
entries = argument.split(',')
else:
entries = argument.split()
return [positive_int(entry) for entry in entries]
def encoding(argument):
"""
Verfies the encoding argument by lookup.
(Directive option conversion function.)
Raises ValueError for unknown encodings.
"""
try:
codecs.lookup(argument)
except LookupError:
raise ValueError('unknown encoding: "%s"' % argument)
return argument
def choice(argument, values):
"""
Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
example::
from docutils.parsers.rst import directives
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
Raise ``ValueError`` if no argument is found or if the argument's value is
not valid (not an entry in the supplied list).
"""
try:
value = argument.lower().strip()
except AttributeError:
raise ValueError('must supply an argument; choose from %s'
% format_values(values))
if value in values:
return value
else:
raise ValueError('"%s" unknown; choose from %s'
% (argument, format_values(values)))
def format_values(values):
return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]),
values[-1])
| {
"repo_name": "MichaelNedzelsky/intellij-community",
"path": "python/helpers/py2only/docutils/parsers/rst/directives/__init__.py",
"copies": "5",
"size": "13312",
"license": "apache-2.0",
"hash": -6457919653988906000,
"line_mean": 32.7012658228,
"line_max": 79,
"alpha_frac": 0.6071965144,
"autogenerated": false,
"ratio": 4.176968936303734,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0026973141825824792,
"num_lines": 395
} |
"""
This package contains directive implementation modules.
"""
__docformat__ = 'reStructuredText'
import re
import codecs
from docutils import nodes
from docutils.parsers.rst.languages import en as _fallback_language_module
_directive_registry = {
'attention': ('admonitions', 'Attention'),
'caution': ('admonitions', 'Caution'),
'danger': ('admonitions', 'Danger'),
'error': ('admonitions', 'Error'),
'important': ('admonitions', 'Important'),
'note': ('admonitions', 'Note'),
'tip': ('admonitions', 'Tip'),
'hint': ('admonitions', 'Hint'),
'warning': ('admonitions', 'Warning'),
'admonition': ('admonitions', 'Admonition'),
'sidebar': ('body', 'Sidebar'),
'topic': ('body', 'Topic'),
'line-block': ('body', 'LineBlock'),
'parsed-literal': ('body', 'ParsedLiteral'),
'rubric': ('body', 'Rubric'),
'epigraph': ('body', 'Epigraph'),
'highlights': ('body', 'Highlights'),
'pull-quote': ('body', 'PullQuote'),
'compound': ('body', 'Compound'),
'container': ('body', 'Container'),
#'questions': ('body', 'question_list'),
'table': ('tables', 'RSTTable'),
'csv-table': ('tables', 'CSVTable'),
'list-table': ('tables', 'ListTable'),
'image': ('images', 'Image'),
'figure': ('images', 'Figure'),
'contents': ('parts', 'Contents'),
'sectnum': ('parts', 'Sectnum'),
'header': ('parts', 'Header'),
'footer': ('parts', 'Footer'),
#'footnotes': ('parts', 'footnotes'),
#'citations': ('parts', 'citations'),
'target-notes': ('references', 'TargetNotes'),
'meta': ('html', 'Meta'),
#'imagemap': ('html', 'imagemap'),
'raw': ('misc', 'Raw'),
'include': ('misc', 'Include'),
'replace': ('misc', 'Replace'),
'unicode': ('misc', 'Unicode'),
'class': ('misc', 'Class'),
'role': ('misc', 'Role'),
'default-role': ('misc', 'DefaultRole'),
'title': ('misc', 'Title'),
'date': ('misc', 'Date'),
'restructuredtext-test-directive': ('misc', 'TestDirective'),}
"""Mapping of directive name to (module name, class name). The
directive name is canonical & must be lowercase. Language-dependent
names are defined in the ``language`` subpackage."""
_directives = {}
"""Cache of imported directives."""
def directive(directive_name, language_module, document):
"""
Locate and return a directive function from its language-dependent name.
If not found in the current language, check English. Return None if the
named directive cannot be found.
"""
normname = directive_name.lower()
messages = []
msg_text = []
if normname in _directives:
return _directives[normname], messages
canonicalname = None
try:
canonicalname = language_module.directives[normname]
except AttributeError, error:
msg_text.append('Problem retrieving directive entry from language '
'module %r: %s.' % (language_module, error))
except KeyError:
msg_text.append('No directive entry for "%s" in module "%s".'
% (directive_name, language_module.__name__))
if not canonicalname:
try:
canonicalname = _fallback_language_module.directives[normname]
msg_text.append('Using English fallback for directive "%s".'
% directive_name)
except KeyError:
msg_text.append('Trying "%s" as canonical directive name.'
% directive_name)
# The canonical name should be an English name, but just in case:
canonicalname = normname
if msg_text:
message = document.reporter.info(
'\n'.join(msg_text), line=document.current_line)
messages.append(message)
try:
modulename, classname = _directive_registry[canonicalname]
except KeyError:
# Error handling done by caller.
return None, messages
try:
module = __import__(modulename, globals(), locals())
except ImportError, detail:
messages.append(document.reporter.error(
'Error importing directive module "%s" (directive "%s"):\n%s'
% (modulename, directive_name, detail),
line=document.current_line))
return None, messages
try:
directive = getattr(module, classname)
_directives[normname] = directive
except AttributeError:
messages.append(document.reporter.error(
'No directive class "%s" in module "%s" (directive "%s").'
% (classname, modulename, directive_name),
line=document.current_line))
return None, messages
return directive, messages
def register_directive(name, directive):
"""
Register a nonstandard application-defined directive function.
Language lookups are not needed for such functions.
"""
_directives[name] = directive
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
else:
return None
def unchanged_required(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
return argument # unchanged!
def unchanged(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
No argument implies empty string ("").
"""
if argument is None:
return u''
else:
return argument # unchanged!
def path(argument):
"""
Return the path argument unwrapped (with newlines removed).
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
path = ''.join([s.strip() for s in argument.splitlines()])
return path
def uri(argument):
"""
Return the URI argument with whitespace removed.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
uri = ''.join(argument.split())
return uri
def nonnegative_int(argument):
"""
Check for a nonnegative integer argument; raise ``ValueError`` if not.
(Directive option conversion function.)
"""
value = int(argument)
if value < 0:
raise ValueError('negative value; must be positive or zero')
return value
def percentage(argument):
"""
Check for an integer percentage value with optional percent sign.
"""
try:
argument = argument.rstrip(' %')
except AttributeError:
pass
return nonnegative_int(argument)
length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc']
def get_measure(argument, units):
"""
Check for a positive argument of one of the units and return a
normalized string of the form "<value><unit>" (without space in
between).
To be called from directive option conversion functions.
"""
match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument)
try:
assert match is not None
float(match.group(1))
except (AssertionError, ValueError):
raise ValueError(
'not a positive measure of one of the following units:\n%s'
% ' '.join(['"%s"' % i for i in units]))
return match.group(1) + match.group(2)
def length_or_unitless(argument):
return get_measure(argument, length_units + [''])
def length_or_percentage_or_unitless(argument, default=''):
"""
Return normalized string of a length or percentage unit.
Add <default> if there is no unit. Raise ValueError if the argument is not
a positive measure of one of the valid CSS units (or without unit).
>>> length_or_percentage_or_unitless('3 pt')
'3pt'
>>> length_or_percentage_or_unitless('3%', 'em')
'3%'
>>> length_or_percentage_or_unitless('3')
'3'
>>> length_or_percentage_or_unitless('3', 'px')
'3px'
"""
try:
return get_measure(argument, length_units + ['%'])
except ValueError:
return get_measure(argument, ['']) + default
def class_option(argument):
"""
Convert the argument into a list of ID-compatible strings and return it.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
names = argument.split()
class_names = []
for name in names:
class_name = nodes.make_id(name)
if not class_name:
raise ValueError('cannot make "%s" into a class name' % name)
class_names.append(class_name)
return class_names
unicode_pattern = re.compile(
r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE)
def unicode_code(code):
r"""
Convert a Unicode character code to a Unicode character.
(Directive option conversion function.)
Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``,
``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style
numeric character entities (e.g. ``☮``). Other text remains as-is.
Raise ValueError for illegal Unicode code values.
"""
try:
if code.isdigit(): # decimal number
return unichr(int(code))
else:
match = unicode_pattern.match(code)
if match: # hex number
value = match.group(1) or match.group(2)
return unichr(int(value, 16))
else: # other text
return code
except OverflowError, detail:
raise ValueError('code too large (%s)' % detail)
def single_char_or_unicode(argument):
"""
A single character is returned as-is. Unicode characters codes are
converted as in `unicode_code`. (Directive option conversion function.)
"""
char = unicode_code(argument)
if len(char) > 1:
raise ValueError('%r invalid; must be a single character or '
'a Unicode code' % char)
return char
def single_char_or_whitespace_or_unicode(argument):
"""
As with `single_char_or_unicode`, but "tab" and "space" are also supported.
(Directive option conversion function.)
"""
if argument == 'tab':
char = '\t'
elif argument == 'space':
char = ' '
else:
char = single_char_or_unicode(argument)
return char
def positive_int(argument):
"""
Converts the argument into an integer. Raises ValueError for negative,
zero, or non-integer values. (Directive option conversion function.)
"""
value = int(argument)
if value < 1:
raise ValueError('negative or zero value; must be positive')
return value
def positive_int_list(argument):
"""
Converts a space- or comma-separated list of values into a Python list
of integers.
(Directive option conversion function.)
Raises ValueError for non-positive-integer values.
"""
if ',' in argument:
entries = argument.split(',')
else:
entries = argument.split()
return [positive_int(entry) for entry in entries]
def encoding(argument):
"""
Verfies the encoding argument by lookup.
(Directive option conversion function.)
Raises ValueError for unknown encodings.
"""
try:
codecs.lookup(argument)
except LookupError:
raise ValueError('unknown encoding: "%s"' % argument)
return argument
def choice(argument, values):
"""
Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
centralfitestoque::
from docutils.parsers.rst import directives
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
Raise ``ValueError`` if no argument is found or if the argument's value is
not valid (not an entry in the supplied list).
"""
try:
value = argument.lower().strip()
except AttributeError:
raise ValueError('must supply an argument; choose from %s'
% format_values(values))
if value in values:
return value
else:
raise ValueError('"%s" unknown; choose from %s'
% (argument, format_values(values)))
def format_values(values):
return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]),
values[-1])
| {
"repo_name": "akiokio/centralfitestoque",
"path": "src/.pycharm_helpers/docutils/parsers/rst/directives/__init__.py",
"copies": "1",
"size": "13322",
"license": "bsd-2-clause",
"hash": -6215334470628386000,
"line_mean": 32.7265822785,
"line_max": 79,
"alpha_frac": 0.6074913677,
"autogenerated": false,
"ratio": 4.173558897243108,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0026973141825824792,
"num_lines": 395
} |
"""
This package contains directive implementation modules.
"""
__docformat__ = 'reStructuredText'
import re
import codecs
from docutils import nodes
from docutils.parsers.rst.languages import en as _fallback_language_module
_directive_registry = {
'attention': ('admonitions', 'Attention'),
'caution': ('admonitions', 'Caution'),
'danger': ('admonitions', 'Danger'),
'error': ('admonitions', 'Error'),
'important': ('admonitions', 'Important'),
'note': ('admonitions', 'Note'),
'tip': ('admonitions', 'Tip'),
'hint': ('admonitions', 'Hint'),
'warning': ('admonitions', 'Warning'),
'admonition': ('admonitions', 'Admonition'),
'sidebar': ('body', 'Sidebar'),
'topic': ('body', 'Topic'),
'line-block': ('body', 'LineBlock'),
'parsed-literal': ('body', 'ParsedLiteral'),
'rubric': ('body', 'Rubric'),
'epigraph': ('body', 'Epigraph'),
'highlights': ('body', 'Highlights'),
'pull-quote': ('body', 'PullQuote'),
'compound': ('body', 'Compound'),
'container': ('body', 'Container'),
#'questions': ('body', 'question_list'),
'table': ('tables', 'RSTTable'),
'csv-table': ('tables', 'CSVTable'),
'list-table': ('tables', 'ListTable'),
'image': ('images', 'Image'),
'figure': ('images', 'Figure'),
'contents': ('parts', 'Contents'),
'sectnum': ('parts', 'Sectnum'),
'header': ('parts', 'Header'),
'footer': ('parts', 'Footer'),
#'footnotes': ('parts', 'footnotes'),
#'citations': ('parts', 'citations'),
'target-notes': ('references', 'TargetNotes'),
'meta': ('html', 'Meta'),
#'imagemap': ('html', 'imagemap'),
'raw': ('misc', 'Raw'),
'include': ('misc', 'Include'),
'replace': ('misc', 'Replace'),
'unicode': ('misc', 'Unicode'),
'class': ('misc', 'Class'),
'role': ('misc', 'Role'),
'default-role': ('misc', 'DefaultRole'),
'title': ('misc', 'Title'),
'date': ('misc', 'Date'),
'restructuredtext-test-directive': ('misc', 'TestDirective'),}
"""Mapping of directive name to (module name, class name). The
directive name is canonical & must be lowercase. Language-dependent
names are defined in the ``language`` subpackage."""
_directives = {}
"""Cache of imported directives."""
def directive(directive_name, language_module, document):
"""
Locate and return a directive function from its language-dependent name.
If not found in the current language, check English. Return None if the
named directive cannot be found.
"""
normname = directive_name.lower()
messages = []
msg_text = []
if normname in _directives:
return _directives[normname], messages
canonicalname = None
try:
canonicalname = language_module.directives[normname]
except AttributeError, error:
msg_text.append('Problem retrieving directive entry from language '
'module %r: %s.' % (language_module, error))
except KeyError:
msg_text.append('No directive entry for "%s" in module "%s".'
% (directive_name, language_module.__name__))
if not canonicalname:
try:
canonicalname = _fallback_language_module.directives[normname]
msg_text.append('Using English fallback for directive "%s".'
% directive_name)
except KeyError:
msg_text.append('Trying "%s" as canonical directive name.'
% directive_name)
# The canonical name should be an English name, but just in case:
canonicalname = normname
if msg_text:
message = document.reporter.info(
'\n'.join(msg_text), line=document.current_line)
messages.append(message)
try:
modulename, classname = _directive_registry[canonicalname]
except KeyError:
# Error handling done by caller.
return None, messages
try:
module = __import__(modulename, globals(), locals())
except ImportError, detail:
messages.append(document.reporter.error(
'Error importing directive module "%s" (directive "%s"):\n%s'
% (modulename, directive_name, detail),
line=document.current_line))
return None, messages
try:
directive = getattr(module, classname)
_directives[normname] = directive
except AttributeError:
messages.append(document.reporter.error(
'No directive class "%s" in module "%s" (directive "%s").'
% (classname, modulename, directive_name),
line=document.current_line))
return None, messages
return directive, messages
def register_directive(name, directive):
"""
Register a nonstandard application-defined directive function.
Language lookups are not needed for such functions.
"""
_directives[name] = directive
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
else:
return None
def unchanged_required(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
return argument # unchanged!
def unchanged(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
No argument implies empty string ("").
"""
if argument is None:
return u''
else:
return argument # unchanged!
def path(argument):
"""
Return the path argument unwrapped (with newlines removed).
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
path = ''.join([s.strip() for s in argument.splitlines()])
return path
def uri(argument):
"""
Return the URI argument with whitespace removed.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
uri = ''.join(argument.split())
return uri
def nonnegative_int(argument):
"""
Check for a nonnegative integer argument; raise ``ValueError`` if not.
(Directive option conversion function.)
"""
value = int(argument)
if value < 0:
raise ValueError('negative value; must be positive or zero')
return value
def percentage(argument):
"""
Check for an integer percentage value with optional percent sign.
"""
try:
argument = argument.rstrip(' %')
except AttributeError:
pass
return nonnegative_int(argument)
length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc']
def get_measure(argument, units):
"""
Check for a positive argument of one of the units and return a
normalized string of the form "<value><unit>" (without space in
between).
To be called from directive option conversion functions.
"""
match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument)
try:
assert match is not None
float(match.group(1))
except (AssertionError, ValueError):
raise ValueError(
'not a positive measure of one of the following units:\n%s'
% ' '.join(['"%s"' % i for i in units]))
return match.group(1) + match.group(2)
def length_or_unitless(argument):
return get_measure(argument, length_units + [''])
def length_or_percentage_or_unitless(argument, default=''):
"""
Return normalized string of a length or percentage unit.
Add <default> if there is no unit. Raise ValueError if the argument is not
a positive measure of one of the valid CSS units (or without unit).
>>> length_or_percentage_or_unitless('3 pt')
'3pt'
>>> length_or_percentage_or_unitless('3%', 'em')
'3%'
>>> length_or_percentage_or_unitless('3')
'3'
>>> length_or_percentage_or_unitless('3', 'px')
'3px'
"""
try:
return get_measure(argument, length_units + ['%'])
except ValueError:
return get_measure(argument, ['']) + default
def class_option(argument):
"""
Convert the argument into a list of ID-compatible strings and return it.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
names = argument.split()
class_names = []
for name in names:
class_name = nodes.make_id(name)
if not class_name:
raise ValueError('cannot make "%s" into a class name' % name)
class_names.append(class_name)
return class_names
unicode_pattern = re.compile(
r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE)
def unicode_code(code):
r"""
Convert a Unicode character code to a Unicode character.
(Directive option conversion function.)
Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``,
``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style
numeric character entities (e.g. ``☮``). Other text remains as-is.
Raise ValueError for illegal Unicode code values.
"""
try:
if code.isdigit(): # decimal number
return unichr(int(code))
else:
match = unicode_pattern.match(code)
if match: # hex number
value = match.group(1) or match.group(2)
return unichr(int(value, 16))
else: # other text
return code
except OverflowError, detail:
raise ValueError('code too large (%s)' % detail)
def single_char_or_unicode(argument):
"""
A single character is returned as-is. Unicode characters codes are
converted as in `unicode_code`. (Directive option conversion function.)
"""
char = unicode_code(argument)
if len(char) > 1:
raise ValueError('%r invalid; must be a single character or '
'a Unicode code' % char)
return char
def single_char_or_whitespace_or_unicode(argument):
"""
As with `single_char_or_unicode`, but "tab" and "space" are also supported.
(Directive option conversion function.)
"""
if argument == 'tab':
char = '\t'
elif argument == 'space':
char = ' '
else:
char = single_char_or_unicode(argument)
return char
def positive_int(argument):
"""
Converts the argument into an integer. Raises ValueError for negative,
zero, or non-integer values. (Directive option conversion function.)
"""
value = int(argument)
if value < 1:
raise ValueError('negative or zero value; must be positive')
return value
def positive_int_list(argument):
"""
Converts a space- or comma-separated list of values into a Python list
of integers.
(Directive option conversion function.)
Raises ValueError for non-positive-integer values.
"""
if ',' in argument:
entries = argument.split(',')
else:
entries = argument.split()
return [positive_int(entry) for entry in entries]
def encoding(argument):
"""
Verfies the encoding argument by lookup.
(Directive option conversion function.)
Raises ValueError for unknown encodings.
"""
try:
codecs.lookup(argument)
except LookupError:
raise ValueError('unknown encoding: "%s"' % argument)
return argument
def choice(argument, values):
"""
Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
example::
from docutils.parsers.rst import directives
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
Raise ``ValueError`` if no argument is found or if the argument's value is
not valid (not an entry in the supplied list).
"""
try:
value = argument.lower().strip()
except AttributeError:
raise ValueError('must supply an argument; choose from %s'
% format_values(values))
if value in values:
return value
else:
raise ValueError('"%s" unknown; choose from %s'
% (argument, format_values(values)))
def format_values(values):
return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]),
values[-1])
| {
"repo_name": "rimbalinux/MSISDNArea",
"path": "docutils/parsers/rst/directives/__init__.py",
"copies": "2",
"size": "13707",
"license": "bsd-3-clause",
"hash": 1357717350783551700,
"line_mean": 32.7012658228,
"line_max": 79,
"alpha_frac": 0.5896986941,
"autogenerated": false,
"ratio": 4.2834375,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.58731361941,
"avg_score": null,
"num_lines": null
} |
"""
Open Document Format (ODF) Writer.
"""
VERSION = '1.0a'
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import tempfile
import zipfile
from xml.dom import minidom
import time
import re
import StringIO
import inspect
import imp
import copy
import docutils
from docutils import frontend, nodes, utils, writers, languages
from docutils.parsers import rst
from docutils.readers import standalone
from docutils.transforms import references
WhichElementTree = ''
try:
# 1. Try to use lxml.
#from lxml import etree
#WhichElementTree = 'lxml'
raise ImportError('Ignoring lxml')
except ImportError, e:
try:
# 2. Try to use ElementTree from the Python standard library.
from xml.etree import ElementTree as etree
WhichElementTree = 'elementtree'
except ImportError, e:
try:
# 3. Try to use a version of ElementTree installed as a separate
# product.
from elementtree import ElementTree as etree
WhichElementTree = 'elementtree'
except ImportError, e:
s1 = 'Must install either a version of Python containing ' \
'ElementTree (Python version >=2.5) or install ElementTree.'
raise ImportError(s1)
#
# Import pygments and odtwriter pygments formatters if possible.
try:
import pygments
import pygments.lexers
from pygmentsformatter import OdtPygmentsProgFormatter, \
OdtPygmentsLaTeXFormatter
except ImportError, exp:
pygments = None
#
# Is the PIL imaging library installed?
try:
import Image
except ImportError, exp:
Image = None
## import warnings
## warnings.warn('importing IPShellEmbed', UserWarning)
## from IPython.Shell import IPShellEmbed
## args = ['-pdb', '-pi1', 'In <\\#>: ', '-pi2', ' .\\D.: ',
## '-po', 'Out<\\#>: ', '-nosep']
## ipshell = IPShellEmbed(args,
## banner = 'Entering IPython. Press Ctrl-D to exit.',
## exit_msg = 'Leaving Interpreter, back to program.')
#
# ElementTree does not support getparent method (lxml does).
# This wrapper class and the following support functions provide
# that support for the ability to get the parent of an element.
#
if WhichElementTree == 'elementtree':
class _ElementInterfaceWrapper(etree._ElementInterface):
def __init__(self, tag, attrib=None):
etree._ElementInterface.__init__(self, tag, attrib)
if attrib is None:
attrib = {}
self.parent = None
def setparent(self, parent):
self.parent = parent
def getparent(self):
return self.parent
#
# Constants and globals
SPACES_PATTERN = re.compile(r'( +)')
TABS_PATTERN = re.compile(r'(\t+)')
FILL_PAT1 = re.compile(r'^ +')
FILL_PAT2 = re.compile(r' {2,}')
TableStylePrefix = 'Table'
GENERATOR_DESC = 'Docutils.org/odf_odt'
NAME_SPACE_1 = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'
CONTENT_NAMESPACE_DICT = CNSD = {
# 'office:version': '1.0',
'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'dom': 'http://www.w3.org/2001/xml-events',
'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'math': 'http://www.w3.org/1998/Math/MathML',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'office': NAME_SPACE_1,
'ooo': 'http://openoffice.org/2004/office',
'oooc': 'http://openoffice.org/2004/calc',
'ooow': 'http://openoffice.org/2004/writer',
'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xforms': 'http://www.w3.org/2002/xforms',
'xlink': 'http://www.w3.org/1999/xlink',
'xsd': 'http://www.w3.org/2001/XMLSchema',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
STYLES_NAMESPACE_DICT = SNSD = {
# 'office:version': '1.0',
'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'dom': 'http://www.w3.org/2001/xml-events',
'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'math': 'http://www.w3.org/1998/Math/MathML',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'office': NAME_SPACE_1,
'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'ooo': 'http://openoffice.org/2004/office',
'oooc': 'http://openoffice.org/2004/calc',
'ooow': 'http://openoffice.org/2004/writer',
'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xlink': 'http://www.w3.org/1999/xlink',
}
MANIFEST_NAMESPACE_DICT = MANNSD = {
'manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}
META_NAMESPACE_DICT = METNSD = {
# 'office:version': '1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'office': NAME_SPACE_1,
'ooo': 'http://openoffice.org/2004/office',
'xlink': 'http://www.w3.org/1999/xlink',
}
#
# Attribute dictionaries for use with ElementTree (not lxml), which
# does not support use of nsmap parameter on Element() and SubElement().
CONTENT_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:dom': 'http://www.w3.org/2001/xml-events',
'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:oooc': 'http://openoffice.org/2004/calc',
'xmlns:ooow': 'http://openoffice.org/2004/writer',
'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xmlns:xforms': 'http://www.w3.org/2002/xforms',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
STYLES_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:dom': 'http://www.w3.org/2001/xml-events',
'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:oooc': 'http://openoffice.org/2004/calc',
'xmlns:ooow': 'http://openoffice.org/2004/writer',
'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}
MANIFEST_NAMESPACE_ATTRIB = {
'xmlns:manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}
META_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}
#
# Functions
#
#
# ElementTree support functions.
# In order to be able to get the parent of elements, must use these
# instead of the functions with same name provided by ElementTree.
#
def Element(tag, attrib=None, nsmap=None, nsdict=CNSD):
if attrib is None:
attrib = {}
tag, attrib = fix_ns(tag, attrib, nsdict)
if WhichElementTree == 'lxml':
el = etree.Element(tag, attrib, nsmap=nsmap)
else:
el = _ElementInterfaceWrapper(tag, attrib)
return el
def SubElement(parent, tag, attrib=None, nsmap=None, nsdict=CNSD):
if attrib is None:
attrib = {}
tag, attrib = fix_ns(tag, attrib, nsdict)
if WhichElementTree == 'lxml':
el = etree.SubElement(parent, tag, attrib, nsmap=nsmap)
else:
el = _ElementInterfaceWrapper(tag, attrib)
parent.append(el)
el.setparent(parent)
return el
def fix_ns(tag, attrib, nsdict):
nstag = add_ns(tag, nsdict)
nsattrib = {}
for key, val in attrib.iteritems():
nskey = add_ns(key, nsdict)
nsattrib[nskey] = val
return nstag, nsattrib
def add_ns(tag, nsdict=CNSD):
if WhichElementTree == 'lxml':
nstag, name = tag.split(':')
ns = nsdict.get(nstag)
if ns is None:
raise RuntimeError, 'Invalid namespace prefix: %s' % nstag
tag = '{%s}%s' % (ns, name,)
return tag
def ToString(et):
outstream = StringIO.StringIO()
et.write(outstream)
s1 = outstream.getvalue()
outstream.close()
return s1
def escape_cdata(text):
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
ascii = ''
for char in text:
if ord(char) >= ord("\x7f"):
ascii += "&#x%X;" % ( ord(char), )
else:
ascii += char
return ascii
#
# Classes
#
WORD_SPLIT_PAT1 = re.compile(r'\b(\w*)\b\W*')
def split_words(line):
# We need whitespace at the end of the string for our regexpr.
line += ' '
words = []
pos1 = 0
mo = WORD_SPLIT_PAT1.search(line, pos1)
while mo is not None:
word = mo.groups()[0]
words.append(word)
pos1 = mo.end()
mo = WORD_SPLIT_PAT1.search(line, pos1)
return words
#
# Information about the indentation level for lists nested inside
# other contexts, e.g. dictionary lists.
class ListLevel(object):
def __init__(self, level, sibling_level=True, nested_level=True):
self.level = level
self.sibling_level = sibling_level
self.nested_level = nested_level
def set_sibling(self, sibling_level): self.sibling_level = sibling_level
def get_sibling(self): return self.sibling_level
def set_nested(self, nested_level): self.nested_level = nested_level
def get_nested(self): return self.nested_level
def set_level(self, level): self.level = level
def get_level(self): return self.level
class Writer(writers.Writer):
MIME_TYPE = 'application/vnd.oasis.opendocument.text'
EXTENSION = '.odt'
supported = ('html', 'html4css1', 'xhtml')
"""Formats this writer supports."""
default_stylesheet = 'styles' + EXTENSION
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = (
'ODF-Specific Options',
None,
(
('Specify a stylesheet. '
'Default: "%s"' % default_stylesheet_path,
['--stylesheet'],
{
'default': default_stylesheet_path,
'dest': 'stylesheet'
}),
('Specify a configuration/mapping file relative to the '
'current working '
'directory for additional ODF options. '
'In particular, this file may contain a section named '
'"Formats" that maps default style names to '
'names to be used in the resulting output file allowing for '
'adhering to external standards. '
'For more info and the format of the configuration/mapping file, '
'see the odtwriter doc.',
['--odf-config-file'],
{'metavar': '<file>'}),
('Obfuscate email addresses to confuse harvesters while still '
'keeping email links usable with standards-compliant browsers.',
['--cloak-email-addresses'],
{'default': False,
'action': 'store_true',
'dest': 'cloak_email_addresses',
'validator': frontend.validate_boolean}),
('Do not obfuscate email addresses.',
['--no-cloak-email-addresses'],
{'default': False,
'action': 'store_false',
'dest': 'cloak_email_addresses',
'validator': frontend.validate_boolean}),
('Specify the thickness of table borders in thousands of a cm. '
'Default is 35.',
['--table-border-thickness'],
{'default': 35,
'validator': frontend.validate_nonnegative_int}),
('Add syntax highlighting in literal code blocks.',
['--add-syntax-highlighting'],
{'default': False,
'action': 'store_true',
'dest': 'add_syntax_highlighting',
'validator': frontend.validate_boolean}),
('Do not add syntax highlighting in literal code blocks. (default)',
['--no-syntax-highlighting'],
{'default': False,
'action': 'store_false',
'dest': 'add_syntax_highlighting',
'validator': frontend.validate_boolean}),
('Create sections for headers. (default)',
['--create-sections'],
{'default': True,
'action': 'store_true',
'dest': 'create_sections',
'validator': frontend.validate_boolean}),
('Do not create sections for headers.',
['--no-sections'],
{'default': True,
'action': 'store_false',
'dest': 'create_sections',
'validator': frontend.validate_boolean}),
('Create links.',
['--create-links'],
{'default': False,
'action': 'store_true',
'dest': 'create_links',
'validator': frontend.validate_boolean}),
('Do not create links. (default)',
['--no-links'],
{'default': False,
'action': 'store_false',
'dest': 'create_links',
'validator': frontend.validate_boolean}),
('Generate endnotes at end of document, not footnotes '
'at bottom of page.',
['--endnotes-end-doc'],
{'default': False,
'action': 'store_true',
'dest': 'endnotes_end_doc',
'validator': frontend.validate_boolean}),
('Generate footnotes at bottom of page, not endnotes '
'at end of document. (default)',
['--no-endnotes-end-doc'],
{'default': False,
'action': 'store_false',
'dest': 'endnotes_end_doc',
'validator': frontend.validate_boolean}),
('Generate a bullet list table of contents, not '
'an ODF/oowriter table of contents.',
['--generate-list-toc'],
{'default': True,
'action': 'store_false',
'dest': 'generate_oowriter_toc',
'validator': frontend.validate_boolean}),
('Generate an ODF/oowriter table of contents, not '
'a bullet list. (default)',
['--generate-oowriter-toc'],
{'default': True,
'action': 'store_true',
'dest': 'generate_oowriter_toc',
'validator': frontend.validate_boolean}),
)
)
settings_defaults = {
'output_encoding_error_handler': 'xmlcharrefreplace',
}
relative_path_settings = (
'stylesheet_path',
)
config_section = 'opendocument odf writer'
config_section_dependencies = (
'writers',
)
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = ODFTranslator
def translate(self):
self.settings = self.document.settings
self.visitor = self.translator_class(self.document)
self.document.walkabout(self.visitor)
self.visitor.add_doc_title()
self.assemble_my_parts()
self.output = self.parts['whole']
def assemble_my_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses.
"""
writers.Writer.assemble_parts(self)
f = tempfile.NamedTemporaryFile()
zfile = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
content = self.visitor.content_astext()
self.write_zip_str(zfile, 'content.xml', content)
self.write_zip_str(zfile, 'mimetype', self.MIME_TYPE)
s1 = self.create_manifest()
self.write_zip_str(zfile, 'META-INF/manifest.xml', s1)
s1 = self.create_meta()
self.write_zip_str(zfile, 'meta.xml', s1)
s1 = self.get_stylesheet()
self.write_zip_str(zfile, 'styles.xml', s1)
s1 = self.get_settings()
self.write_zip_str(zfile, 'settings.xml', s1)
self.store_embedded_files(zfile)
zfile.close()
f.seek(0)
whole = f.read()
f.close()
self.parts['whole'] = whole
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
def write_zip_str(self, zfile, name, bytes):
localtime = time.localtime(time.time())
zinfo = zipfile.ZipInfo(name, localtime)
# Add some standard UNIX file access permissions (-rw-r--r--).
zinfo.external_attr = (0x81a4 & 0xFFFF) << 16L
zinfo.compress_type = zipfile.ZIP_DEFLATED
zfile.writestr(zinfo, bytes)
def store_embedded_files(self, zfile):
embedded_files = self.visitor.get_embedded_file_list()
for source, destination in embedded_files:
if source is None:
continue
try:
# encode/decode
destination1 = destination.decode('latin-1').encode('utf-8')
zfile.write(source, destination1, zipfile.ZIP_STORED)
except OSError, e:
self.document.reporter.warning(
"Can't open file %s." % (source, ))
def get_settings(self):
"""
modeled after get_stylesheet
"""
stylespath = self.settings.stylesheet
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('settings.xml')
zfile.close()
return s1
def get_stylesheet(self):
"""Retrieve the stylesheet from either a .xml file or from
a .odt (zip) file. Return the content as a string.
"""
stylespath = self.settings.stylesheet
ext = os.path.splitext(stylespath)[1]
if ext == '.xml':
stylesfile = open(stylespath, 'r')
s1 = stylesfile.read()
stylesfile.close()
elif ext == self.EXTENSION:
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('styles.xml')
zfile.close()
else:
raise RuntimeError, 'stylesheet path (%s) must be %s or .xml file' %(stylespath, self.EXTENSION)
s1 = self.visitor.setup_page(s1)
return s1
def assemble_parts(self):
pass
def create_manifest(self):
if WhichElementTree == 'lxml':
root = Element('manifest:manifest',
nsmap=MANIFEST_NAMESPACE_DICT,
nsdict=MANIFEST_NAMESPACE_DICT,
)
else:
root = Element('manifest:manifest',
attrib=MANIFEST_NAMESPACE_ATTRIB,
nsdict=MANIFEST_NAMESPACE_DICT,
)
doc = etree.ElementTree(root)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': self.MIME_TYPE,
'manifest:full-path': '/',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'content.xml',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'styles.xml',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'meta.xml',
}, nsdict=MANNSD)
s1 = ToString(doc)
doc = minidom.parseString(s1)
s1 = doc.toprettyxml(' ')
return s1
def create_meta(self):
if WhichElementTree == 'lxml':
root = Element('office:document-meta',
nsmap=META_NAMESPACE_DICT,
nsdict=META_NAMESPACE_DICT,
)
else:
root = Element('office:document-meta',
attrib=META_NAMESPACE_ATTRIB,
nsdict=META_NAMESPACE_DICT,
)
doc = etree.ElementTree(root)
root = SubElement(root, 'office:meta', nsdict=METNSD)
el1 = SubElement(root, 'meta:generator', nsdict=METNSD)
el1.text = 'Docutils/rst2odf.py/%s' % (VERSION, )
s1 = os.environ.get('USER', '')
el1 = SubElement(root, 'meta:initial-creator', nsdict=METNSD)
el1.text = s1
s2 = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())
el1 = SubElement(root, 'meta:creation-date', nsdict=METNSD)
el1.text = s2
el1 = SubElement(root, 'dc:creator', nsdict=METNSD)
el1.text = s1
el1 = SubElement(root, 'dc:date', nsdict=METNSD)
el1.text = s2
el1 = SubElement(root, 'dc:language', nsdict=METNSD)
el1.text = 'en-US'
el1 = SubElement(root, 'meta:editing-cycles', nsdict=METNSD)
el1.text = '1'
el1 = SubElement(root, 'meta:editing-duration', nsdict=METNSD)
el1.text = 'PT00M01S'
title = self.visitor.get_title()
el1 = SubElement(root, 'dc:title', nsdict=METNSD)
if title:
el1.text = title
else:
el1.text = '[no title]'
meta_dict = self.visitor.get_meta_dict()
keywordstr = meta_dict.get('keywords')
if keywordstr is not None:
keywords = split_words(keywordstr)
for keyword in keywords:
el1 = SubElement(root, 'meta:keyword', nsdict=METNSD)
el1.text = keyword
description = meta_dict.get('description')
if description is not None:
el1 = SubElement(root, 'dc:description', nsdict=METNSD)
el1.text = description
s1 = ToString(doc)
#doc = minidom.parseString(s1)
#s1 = doc.toprettyxml(' ')
return s1
# class ODFTranslator(nodes.SparseNodeVisitor):
class ODFTranslator(nodes.GenericNodeVisitor):
used_styles = (
'attribution', 'blockindent', 'blockquote', 'blockquote-bulletitem',
'blockquote-bulletlist', 'blockquote-enumitem', 'blockquote-enumlist',
'bulletitem', 'bulletlist', 'caption', 'centeredtextbody', 'codeblock',
'codeblock-classname', 'codeblock-comment', 'codeblock-functionname',
'codeblock-keyword', 'codeblock-name', 'codeblock-number',
'codeblock-operator', 'codeblock-string', 'emphasis', 'enumitem',
'enumlist', 'epigraph', 'epigraph-bulletitem', 'epigraph-bulletlist',
'epigraph-enumitem', 'epigraph-enumlist', 'footer',
'footnote', 'citation',
'header', 'highlights', 'highlights-bulletitem',
'highlights-bulletlist', 'highlights-enumitem', 'highlights-enumlist',
'horizontalline', 'inlineliteral', 'quotation', 'rubric',
'strong', 'table-title', 'textbody', 'tocbulletlist', 'tocenumlist',
'title',
'subtitle',
'heading1',
'heading2',
'heading3',
'heading4',
'heading5',
'heading6',
'heading7',
'admon-attention-hdr',
'admon-attention-body',
'admon-caution-hdr',
'admon-caution-body',
'admon-danger-hdr',
'admon-danger-body',
'admon-error-hdr',
'admon-error-body',
'admon-generic-hdr',
'admon-generic-body',
'admon-hint-hdr',
'admon-hint-body',
'admon-important-hdr',
'admon-important-body',
'admon-note-hdr',
'admon-note-body',
'admon-tip-hdr',
'admon-tip-body',
'admon-warning-hdr',
'admon-warning-body',
'tableoption',
'tableoption.%c', 'tableoption.%c%d', 'Table%d', 'Table%d.%c',
'Table%d.%c%d',
'lineblock1',
'lineblock2',
'lineblock3',
'lineblock4',
'lineblock5',
'lineblock6',
)
def __init__(self, document):
#nodes.SparseNodeVisitor.__init__(self, document)
nodes.GenericNodeVisitor.__init__(self, document)
self.settings = document.settings
self.format_map = { }
if self.settings.odf_config_file:
from ConfigParser import ConfigParser
parser = ConfigParser()
parser.read(self.settings.odf_config_file)
for rststyle, format in parser.items("Formats"):
if rststyle not in self.used_styles:
self.document.reporter.warning(
'Style "%s" is not a style used by odtwriter.' % (
rststyle, ))
self.format_map[rststyle] = format
self.section_level = 0
self.section_count = 0
# Create ElementTree content and styles documents.
if WhichElementTree == 'lxml':
root = Element(
'office:document-content',
nsmap=CONTENT_NAMESPACE_DICT,
)
else:
root = Element(
'office:document-content',
attrib=CONTENT_NAMESPACE_ATTRIB,
)
self.content_tree = etree.ElementTree(element=root)
self.current_element = root
SubElement(root, 'office:scripts')
SubElement(root, 'office:font-face-decls')
el = SubElement(root, 'office:automatic-styles')
self.automatic_styles = el
el = SubElement(root, 'office:body')
el = self.generate_content_element(el)
self.current_element = el
self.body_text_element = el
self.paragraph_style_stack = [self.rststyle('textbody'), ]
self.list_style_stack = []
self.table_count = 0
self.column_count = ord('A') - 1
self.trace_level = -1
self.optiontablestyles_generated = False
self.field_name = None
self.field_element = None
self.title = None
self.image_count = 0
self.image_style_count = 0
self.image_dict = {}
self.embedded_file_list = []
self.syntaxhighlighting = 1
self.syntaxhighlight_lexer = 'python'
self.header_content = []
self.footer_content = []
self.in_header = False
self.in_footer = False
self.blockstyle = ''
self.in_table_of_contents = False
self.table_of_content_index_body = None
self.list_level = 0
self.footnote_ref_dict = {}
self.footnote_list = []
self.footnote_chars_idx = 0
self.footnote_level = 0
self.pending_ids = [ ]
self.in_paragraph = False
self.found_doc_title = False
self.bumped_list_level_stack = []
self.meta_dict = {}
self.line_block_level = 0
self.line_indent_level = 0
self.citation_id = None
def add_doc_title(self):
text = self.settings.title
if text:
self.title = text
if not self.found_doc_title:
el = Element('text:p', attrib = {
'text:style-name': self.rststyle('title'),
})
el.text = text
self.body_text_element.insert(0, el)
def rststyle(self, name, parameters=( )):
"""
Returns the style name to use for the given style.
If `parameters` is given `name` must contain a matching number of ``%`` and
is used as a format expression with `parameters` as the value.
"""
name1 = name % parameters
stylename = self.format_map.get(name1, 'rststyle-%s' % name1)
return stylename
def generate_content_element(self, root):
return SubElement(root, 'office:text')
def setup_page(self, content):
root_el = etree.fromstring(content)
self.setup_paper(root_el)
if len(self.header_content) > 0 or len(self.footer_content) > 0:
self.add_header_footer(root_el)
new_content = etree.tostring(root_el)
return new_content
def setup_paper(self, root_el):
try:
fin = os.popen("paperconf -s 2> /dev/null")
w, h = map(float, fin.read().split())
fin.close()
except:
w, h = 612, 792 # default to Letter
def walk(el):
if el.tag == "{%s}page-layout-properties" % SNSD["style"] and \
not el.attrib.has_key("{%s}page-width" % SNSD["fo"]):
el.attrib["{%s}page-width" % SNSD["fo"]] = "%.3fpt" % w
el.attrib["{%s}page-height" % SNSD["fo"]] = "%.3fpt" % h
el.attrib["{%s}margin-left" % SNSD["fo"]] = \
el.attrib["{%s}margin-right" % SNSD["fo"]] = \
"%.3fpt" % (.1 * w)
el.attrib["{%s}margin-top" % SNSD["fo"]] = \
el.attrib["{%s}margin-bottom" % SNSD["fo"]] = \
"%.3fpt" % (.1 * h)
else:
for subel in el.getchildren(): walk(subel)
walk(root_el)
def add_header_footer(self, root_el):
path = '{%s}master-styles' % (NAME_SPACE_1, )
master_el = root_el.find(path)
if master_el is None:
return
path = '{%s}master-page' % (SNSD['style'], )
master_el = master_el.find(path)
if master_el is None:
return
el1 = master_el
if len(self.header_content) > 0:
if WhichElementTree == 'lxml':
el2 = SubElement(el1, 'style:header', nsdict=SNSD)
else:
el2 = SubElement(el1, 'style:header',
attrib=STYLES_NAMESPACE_ATTRIB,
nsdict=STYLES_NAMESPACE_DICT,
)
for el in self.header_content:
attrkey = add_ns('text:style-name', nsdict=SNSD)
el.attrib[attrkey] = self.rststyle('header')
el2.append(el)
if len(self.footer_content) > 0:
if WhichElementTree == 'lxml':
el2 = SubElement(el1, 'style:footer', nsdict=SNSD)
else:
el2 = SubElement(el1, 'style:footer',
attrib=STYLES_NAMESPACE_ATTRIB,
nsdict=STYLES_NAMESPACE_DICT,
)
for el in self.footer_content:
attrkey = add_ns('text:style-name', nsdict=SNSD)
el.attrib[attrkey] = self.rststyle('footer')
el2.append(el)
def astext(self):
root = self.content_tree.getroot()
et = etree.ElementTree(root)
s1 = ToString(et)
return s1
def content_astext(self):
return self.astext()
def set_title(self, title): self.title = title
def get_title(self): return self.title
def set_embedded_file_list(self, embedded_file_list):
self.embedded_file_list = embedded_file_list
def get_embedded_file_list(self): return self.embedded_file_list
def get_meta_dict(self): return self.meta_dict
def process_footnotes(self):
for node, el1 in self.footnote_list:
backrefs = node.attributes.get('backrefs', [])
first = True
for ref in backrefs:
el2 = self.footnote_ref_dict.get(ref)
if el2 is not None:
if first:
first = False
el3 = copy.deepcopy(el1)
el2.append(el3)
else:
children = el2.getchildren()
if len(children) > 0: # and 'id' in el2.attrib:
child = children[0]
ref1 = child.text
attribkey = add_ns('text:id', nsdict=SNSD)
id1 = el2.get(attribkey, 'footnote-error')
if id1 is None:
id1 = ''
tag = add_ns('text:note-ref', nsdict=SNSD)
el2.tag = tag
if self.settings.endnotes_end_doc:
note_class = 'endnote'
else:
note_class = 'footnote'
el2.attrib.clear()
attribkey = add_ns('text:note-class', nsdict=SNSD)
el2.attrib[attribkey] = note_class
attribkey = add_ns('text:ref-name', nsdict=SNSD)
el2.attrib[attribkey] = id1
attribkey = add_ns('text:reference-format', nsdict=SNSD)
el2.attrib[attribkey] = 'page'
el2.text = ref1
#
# Utility methods
def append_child(self, tag, attrib=None, parent=None):
if parent is None:
parent = self.current_element
if attrib is None:
el = SubElement(parent, tag)
else:
el = SubElement(parent, tag, attrib)
return el
def append_p(self, style, text=None):
result = self.append_child('text:p', attrib={
'text:style-name': self.rststyle(style)})
self.append_pending_ids(result)
if text is not None:
result.text = text
return result
def append_pending_ids(self, el):
if self.settings.create_links:
for id in self.pending_ids:
SubElement(el, 'text:reference-mark', attrib={
'text:name': id})
self.pending_ids = [ ]
def set_current_element(self, el):
self.current_element = el
def set_to_parent(self):
self.current_element = self.current_element.getparent()
def generate_labeled_block(self, node, label):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
el = self.append_p('blockindent')
return el
def generate_labeled_line(self, node, label):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
el1.tail = node.astext()
return el
def encode(self, text):
text = text.replace(u'\u00a0', " ")
return text
#
# Visitor functions
#
# In alphabetic order, more or less.
# See docutils.docutils.nodes.node_class_names.
#
def dispatch_visit(self, node):
"""Override to catch basic attributes which many nodes have."""
self.handle_basic_atts(node)
nodes.GenericNodeVisitor.dispatch_visit(self, node)
def handle_basic_atts(self, node):
if isinstance(node, nodes.Element) and node['ids']:
self.pending_ids += node['ids']
def default_visit(self, node):
self.document.reporter.warning('missing visit_%s' % (node.tagname, ))
def default_departure(self, node):
self.document.reporter.warning('missing depart_%s' % (node.tagname, ))
def visit_Text(self, node):
# Skip nodes whose text has been processed in parent nodes.
if isinstance(node.parent, docutils.nodes.literal_block):
return
text = node.astext()
# Are we in mixed content? If so, add the text to the
# etree tail of the previous sibling element.
if len(self.current_element.getchildren()) > 0:
if self.current_element.getchildren()[-1].tail:
self.current_element.getchildren()[-1].tail += text
else:
self.current_element.getchildren()[-1].tail = text
else:
if self.current_element.text:
self.current_element.text += text
else:
self.current_element.text = text
def depart_Text(self, node):
pass
#
# Pre-defined fields
#
def visit_address(self, node):
el = self.generate_labeled_block(node, 'Address: ')
self.set_current_element(el)
def depart_address(self, node):
self.set_to_parent()
def visit_author(self, node):
if isinstance(node.parent, nodes.authors):
el = self.append_p('blockindent')
else:
el = self.generate_labeled_block(node, 'Author: ')
self.set_current_element(el)
def depart_author(self, node):
self.set_to_parent()
def visit_authors(self, node):
label = 'Authors:'
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
def depart_authors(self, node):
pass
def visit_contact(self, node):
el = self.generate_labeled_block(node, 'Contact: ')
self.set_current_element(el)
def depart_contact(self, node):
self.set_to_parent()
def visit_copyright(self, node):
el = self.generate_labeled_block(node, 'Copyright: ')
self.set_current_element(el)
def depart_copyright(self, node):
self.set_to_parent()
def visit_date(self, node):
self.generate_labeled_line(node, 'Date: ')
def depart_date(self, node):
pass
def visit_organization(self, node):
el = self.generate_labeled_block(node, 'Organization: ')
self.set_current_element(el)
def depart_organization(self, node):
self.set_to_parent()
def visit_status(self, node):
el = self.generate_labeled_block(node, 'Status: ')
self.set_current_element(el)
def depart_status(self, node):
self.set_to_parent()
def visit_revision(self, node):
self.generate_labeled_line(node, 'Revision: ')
def depart_revision(self, node):
pass
def visit_version(self, node):
el = self.generate_labeled_line(node, 'Version: ')
#self.set_current_element(el)
def depart_version(self, node):
#self.set_to_parent()
pass
def visit_attribution(self, node):
el = self.append_p('attribution', node.astext())
def depart_attribution(self, node):
pass
def visit_block_quote(self, node):
if 'epigraph' in node.attributes['classes']:
self.paragraph_style_stack.append(self.rststyle('epigraph'))
self.blockstyle = self.rststyle('epigraph')
elif 'highlights' in node.attributes['classes']:
self.paragraph_style_stack.append(self.rststyle('highlights'))
self.blockstyle = self.rststyle('highlights')
else:
self.paragraph_style_stack.append(self.rststyle('blockquote'))
self.blockstyle = self.rststyle('blockquote')
self.line_indent_level += 1
def depart_block_quote(self, node):
self.paragraph_style_stack.pop()
self.blockstyle = ''
self.line_indent_level -= 1
def visit_bullet_list(self, node):
self.list_level +=1
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
pass
else:
if node.has_key('classes') and \
'auto-toc' in node.attributes['classes']:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('tocenumlist'),
})
self.list_style_stack.append(self.rststyle('enumitem'))
else:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('tocbulletlist'),
})
self.list_style_stack.append(self.rststyle('bulletitem'))
self.set_current_element(el)
else:
if self.blockstyle == self.rststyle('blockquote'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('blockquote-bulletitem'))
elif self.blockstyle == self.rststyle('highlights'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('highlights-bulletitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('epigraph-bulletitem'))
else:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('bulletlist'),
})
self.list_style_stack.append(self.rststyle('bulletitem'))
self.set_current_element(el)
def depart_bullet_list(self, node):
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
pass
else:
self.set_to_parent()
self.list_style_stack.pop()
else:
self.set_to_parent()
self.list_style_stack.pop()
self.list_level -=1
def visit_caption(self, node):
raise nodes.SkipChildren()
pass
def depart_caption(self, node):
pass
def visit_comment(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'office:annotation', attrib={})
el2 = SubElement(el1, 'text:p', attrib={})
el2.text = node.astext()
def depart_comment(self, node):
pass
def visit_compound(self, node):
# The compound directive currently receives no special treatment.
pass
def depart_compound(self, node):
pass
def visit_container(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
self.paragraph_style_stack.append(self.rststyle(styles[0]))
def depart_container(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
self.paragraph_style_stack.pop()
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
self.paragraph_style_stack.append(self.rststyle('blockindent'))
self.bumped_list_level_stack.append(ListLevel(1))
def depart_definition(self, node):
self.paragraph_style_stack.pop()
self.bumped_list_level_stack.pop()
def visit_definition_list(self, node):
pass
def depart_definition_list(self, node):
pass
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_term(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
#el1.text = node.astext()
self.set_current_element(el1)
def depart_term(self, node):
self.set_to_parent()
self.set_to_parent()
def visit_classifier(self, node):
els = self.current_element.getchildren()
if len(els) > 0:
el = els[-1]
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('emphasis')
})
el1.text = ' (%s)' % (node.astext(), )
def depart_classifier(self, node):
pass
def visit_document(self, node):
pass
def depart_document(self, node):
self.process_footnotes()
def visit_docinfo(self, node):
self.section_level += 1
self.section_count += 1
if self.settings.create_sections:
el = self.append_child('text:section', attrib={
'text:name': 'Section%d' % self.section_count,
'text:style-name': 'Sect%d' % self.section_level,
})
self.set_current_element(el)
def depart_docinfo(self, node):
self.section_level -= 1
if self.settings.create_sections:
self.set_to_parent()
def visit_emphasis(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('emphasis')})
self.set_current_element(el)
def depart_emphasis(self, node):
self.set_to_parent()
def visit_enumerated_list(self, node):
el1 = self.current_element
if self.blockstyle == self.rststyle('blockquote'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-enumlist'),
})
self.list_style_stack.append(self.rststyle('blockquote-enumitem'))
elif self.blockstyle == self.rststyle('highlights'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-enumlist'),
})
self.list_style_stack.append(self.rststyle('highlights-enumitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-enumlist'),
})
self.list_style_stack.append(self.rststyle('epigraph-enumitem'))
else:
liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), )
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle(liststylename),
})
self.list_style_stack.append(self.rststyle('enumitem'))
self.set_current_element(el2)
def depart_enumerated_list(self, node):
self.set_to_parent()
self.list_style_stack.pop()
def visit_list_item(self, node):
# If we are in a "bumped" list level, then wrap this
# list in an outer lists in order to increase the
# indentation level.
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
self.paragraph_style_stack.append(
self.rststyle('contents-%d' % (self.list_level, )))
else:
el1 = self.append_child('text:list-item')
self.set_current_element(el1)
else:
el1 = self.append_child('text:list-item')
el3 = el1
if len(self.bumped_list_level_stack) > 0:
level_obj = self.bumped_list_level_stack[-1]
if level_obj.get_sibling():
level_obj.set_nested(False)
for level_obj1 in self.bumped_list_level_stack:
for idx in range(level_obj1.get_level()):
el2 = self.append_child('text:list', parent=el3)
el3 = self.append_child(
'text:list-item', parent=el2)
self.paragraph_style_stack.append(self.list_style_stack[-1])
self.set_current_element(el3)
def depart_list_item(self, node):
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
self.paragraph_style_stack.pop()
else:
self.set_to_parent()
else:
if len(self.bumped_list_level_stack) > 0:
level_obj = self.bumped_list_level_stack[-1]
if level_obj.get_sibling():
level_obj.set_nested(True)
for level_obj1 in self.bumped_list_level_stack:
for idx in range(level_obj1.get_level()):
self.set_to_parent()
self.set_to_parent()
self.paragraph_style_stack.pop()
self.set_to_parent()
def visit_header(self, node):
self.in_header = True
def depart_header(self, node):
self.in_header = False
def visit_footer(self, node):
self.in_footer = True
def depart_footer(self, node):
self.in_footer = False
def visit_field(self, node):
pass
def depart_field(self, node):
pass
def visit_field_list(self, node):
pass
def depart_field_list(self, node):
pass
def visit_field_name(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = node.astext()
def depart_field_name(self, node):
pass
def visit_field_body(self, node):
self.paragraph_style_stack.append(self.rststyle('blockindent'))
def depart_field_body(self, node):
self.paragraph_style_stack.pop()
def visit_figure(self, node):
pass
def depart_figure(self, node):
pass
def visit_footnote(self, node):
self.footnote_level += 1
self.save_footnote_current = self.current_element
el1 = Element('text:note-body')
self.current_element = el1
self.footnote_list.append((node, el1))
if isinstance(node, docutils.nodes.citation):
self.paragraph_style_stack.append(self.rststyle('citation'))
else:
self.paragraph_style_stack.append(self.rststyle('footnote'))
def depart_footnote(self, node):
self.paragraph_style_stack.pop()
self.current_element = self.save_footnote_current
self.footnote_level -= 1
footnote_chars = [
'*', '**', '***',
'++', '+++',
'##', '###',
'@@', '@@@',
]
def visit_footnote_reference(self, node):
if self.footnote_level <= 0:
id = node.attributes['ids'][0]
refid = node.attributes.get('refid')
if refid is None:
refid = ''
if self.settings.endnotes_end_doc:
note_class = 'endnote'
else:
note_class = 'footnote'
el1 = self.append_child('text:note', attrib={
'text:id': '%s' % (refid, ),
'text:note-class': note_class,
})
note_auto = str(node.attributes.get('auto', 1))
if isinstance(node, docutils.nodes.citation_reference):
citation = '[%s]' % node.astext()
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': citation,
})
el2.text = citation
elif note_auto == '1':
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': node.astext(),
})
el2.text = node.astext()
elif note_auto == '*':
if self.footnote_chars_idx >= len(
ODFTranslator.footnote_chars):
self.footnote_chars_idx = 0
footnote_char = ODFTranslator.footnote_chars[
self.footnote_chars_idx]
self.footnote_chars_idx += 1
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': footnote_char,
})
el2.text = footnote_char
self.footnote_ref_dict[id] = el1
raise nodes.SkipChildren()
def depart_footnote_reference(self, node):
pass
def visit_citation(self, node):
for id in node.attributes['ids']:
self.citation_id = id
break
self.paragraph_style_stack.append(self.rststyle('blockindent'))
self.bumped_list_level_stack.append(ListLevel(1))
def depart_citation(self, node):
self.citation_id = None
self.paragraph_style_stack.pop()
self.bumped_list_level_stack.pop()
def visit_citation_reference(self, node):
if self.settings.create_links:
id = node.attributes['refid']
el = self.append_child('text:reference-ref', attrib={
'text:ref-name': '%s' % (id, ),
'text:reference-format': 'text',
})
el.text = '['
self.set_current_element(el)
elif self.current_element.text is None:
self.current_element.text = '['
else:
self.current_element.text += '['
def depart_citation_reference(self, node):
self.current_element.text += ']'
if self.settings.create_links:
self.set_to_parent()
def visit_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
raise nodes.SkipChildren()
elif self.citation_id is not None:
el = self.append_p('textbody')
self.set_current_element(el)
el.text = '['
if self.settings.create_links:
el1 = self.append_child('text:reference-mark-start', attrib={
'text:name': '%s' % (self.citation_id, ),
})
def depart_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
pass
elif self.citation_id is not None:
self.current_element.text += ']'
if self.settings.create_links:
el = self.append_child('text:reference-mark-end', attrib={
'text:name': '%s' % (self.citation_id, ),
})
self.set_to_parent()
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def check_file_exists(self, path):
if os.path.exists(path):
return 1
else:
return 0
def visit_image(self, node):
# Capture the image file.
if 'uri' in node.attributes:
source = node.attributes['uri']
if not self.check_file_exists(source):
self.document.reporter.warning(
'Cannot find image file %s.' % (source, ))
return
else:
return
if source in self.image_dict:
filename, destination = self.image_dict[source]
else:
self.image_count += 1
filename = os.path.split(source)[1]
destination = 'Pictures/1%08x%s' % (self.image_count, filename, )
spec = (os.path.abspath(source), destination,)
self.embedded_file_list.append(spec)
self.image_dict[source] = (source, destination,)
# Is this a figure (containing an image) or just a plain image?
if self.in_paragraph:
el1 = self.current_element
else:
el1 = SubElement(self.current_element, 'text:p',
attrib={'text:style-name': self.rststyle('textbody')})
el2 = el1
if isinstance(node.parent, docutils.nodes.figure):
el3, el4, caption = self.generate_figure(node, source,
destination, el2)
attrib = {
'draw:blue': '0%',
'draw:color-inversion': 'false',
'draw:color-mode': 'standard',
'draw:contrast': '0%',
'draw:gamma': '100%',
'draw:green': '0%',
'draw:image-opacity': '100%',
'draw:luminance': '0%',
'draw:red': '0%',
'fo:border': 'none',
'fo:clip': 'rect(0in 0in 0in 0in)',
'fo:margin-bottom': '0in',
'fo:margin-left': '0in',
'fo:margin-right': '0in',
'fo:margin-top': '0in',
'fo:padding': '0in',
'style:horizontal-pos': 'from-left',
'style:horizontal-rel': 'paragraph-content',
'style:mirror': 'none',
'style:run-through': 'foreground',
'style:shadow': 'none',
'style:vertical-pos': 'from-top',
'style:vertical-rel': 'paragraph-content',
'style:wrap': 'none',
}
el5, width = self.generate_image(node, source, destination,
el4, attrib)
if caption is not None:
el5.tail = caption
else: #if isinstance(node.parent, docutils.nodes.image):
el3 = self.generate_image(node, source, destination, el2)
def depart_image(self, node):
pass
def get_image_width_height(self, node, attr):
size = None
if attr in node.attributes:
size = node.attributes[attr]
unit = size[-2:]
if unit.isalpha():
size = size[:-2]
else:
unit = 'px'
try:
size = float(size)
except ValueError, e:
self.document.reporter.warning(
'Invalid %s for image: "%s"' % (
attr, node.attributes[attr]))
size = [size, unit]
return size
def get_image_scale(self, node):
if 'scale' in node.attributes:
try:
scale = int(node.attributes['scale'])
if scale < 1: # or scale > 100:
self.document.reporter.warning(
'scale out of range (%s), using 1.' % (scale, ))
scale = 1
scale = scale * 0.01
except ValueError, e:
self.document.reporter.warning(
'Invalid scale for image: "%s"' % (
node.attributes['scale'], ))
else:
scale = 1.0
return scale
def get_image_scaled_width_height(self, node, source):
scale = self.get_image_scale(node)
width = self.get_image_width_height(node, 'width')
height = self.get_image_width_height(node, 'height')
dpi = (72, 72)
if Image is not None and source in self.image_dict:
filename, destination = self.image_dict[source]
imageobj = Image.open(filename, 'r')
dpi = imageobj.info.get('dpi', dpi)
# dpi information can be (xdpi, ydpi) or xydpi
try: iter(dpi)
except: dpi = (dpi, dpi)
else:
imageobj = None
if width is None or height is None:
if imageobj is None:
raise RuntimeError(
'image size not fully specified and PIL not installed')
if width is None: width = [imageobj.size[0], 'px']
if height is None: height = [imageobj.size[1], 'px']
width[0] *= scale
height[0] *= scale
if width[1] == 'px': width = [width[0] / dpi[0], 'in']
if height[1] == 'px': height = [height[0] / dpi[1], 'in']
width[0] = str(width[0])
height[0] = str(height[0])
return ''.join(width), ''.join(height)
def generate_figure(self, node, source, destination, current_element):
caption = None
width, height = self.get_image_scaled_width_height(node, source)
for node1 in node.parent.children:
if node1.tagname == 'caption':
caption = node1.astext()
self.image_style_count += 1
#
# Add the style for the caption.
if caption is not None:
attrib = {
'style:class': 'extra',
'style:family': 'paragraph',
'style:name': 'Caption',
'style:parent-style-name': 'Standard',
}
el1 = SubElement(self.automatic_styles, 'style:style',
attrib=attrib, nsdict=SNSD)
attrib = {
'fo:margin-bottom': '0.0835in',
'fo:margin-top': '0.0835in',
'text:line-number': '0',
'text:number-lines': 'false',
}
el2 = SubElement(el1, 'style:paragraph-properties',
attrib=attrib, nsdict=SNSD)
attrib = {
'fo:font-size': '12pt',
'fo:font-style': 'italic',
'style:font-name': 'Times',
'style:font-name-complex': 'Lucidasans1',
'style:font-size-asian': '12pt',
'style:font-size-complex': '12pt',
'style:font-style-asian': 'italic',
'style:font-style-complex': 'italic',
}
el2 = SubElement(el1, 'style:text-properties',
attrib=attrib, nsdict=SNSD)
style_name = 'rstframestyle%d' % self.image_style_count
# Add the styles
attrib = {
'style:name': style_name,
'style:family': 'graphic',
'style:parent-style-name': 'Frame',
}
el1 = SubElement(self.automatic_styles,
'style:style', attrib=attrib, nsdict=SNSD)
halign = 'center'
valign = 'top'
if 'align' in node.attributes:
align = node.attributes['align'].split()
for val in align:
if val in ('left', 'center', 'right'):
halign = val
elif val in ('top', 'middle', 'bottom'):
valign = val
attrib = {
'fo:margin-left': '0cm',
'fo:margin-right': '0cm',
'fo:margin-top': '0cm',
'fo:margin-bottom': '0cm',
# 'style:wrap': 'dynamic', #vds
'style:number-wrapped-paragraphs': 'no-limit',
'style:vertical-pos': valign,
'style:vertical-rel': 'paragraph',
'style:horizontal-pos': halign,
'style:horizontal-rel': 'paragraph',
'fo:padding': '0cm',
'fo:border': 'none',
}
wrap = False
classes = node.parent.attributes.get('classes')
if classes and 'wrap' in classes:
wrap = True
if wrap:
attrib['style:wrap'] = 'dynamic'
else:
attrib['style:wrap'] = 'none'
el2 = SubElement(el1,
'style:graphic-properties', attrib=attrib, nsdict=SNSD)
attrib = {
'draw:style-name': style_name,
'draw:name': 'Frame1',
'text:anchor-type': 'paragraph',
'draw:z-index': '1',
}
attrib['svg:width'] = width
# dbg
#attrib['svg:height'] = height
el3 = SubElement(current_element, 'draw:frame', attrib=attrib)
attrib = {}
el4 = SubElement(el3, 'draw:text-box', attrib=attrib)
attrib = {
'text:style-name': self.rststyle('caption'),
}
el5 = SubElement(el4, 'text:p', attrib=attrib)
return el3, el5, caption
def generate_image(self, node, source, destination, current_element,
frame_attrs=None):
width, height = self.get_image_scaled_width_height(node, source)
self.image_style_count += 1
style_name = 'rstframestyle%d' % self.image_style_count
# Add the style.
attrib = {
'style:name': style_name,
'style:family': 'graphic',
'style:parent-style-name': 'Graphics',
}
el1 = SubElement(self.automatic_styles,
'style:style', attrib=attrib, nsdict=SNSD)
halign = None
valign = None
if 'align' in node.attributes:
align = node.attributes['align'].split()
for val in align:
if val in ('left', 'center', 'right'):
halign = val
elif val in ('top', 'middle', 'bottom'):
valign = val
if frame_attrs is None:
attrib = {
'style:vertical-pos': 'top',
'style:vertical-rel': 'paragraph',
'style:horizontal-rel': 'paragraph',
'style:mirror': 'none',
'fo:clip': 'rect(0cm 0cm 0cm 0cm)',
'draw:luminance': '0%',
'draw:contrast': '0%',
'draw:red': '0%',
'draw:green': '0%',
'draw:blue': '0%',
'draw:gamma': '100%',
'draw:color-inversion': 'false',
'draw:image-opacity': '100%',
'draw:color-mode': 'standard',
}
else:
attrib = frame_attrs
if halign is not None:
attrib['style:horizontal-pos'] = halign
if valign is not None:
attrib['style:vertical-pos'] = valign
# If there is a classes/wrap directive or we are
# inside a table, add a no-wrap style.
wrap = False
classes = node.attributes.get('classes')
if classes and 'wrap' in classes:
wrap = True
if wrap:
attrib['style:wrap'] = 'dynamic'
else:
attrib['style:wrap'] = 'none'
# If we are inside a table, add a no-wrap style.
if self.is_in_table(node):
attrib['style:wrap'] = 'none'
el2 = SubElement(el1,
'style:graphic-properties', attrib=attrib, nsdict=SNSD)
# Add the content.
#el = SubElement(current_element, 'text:p',
# attrib={'text:style-name': self.rststyle('textbody')})
attrib={
'draw:style-name': style_name,
'draw:name': 'graphics2',
'draw:z-index': '1',
}
if isinstance(node.parent, nodes.TextElement):
attrib['text:anchor-type'] = 'as-char' #vds
else:
attrib['text:anchor-type'] = 'paragraph'
attrib['svg:width'] = width
attrib['svg:height'] = height
el1 = SubElement(current_element, 'draw:frame', attrib=attrib)
el2 = SubElement(el1, 'draw:image', attrib={
'xlink:href': '%s' % (destination, ),
'xlink:type': 'simple',
'xlink:show': 'embed',
'xlink:actuate': 'onLoad',
})
return el1, width
def is_in_table(self, node):
node1 = node.parent
while node1:
if isinstance(node1, docutils.nodes.entry):
return True
node1 = node1.parent
return False
def visit_legend(self, node):
# Currently, the legend receives *no* special treatment.
pass
def depart_legend(self, node):
pass
def visit_line_block(self, node):
self.line_indent_level += 1
self.line_block_level += 1
def depart_line_block(self, node):
if self.line_block_level <= 1:
el1 = SubElement(self.current_element, 'text:p', attrib={
'text:style-name': self.rststyle('lineblock1'),
})
self.line_indent_level -= 1
self.line_block_level -= 1
def visit_line(self, node):
style = 'lineblock%d' % self.line_indent_level
el1 = SubElement(self.current_element, 'text:p', attrib={
'text:style-name': self.rststyle(style),
})
self.current_element = el1
def depart_line(self, node):
self.set_to_parent()
def visit_literal(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('inlineliteral')})
self.set_current_element(el)
def depart_literal(self, node):
self.set_to_parent()
def _calculate_code_block_padding(self, line):
count = 0
matchobj = SPACES_PATTERN.match(line)
if matchobj:
pad = matchobj.group()
count = len(pad)
else:
matchobj = TABS_PATTERN.match(line)
if matchobj:
pad = matchobj.group()
count = len(pad) * 8
return count
def _add_syntax_highlighting(self, insource, language):
lexer = pygments.lexers.get_lexer_by_name(language, stripall=True)
if language in ('latex', 'tex'):
fmtr = OdtPygmentsLaTeXFormatter(lambda name, parameters=():
self.rststyle(name, parameters),
escape_function=escape_cdata)
else:
fmtr = OdtPygmentsProgFormatter(lambda name, parameters=():
self.rststyle(name, parameters),
escape_function=escape_cdata)
outsource = pygments.highlight(insource, lexer, fmtr)
return outsource
def fill_line(self, line):
line = FILL_PAT1.sub(self.fill_func1, line)
line = FILL_PAT2.sub(self.fill_func2, line)
return line
def fill_func1(self, matchobj):
spaces = matchobj.group(0)
repl = '<text:s text:c="%d"/>' % (len(spaces), )
return repl
def fill_func2(self, matchobj):
spaces = matchobj.group(0)
repl = ' <text:s text:c="%d"/>' % (len(spaces) - 1, )
return repl
def visit_literal_block(self, node):
wrapper1 = '<text:p text:style-name="%s">%%s</text:p>' % (
self.rststyle('codeblock'), )
source = node.astext()
if (pygments and
self.settings.add_syntax_highlighting
#and
#node.get('hilight', False)
):
language = node.get('language', 'python')
source = self._add_syntax_highlighting(source, language)
else:
source = escape_cdata(source)
lines = source.split('\n')
lines1 = ['<wrappertag1 xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">']
my_lines = []
for my_line in lines:
my_line = self.fill_line(my_line)
my_line = my_line.replace(" ", "\n")
my_lines.append(my_line)
my_lines_str = '<text:line-break/>'.join(my_lines)
my_lines_str2 = wrapper1 % (my_lines_str, )
lines1.append(my_lines_str2)
lines1.append('</wrappertag1>')
s1 = ''.join(lines1)
if WhichElementTree != "lxml":
s1 = s1.encode("utf-8")
el1 = etree.fromstring(s1)
children = el1.getchildren()
for child in children:
self.current_element.append(child)
def depart_literal_block(self, node):
pass
visit_doctest_block = visit_literal_block
depart_doctest_block = depart_literal_block
def visit_meta(self, node):
name = node.attributes.get('name')
content = node.attributes.get('content')
if name is not None and content is not None:
self.meta_dict[name] = content
def depart_meta(self, node):
pass
def visit_option_list(self, node):
table_name = 'tableoption'
#
# Generate automatic styles
if not self.optiontablestyles_generated:
self.optiontablestyles_generated = True
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(table_name),
'style:family': 'table'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-properties', attrib={
'style:width': '17.59cm',
'table:align': 'left',
'style:shadow': 'none'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle('%s.%%c' % table_name, ( 'A', )),
'style:family': 'table-column'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-column-properties', attrib={
'style:column-width': '4.999cm'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle('%s.%%c' % table_name, ( 'B', )),
'style:family': 'table-column'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-column-properties', attrib={
'style:column-width': '12.587cm'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 1, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:background-color': 'transparent',
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': 'none',
'fo:border-top': '0.035cm solid #000000',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
el2 = SubElement(el1, 'style:background-image', nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 1, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border': '0.035cm solid #000000'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 2, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': 'none',
'fo:border-top': 'none',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 2, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': '0.035cm solid #000000',
'fo:border-top': 'none',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
#
# Generate table data
el = self.append_child('table:table', attrib={
'table:name': self.rststyle(table_name),
'table:style-name': self.rststyle(table_name),
})
el1 = SubElement(el, 'table:table-column', attrib={
'table:style-name': self.rststyle(
'%s.%%c' % table_name, ( 'A', ))})
el1 = SubElement(el, 'table:table-column', attrib={
'table:style-name': self.rststyle(
'%s.%%c' % table_name, ( 'B', ))})
el1 = SubElement(el, 'table:table-header-rows')
el2 = SubElement(el1, 'table:table-row')
el3 = SubElement(el2, 'table:table-cell', attrib={
'table:style-name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 1, )),
'office:value-type': 'string'})
el4 = SubElement(el3, 'text:p', attrib={
'text:style-name': 'Table_20_Heading'})
el4.text= 'Option'
el3 = SubElement(el2, 'table:table-cell', attrib={
'table:style-name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 1, )),
'office:value-type': 'string'})
el4 = SubElement(el3, 'text:p', attrib={
'text:style-name': 'Table_20_Heading'})
el4.text= 'Description'
self.set_current_element(el)
def depart_option_list(self, node):
self.set_to_parent()
def visit_option_list_item(self, node):
el = self.append_child('table:table-row')
self.set_current_element(el)
def depart_option_list_item(self, node):
self.set_to_parent()
def visit_option_group(self, node):
el = self.append_child('table:table-cell', attrib={
'table:style-name': 'Table%d.A2' % self.table_count,
'office:value-type': 'string',
})
self.set_current_element(el)
def depart_option_group(self, node):
self.set_to_parent()
def visit_option(self, node):
el = self.append_child('text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el.text = node.astext()
def depart_option(self, node):
pass
def visit_option_string(self, node):
pass
def depart_option_string(self, node):
pass
def visit_option_argument(self, node):
pass
def depart_option_argument(self, node):
pass
def visit_description(self, node):
el = self.append_child('table:table-cell', attrib={
'table:style-name': 'Table%d.B2' % self.table_count,
'office:value-type': 'string',
})
el1 = SubElement(el, 'text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el1.text = node.astext()
raise nodes.SkipChildren()
def depart_description(self, node):
pass
def visit_paragraph(self, node):
self.in_paragraph = True
if self.in_header:
el = self.append_p('header')
elif self.in_footer:
el = self.append_p('footer')
else:
style_name = self.paragraph_style_stack[-1]
el = self.append_child('text:p',
attrib={'text:style-name': style_name})
self.append_pending_ids(el)
self.set_current_element(el)
def depart_paragraph(self, node):
self.in_paragraph = False
self.set_to_parent()
if self.in_header:
self.header_content.append(
self.current_element.getchildren()[-1])
self.current_element.remove(
self.current_element.getchildren()[-1])
elif self.in_footer:
self.footer_content.append(
self.current_element.getchildren()[-1])
self.current_element.remove(
self.current_element.getchildren()[-1])
def visit_problematic(self, node):
pass
def depart_problematic(self, node):
pass
def visit_raw(self, node):
if 'format' in node.attributes:
formats = node.attributes['format']
formatlist = formats.split()
if 'odt' in formatlist:
rawstr = node.astext()
attrstr = ' '.join(['%s="%s"' % (k, v, )
for k,v in CONTENT_NAMESPACE_ATTRIB.items()])
contentstr = '<stuff %s>%s</stuff>' % (attrstr, rawstr, )
if WhichElementTree != "lxml":
contentstr = contentstr.encode("utf-8")
content = etree.fromstring(contentstr)
elements = content.getchildren()
if len(elements) > 0:
el1 = elements[0]
if self.in_header:
pass
elif self.in_footer:
pass
else:
self.current_element.append(el1)
raise nodes.SkipChildren()
def depart_raw(self, node):
if self.in_header:
pass
elif self.in_footer:
pass
else:
pass
def visit_reference(self, node):
text = node.astext()
if self.settings.create_links:
if node.has_key('refuri'):
href = node['refuri']
if ( self.settings.cloak_email_addresses
and href.startswith('mailto:')):
href = self.cloak_mailto(href)
el = self.append_child('text:a', attrib={
'xlink:href': '%s' % href,
'xlink:type': 'simple',
})
self.set_current_element(el)
elif node.has_key('refid'):
if self.settings.create_links:
href = node['refid']
el = self.append_child('text:reference-ref', attrib={
'text:ref-name': '%s' % href,
'text:reference-format': 'text',
})
else:
self.document.reporter.warning(
'References must have "refuri" or "refid" attribute.')
if (self.in_table_of_contents and
len(node.children) >= 1 and
isinstance(node.children[0], docutils.nodes.generated)):
node.remove(node.children[0])
def depart_reference(self, node):
if self.settings.create_links:
if node.has_key('refuri'):
self.set_to_parent()
def visit_rubric(self, node):
style_name = self.rststyle('rubric')
classes = node.get('classes')
if classes:
class1 = classes[0]
if class1:
style_name = class1
el = SubElement(self.current_element, 'text:h', attrib = {
#'text:outline-level': '%d' % section_level,
#'text:style-name': 'Heading_20_%d' % section_level,
'text:style-name': style_name,
})
text = node.astext()
el.text = self.encode(text)
def depart_rubric(self, node):
pass
def visit_section(self, node, move_ids=1):
self.section_level += 1
self.section_count += 1
if self.settings.create_sections:
el = self.append_child('text:section', attrib={
'text:name': 'Section%d' % self.section_count,
'text:style-name': 'Sect%d' % self.section_level,
})
self.set_current_element(el)
def depart_section(self, node):
self.section_level -= 1
if self.settings.create_sections:
self.set_to_parent()
def visit_strong(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
self.set_current_element(el)
def depart_strong(self, node):
self.set_to_parent()
def visit_substitution_definition(self, node):
raise nodes.SkipChildren()
def depart_substitution_definition(self, node):
pass
def visit_system_message(self, node):
pass
def depart_system_message(self, node):
pass
def visit_table(self, node):
self.table_count += 1
table_name = '%s%%d' % TableStylePrefix
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
'style:family': 'table',
}, nsdict=SNSD)
el1_1 = SubElement(el1, 'style:table-properties', attrib={
#'style:width': '17.59cm',
'table:align': 'margins',
'fo:margin-top': '0in',
'fo:margin-bottom': '0.10in',
}, nsdict=SNSD)
# We use a single cell style for all cells in this table.
# That's probably not correct, but seems to work.
el2 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( self.table_count, 'A', 1, )),
'style:family': 'table-cell',
}, nsdict=SNSD)
line_style1 = '0.%03dcm solid #000000' % (
self.settings.table_border_thickness, )
el2_1 = SubElement(el2, 'style:table-cell-properties', attrib={
'fo:padding': '0.049cm',
'fo:border-left': line_style1,
'fo:border-right': line_style1,
'fo:border-top': line_style1,
'fo:border-bottom': line_style1,
}, nsdict=SNSD)
title = None
for child in node.children:
if child.tagname == 'title':
title = child.astext()
break
if title is not None:
el3 = self.append_p('table-title', title)
else:
pass
el4 = SubElement(self.current_element, 'table:table', attrib={
'table:name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
'table:style-name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
})
self.set_current_element(el4)
self.current_table_style = el1
self.table_width = 0
def depart_table(self, node):
attribkey = add_ns('style:width', nsdict=SNSD)
attribval = '%dcm' % self.table_width
self.current_table_style.attrib[attribkey] = attribval
self.set_to_parent()
def visit_tgroup(self, node):
self.column_count = ord('A') - 1
def depart_tgroup(self, node):
pass
def visit_colspec(self, node):
self.column_count += 1
colspec_name = self.rststyle(
'%s%%d.%%s' % TableStylePrefix,
(self.table_count, chr(self.column_count), )
)
colwidth = node['colwidth']
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': colspec_name,
'style:family': 'table-column',
}, nsdict=SNSD)
el1_1 = SubElement(el1, 'style:table-column-properties', attrib={
'style:column-width': '%dcm' % colwidth }, nsdict=SNSD)
el2 = self.append_child('table:table-column', attrib={
'table:style-name': colspec_name,
})
self.table_width += colwidth
def depart_colspec(self, node):
pass
def visit_thead(self, node):
el = self.append_child('table:table-header-rows')
self.set_current_element(el)
self.in_thead = True
self.paragraph_style_stack.append('Table_20_Heading')
def depart_thead(self, node):
self.set_to_parent()
self.in_thead = False
self.paragraph_style_stack.pop()
def visit_row(self, node):
self.column_count = ord('A') - 1
el = self.append_child('table:table-row')
self.set_current_element(el)
def depart_row(self, node):
self.set_to_parent()
def visit_entry(self, node):
self.column_count += 1
cellspec_name = self.rststyle(
'%s%%d.%%c%%d' % TableStylePrefix,
(self.table_count, 'A', 1, )
)
attrib={
'table:style-name': cellspec_name,
'office:value-type': 'string',
}
morecols = node.get('morecols', 0)
if morecols > 0:
attrib['table:number-columns-spanned'] = '%d' % (morecols + 1,)
self.column_count += morecols
morerows = node.get('morerows', 0)
if morerows > 0:
attrib['table:number-rows-spanned'] = '%d' % (morerows + 1,)
el1 = self.append_child('table:table-cell', attrib=attrib)
self.set_current_element(el1)
def depart_entry(self, node):
self.set_to_parent()
def visit_tbody(self, node):
pass
def depart_tbody(self, node):
pass
def visit_target(self, node):
#
# I don't know how to implement targets in ODF.
# How do we create a target in oowriter? A cross-reference?
if not (node.has_key('refuri') or node.has_key('refid')
or node.has_key('refname')):
pass
else:
pass
def depart_target(self, node):
pass
def visit_title(self, node, move_ids=1, title_type='title'):
if isinstance(node.parent, docutils.nodes.section):
section_level = self.section_level
if section_level > 7:
self.document.reporter.warning(
'Heading/section levels greater than 7 not supported.')
self.document.reporter.warning(
' Reducing to heading level 7 for heading: "%s"' % (
node.astext(), ))
section_level = 7
el1 = self.append_child('text:h', attrib = {
'text:outline-level': '%d' % section_level,
#'text:style-name': 'Heading_20_%d' % section_level,
'text:style-name': self.rststyle(
'heading%d', (section_level, )),
})
self.append_pending_ids(el1)
self.set_current_element(el1)
elif isinstance(node.parent, docutils.nodes.document):
# text = self.settings.title
#else:
# text = node.astext()
el1 = SubElement(self.current_element, 'text:p', attrib = {
'text:style-name': self.rststyle(title_type),
})
self.append_pending_ids(el1)
text = node.astext()
self.title = text
self.found_doc_title = True
self.set_current_element(el1)
def depart_title(self, node):
if (isinstance(node.parent, docutils.nodes.section) or
isinstance(node.parent, docutils.nodes.document)):
self.set_to_parent()
def visit_subtitle(self, node, move_ids=1):
self.visit_title(node, move_ids, title_type='subtitle')
def depart_subtitle(self, node):
self.depart_title(node)
def visit_title_reference(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': self.rststyle('quotation')})
el.text = self.encode(node.astext())
raise nodes.SkipChildren()
def depart_title_reference(self, node):
pass
def generate_table_of_content_entry_template(self, el1):
for idx in range(1, 11):
el2 = SubElement(el1,
'text:table-of-content-entry-template',
attrib={
'text:outline-level': "%d" % (idx, ),
'text:style-name': self.rststyle('contents-%d' % (idx, )),
})
el3 = SubElement(el2, 'text:index-entry-chapter')
el3 = SubElement(el2, 'text:index-entry-text')
el3 = SubElement(el2, 'text:index-entry-tab-stop', attrib={
'style:leader-char': ".",
'style:type': "right",
})
el3 = SubElement(el2, 'text:index-entry-page-number')
def visit_topic(self, node):
if 'classes' in node.attributes:
if 'contents' in node.attributes['classes']:
if self.settings.generate_oowriter_toc:
el1 = self.append_child('text:table-of-content', attrib={
'text:name': 'Table of Contents1',
'text:protected': 'true',
'text:style-name': 'Sect1',
})
el2 = SubElement(el1,
'text:table-of-content-source',
attrib={
'text:outline-level': '10',
})
el3 =SubElement(el2, 'text:index-title-template', attrib={
'text:style-name': 'Contents_20_Heading',
})
el3.text = 'Table of Contents'
self.generate_table_of_content_entry_template(el2)
el4 = SubElement(el1, 'text:index-body')
el5 = SubElement(el4, 'text:index-title')
el6 = SubElement(el5, 'text:p', attrib={
'text:style-name': self.rststyle('contents-heading'),
})
el6.text = 'Table of Contents'
self.save_current_element = self.current_element
self.table_of_content_index_body = el4
self.set_current_element(el4)
else:
el = self.append_p('horizontalline')
el = self.append_p('centeredtextbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = 'Contents'
self.in_table_of_contents = True
elif 'abstract' in node.attributes['classes']:
el = self.append_p('horizontalline')
el = self.append_p('centeredtextbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = 'Abstract'
def depart_topic(self, node):
if 'classes' in node.attributes:
if 'contents' in node.attributes['classes']:
if self.settings.generate_oowriter_toc:
self.update_toc_page_numbers(
self.table_of_content_index_body)
self.set_current_element(self.save_current_element)
else:
el = self.append_p('horizontalline')
self.in_table_of_contents = False
def update_toc_page_numbers(self, el):
collection = []
self.update_toc_collect(el, 0, collection)
self.update_toc_add_numbers(collection)
def update_toc_collect(self, el, level, collection):
collection.append((level, el))
level += 1
for child_el in el.getchildren():
if child_el.tag != 'text:index-body':
self.update_toc_collect(child_el, level, collection)
def update_toc_add_numbers(self, collection):
for level, el1 in collection:
if (el1.tag == 'text:p' and
el1.text != 'Table of Contents'):
el2 = SubElement(el1, 'text:tab')
el2.tail = '9999'
def visit_transition(self, node):
el = self.append_p('horizontalline')
def depart_transition(self, node):
pass
#
# Admonitions
#
def visit_warning(self, node):
self.generate_admonition(node, 'warning')
def depart_warning(self, node):
self.paragraph_style_stack.pop()
def visit_attention(self, node):
self.generate_admonition(node, 'attention')
depart_attention = depart_warning
def visit_caution(self, node):
self.generate_admonition(node, 'caution')
depart_caution = depart_warning
def visit_danger(self, node):
self.generate_admonition(node, 'danger')
depart_danger = depart_warning
def visit_error(self, node):
self.generate_admonition(node, 'error')
depart_error = depart_warning
def visit_hint(self, node):
self.generate_admonition(node, 'hint')
depart_hint = depart_warning
def visit_important(self, node):
self.generate_admonition(node, 'important')
depart_important = depart_warning
def visit_note(self, node):
self.generate_admonition(node, 'note')
depart_note = depart_warning
def visit_tip(self, node):
self.generate_admonition(node, 'tip')
depart_tip = depart_warning
def visit_admonition(self, node):
#import pdb; pdb.set_trace()
title = None
for child in node.children:
if child.tagname == 'title':
title = child.astext()
if title is None:
classes1 = node.get('classes')
if classes1:
title = classes1[0]
self.generate_admonition(node, 'generic', title)
depart_admonition = depart_warning
def generate_admonition(self, node, label, title=None):
el1 = SubElement(self.current_element, 'text:p', attrib = {
'text:style-name': self.rststyle('admon-%s-hdr', ( label, )),
})
if title:
el1.text = title
else:
el1.text = '%s!' % (label.capitalize(), )
s1 = self.rststyle('admon-%s-body', ( label, ))
self.paragraph_style_stack.append(s1)
#
# Roles (e.g. subscript, superscript, strong, ...
#
def visit_subscript(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': 'rststyle-subscript',
})
self.set_current_element(el)
def depart_subscript(self, node):
self.set_to_parent()
def visit_superscript(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': 'rststyle-superscript',
})
self.set_current_element(el)
def depart_superscript(self, node):
self.set_to_parent()
# Use an own reader to modify transformations done.
class Reader(standalone.Reader):
def get_transforms(self):
default = standalone.Reader.get_transforms(self)
if self.settings.create_links:
return default
return [ i
for i in default
if i is not references.DanglingReferences ]
| {
"repo_name": "spreeker/democracygame",
"path": "external_apps/docutils-snapshot/build/lib/docutils/writers/odf_odt/__init__.py",
"copies": "8",
"size": "100388",
"license": "bsd-3-clause",
"hash": -4093276535225539600,
"line_mean": 36.1394746578,
"line_max": 108,
"alpha_frac": 0.5451049926,
"autogenerated": false,
"ratio": 3.756333021515435,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8301438014115435,
"avg_score": null,
"num_lines": null
} |
"""
Open Document Format (ODF) Writer.
"""
VERSION = '1.0a'
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import tempfile
import zipfile
from xml.dom import minidom
import time
import re
import StringIO
import inspect
import imp
import copy
import docutils
from docutils import frontend, nodes, utils, writers, languages
from docutils.parsers import rst
from docutils.readers import standalone
from docutils.transforms import references
WhichElementTree = ''
try:
# 1. Try to use lxml.
#from lxml import etree
#WhichElementTree = 'lxml'
raise ImportError('Ignoring lxml')
except ImportError, e:
try:
# 2. Try to use ElementTree from the Python standard library.
from xml.etree import ElementTree as etree
WhichElementTree = 'elementtree'
except ImportError, e:
try:
# 3. Try to use a version of ElementTree installed as a separate
# product.
from elementtree import ElementTree as etree
WhichElementTree = 'elementtree'
except ImportError, e:
s1 = 'Must install either a version of Python containing ' \
'ElementTree (Python version >=2.5) or install ElementTree.'
raise ImportError(s1)
#
# Import pygments and odtwriter pygments formatters if possible.
try:
import pygments
import pygments.lexers
from pygmentsformatter import OdtPygmentsProgFormatter, \
OdtPygmentsLaTeXFormatter
except ImportError, exp:
pygments = None
#
# Is the PIL imaging library installed?
try:
import Image
except ImportError, exp:
Image = None
## import warnings
## warnings.warn('importing IPShellEmbed', UserWarning)
## from IPython.Shell import IPShellEmbed
## args = ['-pdb', '-pi1', 'In <\\#>: ', '-pi2', ' .\\D.: ',
## '-po', 'Out<\\#>: ', '-nosep']
## ipshell = IPShellEmbed(args,
## banner = 'Entering IPython. Press Ctrl-D to exit.',
## exit_msg = 'Leaving Interpreter, back to program.')
#
# ElementTree does not support getparent method (lxml does).
# This wrapper class and the following support functions provide
# that support for the ability to get the parent of an element.
#
if WhichElementTree == 'elementtree':
class _ElementInterfaceWrapper(etree._ElementInterface):
def __init__(self, tag, attrib=None):
etree._ElementInterface.__init__(self, tag, attrib)
if attrib is None:
attrib = {}
self.parent = None
def setparent(self, parent):
self.parent = parent
def getparent(self):
return self.parent
#
# Constants and globals
SPACES_PATTERN = re.compile(r'( +)')
TABS_PATTERN = re.compile(r'(\t+)')
FILL_PAT1 = re.compile(r'^ +')
FILL_PAT2 = re.compile(r' {2,}')
TableStylePrefix = 'Table'
GENERATOR_DESC = 'Docutils.org/odf_odt'
NAME_SPACE_1 = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'
CONTENT_NAMESPACE_DICT = CNSD = {
# 'office:version': '1.0',
'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'dom': 'http://www.w3.org/2001/xml-events',
'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'math': 'http://www.w3.org/1998/Math/MathML',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'office': NAME_SPACE_1,
'ooo': 'http://openoffice.org/2004/office',
'oooc': 'http://openoffice.org/2004/calc',
'ooow': 'http://openoffice.org/2004/writer',
'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xforms': 'http://www.w3.org/2002/xforms',
'xlink': 'http://www.w3.org/1999/xlink',
'xsd': 'http://www.w3.org/2001/XMLSchema',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
STYLES_NAMESPACE_DICT = SNSD = {
# 'office:version': '1.0',
'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'dom': 'http://www.w3.org/2001/xml-events',
'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'math': 'http://www.w3.org/1998/Math/MathML',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'office': NAME_SPACE_1,
'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'ooo': 'http://openoffice.org/2004/office',
'oooc': 'http://openoffice.org/2004/calc',
'ooow': 'http://openoffice.org/2004/writer',
'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xlink': 'http://www.w3.org/1999/xlink',
}
MANIFEST_NAMESPACE_DICT = MANNSD = {
'manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}
META_NAMESPACE_DICT = METNSD = {
# 'office:version': '1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'office': NAME_SPACE_1,
'ooo': 'http://openoffice.org/2004/office',
'xlink': 'http://www.w3.org/1999/xlink',
}
#
# Attribute dictionaries for use with ElementTree (not lxml), which
# does not support use of nsmap parameter on Element() and SubElement().
CONTENT_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:dom': 'http://www.w3.org/2001/xml-events',
'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:oooc': 'http://openoffice.org/2004/calc',
'xmlns:ooow': 'http://openoffice.org/2004/writer',
'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xmlns:xforms': 'http://www.w3.org/2002/xforms',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
STYLES_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:dom': 'http://www.w3.org/2001/xml-events',
'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:oooc': 'http://openoffice.org/2004/calc',
'xmlns:ooow': 'http://openoffice.org/2004/writer',
'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}
MANIFEST_NAMESPACE_ATTRIB = {
'xmlns:manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}
META_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}
#
# Functions
#
#
# ElementTree support functions.
# In order to be able to get the parent of elements, must use these
# instead of the functions with same name provided by ElementTree.
#
def Element(tag, attrib=None, nsmap=None, nsdict=CNSD):
if attrib is None:
attrib = {}
tag, attrib = fix_ns(tag, attrib, nsdict)
if WhichElementTree == 'lxml':
el = etree.Element(tag, attrib, nsmap=nsmap)
else:
el = _ElementInterfaceWrapper(tag, attrib)
return el
def SubElement(parent, tag, attrib=None, nsmap=None, nsdict=CNSD):
if attrib is None:
attrib = {}
tag, attrib = fix_ns(tag, attrib, nsdict)
if WhichElementTree == 'lxml':
el = etree.SubElement(parent, tag, attrib, nsmap=nsmap)
else:
el = _ElementInterfaceWrapper(tag, attrib)
parent.append(el)
el.setparent(parent)
return el
def fix_ns(tag, attrib, nsdict):
nstag = add_ns(tag, nsdict)
nsattrib = {}
for key, val in attrib.iteritems():
nskey = add_ns(key, nsdict)
nsattrib[nskey] = val
return nstag, nsattrib
def add_ns(tag, nsdict=CNSD):
if WhichElementTree == 'lxml':
nstag, name = tag.split(':')
ns = nsdict.get(nstag)
if ns is None:
raise RuntimeError, 'Invalid namespace prefix: %s' % nstag
tag = '{%s}%s' % (ns, name,)
return tag
def ToString(et):
outstream = StringIO.StringIO()
et.write(outstream)
s1 = outstream.getvalue()
outstream.close()
return s1
def escape_cdata(text):
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
ascii = ''
for char in text:
if ord(char) >= ord("\x7f"):
ascii += "&#x%X;" % ( ord(char), )
else:
ascii += char
return ascii
#
# Classes
#
WORD_SPLIT_PAT1 = re.compile(r'\b(\w*)\b\W*')
def split_words(line):
# We need whitespace at the end of the string for our regexpr.
line += ' '
words = []
pos1 = 0
mo = WORD_SPLIT_PAT1.search(line, pos1)
while mo is not None:
word = mo.groups()[0]
words.append(word)
pos1 = mo.end()
mo = WORD_SPLIT_PAT1.search(line, pos1)
return words
#
# Information about the indentation level for lists nested inside
# other contexts, e.g. dictionary lists.
class ListLevel(object):
def __init__(self, level, sibling_level=True, nested_level=True):
self.level = level
self.sibling_level = sibling_level
self.nested_level = nested_level
def set_sibling(self, sibling_level): self.sibling_level = sibling_level
def get_sibling(self): return self.sibling_level
def set_nested(self, nested_level): self.nested_level = nested_level
def get_nested(self): return self.nested_level
def set_level(self, level): self.level = level
def get_level(self): return self.level
class Writer(writers.Writer):
MIME_TYPE = 'application/vnd.oasis.opendocument.text'
EXTENSION = '.odt'
supported = ('html', 'html4css1', 'xhtml')
"""Formats this writer supports."""
default_stylesheet = 'styles' + EXTENSION
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = (
'ODF-Specific Options',
None,
(
('Specify a stylesheet. '
'Default: "%s"' % default_stylesheet_path,
['--stylesheet'],
{
'default': default_stylesheet_path,
'dest': 'stylesheet'
}),
('Specify a configuration/mapping file relative to the '
'current working '
'directory for additional ODF options. '
'In particular, this file may contain a section named '
'"Formats" that maps default style names to '
'names to be used in the resulting output file allowing for '
'adhering to external standards. '
'For more info and the format of the configuration/mapping file, '
'see the odtwriter doc.',
['--odf-config-file'],
{'metavar': '<file>'}),
('Obfuscate email addresses to confuse harvesters while still '
'keeping email links usable with standards-compliant browsers.',
['--cloak-email-addresses'],
{'default': False,
'action': 'store_true',
'dest': 'cloak_email_addresses',
'validator': frontend.validate_boolean}),
('Do not obfuscate email addresses.',
['--no-cloak-email-addresses'],
{'default': False,
'action': 'store_false',
'dest': 'cloak_email_addresses',
'validator': frontend.validate_boolean}),
('Specify the thickness of table borders in thousands of a cm. '
'Default is 35.',
['--table-border-thickness'],
{'default': 35,
'validator': frontend.validate_nonnegative_int}),
('Add syntax highlighting in literal code blocks.',
['--add-syntax-highlighting'],
{'default': False,
'action': 'store_true',
'dest': 'add_syntax_highlighting',
'validator': frontend.validate_boolean}),
('Do not add syntax highlighting in literal code blocks. (default)',
['--no-syntax-highlighting'],
{'default': False,
'action': 'store_false',
'dest': 'add_syntax_highlighting',
'validator': frontend.validate_boolean}),
('Create sections for headers. (default)',
['--create-sections'],
{'default': True,
'action': 'store_true',
'dest': 'create_sections',
'validator': frontend.validate_boolean}),
('Do not create sections for headers.',
['--no-sections'],
{'default': True,
'action': 'store_false',
'dest': 'create_sections',
'validator': frontend.validate_boolean}),
('Create links.',
['--create-links'],
{'default': False,
'action': 'store_true',
'dest': 'create_links',
'validator': frontend.validate_boolean}),
('Do not create links. (default)',
['--no-links'],
{'default': False,
'action': 'store_false',
'dest': 'create_links',
'validator': frontend.validate_boolean}),
('Generate endnotes at end of document, not footnotes '
'at bottom of page.',
['--endnotes-end-doc'],
{'default': False,
'action': 'store_true',
'dest': 'endnotes_end_doc',
'validator': frontend.validate_boolean}),
('Generate footnotes at bottom of page, not endnotes '
'at end of document. (default)',
['--no-endnotes-end-doc'],
{'default': False,
'action': 'store_false',
'dest': 'endnotes_end_doc',
'validator': frontend.validate_boolean}),
('Generate a bullet list table of contents, not '
'an ODF/oowriter table of contents.',
['--generate-list-toc'],
{'default': True,
'action': 'store_false',
'dest': 'generate_oowriter_toc',
'validator': frontend.validate_boolean}),
('Generate an ODF/oowriter table of contents, not '
'a bullet list. (default)',
['--generate-oowriter-toc'],
{'default': True,
'action': 'store_true',
'dest': 'generate_oowriter_toc',
'validator': frontend.validate_boolean}),
)
)
settings_defaults = {
'output_encoding_error_handler': 'xmlcharrefreplace',
}
relative_path_settings = (
'stylesheet_path',
)
config_section = 'opendocument odf writer'
config_section_dependencies = (
'writers',
)
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = ODFTranslator
def translate(self):
self.settings = self.document.settings
self.visitor = self.translator_class(self.document)
self.document.walkabout(self.visitor)
self.visitor.add_doc_title()
self.assemble_my_parts()
self.output = self.parts['whole']
def assemble_my_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses.
"""
writers.Writer.assemble_parts(self)
f = tempfile.NamedTemporaryFile()
zfile = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
content = self.visitor.content_astext()
self.write_zip_str(zfile, 'content.xml', content)
self.write_zip_str(zfile, 'mimetype', self.MIME_TYPE)
s1 = self.create_manifest()
self.write_zip_str(zfile, 'META-INF/manifest.xml', s1)
s1 = self.create_meta()
self.write_zip_str(zfile, 'meta.xml', s1)
s1 = self.get_stylesheet()
self.write_zip_str(zfile, 'styles.xml', s1)
s1 = self.get_settings()
self.write_zip_str(zfile, 'settings.xml', s1)
self.store_embedded_files(zfile)
zfile.close()
f.seek(0)
whole = f.read()
f.close()
self.parts['whole'] = whole
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
def write_zip_str(self, zfile, name, bytes):
localtime = time.localtime(time.time())
zinfo = zipfile.ZipInfo(name, localtime)
# Add some standard UNIX file access permissions (-rw-r--r--).
zinfo.external_attr = (0x81a4 & 0xFFFF) << 16L
zinfo.compress_type = zipfile.ZIP_DEFLATED
zfile.writestr(zinfo, bytes)
def store_embedded_files(self, zfile):
embedded_files = self.visitor.get_embedded_file_list()
for source, destination in embedded_files:
if source is None:
continue
try:
# encode/decode
destination1 = destination.decode('latin-1').encode('utf-8')
zfile.write(source, destination1, zipfile.ZIP_STORED)
except OSError, e:
self.document.reporter.warning(
"Can't open file %s." % (source, ))
def get_settings(self):
"""
modeled after get_stylesheet
"""
stylespath = self.settings.stylesheet
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('settings.xml')
zfile.close()
return s1
def get_stylesheet(self):
"""Retrieve the stylesheet from either a .xml file or from
a .odt (zip) file. Return the content as a string.
"""
stylespath = self.settings.stylesheet
ext = os.path.splitext(stylespath)[1]
if ext == '.xml':
stylesfile = open(stylespath, 'r')
s1 = stylesfile.read()
stylesfile.close()
elif ext == self.EXTENSION:
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('styles.xml')
zfile.close()
else:
raise RuntimeError, 'stylesheet path (%s) must be %s or .xml file' %(stylespath, self.EXTENSION)
s1 = self.visitor.setup_page(s1)
return s1
def assemble_parts(self):
pass
def create_manifest(self):
if WhichElementTree == 'lxml':
root = Element('manifest:manifest',
nsmap=MANIFEST_NAMESPACE_DICT,
nsdict=MANIFEST_NAMESPACE_DICT,
)
else:
root = Element('manifest:manifest',
attrib=MANIFEST_NAMESPACE_ATTRIB,
nsdict=MANIFEST_NAMESPACE_DICT,
)
doc = etree.ElementTree(root)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': self.MIME_TYPE,
'manifest:full-path': '/',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'content.xml',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'styles.xml',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'meta.xml',
}, nsdict=MANNSD)
s1 = ToString(doc)
doc = minidom.parseString(s1)
s1 = doc.toprettyxml(' ')
return s1
def create_meta(self):
if WhichElementTree == 'lxml':
root = Element('office:document-meta',
nsmap=META_NAMESPACE_DICT,
nsdict=META_NAMESPACE_DICT,
)
else:
root = Element('office:document-meta',
attrib=META_NAMESPACE_ATTRIB,
nsdict=META_NAMESPACE_DICT,
)
doc = etree.ElementTree(root)
root = SubElement(root, 'office:meta', nsdict=METNSD)
el1 = SubElement(root, 'meta:generator', nsdict=METNSD)
el1.text = 'Docutils/rst2odf.py/%s' % (VERSION, )
s1 = os.environ.get('USER', '')
el1 = SubElement(root, 'meta:initial-creator', nsdict=METNSD)
el1.text = s1
s2 = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())
el1 = SubElement(root, 'meta:creation-date', nsdict=METNSD)
el1.text = s2
el1 = SubElement(root, 'dc:creator', nsdict=METNSD)
el1.text = s1
el1 = SubElement(root, 'dc:date', nsdict=METNSD)
el1.text = s2
el1 = SubElement(root, 'dc:language', nsdict=METNSD)
el1.text = 'en-US'
el1 = SubElement(root, 'meta:editing-cycles', nsdict=METNSD)
el1.text = '1'
el1 = SubElement(root, 'meta:editing-duration', nsdict=METNSD)
el1.text = 'PT00M01S'
title = self.visitor.get_title()
el1 = SubElement(root, 'dc:title', nsdict=METNSD)
if title:
el1.text = title
else:
el1.text = '[no title]'
meta_dict = self.visitor.get_meta_dict()
keywordstr = meta_dict.get('keywords')
if keywordstr is not None:
keywords = split_words(keywordstr)
for keyword in keywords:
el1 = SubElement(root, 'meta:keyword', nsdict=METNSD)
el1.text = keyword
description = meta_dict.get('description')
if description is not None:
el1 = SubElement(root, 'dc:description', nsdict=METNSD)
el1.text = description
s1 = ToString(doc)
#doc = minidom.parseString(s1)
#s1 = doc.toprettyxml(' ')
return s1
# class ODFTranslator(nodes.SparseNodeVisitor):
class ODFTranslator(nodes.GenericNodeVisitor):
used_styles = (
'attribution', 'blockindent', 'blockquote', 'blockquote-bulletitem',
'blockquote-bulletlist', 'blockquote-enumitem', 'blockquote-enumlist',
'bulletitem', 'bulletlist', 'caption', 'centeredtextbody', 'codeblock',
'codeblock-classname', 'codeblock-comment', 'codeblock-functionname',
'codeblock-keyword', 'codeblock-name', 'codeblock-number',
'codeblock-operator', 'codeblock-string', 'emphasis', 'enumitem',
'enumlist', 'epigraph', 'epigraph-bulletitem', 'epigraph-bulletlist',
'epigraph-enumitem', 'epigraph-enumlist', 'footer',
'footnote', 'citation',
'header', 'highlights', 'highlights-bulletitem',
'highlights-bulletlist', 'highlights-enumitem', 'highlights-enumlist',
'horizontalline', 'inlineliteral', 'quotation', 'rubric',
'strong', 'table-title', 'textbody', 'tocbulletlist', 'tocenumlist',
'title',
'subtitle',
'heading1',
'heading2',
'heading3',
'heading4',
'heading5',
'heading6',
'heading7',
'admon-attention-hdr',
'admon-attention-body',
'admon-caution-hdr',
'admon-caution-body',
'admon-danger-hdr',
'admon-danger-body',
'admon-error-hdr',
'admon-error-body',
'admon-generic-hdr',
'admon-generic-body',
'admon-hint-hdr',
'admon-hint-body',
'admon-important-hdr',
'admon-important-body',
'admon-note-hdr',
'admon-note-body',
'admon-tip-hdr',
'admon-tip-body',
'admon-warning-hdr',
'admon-warning-body',
'tableoption',
'tableoption.%c', 'tableoption.%c%d', 'Table%d', 'Table%d.%c',
'Table%d.%c%d',
'lineblock1',
'lineblock2',
'lineblock3',
'lineblock4',
'lineblock5',
'lineblock6',
)
def __init__(self, document):
#nodes.SparseNodeVisitor.__init__(self, document)
nodes.GenericNodeVisitor.__init__(self, document)
self.settings = document.settings
self.format_map = { }
if self.settings.odf_config_file:
from ConfigParser import ConfigParser
parser = ConfigParser()
parser.read(self.settings.odf_config_file)
for rststyle, format in parser.items("Formats"):
if rststyle not in self.used_styles:
self.document.reporter.warning(
'Style "%s" is not a style used by odtwriter.' % (
rststyle, ))
self.format_map[rststyle] = format
self.section_level = 0
self.section_count = 0
# Create ElementTree content and styles documents.
if WhichElementTree == 'lxml':
root = Element(
'office:document-content',
nsmap=CONTENT_NAMESPACE_DICT,
)
else:
root = Element(
'office:document-content',
attrib=CONTENT_NAMESPACE_ATTRIB,
)
self.content_tree = etree.ElementTree(element=root)
self.current_element = root
SubElement(root, 'office:scripts')
SubElement(root, 'office:font-face-decls')
el = SubElement(root, 'office:automatic-styles')
self.automatic_styles = el
el = SubElement(root, 'office:body')
el = self.generate_content_element(el)
self.current_element = el
self.body_text_element = el
self.paragraph_style_stack = [self.rststyle('textbody'), ]
self.list_style_stack = []
self.table_count = 0
self.column_count = ord('A') - 1
self.trace_level = -1
self.optiontablestyles_generated = False
self.field_name = None
self.field_element = None
self.title = None
self.image_count = 0
self.image_style_count = 0
self.image_dict = {}
self.embedded_file_list = []
self.syntaxhighlighting = 1
self.syntaxhighlight_lexer = 'python'
self.header_content = []
self.footer_content = []
self.in_header = False
self.in_footer = False
self.blockstyle = ''
self.in_table_of_contents = False
self.table_of_content_index_body = None
self.list_level = 0
self.footnote_ref_dict = {}
self.footnote_list = []
self.footnote_chars_idx = 0
self.footnote_level = 0
self.pending_ids = [ ]
self.in_paragraph = False
self.found_doc_title = False
self.bumped_list_level_stack = []
self.meta_dict = {}
self.line_block_level = 0
self.line_indent_level = 0
self.citation_id = None
def add_doc_title(self):
text = self.settings.title
if text:
self.title = text
if not self.found_doc_title:
el = Element('text:p', attrib = {
'text:style-name': self.rststyle('title'),
})
el.text = text
self.body_text_element.insert(0, el)
def rststyle(self, name, parameters=( )):
"""
Returns the style name to use for the given style.
If `parameters` is given `name` must contain a matching number of ``%`` and
is used as a format expression with `parameters` as the value.
"""
name1 = name % parameters
stylename = self.format_map.get(name1, 'rststyle-%s' % name1)
return stylename
def generate_content_element(self, root):
return SubElement(root, 'office:text')
def setup_page(self, content):
root_el = etree.fromstring(content)
self.setup_paper(root_el)
if len(self.header_content) > 0 or len(self.footer_content) > 0:
self.add_header_footer(root_el)
new_content = etree.tostring(root_el)
return new_content
def setup_paper(self, root_el):
try:
fin = os.popen("paperconf -s 2> /dev/null")
w, h = map(float, fin.read().split())
fin.close()
except:
w, h = 612, 792 # default to Letter
def walk(el):
if el.tag == "{%s}page-layout-properties" % SNSD["style"] and \
not el.attrib.has_key("{%s}page-width" % SNSD["fo"]):
el.attrib["{%s}page-width" % SNSD["fo"]] = "%.3fpt" % w
el.attrib["{%s}page-height" % SNSD["fo"]] = "%.3fpt" % h
el.attrib["{%s}margin-left" % SNSD["fo"]] = \
el.attrib["{%s}margin-right" % SNSD["fo"]] = \
"%.3fpt" % (.1 * w)
el.attrib["{%s}margin-top" % SNSD["fo"]] = \
el.attrib["{%s}margin-bottom" % SNSD["fo"]] = \
"%.3fpt" % (.1 * h)
else:
for subel in el.getchildren(): walk(subel)
walk(root_el)
def add_header_footer(self, root_el):
path = '{%s}master-styles' % (NAME_SPACE_1, )
master_el = root_el.find(path)
if master_el is None:
return
path = '{%s}master-page' % (SNSD['style'], )
master_el = master_el.find(path)
if master_el is None:
return
el1 = master_el
if len(self.header_content) > 0:
if WhichElementTree == 'lxml':
el2 = SubElement(el1, 'style:header', nsdict=SNSD)
else:
el2 = SubElement(el1, 'style:header',
attrib=STYLES_NAMESPACE_ATTRIB,
nsdict=STYLES_NAMESPACE_DICT,
)
for el in self.header_content:
attrkey = add_ns('text:style-name', nsdict=SNSD)
el.attrib[attrkey] = self.rststyle('header')
el2.append(el)
if len(self.footer_content) > 0:
if WhichElementTree == 'lxml':
el2 = SubElement(el1, 'style:footer', nsdict=SNSD)
else:
el2 = SubElement(el1, 'style:footer',
attrib=STYLES_NAMESPACE_ATTRIB,
nsdict=STYLES_NAMESPACE_DICT,
)
for el in self.footer_content:
attrkey = add_ns('text:style-name', nsdict=SNSD)
el.attrib[attrkey] = self.rststyle('footer')
el2.append(el)
def astext(self):
root = self.content_tree.getroot()
et = etree.ElementTree(root)
s1 = ToString(et)
return s1
def content_astext(self):
return self.astext()
def set_title(self, title): self.title = title
def get_title(self): return self.title
def set_embedded_file_list(self, embedded_file_list):
self.embedded_file_list = embedded_file_list
def get_embedded_file_list(self): return self.embedded_file_list
def get_meta_dict(self): return self.meta_dict
def process_footnotes(self):
for node, el1 in self.footnote_list:
backrefs = node.attributes.get('backrefs', [])
first = True
for ref in backrefs:
el2 = self.footnote_ref_dict.get(ref)
if el2 is not None:
if first:
first = False
el3 = copy.deepcopy(el1)
el2.append(el3)
else:
children = el2.getchildren()
if len(children) > 0: # and 'id' in el2.attrib:
child = children[0]
ref1 = child.text
attribkey = add_ns('text:id', nsdict=SNSD)
id1 = el2.get(attribkey, 'footnote-error')
if id1 is None:
id1 = ''
tag = add_ns('text:note-ref', nsdict=SNSD)
el2.tag = tag
if self.settings.endnotes_end_doc:
note_class = 'endnote'
else:
note_class = 'footnote'
el2.attrib.clear()
attribkey = add_ns('text:note-class', nsdict=SNSD)
el2.attrib[attribkey] = note_class
attribkey = add_ns('text:ref-name', nsdict=SNSD)
el2.attrib[attribkey] = id1
attribkey = add_ns('text:reference-format', nsdict=SNSD)
el2.attrib[attribkey] = 'page'
el2.text = ref1
#
# Utility methods
def append_child(self, tag, attrib=None, parent=None):
if parent is None:
parent = self.current_element
if attrib is None:
el = SubElement(parent, tag)
else:
el = SubElement(parent, tag, attrib)
return el
def append_p(self, style, text=None):
result = self.append_child('text:p', attrib={
'text:style-name': self.rststyle(style)})
self.append_pending_ids(result)
if text is not None:
result.text = text
return result
def append_pending_ids(self, el):
if self.settings.create_links:
for id in self.pending_ids:
SubElement(el, 'text:reference-mark', attrib={
'text:name': id})
self.pending_ids = [ ]
def set_current_element(self, el):
self.current_element = el
def set_to_parent(self):
self.current_element = self.current_element.getparent()
def generate_labeled_block(self, node, label):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
el = self.append_p('blockindent')
return el
def generate_labeled_line(self, node, label):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
el1.tail = node.astext()
return el
def encode(self, text):
text = text.replace(u'\u00a0', " ")
return text
#
# Visitor functions
#
# In alphabetic order, more or less.
# See docutils.docutils.nodes.node_class_names.
#
def dispatch_visit(self, node):
"""Override to catch basic attributes which many nodes have."""
self.handle_basic_atts(node)
nodes.GenericNodeVisitor.dispatch_visit(self, node)
def handle_basic_atts(self, node):
if isinstance(node, nodes.Element) and node['ids']:
self.pending_ids += node['ids']
def default_visit(self, node):
self.document.reporter.warning('missing visit_%s' % (node.tagname, ))
def default_departure(self, node):
self.document.reporter.warning('missing depart_%s' % (node.tagname, ))
def visit_Text(self, node):
# Skip nodes whose text has been processed in parent nodes.
if isinstance(node.parent, docutils.nodes.literal_block):
return
text = node.astext()
# Are we in mixed content? If so, add the text to the
# etree tail of the previous sibling element.
if len(self.current_element.getchildren()) > 0:
if self.current_element.getchildren()[-1].tail:
self.current_element.getchildren()[-1].tail += text
else:
self.current_element.getchildren()[-1].tail = text
else:
if self.current_element.text:
self.current_element.text += text
else:
self.current_element.text = text
def depart_Text(self, node):
pass
#
# Pre-defined fields
#
def visit_address(self, node):
el = self.generate_labeled_block(node, 'Address: ')
self.set_current_element(el)
def depart_address(self, node):
self.set_to_parent()
def visit_author(self, node):
if isinstance(node.parent, nodes.authors):
el = self.append_p('blockindent')
else:
el = self.generate_labeled_block(node, 'Author: ')
self.set_current_element(el)
def depart_author(self, node):
self.set_to_parent()
def visit_authors(self, node):
label = 'Authors:'
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
def depart_authors(self, node):
pass
def visit_contact(self, node):
el = self.generate_labeled_block(node, 'Contact: ')
self.set_current_element(el)
def depart_contact(self, node):
self.set_to_parent()
def visit_copyright(self, node):
el = self.generate_labeled_block(node, 'Copyright: ')
self.set_current_element(el)
def depart_copyright(self, node):
self.set_to_parent()
def visit_date(self, node):
self.generate_labeled_line(node, 'Date: ')
def depart_date(self, node):
pass
def visit_organization(self, node):
el = self.generate_labeled_block(node, 'Organization: ')
self.set_current_element(el)
def depart_organization(self, node):
self.set_to_parent()
def visit_status(self, node):
el = self.generate_labeled_block(node, 'Status: ')
self.set_current_element(el)
def depart_status(self, node):
self.set_to_parent()
def visit_revision(self, node):
self.generate_labeled_line(node, 'Revision: ')
def depart_revision(self, node):
pass
def visit_version(self, node):
el = self.generate_labeled_line(node, 'Version: ')
#self.set_current_element(el)
def depart_version(self, node):
#self.set_to_parent()
pass
def visit_attribution(self, node):
el = self.append_p('attribution', node.astext())
def depart_attribution(self, node):
pass
def visit_block_quote(self, node):
if 'epigraph' in node.attributes['classes']:
self.paragraph_style_stack.append(self.rststyle('epigraph'))
self.blockstyle = self.rststyle('epigraph')
elif 'highlights' in node.attributes['classes']:
self.paragraph_style_stack.append(self.rststyle('highlights'))
self.blockstyle = self.rststyle('highlights')
else:
self.paragraph_style_stack.append(self.rststyle('blockquote'))
self.blockstyle = self.rststyle('blockquote')
self.line_indent_level += 1
def depart_block_quote(self, node):
self.paragraph_style_stack.pop()
self.blockstyle = ''
self.line_indent_level -= 1
def visit_bullet_list(self, node):
self.list_level +=1
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
pass
else:
if node.has_key('classes') and \
'auto-toc' in node.attributes['classes']:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('tocenumlist'),
})
self.list_style_stack.append(self.rststyle('enumitem'))
else:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('tocbulletlist'),
})
self.list_style_stack.append(self.rststyle('bulletitem'))
self.set_current_element(el)
else:
if self.blockstyle == self.rststyle('blockquote'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('blockquote-bulletitem'))
elif self.blockstyle == self.rststyle('highlights'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('highlights-bulletitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('epigraph-bulletitem'))
else:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('bulletlist'),
})
self.list_style_stack.append(self.rststyle('bulletitem'))
self.set_current_element(el)
def depart_bullet_list(self, node):
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
pass
else:
self.set_to_parent()
self.list_style_stack.pop()
else:
self.set_to_parent()
self.list_style_stack.pop()
self.list_level -=1
def visit_caption(self, node):
raise nodes.SkipChildren()
pass
def depart_caption(self, node):
pass
def visit_comment(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'office:annotation', attrib={})
el2 = SubElement(el1, 'text:p', attrib={})
el2.text = node.astext()
def depart_comment(self, node):
pass
def visit_compound(self, node):
# The compound directive currently receives no special treatment.
pass
def depart_compound(self, node):
pass
def visit_container(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
self.paragraph_style_stack.append(self.rststyle(styles[0]))
def depart_container(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
self.paragraph_style_stack.pop()
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
self.paragraph_style_stack.append(self.rststyle('blockindent'))
self.bumped_list_level_stack.append(ListLevel(1))
def depart_definition(self, node):
self.paragraph_style_stack.pop()
self.bumped_list_level_stack.pop()
def visit_definition_list(self, node):
pass
def depart_definition_list(self, node):
pass
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_term(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
#el1.text = node.astext()
self.set_current_element(el1)
def depart_term(self, node):
self.set_to_parent()
self.set_to_parent()
def visit_classifier(self, node):
els = self.current_element.getchildren()
if len(els) > 0:
el = els[-1]
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('emphasis')
})
el1.text = ' (%s)' % (node.astext(), )
def depart_classifier(self, node):
pass
def visit_document(self, node):
pass
def depart_document(self, node):
self.process_footnotes()
def visit_docinfo(self, node):
self.section_level += 1
self.section_count += 1
if self.settings.create_sections:
el = self.append_child('text:section', attrib={
'text:name': 'Section%d' % self.section_count,
'text:style-name': 'Sect%d' % self.section_level,
})
self.set_current_element(el)
def depart_docinfo(self, node):
self.section_level -= 1
if self.settings.create_sections:
self.set_to_parent()
def visit_emphasis(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('emphasis')})
self.set_current_element(el)
def depart_emphasis(self, node):
self.set_to_parent()
def visit_enumerated_list(self, node):
el1 = self.current_element
if self.blockstyle == self.rststyle('blockquote'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-enumlist'),
})
self.list_style_stack.append(self.rststyle('blockquote-enumitem'))
elif self.blockstyle == self.rststyle('highlights'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-enumlist'),
})
self.list_style_stack.append(self.rststyle('highlights-enumitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-enumlist'),
})
self.list_style_stack.append(self.rststyle('epigraph-enumitem'))
else:
liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), )
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle(liststylename),
})
self.list_style_stack.append(self.rststyle('enumitem'))
self.set_current_element(el2)
def depart_enumerated_list(self, node):
self.set_to_parent()
self.list_style_stack.pop()
def visit_list_item(self, node):
# If we are in a "bumped" list level, then wrap this
# list in an outer lists in order to increase the
# indentation level.
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
self.paragraph_style_stack.append(
self.rststyle('contents-%d' % (self.list_level, )))
else:
el1 = self.append_child('text:list-item')
self.set_current_element(el1)
else:
el1 = self.append_child('text:list-item')
el3 = el1
if len(self.bumped_list_level_stack) > 0:
level_obj = self.bumped_list_level_stack[-1]
if level_obj.get_sibling():
level_obj.set_nested(False)
for level_obj1 in self.bumped_list_level_stack:
for idx in range(level_obj1.get_level()):
el2 = self.append_child('text:list', parent=el3)
el3 = self.append_child(
'text:list-item', parent=el2)
self.paragraph_style_stack.append(self.list_style_stack[-1])
self.set_current_element(el3)
def depart_list_item(self, node):
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
self.paragraph_style_stack.pop()
else:
self.set_to_parent()
else:
if len(self.bumped_list_level_stack) > 0:
level_obj = self.bumped_list_level_stack[-1]
if level_obj.get_sibling():
level_obj.set_nested(True)
for level_obj1 in self.bumped_list_level_stack:
for idx in range(level_obj1.get_level()):
self.set_to_parent()
self.set_to_parent()
self.paragraph_style_stack.pop()
self.set_to_parent()
def visit_header(self, node):
self.in_header = True
def depart_header(self, node):
self.in_header = False
def visit_footer(self, node):
self.in_footer = True
def depart_footer(self, node):
self.in_footer = False
def visit_field(self, node):
pass
def depart_field(self, node):
pass
def visit_field_list(self, node):
pass
def depart_field_list(self, node):
pass
def visit_field_name(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = node.astext()
def depart_field_name(self, node):
pass
def visit_field_body(self, node):
self.paragraph_style_stack.append(self.rststyle('blockindent'))
def depart_field_body(self, node):
self.paragraph_style_stack.pop()
def visit_figure(self, node):
pass
def depart_figure(self, node):
pass
def visit_footnote(self, node):
self.footnote_level += 1
self.save_footnote_current = self.current_element
el1 = Element('text:note-body')
self.current_element = el1
self.footnote_list.append((node, el1))
if isinstance(node, docutils.nodes.citation):
self.paragraph_style_stack.append(self.rststyle('citation'))
else:
self.paragraph_style_stack.append(self.rststyle('footnote'))
def depart_footnote(self, node):
self.paragraph_style_stack.pop()
self.current_element = self.save_footnote_current
self.footnote_level -= 1
footnote_chars = [
'*', '**', '***',
'++', '+++',
'##', '###',
'@@', '@@@',
]
def visit_footnote_reference(self, node):
if self.footnote_level <= 0:
id = node.attributes['ids'][0]
refid = node.attributes.get('refid')
if refid is None:
refid = ''
if self.settings.endnotes_end_doc:
note_class = 'endnote'
else:
note_class = 'footnote'
el1 = self.append_child('text:note', attrib={
'text:id': '%s' % (refid, ),
'text:note-class': note_class,
})
note_auto = str(node.attributes.get('auto', 1))
if isinstance(node, docutils.nodes.citation_reference):
citation = '[%s]' % node.astext()
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': citation,
})
el2.text = citation
elif note_auto == '1':
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': node.astext(),
})
el2.text = node.astext()
elif note_auto == '*':
if self.footnote_chars_idx >= len(
ODFTranslator.footnote_chars):
self.footnote_chars_idx = 0
footnote_char = ODFTranslator.footnote_chars[
self.footnote_chars_idx]
self.footnote_chars_idx += 1
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': footnote_char,
})
el2.text = footnote_char
self.footnote_ref_dict[id] = el1
raise nodes.SkipChildren()
def depart_footnote_reference(self, node):
pass
def visit_citation(self, node):
for id in node.attributes['ids']:
self.citation_id = id
break
self.paragraph_style_stack.append(self.rststyle('blockindent'))
self.bumped_list_level_stack.append(ListLevel(1))
def depart_citation(self, node):
self.citation_id = None
self.paragraph_style_stack.pop()
self.bumped_list_level_stack.pop()
def visit_citation_reference(self, node):
if self.settings.create_links:
id = node.attributes['refid']
el = self.append_child('text:reference-ref', attrib={
'text:ref-name': '%s' % (id, ),
'text:reference-format': 'text',
})
el.text = '['
self.set_current_element(el)
elif self.current_element.text is None:
self.current_element.text = '['
else:
self.current_element.text += '['
def depart_citation_reference(self, node):
self.current_element.text += ']'
if self.settings.create_links:
self.set_to_parent()
def visit_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
raise nodes.SkipChildren()
elif self.citation_id is not None:
el = self.append_p('textbody')
self.set_current_element(el)
el.text = '['
if self.settings.create_links:
el1 = self.append_child('text:reference-mark-start', attrib={
'text:name': '%s' % (self.citation_id, ),
})
def depart_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
pass
elif self.citation_id is not None:
self.current_element.text += ']'
if self.settings.create_links:
el = self.append_child('text:reference-mark-end', attrib={
'text:name': '%s' % (self.citation_id, ),
})
self.set_to_parent()
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def check_file_exists(self, path):
if os.path.exists(path):
return 1
else:
return 0
def visit_image(self, node):
# Capture the image file.
if 'uri' in node.attributes:
source = node.attributes['uri']
if not self.check_file_exists(source):
self.document.reporter.warning(
'Cannot find image file %s.' % (source, ))
return
else:
return
if source in self.image_dict:
filename, destination = self.image_dict[source]
else:
self.image_count += 1
filename = os.path.split(source)[1]
destination = 'Pictures/1%08x%s' % (self.image_count, filename, )
spec = (os.path.abspath(source), destination,)
self.embedded_file_list.append(spec)
self.image_dict[source] = (source, destination,)
# Is this a figure (containing an image) or just a plain image?
if self.in_paragraph:
el1 = self.current_element
else:
el1 = SubElement(self.current_element, 'text:p',
attrib={'text:style-name': self.rststyle('textbody')})
el2 = el1
if isinstance(node.parent, docutils.nodes.figure):
el3, el4, caption = self.generate_figure(node, source,
destination, el2)
attrib = {
'draw:blue': '0%',
'draw:color-inversion': 'false',
'draw:color-mode': 'standard',
'draw:contrast': '0%',
'draw:gamma': '100%',
'draw:green': '0%',
'draw:image-opacity': '100%',
'draw:luminance': '0%',
'draw:red': '0%',
'fo:border': 'none',
'fo:clip': 'rect(0in 0in 0in 0in)',
'fo:margin-bottom': '0in',
'fo:margin-left': '0in',
'fo:margin-right': '0in',
'fo:margin-top': '0in',
'fo:padding': '0in',
'style:horizontal-pos': 'from-left',
'style:horizontal-rel': 'paragraph-content',
'style:mirror': 'none',
'style:run-through': 'foreground',
'style:shadow': 'none',
'style:vertical-pos': 'from-top',
'style:vertical-rel': 'paragraph-content',
'style:wrap': 'none',
}
el5, width = self.generate_image(node, source, destination,
el4, attrib)
if caption is not None:
el5.tail = caption
else: #if isinstance(node.parent, docutils.nodes.image):
el3 = self.generate_image(node, source, destination, el2)
def depart_image(self, node):
pass
def get_image_width_height(self, node, attr):
size = None
if attr in node.attributes:
size = node.attributes[attr]
unit = size[-2:]
if unit.isalpha():
size = size[:-2]
else:
unit = 'px'
try:
size = float(size)
except ValueError, e:
self.document.reporter.warning(
'Invalid %s for image: "%s"' % (
attr, node.attributes[attr]))
size = [size, unit]
return size
def get_image_scale(self, node):
if 'scale' in node.attributes:
try:
scale = int(node.attributes['scale'])
if scale < 1: # or scale > 100:
self.document.reporter.warning(
'scale out of range (%s), using 1.' % (scale, ))
scale = 1
scale = scale * 0.01
except ValueError, e:
self.document.reporter.warning(
'Invalid scale for image: "%s"' % (
node.attributes['scale'], ))
else:
scale = 1.0
return scale
def get_image_scaled_width_height(self, node, source):
scale = self.get_image_scale(node)
width = self.get_image_width_height(node, 'width')
height = self.get_image_width_height(node, 'height')
dpi = (72, 72)
if Image is not None and source in self.image_dict:
filename, destination = self.image_dict[source]
imageobj = Image.open(filename, 'r')
dpi = imageobj.info.get('dpi', dpi)
# dpi information can be (xdpi, ydpi) or xydpi
try: iter(dpi)
except: dpi = (dpi, dpi)
else:
imageobj = None
if width is None or height is None:
if imageobj is None:
raise RuntimeError(
'image size not fully specified and PIL not installed')
if width is None: width = [imageobj.size[0], 'px']
if height is None: height = [imageobj.size[1], 'px']
width[0] *= scale
height[0] *= scale
if width[1] == 'px': width = [width[0] / dpi[0], 'in']
if height[1] == 'px': height = [height[0] / dpi[1], 'in']
width[0] = str(width[0])
height[0] = str(height[0])
return ''.join(width), ''.join(height)
def generate_figure(self, node, source, destination, current_element):
caption = None
width, height = self.get_image_scaled_width_height(node, source)
for node1 in node.parent.children:
if node1.tagname == 'caption':
caption = node1.astext()
self.image_style_count += 1
#
# Add the style for the caption.
if caption is not None:
attrib = {
'style:class': 'extra',
'style:family': 'paragraph',
'style:name': 'Caption',
'style:parent-style-name': 'Standard',
}
el1 = SubElement(self.automatic_styles, 'style:style',
attrib=attrib, nsdict=SNSD)
attrib = {
'fo:margin-bottom': '0.0835in',
'fo:margin-top': '0.0835in',
'text:line-number': '0',
'text:number-lines': 'false',
}
el2 = SubElement(el1, 'style:paragraph-properties',
attrib=attrib, nsdict=SNSD)
attrib = {
'fo:font-size': '12pt',
'fo:font-style': 'italic',
'style:font-name': 'Times',
'style:font-name-complex': 'Lucidasans1',
'style:font-size-asian': '12pt',
'style:font-size-complex': '12pt',
'style:font-style-asian': 'italic',
'style:font-style-complex': 'italic',
}
el2 = SubElement(el1, 'style:text-properties',
attrib=attrib, nsdict=SNSD)
style_name = 'rstframestyle%d' % self.image_style_count
# Add the styles
attrib = {
'style:name': style_name,
'style:family': 'graphic',
'style:parent-style-name': 'Frame',
}
el1 = SubElement(self.automatic_styles,
'style:style', attrib=attrib, nsdict=SNSD)
halign = 'center'
valign = 'top'
if 'align' in node.attributes:
align = node.attributes['align'].split()
for val in align:
if val in ('left', 'center', 'right'):
halign = val
elif val in ('top', 'middle', 'bottom'):
valign = val
attrib = {
'fo:margin-left': '0cm',
'fo:margin-right': '0cm',
'fo:margin-top': '0cm',
'fo:margin-bottom': '0cm',
# 'style:wrap': 'dynamic', #vds
'style:number-wrapped-paragraphs': 'no-limit',
'style:vertical-pos': valign,
'style:vertical-rel': 'paragraph',
'style:horizontal-pos': halign,
'style:horizontal-rel': 'paragraph',
'fo:padding': '0cm',
'fo:border': 'none',
}
wrap = False
classes = node.parent.attributes.get('classes')
if classes and 'wrap' in classes:
wrap = True
if wrap:
attrib['style:wrap'] = 'dynamic'
else:
attrib['style:wrap'] = 'none'
el2 = SubElement(el1,
'style:graphic-properties', attrib=attrib, nsdict=SNSD)
attrib = {
'draw:style-name': style_name,
'draw:name': 'Frame1',
'text:anchor-type': 'paragraph',
'draw:z-index': '1',
}
attrib['svg:width'] = width
# dbg
#attrib['svg:height'] = height
el3 = SubElement(current_element, 'draw:frame', attrib=attrib)
attrib = {}
el4 = SubElement(el3, 'draw:text-box', attrib=attrib)
attrib = {
'text:style-name': self.rststyle('caption'),
}
el5 = SubElement(el4, 'text:p', attrib=attrib)
return el3, el5, caption
def generate_image(self, node, source, destination, current_element,
frame_attrs=None):
width, height = self.get_image_scaled_width_height(node, source)
self.image_style_count += 1
style_name = 'rstframestyle%d' % self.image_style_count
# Add the style.
attrib = {
'style:name': style_name,
'style:family': 'graphic',
'style:parent-style-name': 'Graphics',
}
el1 = SubElement(self.automatic_styles,
'style:style', attrib=attrib, nsdict=SNSD)
halign = None
valign = None
if 'align' in node.attributes:
align = node.attributes['align'].split()
for val in align:
if val in ('left', 'center', 'right'):
halign = val
elif val in ('top', 'middle', 'bottom'):
valign = val
if frame_attrs is None:
attrib = {
'style:vertical-pos': 'top',
'style:vertical-rel': 'paragraph',
'style:horizontal-rel': 'paragraph',
'style:mirror': 'none',
'fo:clip': 'rect(0cm 0cm 0cm 0cm)',
'draw:luminance': '0%',
'draw:contrast': '0%',
'draw:red': '0%',
'draw:green': '0%',
'draw:blue': '0%',
'draw:gamma': '100%',
'draw:color-inversion': 'false',
'draw:image-opacity': '100%',
'draw:color-mode': 'standard',
}
else:
attrib = frame_attrs
if halign is not None:
attrib['style:horizontal-pos'] = halign
if valign is not None:
attrib['style:vertical-pos'] = valign
# If there is a classes/wrap directive or we are
# inside a table, add a no-wrap style.
wrap = False
classes = node.attributes.get('classes')
if classes and 'wrap' in classes:
wrap = True
if wrap:
attrib['style:wrap'] = 'dynamic'
else:
attrib['style:wrap'] = 'none'
# If we are inside a table, add a no-wrap style.
if self.is_in_table(node):
attrib['style:wrap'] = 'none'
el2 = SubElement(el1,
'style:graphic-properties', attrib=attrib, nsdict=SNSD)
# Add the content.
#el = SubElement(current_element, 'text:p',
# attrib={'text:style-name': self.rststyle('textbody')})
attrib={
'draw:style-name': style_name,
'draw:name': 'graphics2',
'draw:z-index': '1',
}
if isinstance(node.parent, nodes.TextElement):
attrib['text:anchor-type'] = 'as-char' #vds
else:
attrib['text:anchor-type'] = 'paragraph'
attrib['svg:width'] = width
attrib['svg:height'] = height
el1 = SubElement(current_element, 'draw:frame', attrib=attrib)
el2 = SubElement(el1, 'draw:image', attrib={
'xlink:href': '%s' % (destination, ),
'xlink:type': 'simple',
'xlink:show': 'embed',
'xlink:actuate': 'onLoad',
})
return el1, width
def is_in_table(self, node):
node1 = node.parent
while node1:
if isinstance(node1, docutils.nodes.entry):
return True
node1 = node1.parent
return False
def visit_legend(self, node):
# Currently, the legend receives *no* special treatment.
pass
def depart_legend(self, node):
pass
def visit_line_block(self, node):
self.line_indent_level += 1
self.line_block_level += 1
def depart_line_block(self, node):
if self.line_block_level <= 1:
el1 = SubElement(self.current_element, 'text:p', attrib={
'text:style-name': self.rststyle('lineblock1'),
})
self.line_indent_level -= 1
self.line_block_level -= 1
def visit_line(self, node):
style = 'lineblock%d' % self.line_indent_level
el1 = SubElement(self.current_element, 'text:p', attrib={
'text:style-name': self.rststyle(style),
})
self.current_element = el1
def depart_line(self, node):
self.set_to_parent()
def visit_literal(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('inlineliteral')})
self.set_current_element(el)
def depart_literal(self, node):
self.set_to_parent()
def _calculate_code_block_padding(self, line):
count = 0
matchobj = SPACES_PATTERN.match(line)
if matchobj:
pad = matchobj.group()
count = len(pad)
else:
matchobj = TABS_PATTERN.match(line)
if matchobj:
pad = matchobj.group()
count = len(pad) * 8
return count
def _add_syntax_highlighting(self, insource, language):
lexer = pygments.lexers.get_lexer_by_name(language, stripall=True)
if language in ('latex', 'tex'):
fmtr = OdtPygmentsLaTeXFormatter(lambda name, parameters=():
self.rststyle(name, parameters),
escape_function=escape_cdata)
else:
fmtr = OdtPygmentsProgFormatter(lambda name, parameters=():
self.rststyle(name, parameters),
escape_function=escape_cdata)
outsource = pygments.highlight(insource, lexer, fmtr)
return outsource
def fill_line(self, line):
line = FILL_PAT1.sub(self.fill_func1, line)
line = FILL_PAT2.sub(self.fill_func2, line)
return line
def fill_func1(self, matchobj):
spaces = matchobj.group(0)
repl = '<text:s text:c="%d"/>' % (len(spaces), )
return repl
def fill_func2(self, matchobj):
spaces = matchobj.group(0)
repl = ' <text:s text:c="%d"/>' % (len(spaces) - 1, )
return repl
def visit_literal_block(self, node):
wrapper1 = '<text:p text:style-name="%s">%%s</text:p>' % (
self.rststyle('codeblock'), )
source = node.astext()
if (pygments and
self.settings.add_syntax_highlighting
#and
#node.get('hilight', False)
):
language = node.get('language', 'python')
source = self._add_syntax_highlighting(source, language)
else:
source = escape_cdata(source)
lines = source.split('\n')
lines1 = ['<wrappertag1 xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">']
my_lines = []
for my_line in lines:
my_line = self.fill_line(my_line)
my_line = my_line.replace(" ", "\n")
my_lines.append(my_line)
my_lines_str = '<text:line-break/>'.join(my_lines)
my_lines_str2 = wrapper1 % (my_lines_str, )
lines1.append(my_lines_str2)
lines1.append('</wrappertag1>')
s1 = ''.join(lines1)
if WhichElementTree != "lxml":
s1 = s1.encode("utf-8")
el1 = etree.fromstring(s1)
children = el1.getchildren()
for child in children:
self.current_element.append(child)
def depart_literal_block(self, node):
pass
visit_doctest_block = visit_literal_block
depart_doctest_block = depart_literal_block
def visit_meta(self, node):
name = node.attributes.get('name')
content = node.attributes.get('content')
if name is not None and content is not None:
self.meta_dict[name] = content
def depart_meta(self, node):
pass
def visit_option_list(self, node):
table_name = 'tableoption'
#
# Generate automatic styles
if not self.optiontablestyles_generated:
self.optiontablestyles_generated = True
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(table_name),
'style:family': 'table'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-properties', attrib={
'style:width': '17.59cm',
'table:align': 'left',
'style:shadow': 'none'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle('%s.%%c' % table_name, ( 'A', )),
'style:family': 'table-column'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-column-properties', attrib={
'style:column-width': '4.999cm'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle('%s.%%c' % table_name, ( 'B', )),
'style:family': 'table-column'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-column-properties', attrib={
'style:column-width': '12.587cm'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 1, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:background-color': 'transparent',
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': 'none',
'fo:border-top': '0.035cm solid #000000',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
el2 = SubElement(el1, 'style:background-image', nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 1, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border': '0.035cm solid #000000'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 2, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': 'none',
'fo:border-top': 'none',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 2, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': '0.035cm solid #000000',
'fo:border-top': 'none',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
#
# Generate table data
el = self.append_child('table:table', attrib={
'table:name': self.rststyle(table_name),
'table:style-name': self.rststyle(table_name),
})
el1 = SubElement(el, 'table:table-column', attrib={
'table:style-name': self.rststyle(
'%s.%%c' % table_name, ( 'A', ))})
el1 = SubElement(el, 'table:table-column', attrib={
'table:style-name': self.rststyle(
'%s.%%c' % table_name, ( 'B', ))})
el1 = SubElement(el, 'table:table-header-rows')
el2 = SubElement(el1, 'table:table-row')
el3 = SubElement(el2, 'table:table-cell', attrib={
'table:style-name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 1, )),
'office:value-type': 'string'})
el4 = SubElement(el3, 'text:p', attrib={
'text:style-name': 'Table_20_Heading'})
el4.text= 'Option'
el3 = SubElement(el2, 'table:table-cell', attrib={
'table:style-name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 1, )),
'office:value-type': 'string'})
el4 = SubElement(el3, 'text:p', attrib={
'text:style-name': 'Table_20_Heading'})
el4.text= 'Description'
self.set_current_element(el)
def depart_option_list(self, node):
self.set_to_parent()
def visit_option_list_item(self, node):
el = self.append_child('table:table-row')
self.set_current_element(el)
def depart_option_list_item(self, node):
self.set_to_parent()
def visit_option_group(self, node):
el = self.append_child('table:table-cell', attrib={
'table:style-name': 'Table%d.A2' % self.table_count,
'office:value-type': 'string',
})
self.set_current_element(el)
def depart_option_group(self, node):
self.set_to_parent()
def visit_option(self, node):
el = self.append_child('text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el.text = node.astext()
def depart_option(self, node):
pass
def visit_option_string(self, node):
pass
def depart_option_string(self, node):
pass
def visit_option_argument(self, node):
pass
def depart_option_argument(self, node):
pass
def visit_description(self, node):
el = self.append_child('table:table-cell', attrib={
'table:style-name': 'Table%d.B2' % self.table_count,
'office:value-type': 'string',
})
el1 = SubElement(el, 'text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el1.text = node.astext()
raise nodes.SkipChildren()
def depart_description(self, node):
pass
def visit_paragraph(self, node):
self.in_paragraph = True
if self.in_header:
el = self.append_p('header')
elif self.in_footer:
el = self.append_p('footer')
else:
style_name = self.paragraph_style_stack[-1]
el = self.append_child('text:p',
attrib={'text:style-name': style_name})
self.append_pending_ids(el)
self.set_current_element(el)
def depart_paragraph(self, node):
self.in_paragraph = False
self.set_to_parent()
if self.in_header:
self.header_content.append(
self.current_element.getchildren()[-1])
self.current_element.remove(
self.current_element.getchildren()[-1])
elif self.in_footer:
self.footer_content.append(
self.current_element.getchildren()[-1])
self.current_element.remove(
self.current_element.getchildren()[-1])
def visit_problematic(self, node):
pass
def depart_problematic(self, node):
pass
def visit_raw(self, node):
if 'format' in node.attributes:
formats = node.attributes['format']
formatlist = formats.split()
if 'odt' in formatlist:
rawstr = node.astext()
attrstr = ' '.join(['%s="%s"' % (k, v, )
for k,v in CONTENT_NAMESPACE_ATTRIB.items()])
contentstr = '<stuff %s>%s</stuff>' % (attrstr, rawstr, )
if WhichElementTree != "lxml":
contentstr = contentstr.encode("utf-8")
content = etree.fromstring(contentstr)
elements = content.getchildren()
if len(elements) > 0:
el1 = elements[0]
if self.in_header:
pass
elif self.in_footer:
pass
else:
self.current_element.append(el1)
raise nodes.SkipChildren()
def depart_raw(self, node):
if self.in_header:
pass
elif self.in_footer:
pass
else:
pass
def visit_reference(self, node):
text = node.astext()
if self.settings.create_links:
if node.has_key('refuri'):
href = node['refuri']
if ( self.settings.cloak_email_addresses
and href.startswith('mailto:')):
href = self.cloak_mailto(href)
el = self.append_child('text:a', attrib={
'xlink:href': '%s' % href,
'xlink:type': 'simple',
})
self.set_current_element(el)
elif node.has_key('refid'):
if self.settings.create_links:
href = node['refid']
el = self.append_child('text:reference-ref', attrib={
'text:ref-name': '%s' % href,
'text:reference-format': 'text',
})
else:
self.document.reporter.warning(
'References must have "refuri" or "refid" attribute.')
if (self.in_table_of_contents and
len(node.children) >= 1 and
isinstance(node.children[0], docutils.nodes.generated)):
node.remove(node.children[0])
def depart_reference(self, node):
if self.settings.create_links:
if node.has_key('refuri'):
self.set_to_parent()
def visit_rubric(self, node):
style_name = self.rststyle('rubric')
classes = node.get('classes')
if classes:
class1 = classes[0]
if class1:
style_name = class1
el = SubElement(self.current_element, 'text:h', attrib = {
#'text:outline-level': '%d' % section_level,
#'text:style-name': 'Heading_20_%d' % section_level,
'text:style-name': style_name,
})
text = node.astext()
el.text = self.encode(text)
def depart_rubric(self, node):
pass
def visit_section(self, node, move_ids=1):
self.section_level += 1
self.section_count += 1
if self.settings.create_sections:
el = self.append_child('text:section', attrib={
'text:name': 'Section%d' % self.section_count,
'text:style-name': 'Sect%d' % self.section_level,
})
self.set_current_element(el)
def depart_section(self, node):
self.section_level -= 1
if self.settings.create_sections:
self.set_to_parent()
def visit_strong(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
self.set_current_element(el)
def depart_strong(self, node):
self.set_to_parent()
def visit_substitution_definition(self, node):
raise nodes.SkipChildren()
def depart_substitution_definition(self, node):
pass
def visit_system_message(self, node):
pass
def depart_system_message(self, node):
pass
def visit_table(self, node):
self.table_count += 1
table_name = '%s%%d' % TableStylePrefix
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
'style:family': 'table',
}, nsdict=SNSD)
el1_1 = SubElement(el1, 'style:table-properties', attrib={
#'style:width': '17.59cm',
'table:align': 'margins',
'fo:margin-top': '0in',
'fo:margin-bottom': '0.10in',
}, nsdict=SNSD)
# We use a single cell style for all cells in this table.
# That's probably not correct, but seems to work.
el2 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( self.table_count, 'A', 1, )),
'style:family': 'table-cell',
}, nsdict=SNSD)
line_style1 = '0.%03dcm solid #000000' % (
self.settings.table_border_thickness, )
el2_1 = SubElement(el2, 'style:table-cell-properties', attrib={
'fo:padding': '0.049cm',
'fo:border-left': line_style1,
'fo:border-right': line_style1,
'fo:border-top': line_style1,
'fo:border-bottom': line_style1,
}, nsdict=SNSD)
title = None
for child in node.children:
if child.tagname == 'title':
title = child.astext()
break
if title is not None:
el3 = self.append_p('table-title', title)
else:
pass
el4 = SubElement(self.current_element, 'table:table', attrib={
'table:name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
'table:style-name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
})
self.set_current_element(el4)
self.current_table_style = el1
self.table_width = 0
def depart_table(self, node):
attribkey = add_ns('style:width', nsdict=SNSD)
attribval = '%dcm' % self.table_width
self.current_table_style.attrib[attribkey] = attribval
self.set_to_parent()
def visit_tgroup(self, node):
self.column_count = ord('A') - 1
def depart_tgroup(self, node):
pass
def visit_colspec(self, node):
self.column_count += 1
colspec_name = self.rststyle(
'%s%%d.%%s' % TableStylePrefix,
(self.table_count, chr(self.column_count), )
)
colwidth = node['colwidth']
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': colspec_name,
'style:family': 'table-column',
}, nsdict=SNSD)
el1_1 = SubElement(el1, 'style:table-column-properties', attrib={
'style:column-width': '%dcm' % colwidth }, nsdict=SNSD)
el2 = self.append_child('table:table-column', attrib={
'table:style-name': colspec_name,
})
self.table_width += colwidth
def depart_colspec(self, node):
pass
def visit_thead(self, node):
el = self.append_child('table:table-header-rows')
self.set_current_element(el)
self.in_thead = True
self.paragraph_style_stack.append('Table_20_Heading')
def depart_thead(self, node):
self.set_to_parent()
self.in_thead = False
self.paragraph_style_stack.pop()
def visit_row(self, node):
self.column_count = ord('A') - 1
el = self.append_child('table:table-row')
self.set_current_element(el)
def depart_row(self, node):
self.set_to_parent()
def visit_entry(self, node):
self.column_count += 1
cellspec_name = self.rststyle(
'%s%%d.%%c%%d' % TableStylePrefix,
(self.table_count, 'A', 1, )
)
attrib={
'table:style-name': cellspec_name,
'office:value-type': 'string',
}
morecols = node.get('morecols', 0)
if morecols > 0:
attrib['table:number-columns-spanned'] = '%d' % (morecols + 1,)
self.column_count += morecols
morerows = node.get('morerows', 0)
if morerows > 0:
attrib['table:number-rows-spanned'] = '%d' % (morerows + 1,)
el1 = self.append_child('table:table-cell', attrib=attrib)
self.set_current_element(el1)
def depart_entry(self, node):
self.set_to_parent()
def visit_tbody(self, node):
pass
def depart_tbody(self, node):
pass
def visit_target(self, node):
#
# I don't know how to implement targets in ODF.
# How do we create a target in oowriter? A cross-reference?
if not (node.has_key('refuri') or node.has_key('refid')
or node.has_key('refname')):
pass
else:
pass
def depart_target(self, node):
pass
def visit_title(self, node, move_ids=1, title_type='title'):
if isinstance(node.parent, docutils.nodes.section):
section_level = self.section_level
if section_level > 7:
self.document.reporter.warning(
'Heading/section levels greater than 7 not supported.')
self.document.reporter.warning(
' Reducing to heading level 7 for heading: "%s"' % (
node.astext(), ))
section_level = 7
el1 = self.append_child('text:h', attrib = {
'text:outline-level': '%d' % section_level,
#'text:style-name': 'Heading_20_%d' % section_level,
'text:style-name': self.rststyle(
'heading%d', (section_level, )),
})
self.append_pending_ids(el1)
self.set_current_element(el1)
elif isinstance(node.parent, docutils.nodes.document):
# text = self.settings.title
#else:
# text = node.astext()
el1 = SubElement(self.current_element, 'text:p', attrib = {
'text:style-name': self.rststyle(title_type),
})
self.append_pending_ids(el1)
text = node.astext()
self.title = text
self.found_doc_title = True
self.set_current_element(el1)
def depart_title(self, node):
if (isinstance(node.parent, docutils.nodes.section) or
isinstance(node.parent, docutils.nodes.document)):
self.set_to_parent()
def visit_subtitle(self, node, move_ids=1):
self.visit_title(node, move_ids, title_type='subtitle')
def depart_subtitle(self, node):
self.depart_title(node)
def visit_title_reference(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': self.rststyle('quotation')})
el.text = self.encode(node.astext())
raise nodes.SkipChildren()
def depart_title_reference(self, node):
pass
def generate_table_of_content_entry_template(self, el1):
for idx in range(1, 11):
el2 = SubElement(el1,
'text:table-of-content-entry-template',
attrib={
'text:outline-level': "%d" % (idx, ),
'text:style-name': self.rststyle('contents-%d' % (idx, )),
})
el3 = SubElement(el2, 'text:index-entry-chapter')
el3 = SubElement(el2, 'text:index-entry-text')
el3 = SubElement(el2, 'text:index-entry-tab-stop', attrib={
'style:leader-char': ".",
'style:type': "right",
})
el3 = SubElement(el2, 'text:index-entry-page-number')
def visit_topic(self, node):
if 'classes' in node.attributes:
if 'contents' in node.attributes['classes']:
if self.settings.generate_oowriter_toc:
el1 = self.append_child('text:table-of-content', attrib={
'text:name': 'Table of Contents1',
'text:protected': 'true',
'text:style-name': 'Sect1',
})
el2 = SubElement(el1,
'text:table-of-content-source',
attrib={
'text:outline-level': '10',
})
el3 =SubElement(el2, 'text:index-title-template', attrib={
'text:style-name': 'Contents_20_Heading',
})
el3.text = 'Table of Contents'
self.generate_table_of_content_entry_template(el2)
el4 = SubElement(el1, 'text:index-body')
el5 = SubElement(el4, 'text:index-title')
el6 = SubElement(el5, 'text:p', attrib={
'text:style-name': self.rststyle('contents-heading'),
})
el6.text = 'Table of Contents'
self.save_current_element = self.current_element
self.table_of_content_index_body = el4
self.set_current_element(el4)
else:
el = self.append_p('horizontalline')
el = self.append_p('centeredtextbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = 'Contents'
self.in_table_of_contents = True
elif 'abstract' in node.attributes['classes']:
el = self.append_p('horizontalline')
el = self.append_p('centeredtextbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = 'Abstract'
def depart_topic(self, node):
if 'classes' in node.attributes:
if 'contents' in node.attributes['classes']:
if self.settings.generate_oowriter_toc:
self.update_toc_page_numbers(
self.table_of_content_index_body)
self.set_current_element(self.save_current_element)
else:
el = self.append_p('horizontalline')
self.in_table_of_contents = False
def update_toc_page_numbers(self, el):
collection = []
self.update_toc_collect(el, 0, collection)
self.update_toc_add_numbers(collection)
def update_toc_collect(self, el, level, collection):
collection.append((level, el))
level += 1
for child_el in el.getchildren():
if child_el.tag != 'text:index-body':
self.update_toc_collect(child_el, level, collection)
def update_toc_add_numbers(self, collection):
for level, el1 in collection:
if (el1.tag == 'text:p' and
el1.text != 'Table of Contents'):
el2 = SubElement(el1, 'text:tab')
el2.tail = '9999'
def visit_transition(self, node):
el = self.append_p('horizontalline')
def depart_transition(self, node):
pass
#
# Admonitions
#
def visit_warning(self, node):
self.generate_admonition(node, 'warning')
def depart_warning(self, node):
self.paragraph_style_stack.pop()
def visit_attention(self, node):
self.generate_admonition(node, 'attention')
depart_attention = depart_warning
def visit_caution(self, node):
self.generate_admonition(node, 'caution')
depart_caution = depart_warning
def visit_danger(self, node):
self.generate_admonition(node, 'danger')
depart_danger = depart_warning
def visit_error(self, node):
self.generate_admonition(node, 'error')
depart_error = depart_warning
def visit_hint(self, node):
self.generate_admonition(node, 'hint')
depart_hint = depart_warning
def visit_important(self, node):
self.generate_admonition(node, 'important')
depart_important = depart_warning
def visit_note(self, node):
self.generate_admonition(node, 'note')
depart_note = depart_warning
def visit_tip(self, node):
self.generate_admonition(node, 'tip')
depart_tip = depart_warning
def visit_admonition(self, node):
#import pdb; pdb.set_trace()
title = None
for child in node.children:
if child.tagname == 'title':
title = child.astext()
if title is None:
classes1 = node.get('classes')
if classes1:
title = classes1[0]
self.generate_admonition(node, 'generic', title)
depart_admonition = depart_warning
def generate_admonition(self, node, label, title=None):
el1 = SubElement(self.current_element, 'text:p', attrib = {
'text:style-name': self.rststyle('admon-%s-hdr', ( label, )),
})
if title:
el1.text = title
else:
el1.text = '%s!' % (label.capitalize(), )
s1 = self.rststyle('admon-%s-body', ( label, ))
self.paragraph_style_stack.append(s1)
#
# Roles (e.g. subscript, superscript, strong, ...
#
def visit_subscript(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': 'rststyle-subscript',
})
self.set_current_element(el)
def depart_subscript(self, node):
self.set_to_parent()
def visit_superscript(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': 'rststyle-superscript',
})
self.set_current_element(el)
def depart_superscript(self, node):
self.set_to_parent()
# Use an own reader to modify transformations done.
class Reader(standalone.Reader):
def get_transforms(self):
default = standalone.Reader.get_transforms(self)
if self.settings.create_links:
return default
return [ i
for i in default
if i is not references.DanglingReferences ]
| {
"repo_name": "rimbalinux/MSISDNArea",
"path": "docutils/writers/odf_odt/__init__.py",
"copies": "2",
"size": "103091",
"license": "bsd-3-clause",
"hash": -4056316879503788500,
"line_mean": 36.1394746578,
"line_max": 108,
"alpha_frac": 0.5308125831,
"autogenerated": false,
"ratio": 3.845818100425278,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0024877524709229068,
"num_lines": 2703
} |
"""LaTeX2e document tree Writer."""
__docformat__ = 'reStructuredText'
# code contributions from several people included, thanks to all.
# some named: David Abrahams, Julien Letessier, Lele Gaifax, and others.
#
# convention deactivate code by two # i.e. ##.
import sys
import os
import time
import re
import string
from docutils import frontend, nodes, languages, writers, utils, transforms
from docutils.writers.newlatex2e import unicode_map
class Writer(writers.Writer):
supported = ('latex','latex2e')
"""Formats this writer supports."""
settings_spec = (
'LaTeX-Specific Options',
'The LaTeX "--output-encoding" default is "latin-1:strict".',
(('Specify documentclass. Default is "article".',
['--documentclass'],
{'default': 'article', }),
('Specify document options. Multiple options can be given, '
'separated by commas. Default is "a4paper".',
['--documentoptions'],
{'default': 'a4paper', }),
('Use LaTeX footnotes (currently supports only numbered footnotes). '
'Default: no, uses figures.',
['--use-latex-footnotes'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Format for footnote references: one of "superscript" or '
'"brackets". Default is "superscript".',
['--footnote-references'],
{'choices': ['superscript', 'brackets'], 'default': 'superscript',
'metavar': '<format>',
'overrides': 'trim_footnote_reference_space'}),
('Use LaTeX citations. '
'Default: no, uses figures which might get mixed with images.',
['--use-latex-citations'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Format for block quote attributions: one of "dash" (em-dash '
'prefix), "parentheses"/"parens", or "none". Default is "dash".',
['--attribution'],
{'choices': ['dash', 'parentheses', 'parens', 'none'],
'default': 'dash', 'metavar': '<format>'}),
('Specify LaTeX packages/stylesheets. '
' A style is referenced with \\usepackage if extension is '
'".sty" or omitted and with \\input else. '
' Overrides previous --stylesheet and --stylesheet-path settings.',
['--stylesheet'],
{'default': '', 'metavar': '<file>',
'overrides': 'stylesheet_path'}),
('Like --stylesheet, but a relative path is converted from relative '
'to the current working directory to relative to the output file. ',
['--stylesheet-path'],
{'metavar': '<file>', 'overrides': 'stylesheet'}),
('Embed the stylesheet in the output LaTeX file. The stylesheet '
'file must be accessible during processing. '
' Default: link to stylesheets',
['--embed-stylesheet'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Link to the stylesheet(s) in the output file. '
' This is the default (if not changed in a config file).',
['--link-stylesheet'],
{'dest': 'embed_stylesheet', 'action': 'store_false'}),
('Table of contents by Docutils (default) or LaTeX. '
'(Docutils does not know of pagenumbers.) ',
['--use-latex-toc'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Add parts on top of the section hierarchy.',
['--use-part-section'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Enclose titlepage in LaTeX titlepage environment.',
['--use-titlepage-env'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Let LaTeX print author and date, do not show it in docutils '
'document info.',
['--use-latex-docinfo'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
("Use LaTeX abstract environment for the document's abstract. "
'Per default the abstract is an unnumbered section.',
['--use-latex-abstract'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Color of any hyperlinks embedded in text '
'(default: "blue", "0" to disable).',
['--hyperlink-color'], {'default': 'blue'}),
('Enable compound enumerators for nested enumerated lists '
'(e.g. "1.2.a.ii"). Default: disabled.',
['--compound-enumerators'],
{'default': None, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compound enumerators for nested enumerated lists. '
'This is the default.',
['--no-compound-enumerators'],
{'action': 'store_false', 'dest': 'compound_enumerators'}),
('Enable section ("." subsection ...) prefixes for compound '
'enumerators. This has no effect without --compound-enumerators.'
'Default: disabled.',
['--section-prefix-for-enumerators'],
{'default': None, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable section prefixes for compound enumerators. '
'This is the default.',
['--no-section-prefix-for-enumerators'],
{'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
('Set the separator between section number and enumerator '
'for compound enumerated lists. Default is "-".',
['--section-enumerator-separator'],
{'default': '-', 'metavar': '<char>'}),
('When possibile, use the specified environment for literal-blocks. '
'Default is quoting of whitespace and special chars.',
['--literal-block-env'],
{'default': ''}),
('When possibile, use verbatim for literal-blocks. '
'Compatibility alias for "--literal-block-env=verbatim".',
['--use-verbatim-when-possible'],
{'default': 0, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Table style. "standard" with horizontal and vertical lines, '
'"booktabs" (LaTeX booktabs style) only horizontal lines '
'above and below the table and below the header or "nolines". '
'Default: "standard"',
['--table-style'],
{'choices': ['standard', 'booktabs','nolines'],
'default': 'standard',
'metavar': '<format>'}),
('LaTeX graphicx package option. '
'Possible values are "dvips", "pdftex". "auto" includes LaTeX code '
'to use "pdftex" if processing with pdf(la)tex and dvips otherwise. '
'Default is no option.',
['--graphicx-option'],
{'default': ''}),
('LaTeX font encoding. '
'Possible values are "", "T1", "OT1", "LGR,T1" or any other '
'combination of options to the `fontenc` package. '
'Default is "" which does not load `fontenc`.',
['--font-encoding'],
{'default': ''}),
('Per default the latex-writer puts the reference title into '
'hyperreferences. Specify "ref*" or "pageref*" to get the section '
'number or the page number.',
['--reference-label'],
{'default': None, }),
('Specify style and database for bibtex, for example '
'"--use-bibtex=mystyle,mydb1,mydb2".',
['--use-bibtex'],
{'default': None, }),
),)
settings_defaults = {'output_encoding': 'latin-1',
'sectnum_depth': 0 # updated by SectNum transform
}
relative_path_settings = ('stylesheet_path',)
config_section = 'latex2e writer'
config_section_dependencies = ('writers',)
visitor_attributes = ('head_prefix', 'stylesheet', 'head',
'body_prefix', 'body', 'body_suffix')
output = None
"""Final translated form of `document`."""
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = LaTeXTranslator
# Override parent method to add latex-specific transforms
## def get_transforms(self):
## # call the parent class' method
## transforms = writers.Writer.get_transforms(self)
## # print transforms
## # TODO: footnote collection transform
## # transforms.append(footnotes.collect)
## return transforms
def translate(self):
visitor = self.translator_class(self.document)
self.document.walkabout(visitor)
self.output = visitor.astext()
# copy parts
for attr in self.visitor_attributes:
setattr(self, attr, getattr(visitor, attr))
def assemble_parts(self):
writers.Writer.assemble_parts(self)
for part in self.visitor_attributes:
if part.startswith('body'):
# body contains inline elements, so join without newline
self.parts[part] = ''.join(getattr(self, part))
else:
self.parts[part] = '\n'.join(getattr(self, part))
class Babel(object):
"""Language specifics for LaTeX."""
# country code by a.schlock.
# partly manually converted from iso and babel stuff, dialects and some
_ISO639_TO_BABEL = {
'no': 'norsk', #XXX added by hand ( forget about nynorsk?)
'gd': 'scottish', #XXX added by hand
'hu': 'magyar', #XXX added by hand
'pt': 'portuguese',#XXX added by hand
'sl': 'slovenian',
'af': 'afrikaans',
'bg': 'bulgarian',
'br': 'breton',
'ca': 'catalan',
'cs': 'czech',
'cy': 'welsh',
'da': 'danish',
'fr': 'french',
# french, francais, canadien, acadian
'de': 'ngerman', #XXX rather than german
# ngerman, naustrian, german, germanb, austrian
'el': 'greek',
'en': 'english',
# english, USenglish, american, UKenglish, british, canadian
'eo': 'esperanto',
'es': 'spanish',
'et': 'estonian',
'eu': 'basque',
'fi': 'finnish',
'ga': 'irish',
'gl': 'galician',
'he': 'hebrew',
'hr': 'croatian',
'hu': 'hungarian',
'is': 'icelandic',
'it': 'italian',
'la': 'latin',
'nl': 'dutch',
'pl': 'polish',
'pt': 'portuguese',
'ro': 'romanian',
'ru': 'russian',
'sk': 'slovak',
'sr': 'serbian',
'sv': 'swedish',
'tr': 'turkish',
'uk': 'ukrainian'
}
def __init__(self, lang):
self.language = lang
self.quote_index = 0
self.quotes = ('``', "''")
self.setup = '' # language dependent configuration code
# double quotes are "active" in some languages (e.g. German).
# TODO: use \textquotedbl in OT1 font encoding?
self.literal_double_quote = '"'
if self.language.startswith('de'):
self.quotes = ('{\\glqq}', '\\grqq{}')
self.literal_double_quote = '\\dq{}'
if self.language.startswith('it'):
self.literal_double_quote = r'{\char`\"}'
if self.language.startswith('es'):
# reset tilde ~ to the original binding (nobreakspace):
self.setup = ('\n'
r'\addto\shorthandsspanish{\spanishdeactivate{."~<>}}')
def next_quote(self):
q = self.quotes[self.quote_index]
self.quote_index = (self.quote_index+1) % 2
return q
def quote_quotes(self,text):
t = None
for part in text.split('"'):
if t == None:
t = part
else:
t += self.next_quote() + part
return t
def get_language(self):
lang = self.language.split('_')[0] # filter dialects
return self._ISO639_TO_BABEL.get(lang, "")
# Building blocks for the latex preamble
# --------------------------------------
class SortableDict(dict):
"""Dictionary with additional sorting methods"""
def sortedkeys(self):
"""Return sorted list of keys"""
keys = self.keys()
keys.sort()
return keys
def sortedvalues(self):
"""Return list of values sorted by keys"""
return [self[key] for key in self.sortedkeys()]
# A container for LaTeX code snippets that can be
# inserted into the preamble if required in the document.
#
# .. The package 'makecmds' would enable shorter definitions using the
# \providelength and \provideenvironment commands.
# However, it is pretty non-standard (texlive-latex-extra).
class PreambleCmds(object):
"""Building blocks for the latex preamble."""
PreambleCmds.admonition = r"""% admonitions (specially marked "topics")
\providecommand{\DUadmonition}[1]{%
\begin{center}
\fbox{\parbox{0.9\textwidth}{#1}}
\end{center}
}"""
## PreambleCmds.caption = r"""% configure caption layout
## \usepackage{caption}
## \captionsetup{singlelinecheck=false}% no exceptions for one-lined captions"""
PreambleCmds.docinfo = r"""% width of docinfo table:
\DUprovidelength{\DUdocinfowidth}{0.9\textwidth}"""
PreambleCmds.embedded_package_wrapper = r"""\makeatletter
%% embedded stylesheet: %s
%s
\makeatother"""
PreambleCmds.fieldlist = r"""% field list environment:
\ifthenelse{\isundefined{\DUfieldlist}}{
\newenvironment{DUfieldlist}%
{\quote\description}
{\enddescription\endquote}
}{}"""
PreambleCmds.float_settings = r"""\usepackage{float} % float configuration
\floatplacement{figure}{H} % place figures here definitely"""
PreambleCmds.footnote_floats = r"""% settings for footnotes as floats:
\setlength{\floatsep}{0.5em}
\setlength{\textfloatsep}{\fill}
\addtolength{\textfloatsep}{3em}
\renewcommand{\textfraction}{0.5}
\renewcommand{\topfraction}{0.5}
\renewcommand{\bottomfraction}{0.5}
\setcounter{totalnumber}{50}
\setcounter{topnumber}{50}
\setcounter{bottomnumber}{50}"""
PreambleCmds.graphicx_auto = r"""% Check output format
\ifx\pdftexversion\undefined
\usepackage{graphicx}
\else
\usepackage[pdftex]{graphicx}
\fi'))"""
PreambleCmds.inline = r"""% custom roles:
% \DUrole{NAME} calls \docutilsroleNAME if it exists
\providecommand*{\DUrole}[2]{%
\ifcsname docutilsrole#1\endcsname%
\csname docutilsrole#1\endcsname{#2}%
\else%
#2%
\fi%
}"""
PreambleCmds.legend = r"""% legend environment:
\ifthenelse{\isundefined{\DUlegend}}{
\newenvironment{DUlegend}%
{\small}
{}
}{}"""
PreambleCmds.lineblock = r"""% line block environment:
\DUprovidelength{\DUlineblockindent}{2.5em}
\ifthenelse{\isundefined{\DUlineblock}}{
\newenvironment{DUlineblock}[1]{%
\list{}{\setlength{\partopsep}{\parskip}
\addtolength{\partopsep}{\baselineskip}
\setlength{\topsep}{0pt}
\setlength{\itemsep}{0.15\baselineskip}
\setlength{\parsep}{0pt}
\setlength{\leftmargin}{#1}}
\raggedright
}
{\endlist}
}{}"""
PreambleCmds.linking = r"""%% hyperref (PDF hyperlinks):
\ifthenelse{\isundefined{\hypersetup}}{
\usepackage[colorlinks=%s,linkcolor=%s,urlcolor=%s]{hyperref}
}{}"""
PreambleCmds.minitoc = r"""%% local table of contents
\usepackage{minitoc}"""
PreambleCmds.optionlist = r"""% option list:
\providecommand*{\DUoptionlistlabel}[1]{\bf #1 \hfill}
\DUprovidelength{\DUoptionlistindent}{3cm}
\ifthenelse{\isundefined{\DUoptionlist}}{
\newenvironment{DUoptionlist}{%
\list{}{\setlength{\labelwidth}{\DUoptionlistindent}
\setlength{\rightmargin}{1cm}
\setlength{\leftmargin}{\rightmargin}
\addtolength{\leftmargin}{\labelwidth}
\addtolength{\leftmargin}{\labelsep}
\renewcommand{\makelabel}{\DUoptionlistlabel}}
}
{\endlist}
}{}"""
PreambleCmds.providelength = r"""% provide a length variable and set it
\newcommand*{\DUprovidelength}[2]{
\ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
}"""
PreambleCmds.rubric = r"""% rubric (an informal heading):
\providecommand*{\DUrubric}[1]{%
\subsection*{\centering\textit{\textmd{#1}}}%
}"""
PreambleCmds.sidebar = r"""% sidebar (text outside the main text flow)
\providecommand{\DUsidebar}[1]{%
\begin{center}
\fbox{\colorbox[gray]{0.80}{\parbox{0.9\textwidth}{#1}}}
\end{center}
}"""
PreambleCmds.sidebartitle = r"""% sidebar title
\providecommand*{\DUsidebartitle}{\DUtopictitle}"""
PreambleCmds.sidebarsubtitle = r"""% sidebar sub-title
\providecommand*{\DUsidebarsubtitle}[1]{\hspace*{\fill}\\\emph{#1}\smallskip}"""
PreambleCmds.table = r"""\usepackage{longtable}
\usepackage{array}
\setlength{\extrarowheight}{2pt}
\newlength{\DUtablewidth} % internal use in tables"""
PreambleCmds.title = r"""
%%%%%% Title metadata
\title{%s}
\author{%s}
\date{%s}"""
PreambleCmds.titlereference = r"""% title reference role:
\providecommand*{\DUroletitlereference}[1]{\textsl{#1}}"""
PreambleCmds.topictitle = r"""% title for "topics" (admonitions, sidebar)
\providecommand*{\DUtopictitle}[1]{\textbf{#1}\smallskip}"""
PreambleCmds.transition = r"""% transition ([fancy]break, anonymous section)
\providecommand*{\DUtransition}{%
\hspace*{\fill}\hrulefill\hspace*{\fill}
\vskip 0.5\baselineskip
}"""
class DocumentClass(object):
"""Details of a LaTeX document class."""
def __init__(self, document_class, with_part=False):
self.document_class = document_class
self._with_part = with_part
self.sections = ['section', 'subsection', 'subsubsection',
'paragraph', 'subparagraph']
if self.document_class in ('book', 'memoir', 'report',
'scrbook', 'scrreprt'):
self.sections.insert(0, 'chapter')
if self._with_part:
self.sections.insert(0, 'part')
def section(self, level):
"""Return the LaTeX section name for section `level`.
The name depends on the specific document class.
Level is 1,2,3..., as level 0 is the title.
"""
if level <= len(self.sections):
return self.sections[level-1]
else:
return self.sections[-1]
class Table(object):
"""Manage a table while traversing.
Maybe change to a mixin defining the visit/departs, but then
class Table internal variables are in the Translator.
Table style might be
:standard: horizontal and vertical lines
:booktabs: only horizontal lines (requires "booktabs" LaTeX package)
:nolines: (or borderless) no lines
"""
def __init__(self,translator,latex_type,table_style):
self._translator = translator
self._latex_type = latex_type
self._table_style = table_style
self._open = 0
# miscellaneous attributes
self._attrs = {}
self._col_width = []
self._rowspan = []
self.stubs = []
self._in_thead = 0
def open(self):
self._open = 1
self._col_specs = []
self.caption = None
self._attrs = {}
self._in_head = 0 # maybe context with search
def close(self):
self._open = 0
self._col_specs = None
self.caption = None
self._attrs = {}
self.stubs = []
def is_open(self):
return self._open
def set_table_style(self, table_style):
if not table_style in ('standard','booktabs','borderless','nolines'):
return
self._table_style = table_style
def get_latex_type(self):
return self._latex_type
def set(self,attr,value):
self._attrs[attr] = value
def get(self,attr):
if attr in self._attrs:
return self._attrs[attr]
return None
def get_vertical_bar(self):
if self._table_style == 'standard':
return '|'
return ''
# horizontal lines are drawn below a row,
def get_opening(self):
if self._latex_type == 'longtable':
# otherwise longtable might move before paragraph and subparagraph
prefix = '\\leavevmode\n'
else:
prefix = ''
prefix += '\setlength{\DUtablewidth}{\linewidth}'
return '%s\n\\begin{%s}[c]' % (prefix, self._latex_type)
def get_closing(self):
line = ''
if self._table_style == 'booktabs':
line = '\\bottomrule\n'
elif self._table_style == 'standard':
lines = '\\hline\n'
return '%s\\end{%s}' % (line,self._latex_type)
def visit_colspec(self, node):
self._col_specs.append(node)
# "stubs" list is an attribute of the tgroup element:
self.stubs.append(node.attributes.get('stub'))
def get_colspecs(self):
"""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).
"""
width = 80
total_width = 0.0
# first see if we get too wide.
for node in self._col_specs:
colwidth = float(node['colwidth']+1) / width
total_width += colwidth
self._col_width = []
self._rowspan = []
# donot make it full linewidth
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\\DUtablewidth}' % (bar, colwidth+0.005)
return latex_table_spec+bar
def get_column_width(self):
"""Return columnwidth for current cell (not multicell)."""
return '%.2f\\DUtablewidth' % self._col_width[self._cell_in_row-1]
def get_caption(self):
if not self.caption:
return ''
if 1 == self._translator.thead_depth():
return r'\caption{%s}\\' '\n' % self.caption
return r'\caption[]{%s (... continued)}\\' '\n' % self.caption
def need_recurse(self):
if self._latex_type == 'longtable':
return 1 == self._translator.thead_depth()
return 0
def visit_thead(self):
self._in_thead += 1
if self._table_style == 'standard':
return ['\\hline\n']
elif self._table_style == 'booktabs':
return ['\\toprule\n']
return []
def depart_thead(self):
a = []
#if self._table_style == 'standard':
# a.append('\\hline\n')
if self._table_style == 'booktabs':
a.append('\\midrule\n')
if self._latex_type == 'longtable':
if 1 == self._translator.thead_depth():
a.append('\\endfirsthead\n')
else:
a.append('\\endhead\n')
a.append(r'\multicolumn{%d}{c}' % len(self._col_specs) +
r'{\hfill ... continued on next page} \\')
a.append('\n\\endfoot\n\\endlastfoot\n')
# for longtable one could add firsthead, foot and lastfoot
self._in_thead -= 1
return a
def visit_row(self):
self._cell_in_row = 0
def depart_row(self):
res = [' \\\\\n']
self._cell_in_row = None # remove cell counter
for i in range(len(self._rowspan)):
if (self._rowspan[i]>0):
self._rowspan[i] -= 1
if self._table_style == 'standard':
rowspans = [i+1 for i in range(len(self._rowspan))
if (self._rowspan[i]<=0)]
if len(rowspans)==len(self._rowspan):
res.append('\\hline\n')
else:
cline = ''
rowspans.reverse()
# TODO merge clines
while 1:
try:
c_start = rowspans.pop()
except:
break
cline += '\\cline{%d-%d}\n' % (c_start,c_start)
res.append(cline)
return res
def set_rowspan(self,cell,value):
try:
self._rowspan[cell] = value
except:
pass
def get_rowspan(self,cell):
try:
return self._rowspan[cell]
except:
return 0
def get_entry_number(self):
return self._cell_in_row
def visit_entry(self):
self._cell_in_row += 1
def is_stub_column(self):
if len(self.stubs) >= self._cell_in_row:
return self.stubs[self._cell_in_row-1]
return False
class LaTeXTranslator(nodes.NodeVisitor):
# When options are given to the documentclass, latex will pass them
# to other packages, as done with babel.
# Dummy settings might be taken from document settings
# Templates
# ---------
latex_head = r'\documentclass[%s]{%s}'
# conditionally if no hyperref is used dont include
linking = PreambleCmds.linking
generator = '% generated by Docutils <http://docutils.sourceforge.net/>'
# Config setting defaults
# -----------------------
# TODO: use mixins for different implementations.
# list environment for docinfo. else tabularx
use_optionlist_for_docinfo = 0 # NOT YET IN USE
# Use compound enumerations (1.A.1.)
compound_enumerators = 0
# If using compound enumerations, include section information.
section_prefix_for_enumerators = 0
# This is the character that separates the section ("." subsection ...)
# prefix from the regular list enumerator.
section_enumerator_separator = '-'
# default link color
hyperlink_color = 'blue'
# Bookkeeping:
has_latex_toc = False # is there a toc in the doc (needed by minitoc)
def __init__(self, document):
nodes.NodeVisitor.__init__(self, document)
self.settings = settings = document.settings
self.latex_encoding = self.to_latex_encoding(settings.output_encoding)
self.use_latex_toc = settings.use_latex_toc
self.use_latex_docinfo = settings.use_latex_docinfo
self.use_latex_footnotes = settings.use_latex_footnotes
self._use_latex_citations = settings.use_latex_citations
self.embed_stylesheet = settings.embed_stylesheet
self._reference_label = settings.reference_label
self.hyperlink_color = settings.hyperlink_color
self.compound_enumerators = settings.compound_enumerators
self.font_encoding = settings.font_encoding
self.section_prefix_for_enumerators = (
settings.section_prefix_for_enumerators)
self.section_enumerator_separator = (
settings.section_enumerator_separator.replace('_', '\\_'))
if self.hyperlink_color == '0':
self.hyperlink_color = 'black'
self.colorlinks = 'false'
else:
self.colorlinks = 'true'
# literal blocks:
self.literal_block_env = ''
self.literal_block_options = ''
if settings.literal_block_env != '':
(none,
self.literal_block_env,
self.literal_block_options,
none ) = re.split('(\w+)(.*)', settings.literal_block_env)
elif settings.use_verbatim_when_possible:
self.literal_block_env = 'verbatim'
#
if self.settings.use_bibtex:
self.bibtex = self.settings.use_bibtex.split(',',1)
# TODO avoid errors on not declared citations.
else:
self.bibtex = None
# language: labels, bibliographic_fields, and author_separators.
# to allow writing labes for specific languages.
self.language = languages.get_language(settings.language_code)
self.babel = Babel(settings.language_code)
self.author_separator = self.language.author_separators[0]
self.d_options = [self.settings.documentoptions,
self.babel.get_language()]
self.d_options = ','.join([opt for opt in self.d_options if opt])
self.d_class = DocumentClass(settings.documentclass,
settings.use_part_section)
# object for a table while proccessing.
self.table_stack = []
self.active_table = Table(self,'longtable',settings.table_style)
# Two special dictionaries to collect document-specific requirements.
# Values will be inserted
# * in alphabetic order of their keys,
# * only once, even if required multiple times.
self.requirements = SortableDict() # inserted before style sheet
self.fallbacks = SortableDict() # inserted after style sheet
# Page layout with typearea (if there are relevant document options).
if (settings.documentclass.find('scr') == -1 and
(self.d_options.find('DIV') != -1 or
self.d_options.find('BCOR') != -1)):
self.requirements['typearea'] = r'\usepackage{typearea}'
if self.font_encoding == '':
fontenc_header = r'%\usepackage[OT1]{fontenc}'
else:
fontenc_header = r'\usepackage[%s]{fontenc}' % self.font_encoding
if self.settings.graphicx_option == '':
self.graphicx_package = r'\usepackage{graphicx}'
elif self.settings.graphicx_option.lower() == 'auto':
self.graphicx_package = PreambleCmds.graphicx_auto
else:
self.graphicx_package = (r'\usepackage[%s]{graphicx}' %
self.settings.graphicx_option)
# include all supported sections in toc and PDF bookmarks
# (or use documentclass-default (as currently))?
## if self.use_latex_toc:
## self.requirements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
## len(self.d_class.sections))
if not self.settings.sectnum_xform: # section numbering by LaTeX:
sectnum_cmds = []
# sectnum_depth:
# 0 no "sectnum" directive -> no section numbers
# None "sectnum" directive without depth arg -> LaTeX default
# else value of the "depth" argument -> limit to supported
# section levels
if settings.sectnum_depth is not None:
sectnum_depth = min(settings.sectnum_depth,
len(self.d_class.sections))
sectnum_cmds.append(r'\setcounter{secnumdepth}{%d}' %
sectnum_depth)
# start with specified number:
if (hasattr(settings, 'sectnum_start') and
settings.sectnum_start != 1):
sectnum_cmds.append(r'\setcounter{%s}{%d}' %
(self.d_class.sections[0],
settings.sectnum_start-1))
# currently ignored (configure in a stylesheet):
## settings.sectnum_prefix
## settings.sectnum_suffix
if sectnum_cmds:
self.requirements['sectnum'] = '\n'.join(sectnum_cmds)
# packages and/or stylesheets
# ---------------------------
self.stylesheet = ['\n%%% User specified packages and stylesheets']
# get list of style sheets from settings
styles = utils.get_stylesheet_list(settings)
# adapt path if --stylesheet_path is used
if settings.stylesheet_path and not(self.embed_stylesheet):
styles = [utils.relative_path(settings._destination, sheet)
for sheet in styles]
for sheet in styles:
(base, ext) = os.path.splitext(sheet)
is_package = ext in ['.sty', '']
if self.embed_stylesheet:
if is_package:
sheet = base + '.sty' # adapt package name
# wrap in \makeatletter, \makeatother
wrapper = PreambleCmds.embedded_package_wrapper
else:
wrapper = '%% embedded stylesheet: %s\n%s'
settings.record_dependencies.add(sheet)
self.stylesheet.append(wrapper % (sheet, open(sheet).read()))
else: # link to style sheet
if is_package:
self.stylesheet.append(r'\usepackage{%s}' % base)
else:
self.stylesheet.append(r'\input{%s}' % sheet)
## if len(self.stylesheet) == 1: # if there are no styles,
## self.stylesheet = [] # remove comment line
# Part of LaTeX preamble before style sheet(s)
self.head_prefix = [
self.generator,
self.latex_head % (self.d_options,self.settings.documentclass),
## '%%% Requirements',
# multi-language support (language is in document settings)
'\\usepackage{babel}%s' % self.babel.setup,
fontenc_header,
r'\usepackage[%s]{inputenc}' % self.latex_encoding,
r'\usepackage{ifthen}',
r'\usepackage{fixltx2e} % fix LaTeX2e shortcomings',
] # custom requirements will be added later
# Part of LaTeX preamble following the stylesheet
self.head = []
if self.linking: # and maybe check for pdf
self.pdfinfo = []
self.pdfauthor = []
# pdftitle, pdfsubject, pdfauthor, pdfkeywords,
# pdfcreator, pdfproducer
else:
self.pdfinfo = None
# Title metadata: Title, Date, and Author(s)
# separate title, so we can append subtitle.
self.title = []
# if use_latex_docinfo: collects lists of
# author/organization/contact/address lines
self.author_stack = []
# an empty string supresses the "auto-date" feature of \maketitle
self.date = ''
self.body_prefix = ['\n%%% Body\n\\begin{document}\n']
self.body = []
self.body_suffix = ['\n\\end{document}\n']
self.section_level = 0
self.context = []
self.topic_classes = []
# column specification for tables
self.table_caption = None
# Flags to encode
# ---------------
# verbatim: to tell encode not to encode.
self.verbatim = 0
# insert_non_breaking_blanks: to tell encode to replace blanks by "~".
self.insert_non_breaking_blanks = 0
# insert_newline: to tell encode to add latex newline.
self.insert_newline = 0
# inside citation reference labels underscores dont need to be escaped.
self.inside_citation_reference_label = 0
# Stack of section counters so that we don't have to use_latex_toc.
# This will grow and shrink as processing occurs.
# Initialized for potential first-level sections.
self._section_number = [0]
# The current stack of enumerations so that we can expand
# them into a compound enumeration.
self._enumeration_counters = []
# The maximum number of enumeration counters we've used.
# If we go beyond this number, we need to create a new
# counter; otherwise, just reuse an old one.
self._max_enumeration_counters = 0
self._bibitems = []
# docinfo.
self.docinfo = None
# inside literal block: no quote mangling.
self.literal_block = 0
self.literal_block_stack = []
self.literal = 0
def to_latex_encoding(self,docutils_encoding):
"""Translate docutils encoding name into LaTeX's.
Default method is remove "-" and "_" chars from docutils_encoding.
"""
tr = { 'iso-8859-1': 'latin1', # west european
'iso-8859-2': 'latin2', # east european
'iso-8859-3': 'latin3', # esperanto, maltese
'iso-8859-4': 'latin4', # north european, scandinavian, baltic
'iso-8859-5': 'iso88595', # cyrillic (ISO)
'iso-8859-9': 'latin5', # turkish
'iso-8859-15': 'latin9', # latin9, update to latin1.
'mac_cyrillic': 'maccyr', # cyrillic (on Mac)
'windows-1251': 'cp1251', # cyrillic (on Windows)
'koi8-r': 'koi8-r', # cyrillic (Russian)
'koi8-u': 'koi8-u', # cyrillic (Ukrainian)
'windows-1250': 'cp1250', #
'windows-1252': 'cp1252', #
'us-ascii': 'ascii', # ASCII (US)
# unmatched encodings
#'': 'applemac',
#'': 'ansinew', # windows 3.1 ansi
#'': 'ascii', # ASCII encoding for the range 32--127.
#'': 'cp437', # dos latin us
#'': 'cp850', # dos latin 1
#'': 'cp852', # dos latin 2
#'': 'decmulti',
#'': 'latin10',
#'iso-8859-6': '' # arabic
#'iso-8859-7': '' # greek
#'iso-8859-8': '' # hebrew
#'iso-8859-10': '' # latin6, more complete iso-8859-4
}
encoding = docutils_encoding.lower()
if encoding in tr:
return tr[encoding]
# convert: latin-1, latin_1, utf-8 and similar things
encoding = encoding.replace('_', '').replace('-', '')
# strip the error handler
return encoding.split(':')[0]
def language_label(self, docutil_label):
return self.language.labels[docutil_label]
latex_equivalents = {
u'\u00A0' : '~',
u'\u2013' : '{--}',
u'\u2014' : '{---}',
u'\u2018' : '`',
u'\u2019' : "'",
u'\u201A' : ',',
u'\u201C' : '``',
u'\u201D' : "''",
u'\u201E' : ',,',
u'\u2020' : '\\dag{}',
u'\u2021' : '\\ddag{}',
u'\u2026' : '\\dots{}',
u'\u2122' : '\\texttrademark{}',
u'\u21d4' : '$\\Leftrightarrow$',
# greek alphabet ?
}
def unicode_to_latex(self,text):
# see LaTeX codec
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124
# Only some special chracters are translated, for documents with many
# utf-8 chars one should use the LaTeX unicode package.
for uchar in self.latex_equivalents.keys():
text = text.replace(uchar,self.latex_equivalents[uchar])
return text
def ensure_math(self, text):
if not hasattr(self, 'ensure_math_re'):
chars = { # lnot,pm,twosuperior,threesuperior,mu,onesuperior,times,div
'latin1' : '\xac\xb1\xb2\xb3\xb5\xb9\xd7\xf7' ,
# TODO?: also latin5 and latin9
}
self.ensure_math_re = re.compile('([%s])' % chars['latin1'])
text = self.ensure_math_re.sub(r'\\ensuremath{\1}', text)
return text
def encode(self, text):
"""Return text with special characters escaped.
Escape the ten special printing characters ``# $ % & ~ _ ^ \ { }``,
square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
Separate ``-`` (and more in literal text) to prevent input ligatures.
"""
if self.verbatim:
return text
# Bootstrapping: backslash and braces are also part of replacements
# 1. backslash (terminated below)
text = text.replace('\\', r'\textbackslash')
# 2. braces
text = text.replace('{', r'\{')
text = text.replace('}', r'\}')
# 3. terminate \textbackslash
text = text.replace('\\textbackslash', '\\textbackslash{}')
# 4. the remaining special printing characters
text = text.replace('#', r'\#')
text = text.replace('$', r'\$')
text = text.replace('%', r'\%')
text = text.replace('&', r'\&')
text = text.replace('~', r'\textasciitilde{}')
if not self.inside_citation_reference_label:
text = text.replace('_', r'\_')
text = text.replace('^', r'\textasciicircum{}')
# Square brackets
#
# \item and all the other commands with optional arguments check
# if the token right after the macro name is an opening bracket.
# In that case the contents between that bracket and the following
# closing bracket on the same grouping level are taken as the
# optional argument. What makes this unintuitive is the fact that
# the square brackets aren't grouping characters themselves, so in
# your last example \item[[...]] the optional argument consists of
# [... (without the closing bracket).
#
# How to escape?
#
# Square brackets are ordinary chars and cannot be escaped with '\',
# so we put them in a group '{[}'. (Alternative: ensure that all
# macros with optional arguments are terminated with {} and text
# inside any optional argument is put in a group ``[{text}]``).
# Commands with optional args inside an optional arg must be put
# in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
text = text.replace('[', '{[}')
text = text.replace(']', '{]}')
# Workarounds for OT1 font-encoding
if self.font_encoding in ['OT1', '']:
# * out-of-order characters in cmtt
if self.literal_block or self.literal:
# replace underscore by underlined blank, because this has
# correct width.
text = text.replace(r'\_', r'\underline{ }')
# the backslash doesn't work, so we use a mirrored slash.
# \reflectbox is provided by graphicx:
self.requirements['graphicx'] = self.graphicx_package
text = text.replace(r'\textbackslash', r'\reflectbox{/}')
# * ``< | >`` come out as different chars (except for cmtt):
else:
text = text.replace('|', '\\textbar{}')
text = text.replace('<', '\\textless{}')
text = text.replace('>', '\\textgreater{}')
#
# Separate compound characters, e.g. '--' to '-{}-'. (The
# actual separation is done later; see below.)
separate_chars = '-'
if self.literal_block or self.literal:
# In monospace-font, we also separate ',,', '``' and "''"
# and some other characters which can't occur in
# non-literal text.
separate_chars += ',`\'"<>'
# double quotes are 'active' in some languages
text = text.replace('"', self.babel.literal_double_quote)
else:
text = self.babel.quote_quotes(text)
for char in separate_chars * 2:
# Do it twice ("* 2") because otherwise we would replace
# '---' by '-{}--'.
text = text.replace(char + char, char + '{}' + char)
if self.insert_newline or self.literal_block:
# Literal line breaks (in address or literal blocks):
# for blank lines, insert a protected space, to avoid
# ! LaTeX Error: There's no line here to end.
textlines = [line + '~'*(not line.lstrip())
for line in text.split('\n')]
text = '\\\\\n'.join(textlines)
if self.insert_non_breaking_blanks:
text = text.replace(' ', '~')
if not self.latex_encoding.startswith('utf8'):
text = self.unicode_to_latex(text)
text = self.ensure_math(text)
if self.latex_encoding == 'utf8':
# no-break space is not supported by (plain) utf8 input encoding
text = text.replace(u'\u00A0', '~')
return text
def attval(self, text,
whitespace=re.compile('[\n\r\t\v\f]')):
"""Cleanse, encode, and return attribute value text."""
return self.encode(whitespace.sub(' ', text))
def astext(self):
"""Assemble document parts and return as string."""
head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
body = ''.join(self.body_prefix + self.body + self.body_suffix)
return head + '\n' + body
# Tests
# -----
def is_inline(self, node):
"""Check whether a node represents an inline element"""
return isinstance(node.parent, nodes.TextElement)
# Visitor methods
# ---------------
def visit_Text(self, node):
self.body.append(self.encode(node.astext()))
def depart_Text(self, node):
pass
def visit_address(self, node):
self.visit_docinfo_item(node, 'address')
def depart_address(self, node):
self.depart_docinfo_item(node)
def visit_admonition(self, node, name=''):
self.fallbacks['admonition'] = PreambleCmds.admonition
self.fallbacks['topictitle'] = PreambleCmds.topictitle
self.body.append('\n\\DUadmonition{')
if name:
self.body.append('\\DUtopictitle{%s}\n' %
self.language.labels.get(name, name));
## self.body.append('\\vspace{2mm}\n')
def depart_admonition(self, node=None):
self.body.append('}\n')
def visit_attention(self, node):
self.visit_admonition(node, 'attention')
def depart_attention(self, node):
self.depart_admonition()
def visit_author(self, node):
self.visit_docinfo_item(node, 'author')
def depart_author(self, node):
self.depart_docinfo_item(node)
def visit_authors(self, node):
# not used: visit_author is called anyway for each author.
pass
def depart_authors(self, node):
pass
def visit_block_quote(self, node):
self.body.append( '%\n\\begin{quote}\n')
def depart_block_quote(self, node):
self.body.append( '\n\\end{quote}\n')
def visit_bullet_list(self, node):
if 'contents' in self.topic_classes:
self.body.append( '%\n\\begin{list}{}{}\n' )
else:
self.body.append( '%\n\\begin{itemize}\n' )
def depart_bullet_list(self, node):
if 'contents' in self.topic_classes:
self.body.append( '\n\\end{list}\n' )
else:
self.body.append( '\n\\end{itemize}\n' )
def visit_superscript(self, node):
self.body.append(r'\textsuperscript{')
if node['classes']:
self.visit_inline(node)
def depart_superscript(self, node):
if node['classes']:
self.depart_inline(node)
self.body.append('}')
def visit_subscript(self, node):
self.body.append(r'\textsubscript{') # requires `fixltx2e`
if node['classes']:
self.visit_inline(node)
def depart_subscript(self, node):
if node['classes']:
self.depart_inline(node)
self.body.append('}')
def visit_caption(self, node):
self.body.append( '\\caption{' )
def depart_caption(self, node):
self.body.append('}\n')
def visit_caution(self, node):
self.visit_admonition(node, 'caution')
def depart_caution(self, node):
self.depart_admonition()
def visit_title_reference(self, node):
self.fallbacks['titlereference'] = PreambleCmds.titlereference
self.body.append(r'\DUroletitlereference{')
if node['classes']:
self.visit_inline(node)
def depart_title_reference(self, node):
if node['classes']:
self.depart_inline(node)
self.body.append( '}' )
def visit_citation(self, node):
# TODO maybe use cite bibitems
if self._use_latex_citations:
self.context.append(len(self.body))
else:
self.body.append(r'\begin{figure}[b]')
self.append_hypertargets(node)
def depart_citation(self, node):
if self._use_latex_citations:
size = self.context.pop()
label = self.body[size]
text = ''.join(self.body[size+1:])
del self.body[size:]
self._bibitems.append([label, text])
else:
self.body.append('\\end{figure}\n')
def visit_citation_reference(self, node):
if self._use_latex_citations:
if not self.inside_citation_reference_label:
self.body.append(r'\cite{')
self.inside_citation_reference_label = 1
else:
assert self.body[-1] in (' ', '\n'),\
'unexpected non-whitespace while in reference label'
del self.body[-1]
else:
href = ''
if 'refid' in node:
href = node['refid']
elif 'refname' in node:
href = self.document.nameids[node['refname']]
self.body.append('[\\hyperlink{%s}{' % href)
def depart_citation_reference(self, node):
if self._use_latex_citations:
followup_citation = False
# check for a following citation separated by a space or newline
next_siblings = node.traverse(descend=0, siblings=1,
include_self=0)
if len(next_siblings) > 1:
next = next_siblings[0]
if (isinstance(next, nodes.Text) and
next.astext() in (' ', '\n')):
if next_siblings[1].__class__ == node.__class__:
followup_citation = True
if followup_citation:
self.body.append(',')
else:
self.body.append('}')
self.inside_citation_reference_label = 0
else:
self.body.append('}]')
def visit_classifier(self, node):
self.body.append( '(\\textbf{' )
def depart_classifier(self, node):
self.body.append( '})\n' )
def visit_colspec(self, node):
self.active_table.visit_colspec(node)
def depart_colspec(self, node):
pass
def visit_comment(self, node):
# Precede every line with a comment sign, wrap in newlines
self.body.append('\n%% %s\n' % node.astext().replace('\n', '\n% '))
raise nodes.SkipNode
def depart_comment(self, node):
pass
def visit_compound(self, node):
pass
def depart_compound(self, node):
pass
def visit_contact(self, node):
self.visit_docinfo_item(node, 'contact')
def depart_contact(self, node):
self.depart_docinfo_item(node)
def visit_container(self, node):
pass
def depart_container(self, node):
pass
def visit_copyright(self, node):
self.visit_docinfo_item(node, 'copyright')
def depart_copyright(self, node):
self.depart_docinfo_item(node)
def visit_danger(self, node):
self.visit_admonition(node, 'danger')
def depart_danger(self, node):
self.depart_admonition()
def visit_date(self, node):
self.visit_docinfo_item(node, 'date')
def depart_date(self, node):
self.depart_docinfo_item(node)
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
pass
def depart_definition(self, node):
self.body.append('\n')
def visit_definition_list(self, node):
self.body.append( '%\n\\begin{description}\n' )
def depart_definition_list(self, node):
self.body.append( '\\end{description}\n' )
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_description(self, node):
self.body.append(' ')
def depart_description(self, node):
pass
def visit_docinfo(self, node):
# tabularx: automatic width of columns, no page breaks allowed.
self.requirements['tabularx'] = r'\usepackage{tabularx}'
self.requirements['~providelength'] = PreambleCmds.providelength
self.fallbacks['docinfo'] = PreambleCmds.docinfo
self.docinfo = ['%' + '_'*75 + '\n',
'\\begin{center}\n',
'\\begin{tabularx}{\\DUdocinfowidth}{lX}\n']
def depart_docinfo(self, node):
self.docinfo.append('\\end{tabularx}\n')
self.docinfo.append('\\end{center}\n')
self.body = self.docinfo + self.body # prepend to self.body
# clear docinfo, so field names are no longer appended.
self.docinfo = None
def visit_docinfo_item(self, node, name):
if name == 'author':
if self.pdfinfo is not None:
self.pdfauthor += [self.attval(node.astext())]
if self.use_latex_docinfo:
if name in ('author', 'organization', 'contact', 'address'):
# We attach these to the last author. If any of them precedes
# the first author, put them in a separate "author" group
# (in lack of better semantics).
if name == 'author' or not self.author_stack:
self.author_stack.append([])
if name == 'address': # newlines are meaningful
self.insert_newline = 1
text = self.encode(node.astext())
self.insert_newline = 0
else:
text = self.attval(node.astext())
self.author_stack[-1].append(text)
raise nodes.SkipNode
elif name == 'date':
self.date = self.attval(node.astext())
raise nodes.SkipNode
self.docinfo.append('\\textbf{%s}: &\n\t' % self.language_label(name))
if name == 'address':
self.insert_newline = 1
self.docinfo.append('{\\raggedright\n')
self.context.append(' } \\\\\n')
else:
self.context.append(' \\\\\n')
self.context.append(self.docinfo)
self.context.append(len(self.body))
def depart_docinfo_item(self, node):
size = self.context.pop()
dest = self.context.pop()
tail = self.context.pop()
tail = self.body[size:] + [tail]
del self.body[size:]
dest.extend(tail)
# for address we did set insert_newline
self.insert_newline = 0
def visit_doctest_block(self, node):
self.body.append( '\\begin{verbatim}' )
self.verbatim = 1
def depart_doctest_block(self, node):
self.body.append( '\\end{verbatim}\n' )
self.verbatim = 0
def visit_document(self, node):
if self.settings.use_titlepage_env:
self.body_prefix.append('\\begin{titlepage}\n')
# titled document?
if (self.use_latex_docinfo or len(node) and
isinstance(node[0], nodes.title)):
if node['ids']:
self.title += self.labels(node)
self.body_prefix.append('\\maketitle\n\n')
def depart_document(self, node):
# Complete header with information gained from walkabout
# a) conditional requirements (before style sheet)
self.head_prefix += self.requirements.sortedvalues()
# b) coditional fallback definitions (after style sheet)
self.head.append(
'\n%%% Fallback definitions for Docutils-specific commands')
self.head += self.fallbacks.sortedvalues()
# c) hyperlink setup and PDF metadata
self.head.append(self.linking % (self.colorlinks,
self.hyperlink_color,
self.hyperlink_color))
if self.pdfinfo is not None and self.pdfauthor:
self.pdfauthor = self.author_separator.join(self.pdfauthor)
self.pdfinfo.append(' pdfauthor={%s}' % self.pdfauthor)
if self.pdfinfo:
self.head += [r'\hypersetup{'] + self.pdfinfo + ['}']
# d) Title metadata
# NOTE: Docutils puts this into docinfo, so normally we do not want
# LaTeX author/date handling (via \maketitle).
# To deactivate it, self.astext() adds \title{...}, \author{...},
# \date{...}, even if the"..." are empty strings.
if '\\maketitle\n\n' in self.body_prefix:
title = [PreambleCmds.title % (
'%\n '.join(self.title),
' \\and\n'.join(['\\\\\n'.join(author_lines)
for author_lines in self.author_stack]),
self.date)]
self.head += title
# Add bibliography
# TODO insertion point of bibliography should be configurable.
if self._use_latex_citations and len(self._bibitems)>0:
if not self.bibtex:
widest_label = ''
for bi in self._bibitems:
if len(widest_label)<len(bi[0]):
widest_label = bi[0]
self.body.append('\n\\begin{thebibliography}{%s}\n' %
widest_label)
for bi in self._bibitems:
# cite_key: underscores must not be escaped
cite_key = bi[0].replace(r'\_','_')
self.body.append('\\bibitem[%s]{%s}{%s}\n' %
(bi[0], cite_key, bi[1]))
self.body.append('\\end{thebibliography}\n')
else:
self.body.append('\n\\bibliographystyle{%s}\n' %
self.bibtex[0])
self.body.append('\\bibliography{%s}\n' % self.bibtex[1])
# Make sure to generate a toc file if needed for local contents:
if 'minitoc' in self.requirements and not self.has_latex_toc:
self.body.append('\n\\faketableofcontents % for local ToCs\n')
def visit_emphasis(self, node):
self.body.append('\\emph{')
if node['classes']:
self.visit_inline(node)
self.literal_block_stack.append('\\emph{')
def depart_emphasis(self, node):
if node['classes']:
self.depart_inline(node)
self.body.append('}')
self.literal_block_stack.pop()
def visit_entry(self, node):
self.active_table.visit_entry()
# cell separation
# BUG: the following fails, with more than one multirow
# starting in the second column (or later) see
# ../../../test/functional/input/data/latex.txt
if self.active_table.get_entry_number() == 1:
# if the first row is a multirow, this actually is the second row.
# this gets hairy if rowspans follow each other.
if self.active_table.get_rowspan(0):
count = 0
while self.active_table.get_rowspan(count):
count += 1
self.body.append(' & ')
self.active_table.visit_entry() # increment cell count
else:
self.body.append(' & ')
# multirow, multicolumn
# IN WORK BUG TODO HACK continues here
# multirow in LaTeX simply will enlarge the cell over several rows
# (the following n if n is positive, the former if negative).
if 'morerows' in node and 'morecols' in node:
raise NotImplementedError('Cells that '
'span multiple rows *and* columns are not supported, sorry.')
if 'morerows' in node:
self.requirements['multirow'] = r'\usepackage{multirow}'
count = node['morerows'] + 1
self.active_table.set_rowspan(
self.active_table.get_entry_number()-1,count)
self.body.append('\\multirow{%d}{%s}{%%' %
(count,self.active_table.get_column_width()))
self.context.append('}')
elif 'morecols' in node:
# the vertical bar before column is missing if it is the first
# column. the one after always.
if self.active_table.get_entry_number() == 1:
bar1 = self.active_table.get_vertical_bar()
else:
bar1 = ''
count = node['morecols'] + 1
self.body.append('\\multicolumn{%d}{%sl%s}{' %
(count, bar1, self.active_table.get_vertical_bar()))
self.context.append('}')
else:
self.context.append('')
# header / not header
if isinstance(node.parent.parent, nodes.thead):
self.body.append('\\textbf{%')
self.context.append('}')
elif self.active_table.is_stub_column():
self.body.append('\\textbf{')
self.context.append('}')
else:
self.context.append('')
def depart_entry(self, node):
self.body.append(self.context.pop()) # header / not header
self.body.append(self.context.pop()) # multirow/column
# if following row is spanned from above.
if self.active_table.get_rowspan(self.active_table.get_entry_number()):
self.body.append(' & ')
self.active_table.visit_entry() # increment cell count
def visit_row(self, node):
self.active_table.visit_row()
def depart_row(self, node):
self.body.extend(self.active_table.depart_row())
def visit_enumerated_list(self, node):
# We create our own enumeration list environment.
# This allows to set the style and starting value
# and unlimited nesting.
enum_style = {'arabic':'arabic',
'loweralpha':'alph',
'upperalpha':'Alph',
'lowerroman':'roman',
'upperroman':'Roman' }
enum_suffix = ''
if 'suffix' in node:
enum_suffix = node['suffix']
enum_prefix = ''
if 'prefix' in node:
enum_prefix = node['prefix']
if self.compound_enumerators:
pref = ''
if self.section_prefix_for_enumerators and self.section_level:
for i in range(self.section_level):
pref += '%d.' % self._section_number[i]
pref = pref[:-1] + self.section_enumerator_separator
enum_prefix += pref
for ctype, cname in self._enumeration_counters:
enum_prefix += '\\%s{%s}.' % (ctype, cname)
enum_type = 'arabic'
if 'enumtype' in node:
enum_type = node['enumtype']
if enum_type in enum_style:
enum_type = enum_style[enum_type]
counter_name = 'listcnt%d' % len(self._enumeration_counters)
self._enumeration_counters.append((enum_type, counter_name))
# If we haven't used this counter name before, then create a
# new counter; otherwise, reset & reuse the old counter.
if len(self._enumeration_counters) > self._max_enumeration_counters:
self._max_enumeration_counters = len(self._enumeration_counters)
self.body.append('\\newcounter{%s}\n' % counter_name)
else:
self.body.append('\\setcounter{%s}{0}\n' % counter_name)
self.body.append('\\begin{list}{%s\\%s{%s}%s}\n' %
(enum_prefix,enum_type,counter_name,enum_suffix))
self.body.append('{\n')
self.body.append('\\usecounter{%s}\n' % counter_name)
# set start after usecounter, because it initializes to zero.
if 'start' in node:
self.body.append('\\addtocounter{%s}{%d}\n' %
(counter_name,node['start']-1))
## set rightmargin equal to leftmargin
self.body.append('\\setlength{\\rightmargin}{\\leftmargin}\n')
self.body.append('}\n')
def depart_enumerated_list(self, node):
self.body.append('\\end{list}\n')
self._enumeration_counters.pop()
def visit_error(self, node):
self.visit_admonition(node, 'error')
def depart_error(self, node):
self.depart_admonition()
def visit_field(self, node):
# real output is done in siblings: _argument, _body, _name
pass
def depart_field(self, node):
self.body.append('\n')
##self.body.append('%[depart_field]\n')
def visit_field_argument(self, node):
self.body.append('%[visit_field_argument]\n')
def depart_field_argument(self, node):
self.body.append('%[depart_field_argument]\n')
def visit_field_body(self, node):
# BUG by attach as text we loose references.
if self.docinfo:
self.docinfo.append('%s \\\\\n' % self.encode(node.astext()))
raise nodes.SkipNode
# BUG: what happens if not docinfo
def depart_field_body(self, node):
pass
## self.body.append( '\n' )
def visit_field_list(self, node):
self.fallbacks['fieldlist'] = PreambleCmds.fieldlist
if not self.docinfo:
self.body.append('%\n\\begin{DUfieldlist}\n')
def depart_field_list(self, node):
if not self.docinfo:
self.body.append('\\end{DUfieldlist}\n')
def visit_field_name(self, node):
# BUG this duplicates docinfo_item
if self.docinfo:
self.docinfo.append('\\textbf{%s}: &\n\t' %
self.encode(node.astext()))
raise nodes.SkipNode
else:
# Commands with optional args inside an optional arg must be put
# in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
self.body.append('\\item[{')
def depart_field_name(self, node):
if not self.docinfo:
self.body.append(':}]')
def visit_figure(self, node):
self.requirements['float_settings'] = PreambleCmds.float_settings
# ! the 'align' attribute should set "outer alignment" !
# For "inner alignment" use LaTeX default alignment (similar to HTML)
## if ('align' not in node.attributes or
## node.attributes['align'] == 'center'):
## align = '\n\\centering'
## align_end = ''
## else:
## # TODO non vertical space for other alignments.
## align = '\\begin{flush%s}' % node.attributes['align']
## align_end = '\\end{flush%s}' % node.attributes['align']
## self.body.append( '\\begin{figure}%s\n' % align )
## self.context.append( '%s\\end{figure}\n' % align_end )
self.body.append('\\begin{figure}')
self.context.append('\\end{figure}\n')
def depart_figure(self, node):
self.body.append( self.context.pop() )
def visit_footer(self, node):
self.context.append(len(self.body))
def depart_footer(self, node):
start = self.context.pop()
footer = (['\n\\begin{center}\small\n'] +
self.body[start:] + ['\n\\end{center}\n'])
self.body_suffix[:0] = footer
del self.body[start:]
def visit_footnote(self, node):
if self.use_latex_footnotes:
num,text = node.astext().split(None,1)
num = self.encode(num.strip())
self.body.append('\\footnotetext['+num+']')
self.body.append('{')
else:
# use key starting with ~ for sorting after small letters
self.requirements['~footnote_floats'] = (
PreambleCmds.footnote_floats)
self.body.append('\\begin{figure}[b]')
self.append_hypertargets(node)
if node.get('id') == node.get('name'): # explicite label
self.body += self.labels(node)
def depart_footnote(self, node):
if self.use_latex_footnotes:
self.body.append('}\n')
else:
self.body.append('\\end{figure}\n')
def visit_footnote_reference(self, node):
if self.use_latex_footnotes:
self.body.append('\\footnotemark['+self.encode(node.astext())+']')
raise nodes.SkipNode
href = ''
if 'refid' in node:
href = node['refid']
elif 'refname' in node:
href = self.document.nameids[node['refname']]
format = self.settings.footnote_references
if format == 'brackets':
suffix = '['
self.context.append(']')
elif format == 'superscript':
suffix = r'\textsuperscript{'
self.context.append('}')
else: # shouldn't happen
raise AssertionError('Illegal footnote reference format.')
self.body.append('%s\\hyperlink{%s}{' % (suffix,href))
def depart_footnote_reference(self, node):
if self.use_latex_footnotes:
return
self.body.append('}%s' % self.context.pop())
# footnote/citation label
def label_delim(self, node, bracket, superscript):
if isinstance(node.parent, nodes.footnote):
if self.use_latex_footnotes:
raise nodes.SkipNode
if self.settings.footnote_references == 'brackets':
self.body.append(bracket)
else:
self.body.append(superscript)
else:
assert isinstance(node.parent, nodes.citation)
if not self._use_latex_citations:
self.body.append(bracket)
def visit_label(self, node):
"""footnote or citation label: in brackets or as superscript"""
self.label_delim(node, '[', '\\textsuperscript{')
def depart_label(self, node):
self.label_delim(node, ']', '}')
# elements generated by the framework e.g. section numbers.
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def visit_header(self, node):
self.context.append(len(self.body))
def depart_header(self, node):
start = self.context.pop()
self.body_prefix.append('\n\\verb|begin_header|\n')
self.body_prefix.extend(self.body[start:])
self.body_prefix.append('\n\\verb|end_header|\n')
del self.body[start:]
def visit_hint(self, node):
self.visit_admonition(node, 'hint')
def depart_hint(self, node):
self.depart_admonition()
def to_latex_length(self, length_str):
"""Convert string with rst lenght to LaTeX"""
match = re.match('(\d*\.?\d*)\s*(\S*)', length_str)
if not match:
return length_str
value, unit = match.groups()[:2]
# no unit or "DTP" points (called 'bp' in TeX):
if unit in ('', 'pt'):
length_str = '%sbp' % value
# percentage: relate to current line width
elif unit == '%':
length_str = '%.3f\\linewidth' % (float(value)/100.0)
return length_str
def visit_image(self, node):
self.requirements['graphicx'] = self.graphicx_package
attrs = node.attributes
# Add image URI to dependency list, assuming that it's
# referring to a local file.
self.settings.record_dependencies.add(attrs['uri'])
# alignment defaults:
if not 'align' in attrs:
# Set default align of image in a figure to 'center'
if isinstance(node.parent, nodes.figure):
attrs['align'] = 'center'
# query 'align-*' class argument
for cls in node['classes']:
if cls.startswith('align-'):
attrs['align'] = cls.split('-')[1]
# pre- and postfix (prefix inserted in reverse order)
pre = []
post = []
include_graphics_options = []
is_inline = self.is_inline(node)
align_prepost = {
# key == (<is_inline>, <align>)
# By default latex aligns the bottom of an image.
(True, 'bottom'): ('', ''),
(True, 'middle'): (r'\raisebox{-0.5\height}{', '}'),
(True, 'top'): (r'\raisebox{-\height}{', '}'),
(False, 'center'): (r'\noindent\makebox[\textwidth][c]{', '}'),
(False, 'left'): (r'\noindent{', r'\hfill}'),
(False, 'right'): (r'\noindent{\hfill', '}'),}
if 'align' in attrs:
try:
pre.append(align_prepost[is_inline, attrs['align']][0])
post.append(align_prepost[is_inline, attrs['align']][1])
except KeyError:
pass # TODO: warn?
if 'height' in attrs:
include_graphics_options.append('height=%s' %
self.to_latex_length(attrs['height']))
if 'scale' in attrs:
include_graphics_options.append('scale=%f' %
(attrs['scale'] / 100.0))
## # Could also be done with ``scale`` option to
## # ``\includegraphics``; doing it this way for consistency.
## pre.append('\\scalebox{%f}{' % (attrs['scale'] / 100.0,))
## post.append('}')
if 'width' in attrs:
include_graphics_options.append('width=%s' %
self.to_latex_length(attrs['width']))
if not is_inline:
pre.append('\n')
post.append('\n')
pre.reverse()
self.body.extend(pre)
self.append_hypertargets(node)
options = ''
if include_graphics_options:
options = '[%s]' % (','.join(include_graphics_options))
self.body.append('\\includegraphics%s{%s}' %
(options, attrs['uri']))
self.body.extend(post)
def depart_image(self, node):
pass
def visit_important(self, node):
self.visit_admonition(node, 'important')
def depart_important(self, node):
self.depart_admonition()
def visit_interpreted(self, node):
# @@@ Incomplete, pending a proper implementation on the
# Parser/Reader end.
self.visit_literal(node)
def depart_interpreted(self, node):
self.depart_literal(node)
def visit_legend(self, node):
self.fallbacks['legend'] = PreambleCmds.legend
self.body.append('\\begin{DUlegend}')
def depart_legend(self, node):
self.body.append('\\end{DUlegend}\n')
def visit_line(self, node):
self.body.append('\item[] ')
def depart_line(self, node):
self.body.append('\n')
def visit_line_block(self, node):
self.requirements['~providelength'] = PreambleCmds.providelength
self.fallbacks['lineblock'] = PreambleCmds.lineblock
if isinstance(node.parent, nodes.line_block):
self.body.append('\\item[]\n'
'\\begin{DUlineblock}{\\DUlineblockindent}\n')
else:
self.body.append('\n\\begin{DUlineblock}{0em}\n')
def depart_line_block(self, node):
self.body.append('\\end{DUlineblock}\n')
def visit_list_item(self, node):
self.body.append('\n\\item ')
def depart_list_item(self, node):
pass
def visit_literal(self, node):
self.literal = 1
self.body.append('\\texttt{')
if node['classes']:
self.visit_inline(node)
def depart_literal(self, node):
if node['classes']:
self.depart_inline(node)
self.body.append('}')
self.literal = 0
# Literal blocks are used for '::'-prefixed literal-indented
# blocks of text, where the inline markup is not recognized,
# but are also the product of the "parsed-literal" directive,
# where the markup is respected.
#
# In both cases, we want to use a typewriter/monospaced typeface.
# For "real" literal-blocks, we can use \verbatim, while for all
# the others we must use \mbox or \alltt.
#
# We can distinguish between the two kinds by the number of
# siblings that compose this node: if it is composed by a
# single element, it's either
# * a real one,
# * a parsed-literal that does not contain any markup, or
# * a parsed-literal containing just one markup construct.
def is_plaintext(self, node):
"""Check whether a node can be typeset verbatim"""
return (len(node) == 1) and isinstance(node[0], nodes.Text)
def visit_literal_block(self, node):
"""Render a literal block."""
# environments and packages to typeset literal blocks
packages = {'listing': r'\usepackage{moreverb}',
'lstlisting': r'\usepackage{listings}',
'Verbatim': r'\usepackage{fancyvrb}',
# 'verbatim': '',
'verbatimtab': r'\usepackage{moreverb}'}
if not self.active_table.is_open():
# no quote inside tables, to avoid vertical space between
# table border and literal block.
# BUG: fails if normal text preceeds the literal block.
self.body.append('%\n\\begin{quote}')
self.context.append('\n\\end{quote}\n')
else:
self.body.append('\n')
self.context.append('\n')
if self.literal_block_env != '' and self.is_plaintext(node):
self.requirements['literal_block'] = packages.get(
self.literal_block_env, '')
self.verbatim = 1
self.body.append('\\begin{%s}%s\n' % (self.literal_block_env,
self.literal_block_options))
else:
self.literal_block = 1
self.insert_non_breaking_blanks = 1
self.body.append('{\\ttfamily \\raggedright \\noindent\n')
def depart_literal_block(self, node):
if self.verbatim:
self.body.append('\n\\end{%s}\n' % self.literal_block_env)
self.verbatim = 0
else:
self.body.append('\n}')
self.insert_non_breaking_blanks = 0
self.literal_block = 0
self.body.append(self.context.pop())
## def visit_meta(self, node):
## self.body.append('[visit_meta]\n')
# TODO: set keywords for pdf?
# But:
# The reStructuredText "meta" directive creates a "pending" node,
# which contains knowledge that the embedded "meta" node can only
# be handled by HTML-compatible writers. The "pending" node is
# resolved by the docutils.transforms.components.Filter transform,
# which checks that the calling writer supports HTML; if it doesn't,
# the "pending" node (and enclosed "meta" node) is removed from the
# document.
# --- docutils/docs/peps/pep-0258.html#transformer
## def depart_meta(self, node):
## self.body.append('[depart_meta]\n')
def visit_note(self, node):
self.visit_admonition(node, 'note')
def depart_note(self, node):
self.depart_admonition()
def visit_option(self, node):
if self.context[-1]:
# this is not the first option
self.body.append(', ')
def depart_option(self, node):
# flag tha the first option is done.
self.context[-1] += 1
def visit_option_argument(self, node):
"""Append the delimiter betweeen an option and its argument to body."""
self.body.append(node.get('delimiter', ' '))
def depart_option_argument(self, node):
pass
def visit_option_group(self, node):
self.body.append('\n\\item[')
# flag for first option
self.context.append(0)
def depart_option_group(self, node):
self.context.pop() # the flag
self.body.append('] ')
def visit_option_list(self, node):
self.requirements['~providelength'] = PreambleCmds.providelength
self.fallbacks['optionlist'] = PreambleCmds.optionlist
self.body.append('%\n\\begin{DUoptionlist}\n')
def depart_option_list(self, node):
self.body.append('\n\\end{DUoptionlist}\n')
def visit_option_list_item(self, node):
pass
def depart_option_list_item(self, node):
pass
def visit_option_string(self, node):
##self.body.append(self.starttag(node, 'span', '', CLASS='option'))
pass
def depart_option_string(self, node):
##self.body.append('</span>')
pass
def visit_organization(self, node):
self.visit_docinfo_item(node, 'organization')
def depart_organization(self, node):
self.depart_docinfo_item(node)
def visit_paragraph(self, node):
# no newline if the paragraph is first in a list item
if ((isinstance(node.parent, nodes.list_item) or
isinstance(node.parent, nodes.description)) and
node is node.parent[0]):
return
index = node.parent.index(node)
if (isinstance(node.parent, nodes.compound) and
index > 0 and
not isinstance(node.parent[index - 1], nodes.paragraph) and
not isinstance(node.parent[index - 1], nodes.compound)):
return
self.body.append('\n')
if node.get('ids'):
self.body += self.labels(node) + ['\n']
def depart_paragraph(self, node):
self.body.append('\n')
def visit_problematic(self, node):
self.requirements['color'] = r'\usepackage{color}'
self.body.append('%\n')
self.append_hypertargets(node)
self.body.append(r'\hyperlink{%s}{\textbf{\color{red}' % node['refid'])
def depart_problematic(self, node):
self.body.append('}}')
def visit_raw(self, node):
if 'latex' in node.get('format', '').split():
self.body.append(node.astext())
raise nodes.SkipNode
def visit_reference(self, node):
# BUG: hash_char '#' is troublesome in LaTeX.
# mbox and other environments do not like the '#'.
hash_char = '\\#'
if 'refuri' in node:
href = node['refuri'].replace('#', hash_char)
self.body.append('\\href{%s}{' % href.replace('%', '\\%'))
return
if 'refid' in node:
href = node['refid']
elif 'refname' in node:
href = self.document.nameids[node['refname']]
else:
raise AssertionError('Unknown reference.')
if not self.is_inline(node):
self.body.append('\n')
self.body.append('\\hyperref[%s]{' % href)
if self._reference_label and 'refuri' not in node:
self.body.append('\\%s{%s}}' % (self._reference_label,
href.replace(hash_char, '')))
raise nodes.SkipNode
def depart_reference(self, node):
self.body.append('}')
if not self.is_inline(node):
self.body.append('\n')
def visit_revision(self, node):
self.visit_docinfo_item(node, 'revision')
def depart_revision(self, node):
self.depart_docinfo_item(node)
def visit_section(self, node):
self.section_level += 1
# Initialize counter for potential subsections:
self._section_number.append(0)
# Counter for this section's level (initialized by parent section):
self._section_number[self.section_level - 1] += 1
def depart_section(self, node):
# Remove counter for potential subsections:
self._section_number.pop()
self.section_level -= 1
def visit_sidebar(self, node):
# fallback definition requires the color package for background colour
self.requirements['color'] = r'\usepackage{color}'
self.fallbacks['sidebar'] = PreambleCmds.sidebar
self.body.append('\n\\DUsidebar{\n')
def depart_sidebar(self, node):
self.body.append('}\n')
attribution_formats = {'dash': ('---', ''),
'parentheses': ('(', ')'),
'parens': ('(', ')'),
'none': ('', '')}
def visit_attribution(self, node):
prefix, suffix = self.attribution_formats[self.settings.attribution]
self.body.append('\n\\begin{flushright}\n')
self.body.append(prefix)
self.context.append(suffix)
def depart_attribution(self, node):
self.body.append(self.context.pop() + '\n')
self.body.append('\\end{flushright}\n')
def visit_status(self, node):
self.visit_docinfo_item(node, 'status')
def depart_status(self, node):
self.depart_docinfo_item(node)
def visit_strong(self, node):
self.body.append('\\textbf{')
self.literal_block_stack.append('\\textbf{')
if node['classes']:
self.visit_inline(node)
def depart_strong(self, node):
if node['classes']:
self.depart_inline(node)
self.body.append('}')
self.literal_block_stack.pop()
def visit_substitution_definition(self, node):
raise nodes.SkipNode
def visit_substitution_reference(self, node):
self.unimplemented_visit(node)
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.sidebar):
self.fallbacks['sidebarsubtitle'] = PreambleCmds.sidebarsubtitle
self.body.append('\\DUsidebarsubtitle{')
self.context.append('}\n')
elif isinstance(node.parent, nodes.document):
self.title.append(r'\\ % subtitle')
self.title.append(r'\large{%s}' % self.encode(node.astext()))
self.title += self.labels(node, set_anchor=False)
raise nodes.SkipNode
elif isinstance(node.parent, nodes.section):
# Section subtitle:
self.body.append('\\textbf{')
self.context.append('}\\vspace{0.2cm}\n\n\\noindent ')
def depart_subtitle(self, node):
self.body.append(self.context.pop())
def visit_system_message(self, node):
self.requirements['color'] = r'\usepackage{color}'
self.visit_admonition(node)
self.body.append('\\DUtopictitle{System Message:}\n')
self.append_hypertargets(node)
try:
line = ', line~%s' % node['line']
except KeyError:
line = ''
self.body.append('\n%s/%s in %s%s\n' % (node['type'],
node['level'],
self.encode(node['source']),
line))
## self.body.append(r'\color{red}\\')
if len(node['backrefs']) == 1:
self.body.append('\n\\hyperlink{%s}{' % node['backrefs'][0])
def depart_system_message(self, node):
if len(node['backrefs']) == 1:
self.body.append('}')
else:
self.body.append('backrefs: ')
self.body += ['\\hyperlink{%s}{%d}' % (href, i+1)
for (i,href) in enumerate(node['backrefs'])]
self.depart_admonition()
def visit_table(self, node):
self.requirements['table'] = PreambleCmds.table
if self.active_table.is_open():
self.table_stack.append(self.active_table)
# nesting longtable does not work (e.g. 2007-04-18)
self.active_table = Table(self,'tabular',self.settings.table_style)
self.active_table.open()
for cls in node['classes']:
self.active_table.set_table_style(cls)
if self.active_table._table_style == 'booktabs':
self.requirements['booktabs'] = r'\usepackage{booktabs}'
self.body.append('\n' + self.active_table.get_opening())
def depart_table(self, node):
self.body.append(self.active_table.get_closing() + '\n')
self.active_table.close()
if len(self.table_stack)>0:
self.active_table = self.table_stack.pop()
else:
self.active_table.set_table_style(self.settings.table_style)
def append_hypertargets(self, node):
"""Append hypertargets for all ids of `node`"""
# Some viewers place the target's baseline at the top of the window
# so we raise the hypertarget(s) 1 line:
self.body.append('%\n'.join(['\\raisebox{1em}{\\hypertarget{%s}{}}' %
id for id in node['ids']]))
def labels(self, node, set_anchor=True):
"""Return list of label definitions for all ids of `node`
If `set_anchor` is True, an anchor is set with \phantomsection.
"""
labels = ['\\label{%s}' % id for id in node.get('ids', [])]
if set_anchor and labels:
labels.insert(0, '\\phantomsection')
return labels
def visit_target(self, node):
# Skip indirect targets:
if ('refuri' in node # external hyperlink
or 'refid' in node # resolved internal link
or 'refname' in node): # unresolved internal link
## self.body.append('%% %s\n' % node) # for debugging
return
self.body.append('%\n')
self.body += self.labels(node)
def depart_target(self, node):
pass
def visit_tbody(self, node):
# BUG write preamble if not yet done (colspecs not [])
# for tables without heads.
if not self.active_table.get('preamble written'):
self.visit_thead(None)
self.depart_thead(None)
def depart_tbody(self, node):
pass
def visit_term(self, node):
"""definition list term"""
# Commands with optional args inside an optional arg must be put
# in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
self.body.append('\\item[{')
def depart_term(self, node):
# \leavevmode results in a line break if the
# term is followed by an item list.
self.body.append('}] \leavevmode ')
def visit_tgroup(self, node):
#self.body.append(self.starttag(node, 'colgroup'))
#self.context.append('</colgroup>\n')
pass
def depart_tgroup(self, node):
pass
_thead_depth = 0
def thead_depth (self):
return self._thead_depth
def visit_thead(self, node):
self._thead_depth += 1
if 1 == self.thead_depth():
self.body.append('{%s}\n' % self.active_table.get_colspecs())
self.active_table.set('preamble written',1)
self.body.append(self.active_table.get_caption())
self.body.extend(self.active_table.visit_thead())
def depart_thead(self, node):
if node is not None:
self.body.extend(self.active_table.depart_thead())
if self.active_table.need_recurse():
node.walkabout(self)
self._thead_depth -= 1
def visit_tip(self, node):
self.visit_admonition(node, 'tip')
def depart_tip(self, node):
self.depart_admonition()
def bookmark(self, node):
"""Return label and pdfbookmark string for titles."""
result = ['']
if self.settings.sectnum_xform: # "starred" section cmd
# add to the toc and pdfbookmarks
section_name = self.d_class.section(max(self.section_level, 1))
section_title = self.encode(node.astext())
result.append(r'\phantomsection')
result.append(r'\addcontentsline{toc}{%s}{%s}' %
(section_name, section_title))
result += self.labels(node.parent, set_anchor=False)
return '%\n '.join(result) + '%\n'
def visit_title(self, node):
"""Append section and other titles."""
# Topic titles
if isinstance(node.parent, nodes.topic):
# Table of contents
if 'contents' in self.topic_classes:
if self.settings.use_titlepage_env:
self.body.append('\\end{titlepage}\n')
if self.use_latex_toc:
tocdepth = node.parent.get('depth', 0)
if tocdepth:
self.body.append('\n\\setcounter{tocdepth}{%d}' %
tocdepth)
# use the Docutils-provided title for the ToC
self.body.append('\n\\renewcommand{\\contentsname}{')
self.context.append('}\n\\tableofcontents\n\n')
self.has_latex_toc = True
else:
# In LaTeX, alignment of sections is determined by the
# document class. Use \hfill as a workaround.
self.body.append('\\subsubsection*{~\\hfill ')
self.context.append('\\hfill ~%s}\n' % self.bookmark(node))
else: # other topic titles
# TODO: use DUtopictitle:
# self.body.append('\n\\DUtopictitle{')
# self.context.append('}\n')
self.body.append('\n\\subsubsection*{~\\hfill ')
self.context.append('\\hfill ~}\n')
# Admonition titles (render as topic title)
elif isinstance(node.parent, nodes.admonition):
self.fallbacks['topictitle'] = PreambleCmds.topictitle
self.body.append('\\DUtopictitle{')
self.context.append('}\n')
elif isinstance(node.parent, nodes.sidebar):
self.fallbacks['sidebartitle'] = PreambleCmds.sidebartitle
self.body.append('\\DUsidebartitle{')
self.context.append('}\n')
# Table
elif isinstance(node.parent, nodes.table):
# caption must be written after column spec
self.active_table.caption = self.encode(node.astext())
raise nodes.SkipNode
# Document title
elif self.section_level == 0:
self.title.insert(0, self.encode(node.astext()))
if not self.pdfinfo == None:
self.pdfinfo.append(' pdftitle={%s},' %
self.encode(node.astext()) )
raise nodes.SkipNode
# Section title
else:
self.body.append('\n\n')
self.body.append('%' + '_' * 75)
self.body.append('\n\n')
section_name = self.d_class.section(self.section_level)
# number sections?
section_star = '' # LaTeX numbered sections
if (# numbering by Docutils or unsupported level:
self.settings.sectnum_xform or
(self.section_level > len(self.d_class.sections))):
section_star = '*'
self.body.append(r'\%s%s{' % (section_name, section_star))
# System messages heading in red:
if ('system-messages' in node.parent['classes']):
self.requirements['color'] = r'\usepackage{color}'
self.body.append('\color{red}')
self.context.append(self.bookmark(node) + '}\n')
# MAYBE postfix paragraph and subparagraph with \leavemode to
# ensure floats stay in the section and text starts on a new line.
def depart_title(self, node):
self.body.append(self.context.pop())
# too many newlines before paragraphs:
## self.body.append('\n')
def minitoc(self, node):
"""Generate a local table of contents with LaTeX package minitoc"""
# title
if isinstance(node.next_node(), nodes.title):
toctitle = self.encode(node.pop(0).astext())
else: # no title
toctitle = ''
# name-prefix for current section level
section_name = self.d_class.section(self.section_level)
if section_name == 'part':
minitoc_name = 'part'
elif section_name == 'chapter':
minitoc_name = 'mini'
elif (section_name == 'section' and
'chapter' not in self.d_class.sections):
minitoc_name = 'sect'
else: # minitoc only supports local toc in part- or top-level
warn = self.document.reporter.warning
warn('Skipping local ToC at %s level.\n' % section_name +
' Feature not supported with option "use-latex-toc"')
return
# Requirements/Setup
self.requirements['minitoc'] = PreambleCmds.minitoc
self.requirements['minitoc-%s' %
minitoc_name] = r'\do%stoc' % minitoc_name
# depth: (Docutils defaults to unlimited depth)
maxdepth = len(self.d_class.sections)
self.requirements['minitoc-%s-depth' % minitoc_name] = (
r'\mtcsetdepth{%stoc}{%d}' % (minitoc_name, maxdepth))
# Process 'depth' argument (!Docutils stores a relative depth while
# minitoc expects an absolute depth!):
offset = {'sect': 1, 'mini': 0, 'part': 0}
if 'chapter' in self.d_class.sections:
offset['part'] = -1
depth = node.get('depth', 0)
if depth:
self.body.append('\\setcounter{%stocdepth}{%d}' %
(minitoc_name, depth + offset[minitoc_name]))
# title:
self.body.append('\\mtcsettitle{%stoc}{%s}\n' %
(minitoc_name, toctitle))
# the toc-generating command:
self.body.append('\\%stoc\n' % minitoc_name)
def visit_topic(self, node):
self.topic_classes = node['classes']
if ('contents' in node['classes'] and 'local' in node['classes']):
if self.use_latex_toc:
self.minitoc(node)
elif not isinstance(node.next_node(), nodes.title):
self.body += self.labels(node)
elif ('abstract' in self.topic_classes and
self.settings.use_latex_abstract):
self.body.append('\\begin{abstract}')
if isinstance(node.next_node(), nodes.title):
node.pop(0) # dump title
def depart_topic(self, node):
if ('abstract' in self.topic_classes and
self.settings.use_latex_abstract):
self.body.append('\\end{abstract}\n')
self.topic_classes = []
def visit_inline(self, node): # <span>, i.e. custom roles
# insert fallback definition
self.fallbacks['inline'] = PreambleCmds.inline
self.body += [r'\DUrole{%s}{' % cls for cls in node['classes']]
self.context.append('}' * (len(node['classes'])))
def depart_inline(self, node):
self.body.append(self.context.pop())
def visit_rubric(self, node):
self.fallbacks['rubric'] = PreambleCmds.rubric
self.body.append('\n\\DUrubric{')
self.context.append('}\n')
def depart_rubric(self, node):
self.body.append(self.context.pop())
def visit_transition(self, node):
self.fallbacks['transition'] = PreambleCmds.transition
self.body.append('\n\n')
self.body.append('%' + '_' * 75 + '\n')
self.body.append(r'\DUtransition')
self.body.append('\n\n')
def depart_transition(self, node):
pass
def visit_version(self, node):
self.visit_docinfo_item(node, 'version')
def depart_version(self, node):
self.depart_docinfo_item(node)
def visit_warning(self, node):
self.visit_admonition(node, 'warning')
def depart_warning(self, node):
self.depart_admonition()
def unimplemented_visit(self, node):
raise NotImplementedError('visiting unimplemented node type: %s' %
node.__class__.__name__)
# def unknown_visit(self, node):
# def default_visit(self, node):
# vim: set ts=4 et ai :
| {
"repo_name": "spreeker/democracygame",
"path": "external_apps/docutils-snapshot/docutils/writers/latex2e/__init__.py",
"copies": "2",
"size": "99912",
"license": "bsd-3-clause",
"hash": 5680064542448231000,
"line_mean": 37.6058732612,
"line_max": 82,
"alpha_frac": 0.5619044759,
"autogenerated": false,
"ratio": 3.9228866465114454,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002389179437157528,
"num_lines": 2588
} |
"""
This package contains Docutils Writer modules.
"""
__docformat__ = 'reStructuredText'
import docutils
from docutils import languages, Component
from docutils.transforms import universal
class Writer(Component):
"""
Abstract base class for docutils Writers.
Each writer module or package must export a subclass also called 'Writer'.
Each writer must support all standard node types listed in
`docutils.nodes.node_class_names`.
The `write()` method is the main entry point.
"""
component_type = 'writer'
config_section = 'writers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Messages,
universal.FilterMessages,
universal.StripClassesAndElements,]
document = None
"""The document to write (Docutils doctree); set by `write`."""
output = None
"""Final translated form of `document` (Unicode string for text, binary
string for other forms); set by `translate`."""
language = None
"""Language module for the document; set by `write`."""
destination = None
"""`docutils.io` Output object; where to write the document.
Set by `write`."""
def __init__(self):
# Used by HTML and LaTex writer for output fragments:
self.parts = {}
"""Mapping of document part names to fragments of `self.output`.
Values are Unicode strings; encoding is up to the client. The 'whole'
key should contain the entire document output.
"""
def write(self, document, destination):
"""
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.
"""
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
def translate(self):
"""
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.
"""
raise NotImplementedError('subclass must override this method')
def assemble_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses."""
self.parts['whole'] = self.output
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
class UnfilteredWriter(Writer):
"""
A writer that passes the document tree on unchanged (e.g. a
serializer.)
Documents written by UnfilteredWriters are typically reused at a
later date using a subclass of `readers.ReReader`.
"""
def get_transforms(self):
# Do not add any transforms. When the document is reused
# later, the then-used writer will add the appropriate
# transforms.
return Component.get_transforms(self)
_writer_aliases = {
'html': 'html4css1',
'latex': 'latex2e',
'pprint': 'pseudoxml',
'pformat': 'pseudoxml',
'pdf': 'rlpdf',
'xml': 'docutils_xml',
's5': 's5_html'}
def get_writer_class(writer_name):
"""Return the Writer class from the `writer_name` module."""
writer_name = writer_name.lower()
if writer_name in _writer_aliases:
writer_name = _writer_aliases[writer_name]
module = __import__(writer_name, globals(), locals())
return module.Writer
| {
"repo_name": "MER-GROUP/intellij-community",
"path": "python/helpers/py2only/docutils/writers/__init__.py",
"copies": "5",
"size": "4236",
"license": "apache-2.0",
"hash": 7121945599234420000,
"line_mean": 31.3358778626,
"line_max": 78,
"alpha_frac": 0.6501416431,
"autogenerated": false,
"ratio": 4.344615384615385,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7494757027715384,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils Writer modules.
"""
__docformat__ = 'reStructuredText'
import os.path
import docutils
from docutils import languages, Component
from docutils.transforms import universal
class Writer(Component):
"""
Abstract base class for docutils Writers.
Each writer module or package must export a subclass also called 'Writer'.
Each writer must support all standard node types listed in
`docutils.nodes.node_class_names`.
The `write()` method is the main entry point.
"""
component_type = 'writer'
config_section = 'writers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Messages,
universal.FilterMessages,
universal.StripClassesAndElements,]
document = None
"""The document to write (Docutils doctree); set by `write`."""
output = None
"""Final translated form of `document` (Unicode string for text, binary
string for other forms); set by `translate`."""
language = None
"""Language module for the document; set by `write`."""
destination = None
"""`docutils.io` Output object; where to write the document.
Set by `write`."""
def __init__(self):
# Used by HTML and LaTex writer for output fragments:
self.parts = {}
"""Mapping of document part names to fragments of `self.output`.
Values are Unicode strings; encoding is up to the client. The 'whole'
key should contain the entire document output.
"""
def write(self, document, destination):
"""
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.
"""
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
def translate(self):
"""
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.
"""
raise NotImplementedError('subclass must override this method')
def assemble_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses."""
self.parts['whole'] = self.output
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
class UnfilteredWriter(Writer):
"""
A writer that passes the document tree on unchanged (e.g. a
serializer.)
Documents written by UnfilteredWriters are typically reused at a
later date using a subclass of `readers.ReReader`.
"""
def get_transforms(self):
# Do not add any transforms. When the document is reused
# later, the then-used writer will add the appropriate
# transforms.
return Component.get_transforms(self)
_writer_aliases = {
'html': 'html4css1',
'latex': 'latex2e',
'pprint': 'pseudoxml',
'pformat': 'pseudoxml',
'pdf': 'rlpdf',
'xml': 'docutils_xml',
's5': 's5_html'}
def get_writer_class(writer_name):
"""Return the Writer class from the `writer_name` module."""
writer_name = writer_name.lower()
if writer_name in _writer_aliases:
writer_name = _writer_aliases[writer_name]
module = __import__(writer_name, globals(), locals())
return module.Writer
| {
"repo_name": "supersven/intellij-community",
"path": "python/helpers/docutils/writers/__init__.py",
"copies": "49",
"size": "4252",
"license": "apache-2.0",
"hash": 1083218702507392300,
"line_mean": 30.969924812,
"line_max": 78,
"alpha_frac": 0.6505174036,
"autogenerated": false,
"ratio": 4.338775510204082,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils Writer modules.
"""
__docformat__ = 'reStructuredText'
import os.path
import docutils
from docutils import languages, Component
from docutils.transforms import universal
class Writer(Component):
"""
Abstract base class for docutils Writers.
Each writer module or package must export a subclass also called 'Writer'.
Each writer must support all standard node types listed in
`docutils.nodes.node_class_names`.
The `write()` method is the main entry point.
"""
component_type = 'writer'
config_section = 'writers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Messages,
universal.FilterMessages,
universal.StripClassesAndElements,]
document = None
"""The document to write (Docutils doctree); set by `write`."""
output = None
"""Final translated form of `document` (Unicode string for text, binary
string for other forms); set by `translate`."""
language = None
"""Language module for the document; set by `write`."""
destination = None
"""`docutils.io` Output object; where to write the document.
Set by `write`."""
def __init__(self):
# Used by HTML and LaTex writer for output fragments:
self.parts = {}
"""Mapping of document part names to fragments of `self.output`.
Values are Unicode strings; encoding is up to the client. The 'whole'
key should contain the entire document output.
"""
def write(self, document, destination):
"""
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.
"""
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
def translate(self):
"""
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.
"""
raise NotImplementedError('subclass must override this method')
def assemble_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses."""
self.parts['whole'] = self.output
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
class UnfilteredWriter(Writer):
"""
A writer that passes the document tree on unchanged (e.g. a
serializer.)
Documents written by UnfilteredWriters are typically reused at a
later date using a subclass of `readers.ReReader`.
"""
def get_transforms(self):
# Do not add any transforms. When the document is reused
# later, the then-used writer will add the appropriate
# transforms.
return Component.get_transforms(self)
_writer_aliases = {
'html': 'html4css1',
'latex': 'latex2e',
'pprint': 'pseudoxml',
'pformat': 'pseudoxml',
'pdf': 'rlpdf',
'xml': 'docutils_xml',
's5': 's5_html'}
def get_writer_class(writer_name):
"""Return the Writer class from the `writer_name` module."""
writer_name = writer_name.lower()
if writer_name in _writer_aliases:
writer_name = _writer_aliases[writer_name]
module = __import__(writer_name, globals(), locals())
return module.Writer
| {
"repo_name": "rimbalinux/MSISDNArea",
"path": "docutils/writers/__init__.py",
"copies": "2",
"size": "4385",
"license": "bsd-3-clause",
"hash": 3895730597623927000,
"line_mean": 30.969924812,
"line_max": 78,
"alpha_frac": 0.6307867731,
"autogenerated": false,
"ratio": 4.442755825734549,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6073542598834549,
"avg_score": null,
"num_lines": null
} |
"""
This is ``docutils.parsers.rst`` package. It exports a single class, `Parser`,
the reStructuredText parser.
Usage
=====
1. Create a parser::
parser = docutils.parsers.rst.Parser()
Several optional arguments may be passed to modify the parser's behavior.
Please see `Customizing the Parser`_ below for details.
2. Gather input (a multi-line string), by reading a file or the standard
input::
input = sys.stdin.read()
3. Create a new empty `docutils.nodes.document` tree::
document = docutils.utils.new_document(source, settings)
See `docutils.utils.new_document()` for parameter details.
4. Run the parser, populating the document tree::
parser.parse(input, document)
Parser Overview
===============
The reStructuredText parser is implemented as a state machine, examining its
input one line at a time. To understand how the parser works, please first
become familiar with the `docutils.statemachine` module, then see the
`states` module.
Customizing the Parser
----------------------
Anything that isn't already customizable is that way simply because that type
of customizability hasn't been implemented yet. Patches welcome!
When instantiating an object of the `Parser` class, two parameters may be
passed: ``rfc2822`` and ``inliner``. Pass ``rfc2822=1`` to enable an initial
RFC-2822 style header block, parsed as a "field_list" element (with "class"
attribute set to "rfc2822"). Currently this is the only body-level element
which is customizable without subclassing. (Tip: subclass `Parser` and change
its "state_classes" and "initial_state" attributes to refer to new classes.
Contact the author if you need more details.)
The ``inliner`` parameter takes an instance of `states.Inliner` or a subclass.
It handles inline markup recognition. A common extension is the addition of
further implicit hyperlinks, like "RFC 2822". This can be done by subclassing
`states.Inliner`, adding a new method for the implicit markup, and adding a
``(pattern, method)`` pair to the "implicit_dispatch" attribute of the
subclass. See `states.Inliner.implicit_inline()` for details. Explicit
inline markup can be customized in a `states.Inliner` subclass via the
``patterns.initial`` and ``dispatch`` attributes (and new methods as
appropriate).
"""
__docformat__ = 'reStructuredText'
import docutils.parsers
import docutils.statemachine
from docutils.parsers.rst import states
from docutils import frontend, nodes
class Parser(docutils.parsers.Parser):
"""The reStructuredText parser."""
supported = ('restructuredtext', 'rst', 'rest', 'restx', 'rtxt', 'rstx')
"""Aliases this parser supports."""
settings_spec = (
'reStructuredText Parser Options',
None,
(('Recognize and link to standalone PEP references (like "PEP 258").',
['--pep-references'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Base URL for PEP references '
'(default "http://www.python.org/dev/peps/").',
['--pep-base-url'],
{'metavar': '<URL>', 'default': 'http://www.python.org/dev/peps/',
'validator': frontend.validate_url_trailing_slash}),
('Template for PEP file part of URL. (default "pep-%04d")',
['--pep-file-url-template'],
{'metavar': '<URL>', 'default': 'pep-%04d'}),
('Recognize and link to standalone RFC references (like "RFC 822").',
['--rfc-references'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Base URL for RFC references (default "http://www.faqs.org/rfcs/").',
['--rfc-base-url'],
{'metavar': '<URL>', 'default': 'http://www.faqs.org/rfcs/',
'validator': frontend.validate_url_trailing_slash}),
('Set number of spaces for tab expansion (default 8).',
['--tab-width'],
{'metavar': '<width>', 'type': 'int', 'default': 8,
'validator': frontend.validate_nonnegative_int}),
('Remove spaces before footnote references.',
['--trim-footnote-reference-space'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Leave spaces before footnote references.',
['--leave-footnote-reference-space'],
{'action': 'store_false', 'dest': 'trim_footnote_reference_space'}),
('Disable directives that insert the contents of external file '
'("include" & "raw"); replaced with a "warning" system message.',
['--no-file-insertion'],
{'action': 'store_false', 'default': 1,
'dest': 'file_insertion_enabled',
'validator': frontend.validate_boolean}),
('Enable directives that insert the contents of external file '
'("include" & "raw"). Enabled by default.',
['--file-insertion-enabled'],
{'action': 'store_true'}),
('Disable the "raw" directives; replaced with a "warning" '
'system message.',
['--no-raw'],
{'action': 'store_false', 'default': 1, 'dest': 'raw_enabled',
'validator': frontend.validate_boolean}),
('Enable the "raw" directive. Enabled by default.',
['--raw-enabled'],
{'action': 'store_true'}),))
config_section = 'restructuredtext parser'
config_section_dependencies = ('parsers',)
def __init__(self, rfc2822=None, inliner=None):
if rfc2822:
self.initial_state = 'RFC2822Body'
else:
self.initial_state = 'Body'
self.state_classes = states.state_classes
self.inliner = inliner
def parse(self, inputstring, document):
"""Parse `inputstring` and populate `document`, a document tree."""
self.setup_parse(inputstring, document)
self.statemachine = states.RSTStateMachine(
state_classes=self.state_classes,
initial_state=self.initial_state,
debug=document.reporter.debug_flag)
inputlines = docutils.statemachine.string2lines(
inputstring, tab_width=document.settings.tab_width,
convert_whitespace=1)
self.statemachine.run(inputlines, document, inliner=self.inliner)
self.finish_parse()
class DirectiveError(Exception):
"""
Store a message and a system message level.
To be thrown from inside directive code.
Do not instantiate directly -- use `Directive.directive_error()`
instead!
"""
def __init__(self, level, message, source, line):
"""
Initialize with message `message`. `level` is a system message level.
"""
Exception.__init__(self)
self.level = level
self.msg = message
self.source = source
self.line = line
class Directive(object):
"""
Base class for reStructuredText directives.
The following attributes may be set by subclasses. They are
interpreted by the directive parser (which runs the directive
class):
- `required_arguments`: The number of required arguments (default:
0).
- `optional_arguments`: The number of optional arguments (default:
0).
- `final_argument_whitespace`: A boolean, indicating if the final
argument may contain whitespace (default: False).
- `option_spec`: A dictionary, mapping known option names to
conversion functions such as `int` or `float` (default: {}, no
options). Several conversion functions are defined in the
directives/__init__.py module.
Option conversion functions take a single parameter, the option
argument (a string or ``None``), validate it and/or convert it
to the appropriate form. Conversion functions may raise
`ValueError` and `TypeError` exceptions.
- `has_content`: A boolean; True if content is allowed. Client
code must handle the case where content is required but not
supplied (an empty content list will be supplied).
Arguments are normally single whitespace-separated words. The
final argument may contain whitespace and/or newlines if
`final_argument_whitespace` is True.
If the form of the arguments is more complex, specify only one
argument (either required or optional) and set
`final_argument_whitespace` to True; the client code must do any
context-sensitive parsing.
When a directive implementation is being run, the directive class
is instantiated, and the `run()` method is executed. During
instantiation, the following instance variables are set:
- ``name`` is the directive type or name (string).
- ``arguments`` is the list of positional arguments (strings).
- ``options`` is a dictionary mapping option names (strings) to
values (type depends on option conversion functions; see
`option_spec` above).
- ``content`` is a list of strings, the directive content line by line.
- ``lineno`` is the line number of the first line of the directive.
- ``content_offset`` is the line offset of the first line of the content from
the beginning of the current input. Used when initiating a nested parse.
- ``block_text`` is a string containing the entire directive.
- ``state`` is the state which called the directive function.
- ``state_machine`` is the state machine which controls the state which called
the directive function.
Directive functions return a list of nodes which will be inserted
into the document tree at the point where the directive was
encountered. This can be an empty list if there is nothing to
insert.
For ordinary directives, the list must contain body elements or
structural elements. Some directives are intended specifically
for substitution definitions, and must return a list of `Text`
nodes and/or inline elements (suitable for inline insertion, in
place of the substitution reference). Such directives must verify
substitution definition context, typically using code like this::
if not isinstance(state, states.SubstitutionDef):
error = state_machine.reporter.error(
'Invalid context: the "%s" directive can only be used '
'within a substitution definition.' % (name),
nodes.literal_block(block_text, block_text), line=lineno)
return [error]
"""
# There is a "Creating reStructuredText Directives" how-to at
# <http://docutils.sf.net/docs/howto/rst-directives.html>. If you
# update this docstring, please update the how-to as well.
required_arguments = 0
"""Number of required directive arguments."""
optional_arguments = 0
"""Number of optional arguments after the required arguments."""
final_argument_whitespace = False
"""May the final argument contain whitespace?"""
option_spec = None
"""Mapping of option names to validator functions."""
has_content = False
"""May the directive have content?"""
def __init__(self, name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
self.name = name
self.arguments = arguments
self.options = options
self.content = content
self.lineno = lineno
self.content_offset = content_offset
self.block_text = block_text
self.state = state
self.state_machine = state_machine
def run(self):
raise NotImplementedError('Must override run() is subclass.')
# Directive errors:
def directive_error(self, level, message):
"""
Return a DirectiveError suitable for being thrown as an exception.
Call "raise self.directive_error(level, message)" from within
a directive implementation to return one single system message
at level `level`, which automatically gets the directive block
and the line number added.
You'd often use self.error(message) instead, which will
generate an ERROR-level directive error.
"""
# source = self.state_machine.get_source(self.lineno - 1)
try:
(source, line) = self.state_machine.input_lines.info(self.lineno)
except IndexError:
source = self.state_machine.get_source(self.lineno - 1)
line = self.lineno
return DirectiveError(level, message, source, line)
def debug(self, message):
return self.directive_error(0, message)
def info(self, message):
return self.directive_error(1, message)
def warning(self, message):
return self.directive_error(2, message)
def error(self, message):
return self.directive_error(3, message)
def severe(self, message):
return self.directive_error(4, message)
# Convenience methods:
def assert_has_content(self):
"""
Throw an ERROR-level DirectiveError if the directive doesn't
have contents.
"""
if not self.content:
raise self.error('Content block expected for the "%s" directive; '
'none found.' % self.name)
def convert_directive_function(directive_fn):
"""
Define & return a directive class generated from `directive_fn`.
`directive_fn` uses the old-style, functional interface.
"""
class FunctionalDirective(Directive):
option_spec = getattr(directive_fn, 'options', None)
has_content = getattr(directive_fn, 'content', False)
_argument_spec = getattr(directive_fn, 'arguments', (0, 0, False))
required_arguments, optional_arguments, final_argument_whitespace \
= _argument_spec
def run(self):
return directive_fn(
self.name, self.arguments, self.options, self.content,
self.lineno, self.content_offset, self.block_text,
self.state, self.state_machine)
# Return new-style directive.
return FunctionalDirective
| {
"repo_name": "bobthecow/ManipulateCoda",
"path": "src/Support/Library/docutils/parsers/rst/__init__.py",
"copies": "6",
"size": "14192",
"license": "mit",
"hash": 6989899161993571000,
"line_mean": 36.8453333333,
"line_max": 82,
"alpha_frac": 0.655651071,
"autogenerated": false,
"ratio": 4.354710033752685,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00006464883925947693,
"num_lines": 375
} |
"""
This is ``docutils.parsers.rst`` package. It exports a single class, `Parser`,
the reStructuredText parser.
Usage
=====
1. Create a parser::
parser = docutils.parsers.rst.Parser()
Several optional arguments may be passed to modify the parser's behavior.
Please see `Customizing the Parser`_ below for details.
2. Gather input (a multi-line string), by reading a file or the standard
input::
input = sys.stdin.read()
3. Create a new empty `docutils.nodes.document` tree::
document = docutils.utils.new_document(source, settings)
See `docutils.utils.new_document()` for parameter details.
4. Run the parser, populating the document tree::
parser.parse(input, document)
Parser Overview
===============
The reStructuredText parser is implemented as a state machine, examining its
input one line at a time. To understand how the parser works, please first
become familiar with the `docutils.statemachine` module, then see the
`states` module.
Customizing the Parser
----------------------
Anything that isn't already customizable is that way simply because that type
of customizability hasn't been implemented yet. Patches welcome!
When instantiating an object of the `Parser` class, two parameters may be
passed: ``rfc2822`` and ``inliner``. Pass ``rfc2822=1`` to enable an initial
RFC-2822 style header block, parsed as a "field_list" element (with "class"
attribute set to "rfc2822"). Currently this is the only body-level element
which is customizable without subclassing. (Tip: subclass `Parser` and change
its "state_classes" and "initial_state" attributes to refer to new classes.
Contact the author if you need more details.)
The ``inliner`` parameter takes an instance of `states.Inliner` or a subclass.
It handles inline markup recognition. A common extension is the addition of
further implicit hyperlinks, like "RFC 2822". This can be done by subclassing
`states.Inliner`, adding a new method for the implicit markup, and adding a
``(pattern, method)`` pair to the "implicit_dispatch" attribute of the
subclass. See `states.Inliner.implicit_inline()` for details. Explicit
inline markup can be customized in a `states.Inliner` subclass via the
``patterns.initial`` and ``dispatch`` attributes (and new methods as
appropriate).
"""
__docformat__ = 'reStructuredText'
import docutils.parsers
import docutils.statemachine
from docutils.parsers.rst import states
from docutils import frontend, nodes
class Parser(docutils.parsers.Parser):
"""The reStructuredText parser."""
supported = ('restructuredtext', 'rst', 'rest', 'restx', 'rtxt', 'rstx')
"""Aliases this parser supports."""
settings_spec = (
'reStructuredText Parser Options',
None,
(('Recognize and link to standalone PEP references (like "PEP 258").',
['--pep-references'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Base URL for PEP references '
'(default "http://www.python.org/dev/peps/").',
['--pep-base-url'],
{'metavar': '<URL>', 'default': 'http://www.python.org/dev/peps/',
'validator': frontend.validate_url_trailing_slash}),
('Template for PEP file part of URL. (default "pep-%04d")',
['--pep-file-url-template'],
{'metavar': '<URL>', 'default': 'pep-%04d'}),
('Recognize and link to standalone RFC references (like "RFC 822").',
['--rfc-references'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Base URL for RFC references (default "http://www.faqs.org/rfcs/").',
['--rfc-base-url'],
{'metavar': '<URL>', 'default': 'http://www.faqs.org/rfcs/',
'validator': frontend.validate_url_trailing_slash}),
('Set number of spaces for tab expansion (default 8).',
['--tab-width'],
{'metavar': '<width>', 'type': 'int', 'default': 8,
'validator': frontend.validate_nonnegative_int}),
('Remove spaces before footnote references.',
['--trim-footnote-reference-space'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Leave spaces before footnote references.',
['--leave-footnote-reference-space'],
{'action': 'store_false', 'dest': 'trim_footnote_reference_space'}),
('Disable directives that insert the contents of external file '
'("include" & "raw"); replaced with a "warning" system message.',
['--no-file-insertion'],
{'action': 'store_false', 'default': 1,
'dest': 'file_insertion_enabled',
'validator': frontend.validate_boolean}),
('Enable directives that insert the contents of external file '
'("include" & "raw"). Enabled by default.',
['--file-insertion-enabled'],
{'action': 'store_true'}),
('Disable the "raw" directives; replaced with a "warning" '
'system message.',
['--no-raw'],
{'action': 'store_false', 'default': 1, 'dest': 'raw_enabled',
'validator': frontend.validate_boolean}),
('Enable the "raw" directive. Enabled by default.',
['--raw-enabled'],
{'action': 'store_true'}),))
config_section = 'restructuredtext parser'
config_section_dependencies = ('parsers',)
def __init__(self, rfc2822=None, inliner=None):
if rfc2822:
self.initial_state = 'RFC2822Body'
else:
self.initial_state = 'Body'
self.state_classes = states.state_classes
self.inliner = inliner
def parse(self, inputstring, document):
"""Parse `inputstring` and populate `document`, a document tree."""
self.setup_parse(inputstring, document)
self.statemachine = states.RSTStateMachine(
state_classes=self.state_classes,
initial_state=self.initial_state,
debug=document.reporter.debug_flag)
inputlines = docutils.statemachine.string2lines(
inputstring, tab_width=document.settings.tab_width,
convert_whitespace=1)
self.statemachine.run(inputlines, document, inliner=self.inliner)
self.finish_parse()
class DirectiveError(Exception):
"""
Store a message and a system message level.
To be thrown from inside directive code.
Do not instantiate directly -- use `Directive.directive_error()`
instead!
"""
def __init__(self, level, message, source, line):
"""
Initialize with message `message`. `level` is a system message level.
"""
Exception.__init__(self)
self.level = level
self.msg = message
self.source = source
self.line = line
class Directive(object):
"""
Base class for reStructuredText directives.
The following attributes may be set by subclasses. They are
interpreted by the directive parser (which runs the directive
class):
- `required_arguments`: The number of required arguments (default:
0).
- `optional_arguments`: The number of optional arguments (default:
0).
- `final_argument_whitespace`: A boolean, indicating if the final
argument may contain whitespace (default: False).
- `option_spec`: A dictionary, mapping known option names to
conversion functions such as `int` or `float` (default: {}, no
options). Several conversion functions are defined in the
directives/__init__.py module.
Option conversion functions take a single parameter, the option
argument (a string or ``None``), validate it and/or convert it
to the appropriate form. Conversion functions may raise
`ValueError` and `TypeError` exceptions.
- `has_content`: A boolean; True if content is allowed. Client
code must handle the case where content is required but not
supplied (an empty content list will be supplied).
Arguments are normally single whitespace-separated words. The
final argument may contain whitespace and/or newlines if
`final_argument_whitespace` is True.
If the form of the arguments is more complex, specify only one
argument (either required or optional) and set
`final_argument_whitespace` to True; the client code must do any
context-sensitive parsing.
When a directive implementation is being run, the directive class
is instantiated, and the `run()` method is executed. During
instantiation, the following instance variables are set:
- ``name`` is the directive type or name (string).
- ``arguments`` is the list of positional arguments (strings).
- ``options`` is a dictionary mapping option names (strings) to
values (type depends on option conversion functions; see
`option_spec` above).
- ``content`` is a list of strings, the directive content line by line.
- ``lineno`` is the line number of the first line of the directive.
- ``content_offset`` is the line offset of the first line of the content from
the beginning of the current input. Used when initiating a nested parse.
- ``block_text`` is a string containing the entire directive.
- ``state`` is the state which called the directive function.
- ``state_machine`` is the state machine which controls the state which called
the directive function.
Directive functions return a list of nodes which will be inserted
into the document tree at the point where the directive was
encountered. This can be an empty list if there is nothing to
insert.
For ordinary directives, the list must contain body elements or
structural elements. Some directives are intended specifically
for substitution definitions, and must return a list of `Text`
nodes and/or inline elements (suitable for inline insertion, in
place of the substitution reference). Such directives must verify
substitution definition context, typically using code like this::
if not isinstance(state, states.SubstitutionDef):
error = state_machine.reporter.error(
'Invalid context: the "%s" directive can only be used '
'within a substitution definition.' % (name),
nodes.literal_block(block_text, block_text), line=lineno)
return [error]
"""
# There is a "Creating reStructuredText Directives" how-to at
# <http://docutils.sf.net/docs/howto/rst-directives.html>. If you
# update this docstring, please update the how-to as well.
required_arguments = 0
"""Number of required directive arguments."""
optional_arguments = 0
"""Number of optional arguments after the required arguments."""
final_argument_whitespace = False
"""May the final argument contain whitespace?"""
option_spec = None
"""Mapping of option names to validator functions."""
has_content = False
"""May the directive have content?"""
def __init__(self, name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
self.name = name
self.arguments = arguments
self.options = options
self.content = content
self.lineno = lineno
self.content_offset = content_offset
self.block_text = block_text
self.state = state
self.state_machine = state_machine
def run(self):
raise NotImplementedError('Must override run() is subclass.')
# Directive errors:
def directive_error(self, level, message):
"""
Return a DirectiveError suitable for being thrown as an exception.
Call "raise self.directive_error(level, message)" from within
a directive implementation to return one single system message
at level `level`, which automatically gets the directive block
and the line number added.
You'd often use self.error(message) instead, which will
generate an ERROR-level directive error.
"""
# source = self.state_machine.get_source(self.lineno - 1)
try:
(source, line) = self.state_machine.input_lines.info(self.lineno)
except IndexError:
source = self.state_machine.get_source(self.lineno - 1)
line = self.lineno
return DirectiveError(level, message, source, line)
def debug(self, message):
return self.directive_error(0, message)
def info(self, message):
return self.directive_error(1, message)
def warning(self, message):
return self.directive_error(2, message)
def error(self, message):
return self.directive_error(3, message)
def severe(self, message):
return self.directive_error(4, message)
# Convenience methods:
def assert_has_content(self):
"""
Throw an ERROR-level DirectiveError if the directive doesn't
have contents.
"""
if not self.content:
raise self.error('Content block expected for the "%s" directive; '
'none found.' % self.name)
def convert_directive_function(directive_fn):
"""
Define & return a directive class generated from `directive_fn`.
`directive_fn` uses the old-style, functional interface.
"""
class FunctionalDirective(Directive):
option_spec = getattr(directive_fn, 'options', None)
has_content = getattr(directive_fn, 'content', False)
_argument_spec = getattr(directive_fn, 'arguments', (0, 0, False))
required_arguments, optional_arguments, final_argument_whitespace \
= _argument_spec
def run(self):
return directive_fn(
self.name, self.arguments, self.options, self.content,
self.lineno, self.content_offset, self.block_text,
self.state, self.state_machine)
# Return new-style directive.
return FunctionalDirective
| {
"repo_name": "rimbalinux/MSISDNArea",
"path": "docutils/parsers/rst/__init__.py",
"copies": "2",
"size": "14567",
"license": "bsd-3-clause",
"hash": -5441133447148080000,
"line_mean": 36.8453333333,
"line_max": 82,
"alpha_frac": 0.6387725681,
"autogenerated": false,
"ratio": 4.419599514563107,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00006387454580225664,
"num_lines": 375
} |
"""
Simple HyperText Markup Language document tree Writer.
The output conforms to the XHTML version 1.0 Transitional DTD
(*almost* strict). The output contains a minimum of formatting
information. The cascading style sheet "html4css1.css" is required
for proper viewing with a modern graphical browser.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import time
import re
try:
import Image # check for the Python Imaging Library
except ImportError:
Image = None
import docutils
from docutils import frontend, nodes, utils, writers, languages
from docutils.transforms import writer_aux
class Writer(writers.Writer):
supported = ('html', 'html4css1', 'xhtml')
"""Formats this writer supports."""
default_stylesheet = 'html4css1.css'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = (
'HTML-Specific Options',
None,
(('Specify the template file (UTF-8 encoded). Default is "%s".'
% default_template_path,
['--template'],
{'default': default_template_path, 'metavar': '<file>'}),
('Specify comma separated list of stylesheet URLs. '
'Overrides previous --stylesheet and --stylesheet-path settings.',
['--stylesheet'],
{'metavar': '<URL>', 'overrides': 'stylesheet_path'}),
('Specify comma separated list of stylesheet paths. '
'With --link-stylesheet, '
'the path is rewritten relative to the output HTML file. '
'Default: "%s"' % default_stylesheet_path,
['--stylesheet-path'],
{'metavar': '<file>', 'overrides': 'stylesheet',
'default': default_stylesheet_path}),
('Embed the stylesheet(s) in the output HTML file. The stylesheet '
'files must be accessible during processing. This is the default.',
['--embed-stylesheet'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Link to the stylesheet(s) in the output HTML file. '
'Default: embed stylesheets.',
['--link-stylesheet'],
{'dest': 'embed_stylesheet', 'action': 'store_false'}),
('Specify the initial header level. Default is 1 for "<h1>". '
'Does not affect document title & subtitle (see --no-doc-title).',
['--initial-header-level'],
{'choices': '1 2 3 4 5 6'.split(), 'default': '1',
'metavar': '<level>'}),
('Specify the maximum width (in characters) for one-column field '
'names. Longer field names will span an entire row of the table '
'used to render the field list. Default is 14 characters. '
'Use 0 for "no limit".',
['--field-name-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
('Specify the maximum width (in characters) for options in option '
'lists. Longer options will span an entire row of the table used '
'to render the option list. Default is 14 characters. '
'Use 0 for "no limit".',
['--option-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
('Format for footnote references: one of "superscript" or '
'"brackets". Default is "brackets".',
['--footnote-references'],
{'choices': ['superscript', 'brackets'], 'default': 'brackets',
'metavar': '<format>',
'overrides': 'trim_footnote_reference_space'}),
('Format for block quote attributions: one of "dash" (em-dash '
'prefix), "parentheses"/"parens", or "none". Default is "dash".',
['--attribution'],
{'choices': ['dash', 'parentheses', 'parens', 'none'],
'default': 'dash', 'metavar': '<format>'}),
('Remove extra vertical whitespace between items of "simple" bullet '
'lists and enumerated lists. Default: enabled.',
['--compact-lists'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compact simple bullet and enumerated lists.',
['--no-compact-lists'],
{'dest': 'compact_lists', 'action': 'store_false'}),
('Remove extra vertical whitespace between items of simple field '
'lists. Default: enabled.',
['--compact-field-lists'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compact simple field lists.',
['--no-compact-field-lists'],
{'dest': 'compact_field_lists', 'action': 'store_false'}),
('Added to standard table classes. '
'Defined styles: "borderless". Default: ""',
['--table-style'],
{'default': ''}),
('Omit the XML declaration. Use with caution.',
['--no-xml-declaration'],
{'dest': 'xml_declaration', 'default': 1, 'action': 'store_false',
'validator': frontend.validate_boolean}),
('Obfuscate email addresses to confuse harvesters while still '
'keeping email links usable with standards-compliant browsers.',
['--cloak-email-addresses'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),))
settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'}
relative_path_settings = ('stylesheet_path',)
config_section = 'html4css1 writer'
config_section_dependencies = ('writers',)
visitor_attributes = (
'head_prefix', 'head', 'stylesheet', 'body_prefix',
'body_pre_docinfo', 'docinfo', 'body', 'body_suffix',
'title', 'subtitle', 'header', 'footer', 'meta', 'fragment',
'html_prolog', 'html_head', 'html_title', 'html_subtitle',
'html_body')
def get_transforms(self):
return writers.Writer.get_transforms(self) + [writer_aux.Admonitions]
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = HTMLTranslator
def translate(self):
self.visitor = visitor = self.translator_class(self.document)
self.document.walkabout(visitor)
for attr in self.visitor_attributes:
setattr(self, attr, getattr(visitor, attr))
self.output = self.apply_template()
def apply_template(self):
template_file = open(self.document.settings.template, 'rb')
template = unicode(template_file.read(), 'utf-8')
template_file.close()
subs = self.interpolation_dict()
return template % subs
def interpolation_dict(self):
subs = {}
settings = self.document.settings
for attr in self.visitor_attributes:
subs[attr] = ''.join(getattr(self, attr)).rstrip('\n')
subs['encoding'] = settings.output_encoding
subs['version'] = docutils.__version__
return subs
def assemble_parts(self):
writers.Writer.assemble_parts(self)
for part in self.visitor_attributes:
self.parts[part] = ''.join(getattr(self, part))
class HTMLTranslator(nodes.NodeVisitor):
"""
This HTML writer has been optimized to produce visually compact
lists (less vertical whitespace). HTML's mixed content models
allow list items to contain "<li><p>body elements</p></li>" or
"<li>just text</li>" or even "<li>text<p>and body
elements</p>combined</li>", each with different effects. It would
be best to stick with strict body elements in list items, but they
affect vertical spacing in browsers (although they really
shouldn't).
Here is an outline of the optimization:
- Check for and omit <p> tags in "simple" lists: list items
contain either a single paragraph, a nested simple list, or a
paragraph followed by a nested simple list. This means that
this list can be compact:
- Item 1.
- Item 2.
But this list cannot be compact:
- Item 1.
This second paragraph forces space between list items.
- Item 2.
- In non-list contexts, omit <p> tags on a paragraph if that
paragraph is the only child of its parent (footnotes & citations
are allowed a label first).
- Regardless of the above, in definitions, table cells, field bodies,
option descriptions, and list items, mark the first child with
'class="first"' and the last child with 'class="last"'. The stylesheet
sets the margins (top & bottom respectively) to 0 for these elements.
The ``no_compact_lists`` setting (``--no-compact-lists`` command-line
option) disables list whitespace optimization.
"""
xml_declaration = '<?xml version="1.0" encoding="%s" ?>\n'
doctype = (
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
head_prefix_template = ('<html xmlns="http://www.w3.org/1999/xhtml"'
' xml:lang="%s" lang="%s">\n<head>\n')
content_type = ('<meta http-equiv="Content-Type"'
' content="text/html; charset=%s" />\n')
generator = ('<meta name="generator" content="Docutils %s: '
'http://docutils.sourceforge.net/" />\n')
stylesheet_link = '<link rel="stylesheet" href="%s" type="text/css" />\n'
embedded_stylesheet = '<style type="text/css">\n\n%s\n</style>\n'
words_and_spaces = re.compile(r'\S+| +|\n')
sollbruchstelle = re.compile(r'.+\W\W.+|[-?].+', re.U) # wrap point inside word
def __init__(self, document):
nodes.NodeVisitor.__init__(self, document)
self.settings = settings = document.settings
lcode = settings.language_code
self.language = languages.get_language(lcode)
self.meta = [self.content_type % settings.output_encoding,
self.generator % docutils.__version__]
self.head_prefix = []
self.html_prolog = []
if settings.xml_declaration:
self.head_prefix.append(self.xml_declaration
% settings.output_encoding)
# encoding not interpolated:
self.html_prolog.append(self.xml_declaration)
self.head_prefix.extend([self.doctype,
self.head_prefix_template % (lcode, lcode)])
self.html_prolog.append(self.doctype)
self.head = self.meta[:]
# stylesheets
styles = utils.get_stylesheet_list(settings)
if settings.stylesheet_path and not(settings.embed_stylesheet):
styles = [utils.relative_path(settings._destination, sheet)
for sheet in styles]
if settings.embed_stylesheet:
settings.record_dependencies.add(*styles)
self.stylesheet = [self.embedded_stylesheet %
unicode(open(sheet).read(), 'utf-8')
for sheet in styles]
else: # link to stylesheets
self.stylesheet = [self.stylesheet_link % self.encode(stylesheet)
for stylesheet in styles]
self.body_prefix = ['</head>\n<body>\n']
# document title, subtitle display
self.body_pre_docinfo = []
# author, date, etc.
self.docinfo = []
self.body = []
self.fragment = []
self.body_suffix = ['</body>\n</html>\n']
self.section_level = 0
self.initial_header_level = int(settings.initial_header_level)
# A heterogenous stack used in conjunction with the tree traversal.
# Make sure that the pops correspond to the pushes:
self.context = []
self.topic_classes = []
self.colspecs = []
self.compact_p = 1
self.compact_simple = None
self.compact_field_list = None
self.in_docinfo = None
self.in_sidebar = None
self.title = []
self.subtitle = []
self.header = []
self.footer = []
self.html_head = [self.content_type] # charset not interpolated
self.html_title = []
self.html_subtitle = []
self.html_body = []
self.in_document_title = 0
self.in_mailto = 0
self.author_in_authors = None
def astext(self):
return ''.join(self.head_prefix + self.head
+ self.stylesheet + self.body_prefix
+ self.body_pre_docinfo + self.docinfo
+ self.body + self.body_suffix)
def encode(self, text):
"""Encode special characters in `text` & return."""
# @@@ A codec to do these and all other HTML entities would be nice.
text = unicode(text)
return text.translate({
ord('&'): u'&',
ord('<'): u'<',
ord('"'): u'"',
ord('>'): u'>',
ord('@'): u'@', # may thwart some address harvesters
# TODO: convert non-breaking space only if needed?
0xa0: u' '}) # non-breaking space
def cloak_mailto(self, uri):
"""Try to hide a mailto: URL from harvesters."""
# Encode "@" using a URL octet reference (see RFC 1738).
# Further cloaking with HTML entities will be done in the
# `attval` function.
return uri.replace('@', '%40')
def cloak_email(self, addr):
"""Try to hide the link text of a email link from harversters."""
# Surround at-signs and periods with <span> tags. ("@" has
# already been encoded to "@" by the `encode` method.)
addr = addr.replace('@', '<span>@</span>')
addr = addr.replace('.', '<span>.</span>')
return addr
def attval(self, text,
whitespace=re.compile('[\n\r\t\v\f]')):
"""Cleanse, HTML encode, and return attribute value text."""
encoded = self.encode(whitespace.sub(' ', text))
if self.in_mailto and self.settings.cloak_email_addresses:
# Cloak at-signs ("%40") and periods with HTML entities.
encoded = encoded.replace('%40', '%40')
encoded = encoded.replace('.', '.')
return encoded
def starttag(self, node, tagname, suffix='\n', empty=0, **attributes):
"""
Construct and return a start tag given a node (id & class attributes
are extracted), tag name, and optional attributes.
"""
tagname = tagname.lower()
prefix = []
atts = {}
ids = []
for (name, value) in attributes.items():
atts[name.lower()] = value
classes = node.get('classes', [])
if 'class' in atts:
classes.append(atts['class'])
if classes:
atts['class'] = ' '.join(classes)
assert 'id' not in atts
ids.extend(node.get('ids', []))
if 'ids' in atts:
ids.extend(atts['ids'])
del atts['ids']
if ids:
atts['id'] = ids[0]
for id in ids[1:]:
# Add empty "span" elements for additional IDs. Note
# that we cannot use empty "a" elements because there
# may be targets inside of references, but nested "a"
# elements aren't allowed in XHTML (even if they do
# not all have a "href" attribute).
if empty:
# Empty tag. Insert target right in front of element.
prefix.append('<span id="%s"></span>' % id)
else:
# Non-empty tag. Place the auxiliary <span> tag
# *inside* the element, as the first child.
suffix += '<span id="%s"></span>' % id
attlist = atts.items()
attlist.sort()
parts = [tagname]
for name, value in attlist:
# value=None was used for boolean attributes without
# value, but this isn't supported by XHTML.
assert value is not None
if isinstance(value, list):
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
def emptytag(self, node, tagname, suffix='\n', **attributes):
"""Construct and return an XML-compatible empty tag."""
return self.starttag(node, tagname, suffix, empty=1, **attributes)
def set_class_on_child(self, node, class_, index=0):
"""
Set class `class_` on the visible child no. index of `node`.
Do nothing if node has fewer children than `index`.
"""
children = [n for n in node if not isinstance(n, nodes.Invisible)]
try:
child = children[index]
except IndexError:
return
child['classes'].append(class_)
def set_first_last(self, node):
self.set_class_on_child(node, 'first', 0)
self.set_class_on_child(node, 'last', -1)
def visit_Text(self, node):
text = node.astext()
encoded = self.encode(text)
if self.in_mailto and self.settings.cloak_email_addresses:
encoded = self.cloak_email(encoded)
self.body.append(encoded)
def depart_Text(self, node):
pass
def visit_abbreviation(self, node):
# @@@ implementation incomplete ("title" attribute)
self.body.append(self.starttag(node, 'abbr', ''))
def depart_abbreviation(self, node):
self.body.append('</abbr>')
def visit_acronym(self, node):
# @@@ implementation incomplete ("title" attribute)
self.body.append(self.starttag(node, 'acronym', ''))
def depart_acronym(self, node):
self.body.append('</acronym>')
def visit_address(self, node):
self.visit_docinfo_item(node, 'address', meta=None)
self.body.append(self.starttag(node, 'pre', CLASS='address'))
def depart_address(self, node):
self.body.append('\n</pre>\n')
self.depart_docinfo_item()
def visit_admonition(self, node):
self.body.append(self.starttag(node, 'div'))
self.set_first_last(node)
def depart_admonition(self, node=None):
self.body.append('</div>\n')
attribution_formats = {'dash': ('—', ''),
'parentheses': ('(', ')'),
'parens': ('(', ')'),
'none': ('', '')}
def visit_attribution(self, node):
prefix, suffix = self.attribution_formats[self.settings.attribution]
self.context.append(suffix)
self.body.append(
self.starttag(node, 'p', prefix, CLASS='attribution'))
def depart_attribution(self, node):
self.body.append(self.context.pop() + '</p>\n')
def visit_author(self, node):
if isinstance(node.parent, nodes.authors):
if self.author_in_authors:
self.body.append('\n<br />')
else:
self.visit_docinfo_item(node, 'author')
def depart_author(self, node):
if isinstance(node.parent, nodes.authors):
self.author_in_authors += 1
else:
self.depart_docinfo_item()
def visit_authors(self, node):
self.visit_docinfo_item(node, 'authors')
self.author_in_authors = 0 # initialize counter
def depart_authors(self, node):
self.depart_docinfo_item()
self.author_in_authors = None
def visit_block_quote(self, node):
self.body.append(self.starttag(node, 'blockquote'))
def depart_block_quote(self, node):
self.body.append('</blockquote>\n')
def check_simple_list(self, node):
"""Check for a simple list that can be rendered compactly."""
visitor = SimpleListChecker(self.document)
try:
node.walk(visitor)
except nodes.NodeFound:
return None
else:
return 1
def is_compactable(self, node):
return ('compact' in node['classes']
or (self.settings.compact_lists
and 'open' not in node['classes']
and (self.compact_simple
or self.topic_classes == ['contents']
or self.check_simple_list(node))))
def visit_bullet_list(self, node):
atts = {}
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'] = 'simple'
self.body.append(self.starttag(node, 'ul', **atts))
def depart_bullet_list(self, node):
self.compact_simple, self.compact_p = self.context.pop()
self.body.append('</ul>\n')
def visit_caption(self, node):
self.body.append(self.starttag(node, 'p', '', CLASS='caption'))
def depart_caption(self, node):
self.body.append('</p>\n')
def visit_citation(self, node):
self.body.append(self.starttag(node, 'table',
CLASS='docutils citation',
frame="void", rules="none"))
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n'
'<tbody valign="top">\n'
'<tr>')
self.footnote_backrefs(node)
def depart_citation(self, node):
self.body.append('</td></tr>\n'
'</tbody>\n</table>\n')
def visit_citation_reference(self, node):
href = '#' + node['refid']
self.body.append(self.starttag(
node, 'a', '[', CLASS='citation-reference', href=href))
def depart_citation_reference(self, node):
self.body.append(']</a>')
def visit_classifier(self, node):
self.body.append(' <span class="classifier-delimiter">:</span> ')
self.body.append(self.starttag(node, 'span', '', CLASS='classifier'))
def depart_classifier(self, node):
self.body.append('</span>')
def visit_colspec(self, node):
self.colspecs.append(node)
# "stubs" list is an attribute of the tgroup element:
node.parent.stubs.append(node.attributes.get('stub'))
def depart_colspec(self, node):
pass
def write_colspecs(self):
width = 0
for node in self.colspecs:
width += node['colwidth']
for node in self.colspecs:
colwidth = int(node['colwidth'] * 100.0 / width + 0.5)
self.body.append(self.emptytag(node, 'col',
width='%i%%' % colwidth))
self.colspecs = []
def visit_comment(self, node,
sub=re.compile('-(?=-)').sub):
"""Escape double-dashes in comment text."""
self.body.append('<!-- %s -->\n' % sub('- ', node.astext()))
# Content already processed:
raise nodes.SkipNode
def visit_compound(self, node):
self.body.append(self.starttag(node, 'div', CLASS='compound'))
if len(node) > 1:
node[0]['classes'].append('compound-first')
node[-1]['classes'].append('compound-last')
for child in node[1:-1]:
child['classes'].append('compound-middle')
def depart_compound(self, node):
self.body.append('</div>\n')
def visit_container(self, node):
self.body.append(self.starttag(node, 'div', CLASS='container'))
def depart_container(self, node):
self.body.append('</div>\n')
def visit_contact(self, node):
self.visit_docinfo_item(node, 'contact', meta=None)
def depart_contact(self, node):
self.depart_docinfo_item()
def visit_copyright(self, node):
self.visit_docinfo_item(node, 'copyright')
def depart_copyright(self, node):
self.depart_docinfo_item()
def visit_date(self, node):
self.visit_docinfo_item(node, 'date')
def depart_date(self, node):
self.depart_docinfo_item()
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
self.body.append('</dt>\n')
self.body.append(self.starttag(node, 'dd', ''))
self.set_first_last(node)
def depart_definition(self, node):
self.body.append('</dd>\n')
def visit_definition_list(self, node):
self.body.append(self.starttag(node, 'dl', CLASS='docutils'))
def depart_definition_list(self, node):
self.body.append('</dl>\n')
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_description(self, node):
self.body.append(self.starttag(node, 'td', ''))
self.set_first_last(node)
def depart_description(self, node):
self.body.append('</td>')
def visit_docinfo(self, node):
self.context.append(len(self.body))
self.body.append(self.starttag(node, 'table',
CLASS='docinfo',
frame="void", rules="none"))
self.body.append('<col class="docinfo-name" />\n'
'<col class="docinfo-content" />\n'
'<tbody valign="top">\n')
self.in_docinfo = 1
def depart_docinfo(self, node):
self.body.append('</tbody>\n</table>\n')
self.in_docinfo = None
start = self.context.pop()
self.docinfo = self.body[start:]
self.body = []
def visit_docinfo_item(self, node, name, meta=1):
if meta:
meta_tag = '<meta name="%s" content="%s" />\n' \
% (name, self.attval(node.astext()))
self.add_meta(meta_tag)
self.body.append(self.starttag(node, 'tr', ''))
self.body.append('<th class="docinfo-name">%s:</th>\n<td>'
% self.language.labels[name])
if len(node):
if isinstance(node[0], nodes.Element):
node[0]['classes'].append('first')
if isinstance(node[-1], nodes.Element):
node[-1]['classes'].append('last')
def depart_docinfo_item(self):
self.body.append('</td></tr>\n')
def visit_doctest_block(self, node):
self.body.append(self.starttag(node, 'pre', CLASS='doctest-block'))
def depart_doctest_block(self, node):
self.body.append('\n</pre>\n')
def visit_document(self, node):
self.head.append('<title>%s</title>\n'
% self.encode(node.get('title', '')))
def depart_document(self, node):
self.fragment.extend(self.body)
self.body_prefix.append(self.starttag(node, 'div', CLASS='document'))
self.body_suffix.insert(0, '</div>\n')
# skip content-type meta tag with interpolated charset value:
self.html_head.extend(self.head[1:])
self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
+ self.docinfo + self.body
+ self.body_suffix[:-1])
assert not self.context, 'len(context) = %s' % len(self.context)
def visit_emphasis(self, node):
self.body.append(self.starttag(node, 'em', ''))
def depart_emphasis(self, node):
self.body.append('</em>')
def visit_entry(self, node):
atts = {'class': []}
if isinstance(node.parent.parent, nodes.thead):
atts['class'].append('head')
if node.parent.parent.parent.stubs[node.parent.column]:
# "stubs" list is an attribute of the tgroup element
atts['class'].append('stub')
if atts['class']:
tagname = 'th'
atts['class'] = ' '.join(atts['class'])
else:
tagname = 'td'
del atts['class']
node.parent.column += 1
if 'morerows' in node:
atts['rowspan'] = node['morerows'] + 1
if 'morecols' in node:
atts['colspan'] = node['morecols'] + 1
node.parent.column += node['morecols']
self.body.append(self.starttag(node, tagname, '', **atts))
self.context.append('</%s>\n' % tagname.lower())
if len(node) == 0: # empty cell
self.body.append(' ')
self.set_first_last(node)
def depart_entry(self, node):
self.body.append(self.context.pop())
def visit_enumerated_list(self, node):
"""
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.
"""
atts = {}
if 'start' in node:
atts['start'] = node['start']
if 'enumtype' in node:
atts['class'] = node['enumtype']
# @@@ To do: prefix, suffix. How? Change prefix/suffix to a
# single "format" attribute? Use CSS2?
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))
def depart_enumerated_list(self, node):
self.compact_simple, self.compact_p = self.context.pop()
self.body.append('</ol>\n')
def visit_field(self, node):
self.body.append(self.starttag(node, 'tr', '', CLASS='field'))
def depart_field(self, node):
self.body.append('</tr>\n')
def visit_field_body(self, node):
self.body.append(self.starttag(node, 'td', '', CLASS='field-body'))
self.set_class_on_child(node, 'first', 0)
field = node.parent
if (self.compact_field_list or
isinstance(field.parent, nodes.docinfo) or
field.parent.index(field) == len(field.parent) - 1):
# If we are in a compact list, the docinfo, or if this is
# the last field of the field list, do not add vertical
# space after last element.
self.set_class_on_child(node, 'last', -1)
def depart_field_body(self, node):
self.body.append('</td>\n')
def visit_field_list(self, node):
self.context.append((self.compact_field_list, self.compact_p))
self.compact_p = None
if 'compact' in node['classes']:
self.compact_field_list = 1
elif (self.settings.compact_field_lists
and 'open' not in node['classes']):
self.compact_field_list = 1
if self.compact_field_list:
for field in node:
field_body = field[-1]
assert isinstance(field_body, nodes.field_body)
children = [n for n in field_body
if not isinstance(n, nodes.Invisible)]
if not (len(children) == 0 or
len(children) == 1 and
isinstance(children[0],
(nodes.paragraph, nodes.line_block))):
self.compact_field_list = 0
break
self.body.append(self.starttag(node, 'table', frame='void',
rules='none',
CLASS='docutils field-list'))
self.body.append('<col class="field-name" />\n'
'<col class="field-body" />\n'
'<tbody valign="top">\n')
def depart_field_list(self, node):
self.body.append('</tbody>\n</table>\n')
self.compact_field_list, self.compact_p = self.context.pop()
def visit_field_name(self, node):
atts = {}
if self.in_docinfo:
atts['class'] = 'docinfo-name'
else:
atts['class'] = 'field-name'
if ( self.settings.field_name_limit
and len(node.astext()) > self.settings.field_name_limit):
atts['colspan'] = 2
self.context.append('</tr>\n<tr><td> </td>')
else:
self.context.append('')
self.body.append(self.starttag(node, 'th', '', **atts))
def depart_field_name(self, node):
self.body.append(':</th>')
self.body.append(self.context.pop())
def visit_figure(self, node):
atts = {'class': 'figure'}
if node.get('width'):
atts['style'] = 'width: %s' % node['width']
if node.get('align'):
atts['class'] += " align-" + node['align']
self.body.append(self.starttag(node, 'div', **atts))
def depart_figure(self, node):
self.body.append('</div>\n')
def visit_footer(self, node):
self.context.append(len(self.body))
def depart_footer(self, node):
start = self.context.pop()
footer = [self.starttag(node, 'div', CLASS='footer'),
'<hr class="footer" />\n']
footer.extend(self.body[start:])
footer.append('\n</div>\n')
self.footer.extend(footer)
self.body_suffix[:0] = footer
del self.body[start:]
def visit_footnote(self, node):
self.body.append(self.starttag(node, 'table',
CLASS='docutils footnote',
frame="void", rules="none"))
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n'
'<tbody valign="top">\n'
'<tr>')
self.footnote_backrefs(node)
def footnote_backrefs(self, node):
backlinks = []
backrefs = node['backrefs']
if self.settings.footnote_backlinks and backrefs:
if len(backrefs) == 1:
self.context.append('')
self.context.append('</a>')
self.context.append('<a class="fn-backref" href="#%s">'
% backrefs[0])
else:
i = 1
for backref in backrefs:
backlinks.append('<a class="fn-backref" href="#%s">%s</a>'
% (backref, i))
i += 1
self.context.append('<em>(%s)</em> ' % ', '.join(backlinks))
self.context += ['', '']
else:
self.context.append('')
self.context += ['', '']
# If the node does not only consist of a label.
if len(node) > 1:
# If there are preceding backlinks, we do not set class
# 'first', because we need to retain the top-margin.
if not backlinks:
node[1]['classes'].append('first')
node[-1]['classes'].append('last')
def depart_footnote(self, node):
self.body.append('</td></tr>\n'
'</tbody>\n</table>\n')
def visit_footnote_reference(self, node):
href = '#' + node['refid']
format = self.settings.footnote_references
if format == 'brackets':
suffix = '['
self.context.append(']')
else:
assert format == 'superscript'
suffix = '<sup>'
self.context.append('</sup>')
self.body.append(self.starttag(node, 'a', suffix,
CLASS='footnote-reference', href=href))
def depart_footnote_reference(self, node):
self.body.append(self.context.pop() + '</a>')
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def visit_header(self, node):
self.context.append(len(self.body))
def depart_header(self, node):
start = self.context.pop()
header = [self.starttag(node, 'div', CLASS='header')]
header.extend(self.body[start:])
header.append('\n<hr class="header"/>\n</div>\n')
self.body_prefix.extend(header)
self.header.extend(header)
del self.body[start:]
def visit_image(self, node):
atts = {}
atts['src'] = node['uri']
if 'width' in node:
atts['width'] = node['width']
if 'height' in node:
atts['height'] = node['height']
if 'scale' in node:
if Image and not ('width' in node
and 'height' in node):
try:
im = Image.open(str(atts['src']))
except (IOError, # Source image can't be found or opened
UnicodeError): # PIL doesn't like Unicode paths.
pass
else:
if 'width' not in atts:
atts['width'] = str(im.size[0])
if 'height' not in atts:
atts['height'] = str(im.size[1])
del im
for att_name in 'width', 'height':
if att_name in atts:
match = re.match(r'([0-9.]+)(\S*)$', atts[att_name])
assert match
atts[att_name] = '%s%s' % (
float(match.group(1)) * (float(node['scale']) / 100),
match.group(2))
style = []
for att_name in 'width', 'height':
if att_name in atts:
if re.match(r'^[0-9.]+$', atts[att_name]):
# Interpret unitless values as pixels.
atts[att_name] += 'px'
style.append('%s: %s;' % (att_name, atts[att_name]))
del atts[att_name]
if style:
atts['style'] = ' '.join(style)
atts['alt'] = node.get('alt', atts['src'])
if (isinstance(node.parent, nodes.TextElement) or
(isinstance(node.parent, nodes.reference) and
not isinstance(node.parent.parent, nodes.TextElement))):
# Inline context or surrounded by <a>...</a>.
suffix = ''
else:
suffix = '\n'
if 'classes' in node and 'align-center' in node['classes']:
node['align'] = 'center'
if 'align' in node:
if node['align'] == 'center':
# "align" attribute is set in surrounding "div" element.
self.body.append('<div align="center" class="align-center">')
self.context.append('</div>\n')
suffix = ''
else:
# "align" attribute is set in "img" element.
atts['align'] = node['align']
self.context.append('')
atts['class'] = 'align-%s' % node['align']
else:
self.context.append('')
self.body.append(self.emptytag(node, 'img', suffix, **atts))
def depart_image(self, node):
self.body.append(self.context.pop())
def visit_inline(self, node):
self.body.append(self.starttag(node, 'span', ''))
def depart_inline(self, node):
self.body.append('</span>')
def visit_label(self, node):
# Context added in footnote_backrefs.
self.body.append(self.starttag(node, 'td', '%s[' % self.context.pop(),
CLASS='label'))
def depart_label(self, node):
# Context added in footnote_backrefs.
self.body.append(']%s</td><td>%s' % (self.context.pop(), self.context.pop()))
def visit_legend(self, node):
self.body.append(self.starttag(node, 'div', CLASS='legend'))
def depart_legend(self, node):
self.body.append('</div>\n')
def visit_line(self, node):
self.body.append(self.starttag(node, 'div', suffix='', CLASS='line'))
if not len(node):
self.body.append('<br />')
def depart_line(self, node):
self.body.append('</div>\n')
def visit_line_block(self, node):
self.body.append(self.starttag(node, 'div', CLASS='line-block'))
def depart_line_block(self, node):
self.body.append('</div>\n')
def visit_list_item(self, node):
self.body.append(self.starttag(node, 'li', ''))
if len(node):
node[0]['classes'].append('first')
def depart_list_item(self, node):
self.body.append('</li>\n')
def visit_literal(self, node):
"""Process text to prevent tokens from wrapping."""
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():
# Protect text like "--an-option" and the regular expression
# ``[+]?(\d+(\.\d*)?|\.\d+)`` from bad line wrapping
if self.sollbruchstelle.search(token):
self.body.append('<span class="pre">%s</span>'
% self.encode(token))
else:
self.body.append(self.encode(token))
elif token in ('\n', ' '):
# Allow breaks at whitespace:
self.body.append(token)
else:
# Protect runs of multiple spaces; the last space can wrap:
self.body.append(' ' * (len(token) - 1) + ' ')
self.body.append('</tt>')
# Content already processed:
raise nodes.SkipNode
def visit_literal_block(self, node):
self.body.append(self.starttag(node, 'pre', CLASS='literal-block'))
def depart_literal_block(self, node):
self.body.append('\n</pre>\n')
def visit_meta(self, node):
meta = self.emptytag(node, 'meta', **node.non_default_attributes())
self.add_meta(meta)
def depart_meta(self, node):
pass
def add_meta(self, tag):
self.meta.append(tag)
self.head.append(tag)
def visit_option(self, node):
if self.context[-1]:
self.body.append(', ')
self.body.append(self.starttag(node, 'span', '', CLASS='option'))
def depart_option(self, node):
self.body.append('</span>')
self.context[-1] += 1
def visit_option_argument(self, node):
self.body.append(node.get('delimiter', ' '))
self.body.append(self.starttag(node, 'var', ''))
def depart_option_argument(self, node):
self.body.append('</var>')
def visit_option_group(self, node):
atts = {}
if ( self.settings.option_limit
and len(node.astext()) > self.settings.option_limit):
atts['colspan'] = 2
self.context.append('</tr>\n<tr><td> </td>')
else:
self.context.append('')
self.body.append(
self.starttag(node, 'td', CLASS='option-group', **atts))
self.body.append('<kbd>')
self.context.append(0) # count number of options
def depart_option_group(self, node):
self.context.pop()
self.body.append('</kbd></td>\n')
self.body.append(self.context.pop())
def visit_option_list(self, node):
self.body.append(
self.starttag(node, 'table', CLASS='docutils option-list',
frame="void", rules="none"))
self.body.append('<col class="option" />\n'
'<col class="description" />\n'
'<tbody valign="top">\n')
def depart_option_list(self, node):
self.body.append('</tbody>\n</table>\n')
def visit_option_list_item(self, node):
self.body.append(self.starttag(node, 'tr', ''))
def depart_option_list_item(self, node):
self.body.append('</tr>\n')
def visit_option_string(self, node):
pass
def depart_option_string(self, node):
pass
def visit_organization(self, node):
self.visit_docinfo_item(node, 'organization')
def depart_organization(self, node):
self.depart_docinfo_item()
def should_be_compact_paragraph(self, node):
"""
Determine if the <p> tags around paragraph ``node`` can be omitted.
"""
if (isinstance(node.parent, nodes.document) or
isinstance(node.parent, nodes.compound)):
# Never compact paragraphs in document or 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']))):
# Attribute which needs to survive.
return 0
first = isinstance(node.parent[0], nodes.label) # skip label
for child in node.parent.children[first:]:
# only first paragraph can be compact
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
def visit_paragraph(self, node):
if self.should_be_compact_paragraph(node):
self.context.append('')
else:
self.body.append(self.starttag(node, 'p', ''))
self.context.append('</p>\n')
def depart_paragraph(self, node):
self.body.append(self.context.pop())
def visit_problematic(self, node):
if node.hasattr('refid'):
self.body.append('<a href="#%s">' % node['refid'])
self.context.append('</a>')
else:
self.context.append('')
self.body.append(self.starttag(node, 'span', '', CLASS='problematic'))
def depart_problematic(self, node):
self.body.append('</span>')
self.body.append(self.context.pop())
def visit_raw(self, node):
if 'html' in node.get('format', '').split():
t = isinstance(node.parent, nodes.TextElement) and 'span' or 'div'
if node['classes']:
self.body.append(self.starttag(node, t, suffix=''))
self.body.append(node.astext())
if node['classes']:
self.body.append('</%s>' % t)
# Keep non-HTML raw text out of output:
raise nodes.SkipNode
def visit_reference(self, node):
atts = {'class': 'reference'}
if 'refuri' in node:
atts['href'] = node['refuri']
if ( self.settings.cloak_email_addresses
and atts['href'].startswith('mailto:')):
atts['href'] = self.cloak_mailto(atts['href'])
self.in_mailto = 1
atts['class'] += ' external'
else:
assert 'refid' in node, \
'References must have "refuri" or "refid" attribute.'
atts['href'] = '#' + node['refid']
atts['class'] += ' internal'
if not isinstance(node.parent, nodes.TextElement):
assert len(node) == 1 and isinstance(node[0], nodes.image)
atts['class'] += ' image-reference'
self.body.append(self.starttag(node, 'a', '', **atts))
def depart_reference(self, node):
self.body.append('</a>')
if not isinstance(node.parent, nodes.TextElement):
self.body.append('\n')
self.in_mailto = 0
def visit_revision(self, node):
self.visit_docinfo_item(node, 'revision', meta=None)
def depart_revision(self, node):
self.depart_docinfo_item()
def visit_row(self, node):
self.body.append(self.starttag(node, 'tr', ''))
node.column = 0
def depart_row(self, node):
self.body.append('</tr>\n')
def visit_rubric(self, node):
self.body.append(self.starttag(node, 'p', '', CLASS='rubric'))
def depart_rubric(self, node):
self.body.append('</p>\n')
def visit_section(self, node):
self.section_level += 1
self.body.append(
self.starttag(node, 'div', CLASS='section'))
def depart_section(self, node):
self.section_level -= 1
self.body.append('</div>\n')
def visit_sidebar(self, node):
self.body.append(
self.starttag(node, 'div', CLASS='sidebar'))
self.set_first_last(node)
self.in_sidebar = 1
def depart_sidebar(self, node):
self.body.append('</div>\n')
self.in_sidebar = None
def visit_status(self, node):
self.visit_docinfo_item(node, 'status', meta=None)
def depart_status(self, node):
self.depart_docinfo_item()
def visit_strong(self, node):
self.body.append(self.starttag(node, 'strong', ''))
def depart_strong(self, node):
self.body.append('</strong>')
def visit_subscript(self, node):
self.body.append(self.starttag(node, 'sub', ''))
def depart_subscript(self, node):
self.body.append('</sub>')
def visit_substitution_definition(self, node):
"""Internal only."""
raise nodes.SkipNode
def visit_substitution_reference(self, node):
self.unimplemented_visit(node)
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.sidebar):
self.body.append(self.starttag(node, 'p', '',
CLASS='sidebar-subtitle'))
self.context.append('</p>\n')
elif isinstance(node.parent, nodes.document):
self.body.append(self.starttag(node, 'h2', '', CLASS='subtitle'))
self.context.append('</h2>\n')
self.in_document_title = len(self.body)
elif isinstance(node.parent, nodes.section):
tag = 'h%s' % (self.section_level + self.initial_header_level - 1)
self.body.append(
self.starttag(node, tag, '', CLASS='section-subtitle') +
self.starttag({}, 'span', '', CLASS='section-subtitle'))
self.context.append('</span></%s>\n' % tag)
def depart_subtitle(self, node):
self.body.append(self.context.pop())
if self.in_document_title:
self.subtitle = self.body[self.in_document_title:-1]
self.in_document_title = 0
self.body_pre_docinfo.extend(self.body)
self.html_subtitle.extend(self.body)
del self.body[:]
def visit_superscript(self, node):
self.body.append(self.starttag(node, 'sup', ''))
def depart_superscript(self, node):
self.body.append('</sup>')
def visit_system_message(self, node):
self.body.append(self.starttag(node, 'div', CLASS='system-message'))
self.body.append('<p class="system-message-title">')
backref_text = ''
if len(node['backrefs']):
backrefs = node['backrefs']
if len(backrefs) == 1:
backref_text = ('; <em><a href="#%s">backlink</a></em>'
% backrefs[0])
else:
i = 1
backlinks = []
for backref in backrefs:
backlinks.append('<a href="#%s">%s</a>' % (backref, i))
i += 1
backref_text = ('; <em>backlinks: %s</em>'
% ', '.join(backlinks))
if node.hasattr('line'):
line = ', line %s' % node['line']
else:
line = ''
self.body.append('System Message: %s/%s '
'(<tt class="docutils">%s</tt>%s)%s</p>\n'
% (node['type'], node['level'],
self.encode(node['source']), line, backref_text))
def depart_system_message(self, node):
self.body.append('</div>\n')
def visit_table(self, node):
classes = ' '.join(['docutils', self.settings.table_style]).strip()
self.body.append(
self.starttag(node, 'table', CLASS=classes, border="1"))
def depart_table(self, node):
self.body.append('</table>\n')
def visit_target(self, node):
if not ('refuri' in node or 'refid' in node
or 'refname' in node):
self.body.append(self.starttag(node, 'span', '', CLASS='target'))
self.context.append('</span>')
else:
self.context.append('')
def depart_target(self, node):
self.body.append(self.context.pop())
def visit_tbody(self, node):
self.write_colspecs()
self.body.append(self.context.pop()) # '</colgroup>\n' or ''
self.body.append(self.starttag(node, 'tbody', valign='top'))
def depart_tbody(self, node):
self.body.append('</tbody>\n')
def visit_term(self, node):
self.body.append(self.starttag(node, 'dt', ''))
def depart_term(self, node):
"""
Leave the end tag to `self.visit_definition()`, in case there's a
classifier.
"""
pass
def visit_tgroup(self, node):
# Mozilla needs <colgroup>:
self.body.append(self.starttag(node, 'colgroup'))
# Appended by thead or tbody:
self.context.append('</colgroup>\n')
node.stubs = []
def depart_tgroup(self, node):
pass
def visit_thead(self, node):
self.write_colspecs()
self.body.append(self.context.pop()) # '</colgroup>\n'
# There may or may not be a <thead>; this is for <tbody> to use:
self.context.append('')
self.body.append(self.starttag(node, 'thead', valign='bottom'))
def depart_thead(self, node):
self.body.append('</thead>\n')
def visit_title(self, node):
"""Only 6 section levels are supported by HTML."""
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)
def depart_title(self, node):
self.body.append(self.context.pop())
if self.in_document_title:
self.title = self.body[self.in_document_title:-1]
self.in_document_title = 0
self.body_pre_docinfo.extend(self.body)
self.html_title.extend(self.body)
del self.body[:]
def visit_title_reference(self, node):
self.body.append(self.starttag(node, 'cite', ''))
def depart_title_reference(self, node):
self.body.append('</cite>')
def visit_topic(self, node):
self.body.append(self.starttag(node, 'div', CLASS='topic'))
self.topic_classes = node['classes']
def depart_topic(self, node):
self.body.append('</div>\n')
self.topic_classes = []
def visit_transition(self, node):
self.body.append(self.emptytag(node, 'hr', CLASS='docutils'))
def depart_transition(self, node):
pass
def visit_version(self, node):
self.visit_docinfo_item(node, 'version', meta=None)
def depart_version(self, node):
self.depart_docinfo_item()
def unimplemented_visit(self, node):
raise NotImplementedError('visiting unimplemented node type: %s'
% node.__class__.__name__)
class SimpleListChecker(nodes.GenericNodeVisitor):
"""
Raise `nodes.NodeFound` if non-simple list item is encountered.
Here "simple" means a list item containing nothing other than a single
paragraph, a simple list, or a paragraph followed by a simple list.
"""
def default_visit(self, node):
raise nodes.NodeFound
def visit_bullet_list(self, node):
pass
def visit_enumerated_list(self, node):
pass
def visit_list_item(self, node):
children = []
for child in node.children:
if not isinstance(child, nodes.Invisible):
children.append(child)
if (children and isinstance(children[0], nodes.paragraph)
and (isinstance(children[-1], nodes.bullet_list)
or isinstance(children[-1], nodes.enumerated_list))):
children.pop()
if len(children) <= 1:
return
else:
raise nodes.NodeFound
def visit_paragraph(self, node):
raise nodes.SkipNode
def invisible_visit(self, node):
"""Invisible nodes should be ignored."""
raise nodes.SkipNode
visit_comment = invisible_visit
visit_substitution_definition = invisible_visit
visit_target = invisible_visit
visit_pending = invisible_visit
| {
"repo_name": "umitproject/tease-o-matic",
"path": "docutils/writers/html4css1/__init__.py",
"copies": "6",
"size": "59090",
"license": "bsd-3-clause",
"hash": -1363836062000105200,
"line_mean": 37.0980012895,
"line_max": 85,
"alpha_frac": 0.548620748,
"autogenerated": false,
"ratio": 3.9679022293849044,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7516522977384904,
"avg_score": null,
"num_lines": null
} |
"""
Simple HyperText Markup Language document tree Writer.
The output conforms to the XHTML version 1.0 Transitional DTD
(*almost* strict). The output contains a minimum of formatting
information. The cascading style sheet "html4css1.css" is required
for proper viewing with a modern graphical browser.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import time
import re
try:
import Image # check for the Python Imaging Library
except ImportError:
Image = None
import docutils
from docutils import frontend, nodes, utils, writers, languages
from docutils.transforms import writer_aux
class Writer(writers.Writer):
supported = ('html', 'html4css1', 'xhtml')
"""Formats this writer supports."""
default_stylesheet = 'html4css1.css'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = (
'HTML-Specific Options',
None,
(('Specify the template file (UTF-8 encoded). Default is "%s".'
% default_template_path,
['--template'],
{'default': default_template_path, 'metavar': '<file>'}),
('Specify comma separated list of stylesheet URLs. '
'Overrides previous --stylesheet and --stylesheet-path settings.',
['--stylesheet'],
{'metavar': '<URL>', 'overrides': 'stylesheet_path'}),
('Specify comma separated list of stylesheet paths. '
'With --link-stylesheet, '
'the path is rewritten relative to the output HTML file. '
'Default: "%s"' % default_stylesheet_path,
['--stylesheet-path'],
{'metavar': '<file>', 'overrides': 'stylesheet',
'default': default_stylesheet_path}),
('Embed the stylesheet(s) in the output HTML file. The stylesheet '
'files must be accessible during processing. This is the default.',
['--embed-stylesheet'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Link to the stylesheet(s) in the output HTML file. '
'Default: embed stylesheets.',
['--link-stylesheet'],
{'dest': 'embed_stylesheet', 'action': 'store_false'}),
('Specify the initial header level. Default is 1 for "<h1>". '
'Does not affect document title & subtitle (see --no-doc-title).',
['--initial-header-level'],
{'choices': '1 2 3 4 5 6'.split(), 'default': '1',
'metavar': '<level>'}),
('Specify the maximum width (in characters) for one-column field '
'names. Longer field names will span an entire row of the table '
'used to render the field list. Default is 14 characters. '
'Use 0 for "no limit".',
['--field-name-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
('Specify the maximum width (in characters) for options in option '
'lists. Longer options will span an entire row of the table used '
'to render the option list. Default is 14 characters. '
'Use 0 for "no limit".',
['--option-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
('Format for footnote references: one of "superscript" or '
'"brackets". Default is "brackets".',
['--footnote-references'],
{'choices': ['superscript', 'brackets'], 'default': 'brackets',
'metavar': '<format>',
'overrides': 'trim_footnote_reference_space'}),
('Format for block quote attributions: one of "dash" (em-dash '
'prefix), "parentheses"/"parens", or "none". Default is "dash".',
['--attribution'],
{'choices': ['dash', 'parentheses', 'parens', 'none'],
'default': 'dash', 'metavar': '<format>'}),
('Remove extra vertical whitespace between items of "simple" bullet '
'lists and enumerated lists. Default: enabled.',
['--compact-lists'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compact simple bullet and enumerated lists.',
['--no-compact-lists'],
{'dest': 'compact_lists', 'action': 'store_false'}),
('Remove extra vertical whitespace between items of simple field '
'lists. Default: enabled.',
['--compact-field-lists'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compact simple field lists.',
['--no-compact-field-lists'],
{'dest': 'compact_field_lists', 'action': 'store_false'}),
('Added to standard table classes. '
'Defined styles: "borderless". Default: ""',
['--table-style'],
{'default': ''}),
('Omit the XML declaration. Use with caution.',
['--no-xml-declaration'],
{'dest': 'xml_declaration', 'default': 1, 'action': 'store_false',
'validator': frontend.validate_boolean}),
('Obfuscate email addresses to confuse harvesters while still '
'keeping email links usable with standards-compliant browsers.',
['--cloak-email-addresses'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),))
settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'}
relative_path_settings = ('stylesheet_path',)
config_section = 'html4css1 writer'
config_section_dependencies = ('writers',)
visitor_attributes = (
'head_prefix', 'head', 'stylesheet', 'body_prefix',
'body_pre_docinfo', 'docinfo', 'body', 'body_suffix',
'title', 'subtitle', 'header', 'footer', 'meta', 'fragment',
'html_prolog', 'html_head', 'html_title', 'html_subtitle',
'html_body')
def get_transforms(self):
return writers.Writer.get_transforms(self) + [writer_aux.Admonitions]
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = HTMLTranslator
def translate(self):
self.visitor = visitor = self.translator_class(self.document)
self.document.walkabout(visitor)
for attr in self.visitor_attributes:
setattr(self, attr, getattr(visitor, attr))
self.output = self.apply_template()
def apply_template(self):
template_file = open(self.document.settings.template, 'rb')
template = unicode(template_file.read(), 'utf-8')
template_file.close()
subs = self.interpolation_dict()
return template % subs
def interpolation_dict(self):
subs = {}
settings = self.document.settings
for attr in self.visitor_attributes:
subs[attr] = ''.join(getattr(self, attr)).rstrip('\n')
subs['encoding'] = settings.output_encoding
subs['version'] = docutils.__version__
return subs
def assemble_parts(self):
writers.Writer.assemble_parts(self)
for part in self.visitor_attributes:
self.parts[part] = ''.join(getattr(self, part))
class HTMLTranslator(nodes.NodeVisitor):
"""
This HTML writer has been optimized to produce visually compact
lists (less vertical whitespace). HTML's mixed content models
allow list items to contain "<li><p>body elements</p></li>" or
"<li>just text</li>" or even "<li>text<p>and body
elements</p>combined</li>", each with different effects. It would
be best to stick with strict body elements in list items, but they
affect vertical spacing in browsers (although they really
shouldn't).
Here is an outline of the optimization:
- Check for and omit <p> tags in "simple" lists: list items
contain either a single paragraph, a nested simple list, or a
paragraph followed by a nested simple list. This means that
this list can be compact:
- Item 1.
- Item 2.
But this list cannot be compact:
- Item 1.
This second paragraph forces space between list items.
- Item 2.
- In non-list contexts, omit <p> tags on a paragraph if that
paragraph is the only child of its parent (footnotes & citations
are allowed a label first).
- Regardless of the above, in definitions, table cells, field bodies,
option descriptions, and list items, mark the first child with
'class="first"' and the last child with 'class="last"'. The stylesheet
sets the margins (top & bottom respectively) to 0 for these elements.
The ``no_compact_lists`` setting (``--no-compact-lists`` command-line
option) disables list whitespace optimization.
"""
xml_declaration = '<?xml version="1.0" encoding="%s" ?>\n'
doctype = (
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
head_prefix_template = ('<html xmlns="http://www.w3.org/1999/xhtml"'
' xml:lang="%s" lang="%s">\n<head>\n')
content_type = ('<meta http-equiv="Content-Type"'
' content="text/html; charset=%s" />\n')
generator = ('<meta name="generator" content="Docutils %s: '
'http://docutils.sourceforge.net/" />\n')
stylesheet_link = '<link rel="stylesheet" href="%s" type="text/css" />\n'
embedded_stylesheet = '<style type="text/css">\n\n%s\n</style>\n'
words_and_spaces = re.compile(r'\S+| +|\n')
sollbruchstelle = re.compile(r'.+\W\W.+|[-?].+', re.U) # wrap point inside word
def __init__(self, document):
nodes.NodeVisitor.__init__(self, document)
self.settings = settings = document.settings
lcode = settings.language_code
self.language = languages.get_language(lcode)
self.meta = [self.content_type % settings.output_encoding,
self.generator % docutils.__version__]
self.head_prefix = []
self.html_prolog = []
if settings.xml_declaration:
self.head_prefix.append(self.xml_declaration
% settings.output_encoding)
# encoding not interpolated:
self.html_prolog.append(self.xml_declaration)
self.head_prefix.extend([self.doctype,
self.head_prefix_template % (lcode, lcode)])
self.html_prolog.append(self.doctype)
self.head = self.meta[:]
# stylesheets
styles = utils.get_stylesheet_list(settings)
if settings.stylesheet_path and not(settings.embed_stylesheet):
styles = [utils.relative_path(settings._destination, sheet)
for sheet in styles]
if settings.embed_stylesheet:
settings.record_dependencies.add(*styles)
self.stylesheet = [self.embedded_stylesheet %
unicode(open(sheet).read(), 'utf-8')
for sheet in styles]
else: # link to stylesheets
self.stylesheet = [self.stylesheet_link % self.encode(stylesheet)
for stylesheet in styles]
self.body_prefix = ['</head>\n<body>\n']
# document title, subtitle display
self.body_pre_docinfo = []
# author, date, etc.
self.docinfo = []
self.body = []
self.fragment = []
self.body_suffix = ['</body>\n</html>\n']
self.section_level = 0
self.initial_header_level = int(settings.initial_header_level)
# A heterogenous stack used in conjunction with the tree traversal.
# Make sure that the pops correspond to the pushes:
self.context = []
self.topic_classes = []
self.colspecs = []
self.compact_p = 1
self.compact_simple = None
self.compact_field_list = None
self.in_docinfo = None
self.in_sidebar = None
self.title = []
self.subtitle = []
self.header = []
self.footer = []
self.html_head = [self.content_type] # charset not interpolated
self.html_title = []
self.html_subtitle = []
self.html_body = []
self.in_document_title = 0
self.in_mailto = 0
self.author_in_authors = None
def astext(self):
return ''.join(self.head_prefix + self.head
+ self.stylesheet + self.body_prefix
+ self.body_pre_docinfo + self.docinfo
+ self.body + self.body_suffix)
def encode(self, text):
"""Encode special characters in `text` & return."""
# @@@ A codec to do these and all other HTML entities would be nice.
text = unicode(text)
return text.translate({
ord('&'): u'&',
ord('<'): u'<',
ord('"'): u'"',
ord('>'): u'>',
ord('@'): u'@', # may thwart some address harvesters
# TODO: convert non-breaking space only if needed?
0xa0: u' '}) # non-breaking space
def cloak_mailto(self, uri):
"""Try to hide a mailto: URL from harvesters."""
# Encode "@" using a URL octet reference (see RFC 1738).
# Further cloaking with HTML entities will be done in the
# `attval` function.
return uri.replace('@', '%40')
def cloak_email(self, addr):
"""Try to hide the link text of a email link from harversters."""
# Surround at-signs and periods with <span> tags. ("@" has
# already been encoded to "@" by the `encode` method.)
addr = addr.replace('@', '<span>@</span>')
addr = addr.replace('.', '<span>.</span>')
return addr
def attval(self, text,
whitespace=re.compile('[\n\r\t\v\f]')):
"""Cleanse, HTML encode, and return attribute value text."""
encoded = self.encode(whitespace.sub(' ', text))
if self.in_mailto and self.settings.cloak_email_addresses:
# Cloak at-signs ("%40") and periods with HTML entities.
encoded = encoded.replace('%40', '%40')
encoded = encoded.replace('.', '.')
return encoded
def starttag(self, node, tagname, suffix='\n', empty=0, **attributes):
"""
Construct and return a start tag given a node (id & class attributes
are extracted), tag name, and optional attributes.
"""
tagname = tagname.lower()
prefix = []
atts = {}
ids = []
for (name, value) in attributes.items():
atts[name.lower()] = value
classes = node.get('classes', [])
if 'class' in atts:
classes.append(atts['class'])
if classes:
atts['class'] = ' '.join(classes)
assert 'id' not in atts
ids.extend(node.get('ids', []))
if 'ids' in atts:
ids.extend(atts['ids'])
del atts['ids']
if ids:
atts['id'] = ids[0]
for id in ids[1:]:
# Add empty "span" elements for additional IDs. Note
# that we cannot use empty "a" elements because there
# may be targets inside of references, but nested "a"
# elements aren't allowed in XHTML (even if they do
# not all have a "href" attribute).
if empty:
# Empty tag. Insert target right in front of element.
prefix.append('<span id="%s"></span>' % id)
else:
# Non-empty tag. Place the auxiliary <span> tag
# *inside* the element, as the first child.
suffix += '<span id="%s"></span>' % id
attlist = atts.items()
attlist.sort()
parts = [tagname]
for name, value in attlist:
# value=None was used for boolean attributes without
# value, but this isn't supported by XHTML.
assert value is not None
if isinstance(value, list):
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
def emptytag(self, node, tagname, suffix='\n', **attributes):
"""Construct and return an XML-compatible empty tag."""
return self.starttag(node, tagname, suffix, empty=1, **attributes)
def set_class_on_child(self, node, class_, index=0):
"""
Set class `class_` on the visible child no. index of `node`.
Do nothing if node has fewer children than `index`.
"""
children = [n for n in node if not isinstance(n, nodes.Invisible)]
try:
child = children[index]
except IndexError:
return
child['classes'].append(class_)
def set_first_last(self, node):
self.set_class_on_child(node, 'first', 0)
self.set_class_on_child(node, 'last', -1)
def visit_Text(self, node):
text = node.astext()
encoded = self.encode(text)
if self.in_mailto and self.settings.cloak_email_addresses:
encoded = self.cloak_email(encoded)
self.body.append(encoded)
def depart_Text(self, node):
pass
def visit_abbreviation(self, node):
# @@@ implementation incomplete ("title" attribute)
self.body.append(self.starttag(node, 'abbr', ''))
def depart_abbreviation(self, node):
self.body.append('</abbr>')
def visit_acronym(self, node):
# @@@ implementation incomplete ("title" attribute)
self.body.append(self.starttag(node, 'acronym', ''))
def depart_acronym(self, node):
self.body.append('</acronym>')
def visit_address(self, node):
self.visit_docinfo_item(node, 'address', meta=None)
self.body.append(self.starttag(node, 'pre', CLASS='address'))
def depart_address(self, node):
self.body.append('\n</pre>\n')
self.depart_docinfo_item()
def visit_admonition(self, node):
self.body.append(self.starttag(node, 'div'))
self.set_first_last(node)
def depart_admonition(self, node=None):
self.body.append('</div>\n')
attribution_formats = {'dash': ('—', ''),
'parentheses': ('(', ')'),
'parens': ('(', ')'),
'none': ('', '')}
def visit_attribution(self, node):
prefix, suffix = self.attribution_formats[self.settings.attribution]
self.context.append(suffix)
self.body.append(
self.starttag(node, 'p', prefix, CLASS='attribution'))
def depart_attribution(self, node):
self.body.append(self.context.pop() + '</p>\n')
def visit_author(self, node):
if isinstance(node.parent, nodes.authors):
if self.author_in_authors:
self.body.append('\n<br />')
else:
self.visit_docinfo_item(node, 'author')
def depart_author(self, node):
if isinstance(node.parent, nodes.authors):
self.author_in_authors += 1
else:
self.depart_docinfo_item()
def visit_authors(self, node):
self.visit_docinfo_item(node, 'authors')
self.author_in_authors = 0 # initialize counter
def depart_authors(self, node):
self.depart_docinfo_item()
self.author_in_authors = None
def visit_block_quote(self, node):
self.body.append(self.starttag(node, 'blockquote'))
def depart_block_quote(self, node):
self.body.append('</blockquote>\n')
def check_simple_list(self, node):
"""Check for a simple list that can be rendered compactly."""
visitor = SimpleListChecker(self.document)
try:
node.walk(visitor)
except nodes.NodeFound:
return None
else:
return 1
def is_compactable(self, node):
return ('compact' in node['classes']
or (self.settings.compact_lists
and 'open' not in node['classes']
and (self.compact_simple
or self.topic_classes == ['contents']
or self.check_simple_list(node))))
def visit_bullet_list(self, node):
atts = {}
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'] = 'simple'
self.body.append(self.starttag(node, 'ul', **atts))
def depart_bullet_list(self, node):
self.compact_simple, self.compact_p = self.context.pop()
self.body.append('</ul>\n')
def visit_caption(self, node):
self.body.append(self.starttag(node, 'p', '', CLASS='caption'))
def depart_caption(self, node):
self.body.append('</p>\n')
def visit_citation(self, node):
self.body.append(self.starttag(node, 'table',
CLASS='docutils citation',
frame="void", rules="none"))
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n'
'<tbody valign="top">\n'
'<tr>')
self.footnote_backrefs(node)
def depart_citation(self, node):
self.body.append('</td></tr>\n'
'</tbody>\n</table>\n')
def visit_citation_reference(self, node):
href = '#' + node['refid']
self.body.append(self.starttag(
node, 'a', '[', CLASS='citation-reference', href=href))
def depart_citation_reference(self, node):
self.body.append(']</a>')
def visit_classifier(self, node):
self.body.append(' <span class="classifier-delimiter">:</span> ')
self.body.append(self.starttag(node, 'span', '', CLASS='classifier'))
def depart_classifier(self, node):
self.body.append('</span>')
def visit_colspec(self, node):
self.colspecs.append(node)
# "stubs" list is an attribute of the tgroup element:
node.parent.stubs.append(node.attributes.get('stub'))
def depart_colspec(self, node):
pass
def write_colspecs(self):
width = 0
for node in self.colspecs:
width += node['colwidth']
for node in self.colspecs:
colwidth = int(node['colwidth'] * 100.0 / width + 0.5)
self.body.append(self.emptytag(node, 'col',
width='%i%%' % colwidth))
self.colspecs = []
def visit_comment(self, node,
sub=re.compile('-(?=-)').sub):
"""Escape double-dashes in comment text."""
self.body.append('<!-- %s -->\n' % sub('- ', node.astext()))
# Content already processed:
raise nodes.SkipNode
def visit_compound(self, node):
self.body.append(self.starttag(node, 'div', CLASS='compound'))
if len(node) > 1:
node[0]['classes'].append('compound-first')
node[-1]['classes'].append('compound-last')
for child in node[1:-1]:
child['classes'].append('compound-middle')
def depart_compound(self, node):
self.body.append('</div>\n')
def visit_container(self, node):
self.body.append(self.starttag(node, 'div', CLASS='container'))
def depart_container(self, node):
self.body.append('</div>\n')
def visit_contact(self, node):
self.visit_docinfo_item(node, 'contact', meta=None)
def depart_contact(self, node):
self.depart_docinfo_item()
def visit_copyright(self, node):
self.visit_docinfo_item(node, 'copyright')
def depart_copyright(self, node):
self.depart_docinfo_item()
def visit_date(self, node):
self.visit_docinfo_item(node, 'date')
def depart_date(self, node):
self.depart_docinfo_item()
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
self.body.append('</dt>\n')
self.body.append(self.starttag(node, 'dd', ''))
self.set_first_last(node)
def depart_definition(self, node):
self.body.append('</dd>\n')
def visit_definition_list(self, node):
self.body.append(self.starttag(node, 'dl', CLASS='docutils'))
def depart_definition_list(self, node):
self.body.append('</dl>\n')
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_description(self, node):
self.body.append(self.starttag(node, 'td', ''))
self.set_first_last(node)
def depart_description(self, node):
self.body.append('</td>')
def visit_docinfo(self, node):
self.context.append(len(self.body))
self.body.append(self.starttag(node, 'table',
CLASS='docinfo',
frame="void", rules="none"))
self.body.append('<col class="docinfo-name" />\n'
'<col class="docinfo-content" />\n'
'<tbody valign="top">\n')
self.in_docinfo = 1
def depart_docinfo(self, node):
self.body.append('</tbody>\n</table>\n')
self.in_docinfo = None
start = self.context.pop()
self.docinfo = self.body[start:]
self.body = []
def visit_docinfo_item(self, node, name, meta=1):
if meta:
meta_tag = '<meta name="%s" content="%s" />\n' \
% (name, self.attval(node.astext()))
self.add_meta(meta_tag)
self.body.append(self.starttag(node, 'tr', ''))
self.body.append('<th class="docinfo-name">%s:</th>\n<td>'
% self.language.labels[name])
if len(node):
if isinstance(node[0], nodes.Element):
node[0]['classes'].append('first')
if isinstance(node[-1], nodes.Element):
node[-1]['classes'].append('last')
def depart_docinfo_item(self):
self.body.append('</td></tr>\n')
def visit_doctest_block(self, node):
self.body.append(self.starttag(node, 'pre', CLASS='doctest-block'))
def depart_doctest_block(self, node):
self.body.append('\n</pre>\n')
def visit_document(self, node):
self.head.append('<title>%s</title>\n'
% self.encode(node.get('title', '')))
def depart_document(self, node):
self.fragment.extend(self.body)
self.body_prefix.append(self.starttag(node, 'div', CLASS='document'))
self.body_suffix.insert(0, '</div>\n')
# skip content-type meta tag with interpolated charset value:
self.html_head.extend(self.head[1:])
self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
+ self.docinfo + self.body
+ self.body_suffix[:-1])
assert not self.context, 'len(context) = %s' % len(self.context)
def visit_emphasis(self, node):
self.body.append(self.starttag(node, 'em', ''))
def depart_emphasis(self, node):
self.body.append('</em>')
def visit_entry(self, node):
atts = {'class': []}
if isinstance(node.parent.parent, nodes.thead):
atts['class'].append('head')
if node.parent.parent.parent.stubs[node.parent.column]:
# "stubs" list is an attribute of the tgroup element
atts['class'].append('stub')
if atts['class']:
tagname = 'th'
atts['class'] = ' '.join(atts['class'])
else:
tagname = 'td'
del atts['class']
node.parent.column += 1
if 'morerows' in node:
atts['rowspan'] = node['morerows'] + 1
if 'morecols' in node:
atts['colspan'] = node['morecols'] + 1
node.parent.column += node['morecols']
self.body.append(self.starttag(node, tagname, '', **atts))
self.context.append('</%s>\n' % tagname.lower())
if len(node) == 0: # empty cell
self.body.append(' ')
self.set_first_last(node)
def depart_entry(self, node):
self.body.append(self.context.pop())
def visit_enumerated_list(self, node):
"""
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.
"""
atts = {}
if 'start' in node:
atts['start'] = node['start']
if 'enumtype' in node:
atts['class'] = node['enumtype']
# @@@ To do: prefix, suffix. How? Change prefix/suffix to a
# single "format" attribute? Use CSS2?
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))
def depart_enumerated_list(self, node):
self.compact_simple, self.compact_p = self.context.pop()
self.body.append('</ol>\n')
def visit_field(self, node):
self.body.append(self.starttag(node, 'tr', '', CLASS='field'))
def depart_field(self, node):
self.body.append('</tr>\n')
def visit_field_body(self, node):
self.body.append(self.starttag(node, 'td', '', CLASS='field-body'))
self.set_class_on_child(node, 'first', 0)
field = node.parent
if (self.compact_field_list or
isinstance(field.parent, nodes.docinfo) or
field.parent.index(field) == len(field.parent) - 1):
# If we are in a compact list, the docinfo, or if this is
# the last field of the field list, do not add vertical
# space after last element.
self.set_class_on_child(node, 'last', -1)
def depart_field_body(self, node):
self.body.append('</td>\n')
def visit_field_list(self, node):
self.context.append((self.compact_field_list, self.compact_p))
self.compact_p = None
if 'compact' in node['classes']:
self.compact_field_list = 1
elif (self.settings.compact_field_lists
and 'open' not in node['classes']):
self.compact_field_list = 1
if self.compact_field_list:
for field in node:
field_body = field[-1]
assert isinstance(field_body, nodes.field_body)
children = [n for n in field_body
if not isinstance(n, nodes.Invisible)]
if not (len(children) == 0 or
len(children) == 1 and
isinstance(children[0],
(nodes.paragraph, nodes.line_block))):
self.compact_field_list = 0
break
self.body.append(self.starttag(node, 'table', frame='void',
rules='none',
CLASS='docutils field-list'))
self.body.append('<col class="field-name" />\n'
'<col class="field-body" />\n'
'<tbody valign="top">\n')
def depart_field_list(self, node):
self.body.append('</tbody>\n</table>\n')
self.compact_field_list, self.compact_p = self.context.pop()
def visit_field_name(self, node):
atts = {}
if self.in_docinfo:
atts['class'] = 'docinfo-name'
else:
atts['class'] = 'field-name'
if ( self.settings.field_name_limit
and len(node.astext()) > self.settings.field_name_limit):
atts['colspan'] = 2
self.context.append('</tr>\n<tr><td> </td>')
else:
self.context.append('')
self.body.append(self.starttag(node, 'th', '', **atts))
def depart_field_name(self, node):
self.body.append(':</th>')
self.body.append(self.context.pop())
def visit_figure(self, node):
atts = {'class': 'figure'}
if node.get('width'):
atts['style'] = 'width: %s' % node['width']
if node.get('align'):
atts['class'] += " align-" + node['align']
self.body.append(self.starttag(node, 'div', **atts))
def depart_figure(self, node):
self.body.append('</div>\n')
def visit_footer(self, node):
self.context.append(len(self.body))
def depart_footer(self, node):
start = self.context.pop()
footer = [self.starttag(node, 'div', CLASS='footer'),
'<hr class="footer" />\n']
footer.extend(self.body[start:])
footer.append('\n</div>\n')
self.footer.extend(footer)
self.body_suffix[:0] = footer
del self.body[start:]
def visit_footnote(self, node):
self.body.append(self.starttag(node, 'table',
CLASS='docutils footnote',
frame="void", rules="none"))
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n'
'<tbody valign="top">\n'
'<tr>')
self.footnote_backrefs(node)
def footnote_backrefs(self, node):
backlinks = []
backrefs = node['backrefs']
if self.settings.footnote_backlinks and backrefs:
if len(backrefs) == 1:
self.context.append('')
self.context.append('</a>')
self.context.append('<a class="fn-backref" href="#%s">'
% backrefs[0])
else:
i = 1
for backref in backrefs:
backlinks.append('<a class="fn-backref" href="#%s">%s</a>'
% (backref, i))
i += 1
self.context.append('<em>(%s)</em> ' % ', '.join(backlinks))
self.context += ['', '']
else:
self.context.append('')
self.context += ['', '']
# If the node does not only consist of a label.
if len(node) > 1:
# If there are preceding backlinks, we do not set class
# 'first', because we need to retain the top-margin.
if not backlinks:
node[1]['classes'].append('first')
node[-1]['classes'].append('last')
def depart_footnote(self, node):
self.body.append('</td></tr>\n'
'</tbody>\n</table>\n')
def visit_footnote_reference(self, node):
href = '#' + node['refid']
format = self.settings.footnote_references
if format == 'brackets':
suffix = '['
self.context.append(']')
else:
assert format == 'superscript'
suffix = '<sup>'
self.context.append('</sup>')
self.body.append(self.starttag(node, 'a', suffix,
CLASS='footnote-reference', href=href))
def depart_footnote_reference(self, node):
self.body.append(self.context.pop() + '</a>')
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def visit_header(self, node):
self.context.append(len(self.body))
def depart_header(self, node):
start = self.context.pop()
header = [self.starttag(node, 'div', CLASS='header')]
header.extend(self.body[start:])
header.append('\n<hr class="header"/>\n</div>\n')
self.body_prefix.extend(header)
self.header.extend(header)
del self.body[start:]
def visit_image(self, node):
atts = {}
atts['src'] = node['uri']
if 'width' in node:
atts['width'] = node['width']
if 'height' in node:
atts['height'] = node['height']
if 'scale' in node:
if Image and not ('width' in node
and 'height' in node):
try:
im = Image.open(str(atts['src']))
except (IOError, # Source image can't be found or opened
UnicodeError): # PIL doesn't like Unicode paths.
pass
else:
if 'width' not in atts:
atts['width'] = str(im.size[0])
if 'height' not in atts:
atts['height'] = str(im.size[1])
del im
for att_name in 'width', 'height':
if att_name in atts:
match = re.match(r'([0-9.]+)(\S*)$', atts[att_name])
assert match
atts[att_name] = '%s%s' % (
float(match.group(1)) * (float(node['scale']) / 100),
match.group(2))
style = []
for att_name in 'width', 'height':
if att_name in atts:
if re.match(r'^[0-9.]+$', atts[att_name]):
# Interpret unitless values as pixels.
atts[att_name] += 'px'
style.append('%s: %s;' % (att_name, atts[att_name]))
del atts[att_name]
if style:
atts['style'] = ' '.join(style)
atts['alt'] = node.get('alt', atts['src'])
if (isinstance(node.parent, nodes.TextElement) or
(isinstance(node.parent, nodes.reference) and
not isinstance(node.parent.parent, nodes.TextElement))):
# Inline context or surrounded by <a>...</a>.
suffix = ''
else:
suffix = '\n'
if 'classes' in node and 'align-center' in node['classes']:
node['align'] = 'center'
if 'align' in node:
if node['align'] == 'center':
# "align" attribute is set in surrounding "div" element.
self.body.append('<div align="center" class="align-center">')
self.context.append('</div>\n')
suffix = ''
else:
# "align" attribute is set in "img" element.
atts['align'] = node['align']
self.context.append('')
atts['class'] = 'align-%s' % node['align']
else:
self.context.append('')
self.body.append(self.emptytag(node, 'img', suffix, **atts))
def depart_image(self, node):
self.body.append(self.context.pop())
def visit_inline(self, node):
self.body.append(self.starttag(node, 'span', ''))
def depart_inline(self, node):
self.body.append('</span>')
def visit_label(self, node):
# Context added in footnote_backrefs.
self.body.append(self.starttag(node, 'td', '%s[' % self.context.pop(),
CLASS='label'))
def depart_label(self, node):
# Context added in footnote_backrefs.
self.body.append(']%s</td><td>%s' % (self.context.pop(), self.context.pop()))
def visit_legend(self, node):
self.body.append(self.starttag(node, 'div', CLASS='legend'))
def depart_legend(self, node):
self.body.append('</div>\n')
def visit_line(self, node):
self.body.append(self.starttag(node, 'div', suffix='', CLASS='line'))
if not len(node):
self.body.append('<br />')
def depart_line(self, node):
self.body.append('</div>\n')
def visit_line_block(self, node):
self.body.append(self.starttag(node, 'div', CLASS='line-block'))
def depart_line_block(self, node):
self.body.append('</div>\n')
def visit_list_item(self, node):
self.body.append(self.starttag(node, 'li', ''))
if len(node):
node[0]['classes'].append('first')
def depart_list_item(self, node):
self.body.append('</li>\n')
def visit_literal(self, node):
"""Process text to prevent tokens from wrapping."""
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():
# Protect text like "--an-option" and the regular expression
# ``[+]?(\d+(\.\d*)?|\.\d+)`` from bad line wrapping
if self.sollbruchstelle.search(token):
self.body.append('<span class="pre">%s</span>'
% self.encode(token))
else:
self.body.append(self.encode(token))
elif token in ('\n', ' '):
# Allow breaks at whitespace:
self.body.append(token)
else:
# Protect runs of multiple spaces; the last space can wrap:
self.body.append(' ' * (len(token) - 1) + ' ')
self.body.append('</tt>')
# Content already processed:
raise nodes.SkipNode
def visit_literal_block(self, node):
self.body.append(self.starttag(node, 'pre', CLASS='literal-block'))
def depart_literal_block(self, node):
self.body.append('\n</pre>\n')
def visit_meta(self, node):
meta = self.emptytag(node, 'meta', **node.non_default_attributes())
self.add_meta(meta)
def depart_meta(self, node):
pass
def add_meta(self, tag):
self.meta.append(tag)
self.head.append(tag)
def visit_option(self, node):
if self.context[-1]:
self.body.append(', ')
self.body.append(self.starttag(node, 'span', '', CLASS='option'))
def depart_option(self, node):
self.body.append('</span>')
self.context[-1] += 1
def visit_option_argument(self, node):
self.body.append(node.get('delimiter', ' '))
self.body.append(self.starttag(node, 'var', ''))
def depart_option_argument(self, node):
self.body.append('</var>')
def visit_option_group(self, node):
atts = {}
if ( self.settings.option_limit
and len(node.astext()) > self.settings.option_limit):
atts['colspan'] = 2
self.context.append('</tr>\n<tr><td> </td>')
else:
self.context.append('')
self.body.append(
self.starttag(node, 'td', CLASS='option-group', **atts))
self.body.append('<kbd>')
self.context.append(0) # count number of options
def depart_option_group(self, node):
self.context.pop()
self.body.append('</kbd></td>\n')
self.body.append(self.context.pop())
def visit_option_list(self, node):
self.body.append(
self.starttag(node, 'table', CLASS='docutils option-list',
frame="void", rules="none"))
self.body.append('<col class="option" />\n'
'<col class="description" />\n'
'<tbody valign="top">\n')
def depart_option_list(self, node):
self.body.append('</tbody>\n</table>\n')
def visit_option_list_item(self, node):
self.body.append(self.starttag(node, 'tr', ''))
def depart_option_list_item(self, node):
self.body.append('</tr>\n')
def visit_option_string(self, node):
pass
def depart_option_string(self, node):
pass
def visit_organization(self, node):
self.visit_docinfo_item(node, 'organization')
def depart_organization(self, node):
self.depart_docinfo_item()
def should_be_compact_paragraph(self, node):
"""
Determine if the <p> tags around paragraph ``node`` can be omitted.
"""
if (isinstance(node.parent, nodes.document) or
isinstance(node.parent, nodes.compound)):
# Never compact paragraphs in document or 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']))):
# Attribute which needs to survive.
return 0
first = isinstance(node.parent[0], nodes.label) # skip label
for child in node.parent.children[first:]:
# only first paragraph can be compact
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
def visit_paragraph(self, node):
if self.should_be_compact_paragraph(node):
self.context.append('')
else:
self.body.append(self.starttag(node, 'p', ''))
self.context.append('</p>\n')
def depart_paragraph(self, node):
self.body.append(self.context.pop())
def visit_problematic(self, node):
if node.hasattr('refid'):
self.body.append('<a href="#%s">' % node['refid'])
self.context.append('</a>')
else:
self.context.append('')
self.body.append(self.starttag(node, 'span', '', CLASS='problematic'))
def depart_problematic(self, node):
self.body.append('</span>')
self.body.append(self.context.pop())
def visit_raw(self, node):
if 'html' in node.get('format', '').split():
t = isinstance(node.parent, nodes.TextElement) and 'span' or 'div'
if node['classes']:
self.body.append(self.starttag(node, t, suffix=''))
self.body.append(node.astext())
if node['classes']:
self.body.append('</%s>' % t)
# Keep non-HTML raw text out of output:
raise nodes.SkipNode
def visit_reference(self, node):
atts = {'class': 'reference'}
if 'refuri' in node:
atts['href'] = node['refuri']
if ( self.settings.cloak_email_addresses
and atts['href'].startswith('mailto:')):
atts['href'] = self.cloak_mailto(atts['href'])
self.in_mailto = 1
atts['class'] += ' external'
else:
assert 'refid' in node, \
'References must have "refuri" or "refid" attribute.'
atts['href'] = '#' + node['refid']
atts['class'] += ' internal'
if not isinstance(node.parent, nodes.TextElement):
assert len(node) == 1 and isinstance(node[0], nodes.image)
atts['class'] += ' image-reference'
self.body.append(self.starttag(node, 'a', '', **atts))
def depart_reference(self, node):
self.body.append('</a>')
if not isinstance(node.parent, nodes.TextElement):
self.body.append('\n')
self.in_mailto = 0
def visit_revision(self, node):
self.visit_docinfo_item(node, 'revision', meta=None)
def depart_revision(self, node):
self.depart_docinfo_item()
def visit_row(self, node):
self.body.append(self.starttag(node, 'tr', ''))
node.column = 0
def depart_row(self, node):
self.body.append('</tr>\n')
def visit_rubric(self, node):
self.body.append(self.starttag(node, 'p', '', CLASS='rubric'))
def depart_rubric(self, node):
self.body.append('</p>\n')
def visit_section(self, node):
self.section_level += 1
self.body.append(
self.starttag(node, 'div', CLASS='section'))
def depart_section(self, node):
self.section_level -= 1
self.body.append('</div>\n')
def visit_sidebar(self, node):
self.body.append(
self.starttag(node, 'div', CLASS='sidebar'))
self.set_first_last(node)
self.in_sidebar = 1
def depart_sidebar(self, node):
self.body.append('</div>\n')
self.in_sidebar = None
def visit_status(self, node):
self.visit_docinfo_item(node, 'status', meta=None)
def depart_status(self, node):
self.depart_docinfo_item()
def visit_strong(self, node):
self.body.append(self.starttag(node, 'strong', ''))
def depart_strong(self, node):
self.body.append('</strong>')
def visit_subscript(self, node):
self.body.append(self.starttag(node, 'sub', ''))
def depart_subscript(self, node):
self.body.append('</sub>')
def visit_substitution_definition(self, node):
"""Internal only."""
raise nodes.SkipNode
def visit_substitution_reference(self, node):
self.unimplemented_visit(node)
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.sidebar):
self.body.append(self.starttag(node, 'p', '',
CLASS='sidebar-subtitle'))
self.context.append('</p>\n')
elif isinstance(node.parent, nodes.document):
self.body.append(self.starttag(node, 'h2', '', CLASS='subtitle'))
self.context.append('</h2>\n')
self.in_document_title = len(self.body)
elif isinstance(node.parent, nodes.section):
tag = 'h%s' % (self.section_level + self.initial_header_level - 1)
self.body.append(
self.starttag(node, tag, '', CLASS='section-subtitle') +
self.starttag({}, 'span', '', CLASS='section-subtitle'))
self.context.append('</span></%s>\n' % tag)
def depart_subtitle(self, node):
self.body.append(self.context.pop())
if self.in_document_title:
self.subtitle = self.body[self.in_document_title:-1]
self.in_document_title = 0
self.body_pre_docinfo.extend(self.body)
self.html_subtitle.extend(self.body)
del self.body[:]
def visit_superscript(self, node):
self.body.append(self.starttag(node, 'sup', ''))
def depart_superscript(self, node):
self.body.append('</sup>')
def visit_system_message(self, node):
self.body.append(self.starttag(node, 'div', CLASS='system-message'))
self.body.append('<p class="system-message-title">')
backref_text = ''
if len(node['backrefs']):
backrefs = node['backrefs']
if len(backrefs) == 1:
backref_text = ('; <em><a href="#%s">backlink</a></em>'
% backrefs[0])
else:
i = 1
backlinks = []
for backref in backrefs:
backlinks.append('<a href="#%s">%s</a>' % (backref, i))
i += 1
backref_text = ('; <em>backlinks: %s</em>'
% ', '.join(backlinks))
if node.hasattr('line'):
line = ', line %s' % node['line']
else:
line = ''
self.body.append('System Message: %s/%s '
'(<tt class="docutils">%s</tt>%s)%s</p>\n'
% (node['type'], node['level'],
self.encode(node['source']), line, backref_text))
def depart_system_message(self, node):
self.body.append('</div>\n')
def visit_table(self, node):
classes = ' '.join(['docutils', self.settings.table_style]).strip()
self.body.append(
self.starttag(node, 'table', CLASS=classes, border="1"))
def depart_table(self, node):
self.body.append('</table>\n')
def visit_target(self, node):
if not ('refuri' in node or 'refid' in node
or 'refname' in node):
self.body.append(self.starttag(node, 'span', '', CLASS='target'))
self.context.append('</span>')
else:
self.context.append('')
def depart_target(self, node):
self.body.append(self.context.pop())
def visit_tbody(self, node):
self.write_colspecs()
self.body.append(self.context.pop()) # '</colgroup>\n' or ''
self.body.append(self.starttag(node, 'tbody', valign='top'))
def depart_tbody(self, node):
self.body.append('</tbody>\n')
def visit_term(self, node):
self.body.append(self.starttag(node, 'dt', ''))
def depart_term(self, node):
"""
Leave the end tag to `self.visit_definition()`, in case there's a
classifier.
"""
pass
def visit_tgroup(self, node):
# Mozilla needs <colgroup>:
self.body.append(self.starttag(node, 'colgroup'))
# Appended by thead or tbody:
self.context.append('</colgroup>\n')
node.stubs = []
def depart_tgroup(self, node):
pass
def visit_thead(self, node):
self.write_colspecs()
self.body.append(self.context.pop()) # '</colgroup>\n'
# There may or may not be a <thead>; this is for <tbody> to use:
self.context.append('')
self.body.append(self.starttag(node, 'thead', valign='bottom'))
def depart_thead(self, node):
self.body.append('</thead>\n')
def visit_title(self, node):
"""Only 6 section levels are supported by HTML."""
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)
def depart_title(self, node):
self.body.append(self.context.pop())
if self.in_document_title:
self.title = self.body[self.in_document_title:-1]
self.in_document_title = 0
self.body_pre_docinfo.extend(self.body)
self.html_title.extend(self.body)
del self.body[:]
def visit_title_reference(self, node):
self.body.append(self.starttag(node, 'cite', ''))
def depart_title_reference(self, node):
self.body.append('</cite>')
def visit_topic(self, node):
self.body.append(self.starttag(node, 'div', CLASS='topic'))
self.topic_classes = node['classes']
def depart_topic(self, node):
self.body.append('</div>\n')
self.topic_classes = []
def visit_transition(self, node):
self.body.append(self.emptytag(node, 'hr', CLASS='docutils'))
def depart_transition(self, node):
pass
def visit_version(self, node):
self.visit_docinfo_item(node, 'version', meta=None)
def depart_version(self, node):
self.depart_docinfo_item()
def unimplemented_visit(self, node):
raise NotImplementedError('visiting unimplemented node type: %s'
% node.__class__.__name__)
class SimpleListChecker(nodes.GenericNodeVisitor):
"""
Raise `nodes.NodeFound` if non-simple list item is encountered.
Here "simple" means a list item containing nothing other than a single
paragraph, a simple list, or a paragraph followed by a simple list.
"""
def default_visit(self, node):
raise nodes.NodeFound
def visit_bullet_list(self, node):
pass
def visit_enumerated_list(self, node):
pass
def visit_list_item(self, node):
children = []
for child in node.children:
if not isinstance(child, nodes.Invisible):
children.append(child)
if (children and isinstance(children[0], nodes.paragraph)
and (isinstance(children[-1], nodes.bullet_list)
or isinstance(children[-1], nodes.enumerated_list))):
children.pop()
if len(children) <= 1:
return
else:
raise nodes.NodeFound
def visit_paragraph(self, node):
raise nodes.SkipNode
def invisible_visit(self, node):
"""Invisible nodes should be ignored."""
raise nodes.SkipNode
visit_comment = invisible_visit
visit_substitution_definition = invisible_visit
visit_target = invisible_visit
visit_pending = invisible_visit
| {
"repo_name": "rimbalinux/LMD3",
"path": "docutils/writers/html4css1/__init__.py",
"copies": "2",
"size": "60641",
"license": "bsd-3-clause",
"hash": -7689416582410206000,
"line_mean": 37.0980012895,
"line_max": 85,
"alpha_frac": 0.5345888096,
"autogenerated": false,
"ratio": 4.051646956637937,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00021916854121389122,
"num_lines": 1551
} |
"""
This is the Docutils (Python Documentation Utilities) package.
Package Structure
=================
Modules:
- __init__.py: Contains component base classes, exception classes, and
Docutils version information.
- core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience
functions.
- frontend.py: Runtime settings (command-line interface, configuration files)
processing, for Docutils front-ends.
- io.py: Provides a uniform API for low-level input and output.
- nodes.py: Docutils document tree (doctree) node class library.
- statemachine.py: A finite state machine specialized for
regular-expression-based text filters.
- urischemes.py: Contains a complete mapping of known URI addressing
scheme names to descriptions.
- utils.py: Contains the ``Reporter`` system warning class and miscellaneous
utilities.
Subpackages:
- languages: Language-specific mappings of terms.
- parsers: Syntax-specific input parser modules or packages.
- readers: Context-specific input handlers which understand the data
source and manage a parser.
- transforms: Modules used by readers and writers to modify DPS
doctrees.
- writers: Format-specific output translators.
"""
__docformat__ = 'reStructuredText'
__version__ = '0.6'
"""``major.minor.micro`` version number. The micro number is bumped for API
changes, for new functionality, and for interim project releases. The minor
number is bumped whenever there is a significant project release. The major
number will be bumped when the project is feature-complete, and perhaps if
there is a major change in the design."""
__version_details__ = 'release'
"""Extra version details (e.g. 'snapshot 2005-05-29, r3410', 'repository',
'release'), modified automatically & manually."""
class ApplicationError(StandardError): pass
class DataError(ApplicationError): pass
class SettingsSpec:
"""
Runtime setting specification base class.
SettingsSpec subclass objects used by `docutils.frontend.OptionParser`.
"""
settings_spec = ()
"""Runtime settings specification. Override in subclasses.
Defines runtime settings and associated command-line options, as used by
`docutils.frontend.OptionParser`. This is a tuple of:
- Option group title (string or `None` which implies no group, just a list
of single options).
- Description (string or `None`).
- A sequence of option tuples. Each consists of:
- Help text (string)
- List of option strings (e.g. ``['-Q', '--quux']``).
- Dictionary of keyword arguments sent to the OptionParser/OptionGroup
``add_option`` method.
Runtime setting names are derived implicitly from long option names
('--a-setting' becomes ``settings.a_setting``) or explicitly from the
'dest' keyword argument.
Most settings will also have a 'validator' keyword & function. The
validator function validates setting values (from configuration files
and command-line option arguments) and converts them to appropriate
types. For example, the ``docutils.frontend.validate_boolean``
function, **required by all boolean settings**, converts true values
('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off',
'no', 'false', and '') to 0. Validators need only be set once per
setting. See the `docutils.frontend.validate_*` functions.
See the optparse docs for more details.
- More triples of group title, description, options, as many times as
needed. Thus, `settings_spec` tuples can be simply concatenated.
"""
settings_defaults = None
"""A dictionary of defaults for settings not in `settings_spec` (internal
settings, intended to be inaccessible by command-line and config file).
Override in subclasses."""
settings_default_overrides = None
"""A dictionary of auxiliary defaults, to override defaults for settings
defined in other components. Override in subclasses."""
relative_path_settings = ()
"""Settings containing filesystem paths. Override in subclasses.
Settings listed here are to be interpreted relative to the current working
directory."""
config_section = None
"""The name of the config file section specific to this component
(lowercase, no brackets). Override in subclasses."""
config_section_dependencies = None
"""A list of names of config file sections that are to be applied before
`config_section`, in order (from general to specific). In other words,
the settings in `config_section` are to be overlaid on top of the settings
from these sections. The "general" section is assumed implicitly.
Override in subclasses."""
class TransformSpec:
"""
Runtime transform specification base class.
TransformSpec subclass objects used by `docutils.transforms.Transformer`.
"""
def get_transforms(self):
"""Transforms required by this class. Override in subclasses."""
if self.default_transforms != ():
import warnings
warnings.warn('default_transforms attribute deprecated.\n'
'Use get_transforms() method instead.',
DeprecationWarning)
return list(self.default_transforms)
return []
# Deprecated; for compatibility.
default_transforms = ()
unknown_reference_resolvers = ()
"""List of functions to try to resolve unknown references. Unknown
references have a 'refname' attribute which doesn't correspond to any
target in the document. Called when the transforms in
`docutils.tranforms.references` are unable to find a correct target. The
list should contain functions which will try to resolve unknown
references, with the following signature::
def reference_resolver(node):
'''Returns boolean: true if resolved, false if not.'''
If the function is able to resolve the reference, it should also remove
the 'refname' attribute and mark the node as resolved::
del node['refname']
node.resolved = 1
Each function must have a "priority" attribute which will affect the order
the unknown_reference_resolvers are run::
reference_resolver.priority = 100
Override in subclasses."""
class Component(SettingsSpec, TransformSpec):
"""Base class for Docutils components."""
component_type = None
"""Name of the component type ('reader', 'parser', 'writer'). Override in
subclasses."""
supported = ()
"""Names for this component. Override in subclasses."""
def supports(self, format):
"""
Is `format` supported by this component?
To be used by transforms to ask the dependent component if it supports
a certain input context or output format.
"""
return format in self.supported
| {
"repo_name": "edisonlz/fruit",
"path": "web_project/base/site-packages/docutils/__init__.py",
"copies": "6",
"size": "7083",
"license": "apache-2.0",
"hash": 2103470691239159000,
"line_mean": 33.7205882353,
"line_max": 78,
"alpha_frac": 0.6970210363,
"autogenerated": false,
"ratio": 4.578539107950872,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8275560144250872,
"avg_score": null,
"num_lines": null
} |
"""
This is ``docutils.parsers.rst`` package. It exports a single class, `Parser`,
the reStructuredText parser.
Usage
=====
1. Create a parser::
parser = docutils.parsers.rst.Parser()
Several optional arguments may be passed to modify the parser's behavior.
Please see `Customizing the Parser`_ below for details.
2. Gather input (a multi-line string), by reading a file or the standard
input::
input = sys.stdin.read()
3. Create a new empty `docutils.nodes.document` tree::
document = docutils.utils.new_document(source, settings)
See `docutils.utils.new_document()` for parameter details.
4. Run the parser, populating the document tree::
parser.parse(input, document)
Parser Overview
===============
The reStructuredText parser is implemented as a state machine, examining its
input one line at a time. To understand how the parser works, please first
become familiar with the `docutils.statemachine` module, then see the
`states` module.
Customizing the Parser
----------------------
Anything that isn't already customizable is that way simply because that type
of customizability hasn't been implemented yet. Patches welcome!
When instantiating an object of the `Parser` class, two parameters may be
passed: ``rfc2822`` and ``inliner``. Pass ``rfc2822=1`` to enable an initial
RFC-2822 style header block, parsed as a "field_list" element (with "class"
attribute set to "rfc2822"). Currently this is the only body-level element
which is customizable without subclassing. (Tip: subclass `Parser` and change
its "state_classes" and "initial_state" attributes to refer to new classes.
Contact the author if you need more details.)
The ``inliner`` parameter takes an instance of `states.Inliner` or a subclass.
It handles inline markup recognition. A common extension is the addition of
further implicit hyperlinks, like "RFC 2822". This can be done by subclassing
`states.Inliner`, adding a new method for the implicit markup, and adding a
``(pattern, method)`` pair to the "implicit_dispatch" attribute of the
subclass. See `states.Inliner.implicit_inline()` for details. Explicit
inline markup can be customized in a `states.Inliner` subclass via the
``patterns.initial`` and ``dispatch`` attributes (and new methods as
appropriate).
"""
__docformat__ = 'reStructuredText'
import docutils.parsers
import docutils.statemachine
from docutils.parsers.rst import states
from docutils import frontend, nodes
class Parser(docutils.parsers.Parser):
"""The reStructuredText parser."""
supported = ('restructuredtext', 'rst', 'rest', 'restx', 'rtxt', 'rstx')
"""Aliases this parser supports."""
settings_spec = (
'reStructuredText Parser Options',
None,
(('Recognize and link to standalone PEP references (like "PEP 258").',
['--pep-references'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Base URL for PEP references '
'(default "http://www.python.org/dev/peps/").',
['--pep-base-url'],
{'metavar': '<URL>', 'default': 'http://www.python.org/dev/peps/',
'validator': frontend.validate_url_trailing_slash}),
('Template for PEP file part of URL. (default "pep-%04d")',
['--pep-file-url-template'],
{'metavar': '<URL>', 'default': 'pep-%04d'}),
('Recognize and link to standalone RFC references (like "RFC 822").',
['--rfc-references'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Base URL for RFC references (default "http://www.faqs.org/rfcs/").',
['--rfc-base-url'],
{'metavar': '<URL>', 'default': 'http://www.faqs.org/rfcs/',
'validator': frontend.validate_url_trailing_slash}),
('Set number of spaces for tab expansion (default 8).',
['--tab-width'],
{'metavar': '<width>', 'type': 'int', 'default': 8,
'validator': frontend.validate_nonnegative_int}),
('Remove spaces before footnote references.',
['--trim-footnote-reference-space'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Leave spaces before footnote references.',
['--leave-footnote-reference-space'],
{'action': 'store_false', 'dest': 'trim_footnote_reference_space'}),
('Disable directives that insert the contents of external file '
'("include" & "raw"); replaced with a "warning" system message.',
['--no-file-insertion'],
{'action': 'store_false', 'default': 1,
'dest': 'file_insertion_enabled',
'validator': frontend.validate_boolean}),
('Enable directives that insert the contents of external file '
'("include" & "raw"). Enabled by default.',
['--file-insertion-enabled'],
{'action': 'store_true'}),
('Disable the "raw" directives; replaced with a "warning" '
'system message.',
['--no-raw'],
{'action': 'store_false', 'default': 1, 'dest': 'raw_enabled',
'validator': frontend.validate_boolean}),
('Enable the "raw" directive. Enabled by default.',
['--raw-enabled'],
{'action': 'store_true'}),))
config_section = 'restructuredtext parser'
config_section_dependencies = ('parsers',)
def __init__(self, rfc2822=None, inliner=None):
if rfc2822:
self.initial_state = 'RFC2822Body'
else:
self.initial_state = 'Body'
self.state_classes = states.state_classes
self.inliner = inliner
def parse(self, inputstring, document):
"""Parse `inputstring` and populate `document`, a document tree."""
self.setup_parse(inputstring, document)
self.statemachine = states.RSTStateMachine(
state_classes=self.state_classes,
initial_state=self.initial_state,
debug=document.reporter.debug_flag)
inputlines = docutils.statemachine.string2lines(
inputstring, tab_width=document.settings.tab_width,
convert_whitespace=1)
self.statemachine.run(inputlines, document, inliner=self.inliner)
self.finish_parse()
class DirectiveError(Exception):
"""
Store a message and a system message level.
To be thrown from inside directive code.
Do not instantiate directly -- use `Directive.directive_error()`
instead!
"""
def __init__(self, level, message):
"""Set error `message` and `level`"""
Exception.__init__(self)
self.level = level
self.msg = message
class Directive(object):
"""
Base class for reStructuredText directives.
The following attributes may be set by subclasses. They are
interpreted by the directive parser (which runs the directive
class):
- `required_arguments`: The number of required arguments (default:
0).
- `optional_arguments`: The number of optional arguments (default:
0).
- `final_argument_whitespace`: A boolean, indicating if the final
argument may contain whitespace (default: False).
- `option_spec`: A dictionary, mapping known option names to
conversion functions such as `int` or `float` (default: {}, no
options). Several conversion functions are defined in the
directives/__init__.py module.
Option conversion functions take a single parameter, the option
argument (a string or ``None``), validate it and/or convert it
to the appropriate form. Conversion functions may raise
`ValueError` and `TypeError` exceptions.
- `has_content`: A boolean; True if content is allowed. Client
code must handle the case where content is required but not
supplied (an empty content list will be supplied).
Arguments are normally single whitespace-separated words. The
final argument may contain whitespace and/or newlines if
`final_argument_whitespace` is True.
If the form of the arguments is more complex, specify only one
argument (either required or optional) and set
`final_argument_whitespace` to True; the client code must do any
context-sensitive parsing.
When a directive implementation is being run, the directive class
is instantiated, and the `run()` method is executed. During
instantiation, the following instance variables are set:
- ``name`` is the directive type or name (string).
- ``arguments`` is the list of positional arguments (strings).
- ``options`` is a dictionary mapping option names (strings) to
values (type depends on option conversion functions; see
`option_spec` above).
- ``content`` is a list of strings, the directive content line by line.
- ``lineno`` is the absolute line number of the first line
of the directive.
- ``src`` is the name (or path) of the rst source of the directive.
- ``srcline`` is the line number of the first line of the directive
in its source. It may differ from ``lineno``, if the main source
includes other sources with the ``.. include::`` directive.
- ``content_offset`` is the line offset of the first line of the content from
the beginning of the current input. Used when initiating a nested parse.
- ``block_text`` is a string containing the entire directive.
- ``state`` is the state which called the directive function.
- ``state_machine`` is the state machine which controls the state which called
the directive function.
Directive functions return a list of nodes which will be inserted
into the document tree at the point where the directive was
encountered. This can be an empty list if there is nothing to
insert.
For ordinary directives, the list must contain body elements or
structural elements. Some directives are intended specifically
for substitution definitions, and must return a list of `Text`
nodes and/or inline elements (suitable for inline insertion, in
place of the substitution reference). Such directives must verify
substitution definition context, typically using code like this::
if not isinstance(state, states.SubstitutionDef):
error = state_machine.reporter.error(
'Invalid context: the "%s" directive can only be used '
'within a substitution definition.' % (name),
nodes.literal_block(block_text, block_text), line=lineno)
return [error]
"""
# There is a "Creating reStructuredText Directives" how-to at
# <http://docutils.sf.net/docs/howto/rst-directives.html>. If you
# update this docstring, please update the how-to as well.
required_arguments = 0
"""Number of required directive arguments."""
optional_arguments = 0
"""Number of optional arguments after the required arguments."""
final_argument_whitespace = False
"""May the final argument contain whitespace?"""
option_spec = None
"""Mapping of option names to validator functions."""
has_content = False
"""May the directive have content?"""
def __init__(self, name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
self.name = name
self.arguments = arguments
self.options = options
self.content = content
self.lineno = lineno
self.content_offset = content_offset
self.block_text = block_text
self.state = state
self.state_machine = state_machine
self.src, self.scrline = state_machine.get_source_and_line(lineno)
def run(self):
raise NotImplementedError('Must override run() is subclass.')
# Directive errors:
def directive_error(self, level, message):
"""
Return a DirectiveError suitable for being thrown as an exception.
Call "raise self.directive_error(level, message)" from within
a directive implementation to return one single system message
at level `level`, which automatically gets the directive block
and the line number added.
You'd often use self.error(message) instead, which will
generate an ERROR-level directive error.
"""
return DirectiveError(level, message)
def debug(self, message):
return self.directive_error(0, message)
def info(self, message):
return self.directive_error(1, message)
def warning(self, message):
return self.directive_error(2, message)
def error(self, message):
return self.directive_error(3, message)
def severe(self, message):
return self.directive_error(4, message)
# Convenience methods:
def assert_has_content(self):
"""
Throw an ERROR-level DirectiveError if the directive doesn't
have contents.
"""
if not self.content:
raise self.error('Content block expected for the "%s" directive; '
'none found.' % self.name)
def convert_directive_function(directive_fn):
"""
Define & return a directive class generated from `directive_fn`.
`directive_fn` uses the old-style, functional interface.
"""
class FunctionalDirective(Directive):
option_spec = getattr(directive_fn, 'options', None)
has_content = getattr(directive_fn, 'content', False)
_argument_spec = getattr(directive_fn, 'arguments', (0, 0, False))
required_arguments, optional_arguments, final_argument_whitespace \
= _argument_spec
def run(self):
return directive_fn(
self.name, self.arguments, self.options, self.content,
self.lineno, self.content_offset, self.block_text,
self.state, self.state_machine)
# Return new-style directive.
return FunctionalDirective
| {
"repo_name": "romankagan/DDBWorkbench",
"path": "python/helpers/docutils/parsers/rst/__init__.py",
"copies": "42",
"size": "14143",
"license": "apache-2.0",
"hash": 5651680125993455000,
"line_mean": 36.9168900804,
"line_max": 82,
"alpha_frac": 0.6579226472,
"autogenerated": false,
"ratio": 4.354371921182266,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
Simple HyperText Markup Language document tree Writer.
The output conforms to the XHTML version 1.0 Transitional DTD
(*almost* strict). The output contains a minimum of formatting
information. The cascading style sheet "html4css1.css" is required
for proper viewing with a modern graphical browser.
"""
__docformat__ = 'reStructuredText'
import os
import os.path
import re
try:
import Image # check for the Python Imaging Library
except ImportError:
Image = None
import docutils
from docutils import frontend, nodes, utils, writers, languages, io
from docutils.transforms import writer_aux
class Writer(writers.Writer):
supported = ('html', 'html4css1', 'xhtml')
"""Formats this writer supports."""
default_stylesheet = 'html4css1.css'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = (
'HTML-Specific Options',
None,
(('Specify the template file (UTF-8 encoded). Default is "%s".'
% default_template_path,
['--template'],
{'default': default_template_path, 'metavar': '<file>'}),
('Specify comma separated list of stylesheet URLs. '
'Overrides previous --stylesheet and --stylesheet-path settings.',
['--stylesheet'],
{'metavar': '<URL>', 'overrides': 'stylesheet_path'}),
('Specify comma separated list of stylesheet paths. '
'With --link-stylesheet, '
'the path is rewritten relative to the output HTML file. '
'Default: "%s"' % default_stylesheet_path,
['--stylesheet-path'],
{'metavar': '<file>', 'overrides': 'stylesheet',
'default': default_stylesheet_path}),
('Embed the stylesheet(s) in the output HTML file. The stylesheet '
'files must be accessible during processing. This is the default.',
['--embed-stylesheet'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Link to the stylesheet(s) in the output HTML file. '
'Default: embed stylesheets.',
['--link-stylesheet'],
{'dest': 'embed_stylesheet', 'action': 'store_false'}),
('Specify the initial header level. Default is 1 for "<h1>". '
'Does not affect document title & subtitle (see --no-doc-title).',
['--initial-header-level'],
{'choices': '1 2 3 4 5 6'.split(), 'default': '1',
'metavar': '<level>'}),
('Specify the maximum width (in characters) for one-column field '
'names. Longer field names will span an entire row of the table '
'used to render the field list. Default is 14 characters. '
'Use 0 for "no limit".',
['--field-name-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
('Specify the maximum width (in characters) for options in option '
'lists. Longer options will span an entire row of the table used '
'to render the option list. Default is 14 characters. '
'Use 0 for "no limit".',
['--option-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
('Format for footnote references: one of "superscript" or '
'"brackets". Default is "brackets".',
['--footnote-references'],
{'choices': ['superscript', 'brackets'], 'default': 'brackets',
'metavar': '<format>',
'overrides': 'trim_footnote_reference_space'}),
('Format for block quote attributions: one of "dash" (em-dash '
'prefix), "parentheses"/"parens", or "none". Default is "dash".',
['--attribution'],
{'choices': ['dash', 'parentheses', 'parens', 'none'],
'default': 'dash', 'metavar': '<format>'}),
('Remove extra vertical whitespace between items of "simple" bullet '
'lists and enumerated lists. Default: enabled.',
['--compact-lists'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compact simple bullet and enumerated lists.',
['--no-compact-lists'],
{'dest': 'compact_lists', 'action': 'store_false'}),
('Remove extra vertical whitespace between items of simple field '
'lists. Default: enabled.',
['--compact-field-lists'],
{'default': 1, 'action': 'store_true',
'validator': frontend.validate_boolean}),
('Disable compact simple field lists.',
['--no-compact-field-lists'],
{'dest': 'compact_field_lists', 'action': 'store_false'}),
('Added to standard table classes. '
'Defined styles: "borderless". Default: ""',
['--table-style'],
{'default': ''}),
('Omit the XML declaration. Use with caution.',
['--no-xml-declaration'],
{'dest': 'xml_declaration', 'default': 1, 'action': 'store_false',
'validator': frontend.validate_boolean}),
('Obfuscate email addresses to confuse harvesters while still '
'keeping email links usable with standards-compliant browsers.',
['--cloak-email-addresses'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),))
settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'}
relative_path_settings = ('stylesheet_path',)
config_section = 'html4css1 writer'
config_section_dependencies = ('writers',)
visitor_attributes = (
'head_prefix', 'head', 'stylesheet', 'body_prefix',
'body_pre_docinfo', 'docinfo', 'body', 'body_suffix',
'title', 'subtitle', 'header', 'footer', 'meta', 'fragment',
'html_prolog', 'html_head', 'html_title', 'html_subtitle',
'html_body')
def get_transforms(self):
return writers.Writer.get_transforms(self) + [writer_aux.Admonitions]
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = HTMLTranslator
def translate(self):
self.visitor = visitor = self.translator_class(self.document)
self.document.walkabout(visitor)
for attr in self.visitor_attributes:
setattr(self, attr, getattr(visitor, attr))
self.output = self.apply_template()
def apply_template(self):
template_file = open(self.document.settings.template, 'rb')
template = unicode(template_file.read(), 'utf-8')
template_file.close()
subs = self.interpolation_dict()
return template % subs
def interpolation_dict(self):
subs = {}
settings = self.document.settings
for attr in self.visitor_attributes:
subs[attr] = ''.join(getattr(self, attr)).rstrip('\n')
subs['encoding'] = settings.output_encoding
subs['version'] = docutils.__version__
return subs
def assemble_parts(self):
writers.Writer.assemble_parts(self)
for part in self.visitor_attributes:
self.parts[part] = ''.join(getattr(self, part))
class HTMLTranslator(nodes.NodeVisitor):
"""
This HTML writer has been optimized to produce visually compact
lists (less vertical whitespace). HTML's mixed content models
allow list items to contain "<li><p>body elements</p></li>" or
"<li>just text</li>" or even "<li>text<p>and body
elements</p>combined</li>", each with different effects. It would
be best to stick with strict body elements in list items, but they
affect vertical spacing in browsers (although they really
shouldn't).
Here is an outline of the optimization:
- Check for and omit <p> tags in "simple" lists: list items
contain either a single paragraph, a nested simple list, or a
paragraph followed by a nested simple list. This means that
this list can be compact:
- Item 1.
- Item 2.
But this list cannot be compact:
- Item 1.
This second paragraph forces space between list items.
- Item 2.
- In non-list contexts, omit <p> tags on a paragraph if that
paragraph is the only child of its parent (footnotes & citations
are allowed a label first).
- Regardless of the above, in definitions, table cells, field bodies,
option descriptions, and list items, mark the first child with
'class="first"' and the last child with 'class="last"'. The stylesheet
sets the margins (top & bottom respectively) to 0 for these elements.
The ``no_compact_lists`` setting (``--no-compact-lists`` command-line
option) disables list whitespace optimization.
"""
xml_declaration = '<?xml version="1.0" encoding="%s" ?>\n'
doctype = (
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
head_prefix_template = ('<html xmlns="http://www.w3.org/1999/xhtml"'
' xml:lang="%s" lang="%s">\n<head>\n')
content_type = ('<meta http-equiv="Content-Type"'
' content="text/html; charset=%s" />\n')
generator = ('<meta name="generator" content="Docutils %s: '
'http://docutils.sourceforge.net/" />\n')
stylesheet_link = '<link rel="stylesheet" href="%s" type="text/css" />\n'
embedded_stylesheet = '<style type="text/css">\n\n%s\n</style>\n'
words_and_spaces = re.compile(r'\S+| +|\n')
sollbruchstelle = re.compile(r'.+\W\W.+|[-?].+', re.U) # wrap point inside word
def __init__(self, document):
nodes.NodeVisitor.__init__(self, document)
self.settings = settings = document.settings
lcode = settings.language_code
self.language = languages.get_language(lcode)
self.meta = [self.content_type % settings.output_encoding,
self.generator % docutils.__version__]
self.head_prefix = []
self.html_prolog = []
if settings.xml_declaration:
self.head_prefix.append(self.xml_declaration
% settings.output_encoding)
# encoding not interpolated:
self.html_prolog.append(self.xml_declaration)
self.head_prefix.extend([self.doctype,
self.head_prefix_template % (lcode, lcode)])
self.html_prolog.append(self.doctype)
self.head = self.meta[:]
# stylesheets
styles = utils.get_stylesheet_list(settings)
if settings.stylesheet_path and not(settings.embed_stylesheet):
styles = [utils.relative_path(settings._destination, sheet)
for sheet in styles]
if settings.embed_stylesheet:
settings.record_dependencies.add(*styles)
self.stylesheet = [self.embedded_stylesheet %
io.FileInput(source_path=sheet, encoding='utf-8').read()
for sheet in styles]
else: # link to stylesheets
self.stylesheet = [self.stylesheet_link % self.encode(stylesheet)
for stylesheet in styles]
self.body_prefix = ['</head>\n<body>\n']
# document title, subtitle display
self.body_pre_docinfo = []
# author, date, etc.
self.docinfo = []
self.body = []
self.fragment = []
self.body_suffix = ['</body>\n</html>\n']
self.section_level = 0
self.initial_header_level = int(settings.initial_header_level)
# A heterogenous stack used in conjunction with the tree traversal.
# Make sure that the pops correspond to the pushes:
self.context = []
self.topic_classes = []
self.colspecs = []
self.compact_p = 1
self.compact_simple = None
self.compact_field_list = None
self.in_docinfo = None
self.in_sidebar = None
self.title = []
self.subtitle = []
self.header = []
self.footer = []
self.html_head = [self.content_type] # charset not interpolated
self.html_title = []
self.html_subtitle = []
self.html_body = []
self.in_document_title = 0
self.in_mailto = 0
self.author_in_authors = None
def astext(self):
return ''.join(self.head_prefix + self.head
+ self.stylesheet + self.body_prefix
+ self.body_pre_docinfo + self.docinfo
+ self.body + self.body_suffix)
def encode(self, text):
"""Encode special characters in `text` & return."""
# @@@ A codec to do these and all other HTML entities would be nice.
text = unicode(text)
return text.translate({
ord('&'): u'&',
ord('<'): u'<',
ord('"'): u'"',
ord('>'): u'>',
ord('@'): u'@', # may thwart some address harvesters
# TODO: convert non-breaking space only if needed?
0xa0: u' '}) # non-breaking space
def cloak_mailto(self, uri):
"""Try to hide a mailto: URL from harvesters."""
# Encode "@" using a URL octet reference (see RFC 1738).
# Further cloaking with HTML entities will be done in the
# `attval` function.
return uri.replace('@', '%40')
def cloak_email(self, addr):
"""Try to hide the link text of a email link from harversters."""
# Surround at-signs and periods with <span> tags. ("@" has
# already been encoded to "@" by the `encode` method.)
addr = addr.replace('@', '<span>@</span>')
addr = addr.replace('.', '<span>.</span>')
return addr
def attval(self, text,
whitespace=re.compile('[\n\r\t\v\f]')):
"""Cleanse, HTML encode, and return attribute value text."""
encoded = self.encode(whitespace.sub(' ', text))
if self.in_mailto and self.settings.cloak_email_addresses:
# Cloak at-signs ("%40") and periods with HTML entities.
encoded = encoded.replace('%40', '%40')
encoded = encoded.replace('.', '.')
return encoded
def starttag(self, node, tagname, suffix='\n', empty=0, **attributes):
"""
Construct and return a start tag given a node (id & class attributes
are extracted), tag name, and optional attributes.
"""
tagname = tagname.lower()
prefix = []
atts = {}
ids = []
for (name, value) in attributes.items():
atts[name.lower()] = value
classes = node.get('classes', [])
if 'class' in atts:
classes.append(atts['class'])
if classes:
atts['class'] = ' '.join(classes)
assert 'id' not in atts
ids.extend(node.get('ids', []))
if 'ids' in atts:
ids.extend(atts['ids'])
del atts['ids']
if ids:
atts['id'] = ids[0]
for id in ids[1:]:
# Add empty "span" elements for additional IDs. Note
# that we cannot use empty "a" elements because there
# may be targets inside of references, but nested "a"
# elements aren't allowed in XHTML (even if they do
# not all have a "href" attribute).
if empty:
# Empty tag. Insert target right in front of element.
prefix.append('<span id="%s"></span>' % id)
else:
# Non-empty tag. Place the auxiliary <span> tag
# *inside* the element, as the first child.
suffix += '<span id="%s"></span>' % id
attlist = atts.items()
attlist.sort()
parts = [tagname]
for name, value in attlist:
# value=None was used for boolean attributes without
# value, but this isn't supported by XHTML.
assert value is not None
if isinstance(value, list):
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
def emptytag(self, node, tagname, suffix='\n', **attributes):
"""Construct and return an XML-compatible empty tag."""
return self.starttag(node, tagname, suffix, empty=1, **attributes)
def set_class_on_child(self, node, class_, index=0):
"""
Set class `class_` on the visible child no. index of `node`.
Do nothing if node has fewer children than `index`.
"""
children = [n for n in node if not isinstance(n, nodes.Invisible)]
try:
child = children[index]
except IndexError:
return
child['classes'].append(class_)
def set_first_last(self, node):
self.set_class_on_child(node, 'first', 0)
self.set_class_on_child(node, 'last', -1)
def visit_Text(self, node):
text = node.astext()
encoded = self.encode(text)
if self.in_mailto and self.settings.cloak_email_addresses:
encoded = self.cloak_email(encoded)
self.body.append(encoded)
def depart_Text(self, node):
pass
def visit_abbreviation(self, node):
# @@@ implementation incomplete ("title" attribute)
self.body.append(self.starttag(node, 'abbr', ''))
def depart_abbreviation(self, node):
self.body.append('</abbr>')
def visit_acronym(self, node):
# @@@ implementation incomplete ("title" attribute)
self.body.append(self.starttag(node, 'acronym', ''))
def depart_acronym(self, node):
self.body.append('</acronym>')
def visit_address(self, node):
self.visit_docinfo_item(node, 'address', meta=None)
self.body.append(self.starttag(node, 'pre', CLASS='address'))
def depart_address(self, node):
self.body.append('\n</pre>\n')
self.depart_docinfo_item()
def visit_admonition(self, node):
self.body.append(self.starttag(node, 'div'))
self.set_first_last(node)
def depart_admonition(self, node=None):
self.body.append('</div>\n')
attribution_formats = {'dash': ('—', ''),
'parentheses': ('(', ')'),
'parens': ('(', ')'),
'none': ('', '')}
def visit_attribution(self, node):
prefix, suffix = self.attribution_formats[self.settings.attribution]
self.context.append(suffix)
self.body.append(
self.starttag(node, 'p', prefix, CLASS='attribution'))
def depart_attribution(self, node):
self.body.append(self.context.pop() + '</p>\n')
def visit_author(self, node):
if isinstance(node.parent, nodes.authors):
if self.author_in_authors:
self.body.append('\n<br />')
else:
self.visit_docinfo_item(node, 'author')
def depart_author(self, node):
if isinstance(node.parent, nodes.authors):
self.author_in_authors += 1
else:
self.depart_docinfo_item()
def visit_authors(self, node):
self.visit_docinfo_item(node, 'authors')
self.author_in_authors = 0 # initialize counter
def depart_authors(self, node):
self.depart_docinfo_item()
self.author_in_authors = None
def visit_block_quote(self, node):
self.body.append(self.starttag(node, 'blockquote'))
def depart_block_quote(self, node):
self.body.append('</blockquote>\n')
def check_simple_list(self, node):
"""Check for a simple list that can be rendered compactly."""
visitor = SimpleListChecker(self.document)
try:
node.walk(visitor)
except nodes.NodeFound:
return None
else:
return 1
def is_compactable(self, node):
return ('compact' in node['classes']
or (self.settings.compact_lists
and 'open' not in node['classes']
and (self.compact_simple
or self.topic_classes == ['contents']
or self.check_simple_list(node))))
def visit_bullet_list(self, node):
atts = {}
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'] = 'simple'
self.body.append(self.starttag(node, 'ul', **atts))
def depart_bullet_list(self, node):
self.compact_simple, self.compact_p = self.context.pop()
self.body.append('</ul>\n')
def visit_caption(self, node):
self.body.append(self.starttag(node, 'p', '', CLASS='caption'))
def depart_caption(self, node):
self.body.append('</p>\n')
def visit_citation(self, node):
self.body.append(self.starttag(node, 'table',
CLASS='docutils citation',
frame="void", rules="none"))
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n'
'<tbody valign="top">\n'
'<tr>')
self.footnote_backrefs(node)
def depart_citation(self, node):
self.body.append('</td></tr>\n'
'</tbody>\n</table>\n')
def visit_citation_reference(self, node):
href = '#' + node['refid']
self.body.append(self.starttag(
node, 'a', '[', CLASS='citation-reference', href=href))
def depart_citation_reference(self, node):
self.body.append(']</a>')
def visit_classifier(self, node):
self.body.append(' <span class="classifier-delimiter">:</span> ')
self.body.append(self.starttag(node, 'span', '', CLASS='classifier'))
def depart_classifier(self, node):
self.body.append('</span>')
def visit_colspec(self, node):
self.colspecs.append(node)
# "stubs" list is an attribute of the tgroup element:
node.parent.stubs.append(node.attributes.get('stub'))
def depart_colspec(self, node):
pass
def write_colspecs(self):
width = 0
for node in self.colspecs:
width += node['colwidth']
for node in self.colspecs:
colwidth = int(node['colwidth'] * 100.0 / width + 0.5)
self.body.append(self.emptytag(node, 'col',
width='%i%%' % colwidth))
self.colspecs = []
def visit_comment(self, node,
sub=re.compile('-(?=-)').sub):
"""Escape double-dashes in comment text."""
self.body.append('<!-- %s -->\n' % sub('- ', node.astext()))
# Content already processed:
raise nodes.SkipNode
def visit_compound(self, node):
self.body.append(self.starttag(node, 'div', CLASS='compound'))
if len(node) > 1:
node[0]['classes'].append('compound-first')
node[-1]['classes'].append('compound-last')
for child in node[1:-1]:
child['classes'].append('compound-middle')
def depart_compound(self, node):
self.body.append('</div>\n')
def visit_container(self, node):
self.body.append(self.starttag(node, 'div', CLASS='container'))
def depart_container(self, node):
self.body.append('</div>\n')
def visit_contact(self, node):
self.visit_docinfo_item(node, 'contact', meta=None)
def depart_contact(self, node):
self.depart_docinfo_item()
def visit_copyright(self, node):
self.visit_docinfo_item(node, 'copyright')
def depart_copyright(self, node):
self.depart_docinfo_item()
def visit_date(self, node):
self.visit_docinfo_item(node, 'date')
def depart_date(self, node):
self.depart_docinfo_item()
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
self.body.append('</dt>\n')
self.body.append(self.starttag(node, 'dd', ''))
self.set_first_last(node)
def depart_definition(self, node):
self.body.append('</dd>\n')
def visit_definition_list(self, node):
self.body.append(self.starttag(node, 'dl', CLASS='docutils'))
def depart_definition_list(self, node):
self.body.append('</dl>\n')
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_description(self, node):
self.body.append(self.starttag(node, 'td', ''))
self.set_first_last(node)
def depart_description(self, node):
self.body.append('</td>')
def visit_docinfo(self, node):
self.context.append(len(self.body))
self.body.append(self.starttag(node, 'table',
CLASS='docinfo',
frame="void", rules="none"))
self.body.append('<col class="docinfo-name" />\n'
'<col class="docinfo-content" />\n'
'<tbody valign="top">\n')
self.in_docinfo = 1
def depart_docinfo(self, node):
self.body.append('</tbody>\n</table>\n')
self.in_docinfo = None
start = self.context.pop()
self.docinfo = self.body[start:]
self.body = []
def visit_docinfo_item(self, node, name, meta=1):
if meta:
meta_tag = '<meta name="%s" content="%s" />\n' \
% (name, self.attval(node.astext()))
self.add_meta(meta_tag)
self.body.append(self.starttag(node, 'tr', ''))
self.body.append('<th class="docinfo-name">%s:</th>\n<td>'
% self.language.labels[name])
if len(node):
if isinstance(node[0], nodes.Element):
node[0]['classes'].append('first')
if isinstance(node[-1], nodes.Element):
node[-1]['classes'].append('last')
def depart_docinfo_item(self):
self.body.append('</td></tr>\n')
def visit_doctest_block(self, node):
self.body.append(self.starttag(node, 'pre', CLASS='doctest-block'))
def depart_doctest_block(self, node):
self.body.append('\n</pre>\n')
def visit_document(self, node):
self.head.append('<title>%s</title>\n'
% self.encode(node.get('title', '')))
def depart_document(self, node):
self.fragment.extend(self.body)
self.body_prefix.append(self.starttag(node, 'div', CLASS='document'))
self.body_suffix.insert(0, '</div>\n')
# skip content-type meta tag with interpolated charset value:
self.html_head.extend(self.head[1:])
self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
+ self.docinfo + self.body
+ self.body_suffix[:-1])
assert not self.context, 'len(context) = %s' % len(self.context)
def visit_emphasis(self, node):
self.body.append(self.starttag(node, 'em', ''))
def depart_emphasis(self, node):
self.body.append('</em>')
def visit_entry(self, node):
atts = {'class': []}
if isinstance(node.parent.parent, nodes.thead):
atts['class'].append('head')
if node.parent.parent.parent.stubs[node.parent.column]:
# "stubs" list is an attribute of the tgroup element
atts['class'].append('stub')
if atts['class']:
tagname = 'th'
atts['class'] = ' '.join(atts['class'])
else:
tagname = 'td'
del atts['class']
node.parent.column += 1
if 'morerows' in node:
atts['rowspan'] = node['morerows'] + 1
if 'morecols' in node:
atts['colspan'] = node['morecols'] + 1
node.parent.column += node['morecols']
self.body.append(self.starttag(node, tagname, '', **atts))
self.context.append('</%s>\n' % tagname.lower())
if len(node) == 0: # empty cell
self.body.append(' ')
self.set_first_last(node)
def depart_entry(self, node):
self.body.append(self.context.pop())
def visit_enumerated_list(self, node):
"""
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.
"""
atts = {}
if 'start' in node:
atts['start'] = node['start']
if 'enumtype' in node:
atts['class'] = node['enumtype']
# @@@ To do: prefix, suffix. How? Change prefix/suffix to a
# single "format" attribute? Use CSS2?
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))
def depart_enumerated_list(self, node):
self.compact_simple, self.compact_p = self.context.pop()
self.body.append('</ol>\n')
def visit_field(self, node):
self.body.append(self.starttag(node, 'tr', '', CLASS='field'))
def depart_field(self, node):
self.body.append('</tr>\n')
def visit_field_body(self, node):
self.body.append(self.starttag(node, 'td', '', CLASS='field-body'))
self.set_class_on_child(node, 'first', 0)
field = node.parent
if (self.compact_field_list or
isinstance(field.parent, nodes.docinfo) or
field.parent.index(field) == len(field.parent) - 1):
# If we are in a compact list, the docinfo, or if this is
# the last field of the field list, do not add vertical
# space after last element.
self.set_class_on_child(node, 'last', -1)
def depart_field_body(self, node):
self.body.append('</td>\n')
def visit_field_list(self, node):
self.context.append((self.compact_field_list, self.compact_p))
self.compact_p = None
if 'compact' in node['classes']:
self.compact_field_list = 1
elif (self.settings.compact_field_lists
and 'open' not in node['classes']):
self.compact_field_list = 1
if self.compact_field_list:
for field in node:
field_body = field[-1]
assert isinstance(field_body, nodes.field_body)
children = [n for n in field_body
if not isinstance(n, nodes.Invisible)]
if not (len(children) == 0 or
len(children) == 1 and
isinstance(children[0],
(nodes.paragraph, nodes.line_block))):
self.compact_field_list = 0
break
self.body.append(self.starttag(node, 'table', frame='void',
rules='none',
CLASS='docutils field-list'))
self.body.append('<col class="field-name" />\n'
'<col class="field-body" />\n'
'<tbody valign="top">\n')
def depart_field_list(self, node):
self.body.append('</tbody>\n</table>\n')
self.compact_field_list, self.compact_p = self.context.pop()
def visit_field_name(self, node):
atts = {}
if self.in_docinfo:
atts['class'] = 'docinfo-name'
else:
atts['class'] = 'field-name'
if ( self.settings.field_name_limit
and len(node.astext()) > self.settings.field_name_limit):
atts['colspan'] = 2
self.context.append('</tr>\n<tr><td> </td>')
else:
self.context.append('')
self.body.append(self.starttag(node, 'th', '', **atts))
def depart_field_name(self, node):
self.body.append(':</th>')
self.body.append(self.context.pop())
def visit_figure(self, node):
atts = {'class': 'figure'}
if node.get('width'):
atts['style'] = 'width: %s' % node['width']
if node.get('align'):
atts['class'] += " align-" + node['align']
self.body.append(self.starttag(node, 'div', **atts))
def depart_figure(self, node):
self.body.append('</div>\n')
def visit_footer(self, node):
self.context.append(len(self.body))
def depart_footer(self, node):
start = self.context.pop()
footer = [self.starttag(node, 'div', CLASS='footer'),
'<hr class="footer" />\n']
footer.extend(self.body[start:])
footer.append('\n</div>\n')
self.footer.extend(footer)
self.body_suffix[:0] = footer
del self.body[start:]
def visit_footnote(self, node):
self.body.append(self.starttag(node, 'table',
CLASS='docutils footnote',
frame="void", rules="none"))
self.body.append('<colgroup><col class="label" /><col /></colgroup>\n'
'<tbody valign="top">\n'
'<tr>')
self.footnote_backrefs(node)
def footnote_backrefs(self, node):
backlinks = []
backrefs = node['backrefs']
if self.settings.footnote_backlinks and backrefs:
if len(backrefs) == 1:
self.context.append('')
self.context.append('</a>')
self.context.append('<a class="fn-backref" href="#%s">'
% backrefs[0])
else:
i = 1
for backref in backrefs:
backlinks.append('<a class="fn-backref" href="#%s">%s</a>'
% (backref, i))
i += 1
self.context.append('<em>(%s)</em> ' % ', '.join(backlinks))
self.context += ['', '']
else:
self.context.append('')
self.context += ['', '']
# If the node does not only consist of a label.
if len(node) > 1:
# If there are preceding backlinks, we do not set class
# 'first', because we need to retain the top-margin.
if not backlinks:
node[1]['classes'].append('first')
node[-1]['classes'].append('last')
def depart_footnote(self, node):
self.body.append('</td></tr>\n'
'</tbody>\n</table>\n')
def visit_footnote_reference(self, node):
href = '#' + node['refid']
format = self.settings.footnote_references
if format == 'brackets':
suffix = '['
self.context.append(']')
else:
assert format == 'superscript'
suffix = '<sup>'
self.context.append('</sup>')
self.body.append(self.starttag(node, 'a', suffix,
CLASS='footnote-reference', href=href))
def depart_footnote_reference(self, node):
self.body.append(self.context.pop() + '</a>')
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def visit_header(self, node):
self.context.append(len(self.body))
def depart_header(self, node):
start = self.context.pop()
header = [self.starttag(node, 'div', CLASS='header')]
header.extend(self.body[start:])
header.append('\n<hr class="header"/>\n</div>\n')
self.body_prefix.extend(header)
self.header.extend(header)
del self.body[start:]
def visit_image(self, node):
atts = {}
uri = node['uri']
# place SVG and SWF images in an <object> element
types = {'.svg': 'image/svg+xml',
'.swf': 'application/x-shockwave-flash'}
ext = os.path.splitext(uri)[1].lower()
if ext in ('.svg', '.swf'):
atts['data'] = uri
atts['type'] = types[ext]
else:
atts['src'] = uri
atts['alt'] = node.get('alt', uri)
# image size
if 'width' in node:
atts['width'] = node['width']
if 'height' in node:
atts['height'] = node['height']
if 'scale' in node:
if Image and not ('width' in node and 'height' in node):
try:
im = Image.open(str(uri))
except (IOError, # Source image can't be found or opened
UnicodeError): # PIL doesn't like Unicode paths.
pass
else:
if 'width' not in atts:
atts['width'] = str(im.size[0])
if 'height' not in atts:
atts['height'] = str(im.size[1])
del im
for att_name in 'width', 'height':
if att_name in atts:
match = re.match(r'([0-9.]+)(\S*)$', atts[att_name])
assert match
atts[att_name] = '%s%s' % (
float(match.group(1)) * (float(node['scale']) / 100),
match.group(2))
style = []
for att_name in 'width', 'height':
if att_name in atts:
if re.match(r'^[0-9.]+$', atts[att_name]):
# Interpret unitless values as pixels.
atts[att_name] += 'px'
style.append('%s: %s;' % (att_name, atts[att_name]))
del atts[att_name]
if style:
atts['style'] = ' '.join(style)
if (isinstance(node.parent, nodes.TextElement) or
(isinstance(node.parent, nodes.reference) and
not isinstance(node.parent.parent, nodes.TextElement))):
# Inline context or surrounded by <a>...</a>.
suffix = ''
else:
suffix = '\n'
if 'align' in node:
atts['class'] = 'align-%s' % node['align']
self.context.append('')
if ext in ('.svg', '.swf'): # place in an object element,
# do NOT use an empty tag: incorrect rendering in browsers
self.body.append(self.starttag(node, 'object', suffix, **atts) +
node.get('alt', uri) + '</object>' + suffix)
else:
self.body.append(self.emptytag(node, 'img', suffix, **atts))
def depart_image(self, node):
self.body.append(self.context.pop())
def visit_inline(self, node):
self.body.append(self.starttag(node, 'span', ''))
def depart_inline(self, node):
self.body.append('</span>')
def visit_label(self, node):
# Context added in footnote_backrefs.
self.body.append(self.starttag(node, 'td', '%s[' % self.context.pop(),
CLASS='label'))
def depart_label(self, node):
# Context added in footnote_backrefs.
self.body.append(']%s</td><td>%s' % (self.context.pop(), self.context.pop()))
def visit_legend(self, node):
self.body.append(self.starttag(node, 'div', CLASS='legend'))
def depart_legend(self, node):
self.body.append('</div>\n')
def visit_line(self, node):
self.body.append(self.starttag(node, 'div', suffix='', CLASS='line'))
if not len(node):
self.body.append('<br />')
def depart_line(self, node):
self.body.append('</div>\n')
def visit_line_block(self, node):
self.body.append(self.starttag(node, 'div', CLASS='line-block'))
def depart_line_block(self, node):
self.body.append('</div>\n')
def visit_list_item(self, node):
self.body.append(self.starttag(node, 'li', ''))
if len(node):
node[0]['classes'].append('first')
def depart_list_item(self, node):
self.body.append('</li>\n')
def visit_literal(self, node):
"""Process text to prevent tokens from wrapping."""
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():
# Protect text like "--an-option" and the regular expression
# ``[+]?(\d+(\.\d*)?|\.\d+)`` from bad line wrapping
if self.sollbruchstelle.search(token):
self.body.append('<span class="pre">%s</span>'
% self.encode(token))
else:
self.body.append(self.encode(token))
elif token in ('\n', ' '):
# Allow breaks at whitespace:
self.body.append(token)
else:
# Protect runs of multiple spaces; the last space can wrap:
self.body.append(' ' * (len(token) - 1) + ' ')
self.body.append('</tt>')
# Content already processed:
raise nodes.SkipNode
def visit_literal_block(self, node):
self.body.append(self.starttag(node, 'pre', CLASS='literal-block'))
def depart_literal_block(self, node):
self.body.append('\n</pre>\n')
def visit_meta(self, node):
meta = self.emptytag(node, 'meta', **node.non_default_attributes())
self.add_meta(meta)
def depart_meta(self, node):
pass
def add_meta(self, tag):
self.meta.append(tag)
self.head.append(tag)
def visit_option(self, node):
if self.context[-1]:
self.body.append(', ')
self.body.append(self.starttag(node, 'span', '', CLASS='option'))
def depart_option(self, node):
self.body.append('</span>')
self.context[-1] += 1
def visit_option_argument(self, node):
self.body.append(node.get('delimiter', ' '))
self.body.append(self.starttag(node, 'var', ''))
def depart_option_argument(self, node):
self.body.append('</var>')
def visit_option_group(self, node):
atts = {}
if ( self.settings.option_limit
and len(node.astext()) > self.settings.option_limit):
atts['colspan'] = 2
self.context.append('</tr>\n<tr><td> </td>')
else:
self.context.append('')
self.body.append(
self.starttag(node, 'td', CLASS='option-group', **atts))
self.body.append('<kbd>')
self.context.append(0) # count number of options
def depart_option_group(self, node):
self.context.pop()
self.body.append('</kbd></td>\n')
self.body.append(self.context.pop())
def visit_option_list(self, node):
self.body.append(
self.starttag(node, 'table', CLASS='docutils option-list',
frame="void", rules="none"))
self.body.append('<col class="option" />\n'
'<col class="description" />\n'
'<tbody valign="top">\n')
def depart_option_list(self, node):
self.body.append('</tbody>\n</table>\n')
def visit_option_list_item(self, node):
self.body.append(self.starttag(node, 'tr', ''))
def depart_option_list_item(self, node):
self.body.append('</tr>\n')
def visit_option_string(self, node):
pass
def depart_option_string(self, node):
pass
def visit_organization(self, node):
self.visit_docinfo_item(node, 'organization')
def depart_organization(self, node):
self.depart_docinfo_item()
def should_be_compact_paragraph(self, node):
"""
Determine if the <p> tags around paragraph ``node`` can be omitted.
"""
if (isinstance(node.parent, nodes.document) or
isinstance(node.parent, nodes.compound)):
# Never compact paragraphs in document or 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']))):
# Attribute which needs to survive.
return 0
first = isinstance(node.parent[0], nodes.label) # skip label
for child in node.parent.children[first:]:
# only first paragraph can be compact
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
def visit_paragraph(self, node):
if self.should_be_compact_paragraph(node):
self.context.append('')
else:
self.body.append(self.starttag(node, 'p', ''))
self.context.append('</p>\n')
def depart_paragraph(self, node):
self.body.append(self.context.pop())
def visit_problematic(self, node):
if node.hasattr('refid'):
self.body.append('<a href="#%s">' % node['refid'])
self.context.append('</a>')
else:
self.context.append('')
self.body.append(self.starttag(node, 'span', '', CLASS='problematic'))
def depart_problematic(self, node):
self.body.append('</span>')
self.body.append(self.context.pop())
def visit_raw(self, node):
if 'html' in node.get('format', '').split():
t = isinstance(node.parent, nodes.TextElement) and 'span' or 'div'
if node['classes']:
self.body.append(self.starttag(node, t, suffix=''))
self.body.append(node.astext())
if node['classes']:
self.body.append('</%s>' % t)
# Keep non-HTML raw text out of output:
raise nodes.SkipNode
def visit_reference(self, node):
atts = {'class': 'reference'}
if 'refuri' in node:
atts['href'] = node['refuri']
if ( self.settings.cloak_email_addresses
and atts['href'].startswith('mailto:')):
atts['href'] = self.cloak_mailto(atts['href'])
self.in_mailto = 1
atts['class'] += ' external'
else:
assert 'refid' in node, \
'References must have "refuri" or "refid" attribute.'
atts['href'] = '#' + node['refid']
atts['class'] += ' internal'
if not isinstance(node.parent, nodes.TextElement):
assert len(node) == 1 and isinstance(node[0], nodes.image)
atts['class'] += ' image-reference'
self.body.append(self.starttag(node, 'a', '', **atts))
def depart_reference(self, node):
self.body.append('</a>')
if not isinstance(node.parent, nodes.TextElement):
self.body.append('\n')
self.in_mailto = 0
def visit_revision(self, node):
self.visit_docinfo_item(node, 'revision', meta=None)
def depart_revision(self, node):
self.depart_docinfo_item()
def visit_row(self, node):
self.body.append(self.starttag(node, 'tr', ''))
node.column = 0
def depart_row(self, node):
self.body.append('</tr>\n')
def visit_rubric(self, node):
self.body.append(self.starttag(node, 'p', '', CLASS='rubric'))
def depart_rubric(self, node):
self.body.append('</p>\n')
def visit_section(self, node):
self.section_level += 1
self.body.append(
self.starttag(node, 'div', CLASS='section'))
def depart_section(self, node):
self.section_level -= 1
self.body.append('</div>\n')
def visit_sidebar(self, node):
self.body.append(
self.starttag(node, 'div', CLASS='sidebar'))
self.set_first_last(node)
self.in_sidebar = 1
def depart_sidebar(self, node):
self.body.append('</div>\n')
self.in_sidebar = None
def visit_status(self, node):
self.visit_docinfo_item(node, 'status', meta=None)
def depart_status(self, node):
self.depart_docinfo_item()
def visit_strong(self, node):
self.body.append(self.starttag(node, 'strong', ''))
def depart_strong(self, node):
self.body.append('</strong>')
def visit_subscript(self, node):
self.body.append(self.starttag(node, 'sub', ''))
def depart_subscript(self, node):
self.body.append('</sub>')
def visit_substitution_definition(self, node):
"""Internal only."""
raise nodes.SkipNode
def visit_substitution_reference(self, node):
self.unimplemented_visit(node)
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.sidebar):
self.body.append(self.starttag(node, 'p', '',
CLASS='sidebar-subtitle'))
self.context.append('</p>\n')
elif isinstance(node.parent, nodes.document):
self.body.append(self.starttag(node, 'h2', '', CLASS='subtitle'))
self.context.append('</h2>\n')
self.in_document_title = len(self.body)
elif isinstance(node.parent, nodes.section):
tag = 'h%s' % (self.section_level + self.initial_header_level - 1)
self.body.append(
self.starttag(node, tag, '', CLASS='section-subtitle') +
self.starttag({}, 'span', '', CLASS='section-subtitle'))
self.context.append('</span></%s>\n' % tag)
def depart_subtitle(self, node):
self.body.append(self.context.pop())
if self.in_document_title:
self.subtitle = self.body[self.in_document_title:-1]
self.in_document_title = 0
self.body_pre_docinfo.extend(self.body)
self.html_subtitle.extend(self.body)
del self.body[:]
def visit_superscript(self, node):
self.body.append(self.starttag(node, 'sup', ''))
def depart_superscript(self, node):
self.body.append('</sup>')
def visit_system_message(self, node):
self.body.append(self.starttag(node, 'div', CLASS='system-message'))
self.body.append('<p class="system-message-title">')
backref_text = ''
if len(node['backrefs']):
backrefs = node['backrefs']
if len(backrefs) == 1:
backref_text = ('; <em><a href="#%s">backlink</a></em>'
% backrefs[0])
else:
i = 1
backlinks = []
for backref in backrefs:
backlinks.append('<a href="#%s">%s</a>' % (backref, i))
i += 1
backref_text = ('; <em>backlinks: %s</em>'
% ', '.join(backlinks))
if node.hasattr('line'):
line = ', line %s' % node['line']
else:
line = ''
self.body.append('System Message: %s/%s '
'(<tt class="docutils">%s</tt>%s)%s</p>\n'
% (node['type'], node['level'],
self.encode(node['source']), line, backref_text))
def depart_system_message(self, node):
self.body.append('</div>\n')
def visit_table(self, node):
classes = ' '.join(['docutils', self.settings.table_style]).strip()
self.body.append(
self.starttag(node, 'table', CLASS=classes, border="1"))
def depart_table(self, node):
self.body.append('</table>\n')
def visit_target(self, node):
if not ('refuri' in node or 'refid' in node
or 'refname' in node):
self.body.append(self.starttag(node, 'span', '', CLASS='target'))
self.context.append('</span>')
else:
self.context.append('')
def depart_target(self, node):
self.body.append(self.context.pop())
def visit_tbody(self, node):
self.write_colspecs()
self.body.append(self.context.pop()) # '</colgroup>\n' or ''
self.body.append(self.starttag(node, 'tbody', valign='top'))
def depart_tbody(self, node):
self.body.append('</tbody>\n')
def visit_term(self, node):
self.body.append(self.starttag(node, 'dt', ''))
def depart_term(self, node):
"""
Leave the end tag to `self.visit_definition()`, in case there's a
classifier.
"""
pass
def visit_tgroup(self, node):
# Mozilla needs <colgroup>:
self.body.append(self.starttag(node, 'colgroup'))
# Appended by thead or tbody:
self.context.append('</colgroup>\n')
node.stubs = []
def depart_tgroup(self, node):
pass
def visit_thead(self, node):
self.write_colspecs()
self.body.append(self.context.pop()) # '</colgroup>\n'
# There may or may not be a <thead>; this is for <tbody> to use:
self.context.append('')
self.body.append(self.starttag(node, 'thead', valign='bottom'))
def depart_thead(self, node):
self.body.append('</thead>\n')
def visit_title(self, node):
"""Only 6 section levels are supported by HTML."""
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)
def depart_title(self, node):
self.body.append(self.context.pop())
if self.in_document_title:
self.title = self.body[self.in_document_title:-1]
self.in_document_title = 0
self.body_pre_docinfo.extend(self.body)
self.html_title.extend(self.body)
del self.body[:]
def visit_title_reference(self, node):
self.body.append(self.starttag(node, 'cite', ''))
def depart_title_reference(self, node):
self.body.append('</cite>')
def visit_topic(self, node):
self.body.append(self.starttag(node, 'div', CLASS='topic'))
self.topic_classes = node['classes']
def depart_topic(self, node):
self.body.append('</div>\n')
self.topic_classes = []
def visit_transition(self, node):
self.body.append(self.emptytag(node, 'hr', CLASS='docutils'))
def depart_transition(self, node):
pass
def visit_version(self, node):
self.visit_docinfo_item(node, 'version', meta=None)
def depart_version(self, node):
self.depart_docinfo_item()
def unimplemented_visit(self, node):
raise NotImplementedError('visiting unimplemented node type: %s'
% node.__class__.__name__)
class SimpleListChecker(nodes.GenericNodeVisitor):
"""
Raise `nodes.NodeFound` if non-simple list item is encountered.
Here "simple" means a list item containing nothing other than a single
paragraph, a simple list, or a paragraph followed by a simple list.
"""
def default_visit(self, node):
raise nodes.NodeFound
def visit_bullet_list(self, node):
pass
def visit_enumerated_list(self, node):
pass
def visit_list_item(self, node):
children = []
for child in node.children:
if not isinstance(child, nodes.Invisible):
children.append(child)
if (children and isinstance(children[0], nodes.paragraph)
and (isinstance(children[-1], nodes.bullet_list)
or isinstance(children[-1], nodes.enumerated_list))):
children.pop()
if len(children) <= 1:
return
else:
raise nodes.NodeFound
def visit_paragraph(self, node):
raise nodes.SkipNode
def invisible_visit(self, node):
"""Invisible nodes should be ignored."""
raise nodes.SkipNode
visit_comment = invisible_visit
visit_substitution_definition = invisible_visit
visit_target = invisible_visit
visit_pending = invisible_visit
| {
"repo_name": "MichaelNedzelsky/intellij-community",
"path": "python/helpers/py2only/docutils/writers/html4css1/__init__.py",
"copies": "5",
"size": "59134",
"license": "apache-2.0",
"hash": 8381569059715312000,
"line_mean": 37.1509677419,
"line_max": 85,
"alpha_frac": 0.5491933575,
"autogenerated": false,
"ratio": 3.9602196624698633,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7009413019969863,
"avg_score": null,
"num_lines": null
} |
"""
PEP HTML Writer.
"""
__docformat__ = 'reStructuredText'
import os
import os.path
from docutils import frontend, nodes, utils
from docutils.writers import html4css1
class Writer(html4css1.Writer):
default_stylesheet = 'pep.css'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = html4css1.Writer.settings_spec + (
'PEP/HTML-Specific Options',
'For the PEP/HTML writer, the default value for the --stylesheet-path '
'option is "%s", and the default value for --template is "%s". '
'See HTML-Specific Options above.'
% (default_stylesheet_path, default_template_path),
(('Python\'s home URL. Default is "http://www.python.org".',
['--python-home'],
{'default': 'http://www.python.org', 'metavar': '<URL>'}),
('Home URL prefix for PEPs. Default is "." (current directory).',
['--pep-home'],
{'default': '.', 'metavar': '<URL>'}),
# For testing.
(frontend.SUPPRESS_HELP,
['--no-random'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),))
settings_default_overrides = {'stylesheet_path': default_stylesheet_path,
'template': default_template_path,}
relative_path_settings = (html4css1.Writer.relative_path_settings
+ ('template',))
config_section = 'pep_html writer'
config_section_dependencies = ('writers', 'html4css1 writer')
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = HTMLTranslator
def interpolation_dict(self):
subs = html4css1.Writer.interpolation_dict(self)
settings = self.document.settings
pyhome = settings.python_home
subs['pyhome'] = pyhome
subs['pephome'] = settings.pep_home
if pyhome == '..':
subs['pepindex'] = '.'
else:
subs['pepindex'] = pyhome + '/dev/peps'
index = self.document.first_child_matching_class(nodes.field_list)
header = self.document[index]
self.pepnum = header[0][1].astext()
subs['pep'] = self.pepnum
if settings.no_random:
subs['banner'] = 0
else:
import random
subs['banner'] = random.randrange(64)
try:
subs['pepnum'] = '%04i' % int(self.pepnum)
except ValueError:
subs['pepnum'] = self.pepnum
self.title = header[1][1].astext()
subs['title'] = self.title
subs['body'] = ''.join(
self.body_pre_docinfo + self.docinfo + self.body)
return subs
def assemble_parts(self):
html4css1.Writer.assemble_parts(self)
self.parts['title'] = [self.title]
self.parts['pepnum'] = self.pepnum
class HTMLTranslator(html4css1.HTMLTranslator):
def depart_field_list(self, node):
html4css1.HTMLTranslator.depart_field_list(self, node)
if 'rfc2822' in node['classes']:
self.body.append('<hr />\n')
| {
"repo_name": "Soya93/Extract-Refactoring",
"path": "python/helpers/py2only/docutils/writers/pep_html/__init__.py",
"copies": "5",
"size": "3533",
"license": "apache-2.0",
"hash": -7224462880800877000,
"line_mean": 33.637254902,
"line_max": 79,
"alpha_frac": 0.5912821964,
"autogenerated": false,
"ratio": 3.7786096256684494,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0006069094304388421,
"num_lines": 102
} |
"""
PEP HTML Writer.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import codecs
import docutils
from docutils import frontend, nodes, utils, writers
from docutils.writers import html4css1
class Writer(html4css1.Writer):
default_stylesheet = 'pep.css'
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = html4css1.Writer.settings_spec + (
'PEP/HTML-Specific Options',
'For the PEP/HTML writer, the default value for the --stylesheet-path '
'option is "%s", and the default value for --template is "%s". '
'See HTML-Specific Options above.'
% (default_stylesheet_path, default_template_path),
(('Python\'s home URL. Default is "http://www.python.org".',
['--python-home'],
{'default': 'http://www.python.org', 'metavar': '<URL>'}),
('Home URL prefix for PEPs. Default is "." (current directory).',
['--pep-home'],
{'default': '.', 'metavar': '<URL>'}),
# For testing.
(frontend.SUPPRESS_HELP,
['--no-random'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),))
settings_default_overrides = {'stylesheet_path': default_stylesheet_path,
'template': default_template_path,}
relative_path_settings = (html4css1.Writer.relative_path_settings
+ ('template',))
config_section = 'pep_html writer'
config_section_dependencies = ('writers', 'html4css1 writer')
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = HTMLTranslator
def interpolation_dict(self):
subs = html4css1.Writer.interpolation_dict(self)
settings = self.document.settings
pyhome = settings.python_home
subs['pyhome'] = pyhome
subs['pephome'] = settings.pep_home
if pyhome == '..':
subs['pepindex'] = '.'
else:
subs['pepindex'] = pyhome + '/dev/peps'
index = self.document.first_child_matching_class(nodes.field_list)
header = self.document[index]
self.pepnum = header[0][1].astext()
subs['pep'] = self.pepnum
if settings.no_random:
subs['banner'] = 0
else:
import random
subs['banner'] = random.randrange(64)
try:
subs['pepnum'] = '%04i' % int(self.pepnum)
except ValueError:
subs['pepnum'] = self.pepnum
self.title = header[1][1].astext()
subs['title'] = self.title
subs['body'] = ''.join(
self.body_pre_docinfo + self.docinfo + self.body)
return subs
def assemble_parts(self):
html4css1.Writer.assemble_parts(self)
self.parts['title'] = [self.title]
self.parts['pepnum'] = self.pepnum
class HTMLTranslator(html4css1.HTMLTranslator):
def depart_field_list(self, node):
html4css1.HTMLTranslator.depart_field_list(self, node)
if 'rfc2822' in node['classes']:
self.body.append('<hr />\n')
| {
"repo_name": "ajaxsys/dict-admin",
"path": "docutils/writers/pep_html/__init__.py",
"copies": "2",
"size": "3688",
"license": "bsd-3-clause",
"hash": -1032486783577772000,
"line_mean": 33.1238095238,
"line_max": 79,
"alpha_frac": 0.5778199566,
"autogenerated": false,
"ratio": 3.849686847599165,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005771060471355264,
"num_lines": 105
} |
"""
This is the Docutils (Python Documentation Utilities) package.
Package Structure
=================
Modules:
- __init__.py: Contains component base classes, exception classes, and
Docutils version information.
- core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience
functions.
- frontend.py: Runtime settings (command-line interface, configuration files)
processing, for Docutils front-ends.
- io.py: Provides a uniform API for low-level input and output.
- nodes.py: Docutils document tree (doctree) node class library.
- statemachine.py: A finite state machine specialized for
regular-expression-based text filters.
- urischemes.py: Contains a complete mapping of known URI addressing
scheme names to descriptions.
- utils.py: Contains the ``Reporter`` system warning class and miscellaneous
utilities.
Subpackages:
- languages: Language-specific mappings of terms.
- parsers: Syntax-specific input parser modules or packages.
- readers: Context-specific input handlers which understand the data
source and manage a parser.
- transforms: Modules used by readers and writers to modify DPS
doctrees.
- writers: Format-specific output translators.
"""
__docformat__ = 'reStructuredText'
__version__ = '0.8'
"""``major.minor.micro`` version number. The micro number is bumped for API
changes, for new functionality, and for interim project releases. The minor
number is bumped whenever there is a significant project release. The major
number will be bumped when the project is feature-complete, and perhaps if
there is a major change in the design."""
__version_details__ = 'snapshot 2010-09-01, r6395'
"""Extra version details (e.g. 'snapshot 2005-05-29, r3410', 'repository',
'release'), modified automatically & manually."""
class ApplicationError(StandardError): pass
class DataError(ApplicationError): pass
class SettingsSpec:
"""
Runtime setting specification base class.
SettingsSpec subclass objects used by `docutils.frontend.OptionParser`.
"""
settings_spec = ()
"""Runtime settings specification. Override in subclasses.
Defines runtime settings and associated command-line options, as used by
`docutils.frontend.OptionParser`. This is a tuple of:
- Option group title (string or `None` which implies no group, just a list
of single options).
- Description (string or `None`).
- A sequence of option tuples. Each consists of:
- Help text (string)
- List of option strings (e.g. ``['-Q', '--quux']``).
- Dictionary of keyword arguments sent to the OptionParser/OptionGroup
``add_option`` method.
Runtime setting names are derived implicitly from long option names
('--a-setting' becomes ``settings.a_setting``) or explicitly from the
'dest' keyword argument.
Most settings will also have a 'validator' keyword & function. The
validator function validates setting values (from configuration files
and command-line option arguments) and converts them to appropriate
types. For centralfitestoque, the ``docutils.frontend.validate_boolean``
function, **required by all boolean settings**, converts true values
('1', 'on', 'yes', and 'true') to 1 and false values ('0', 'off',
'no', 'false', and '') to 0. Validators need only be set once per
setting. See the `docutils.frontend.validate_*` functions.
See the optparse docs for more details.
- More triples of group title, description, options, as many times as
needed. Thus, `settings_spec` tuples can be simply concatenated.
"""
settings_defaults = None
"""A dictionary of defaults for settings not in `settings_spec` (internal
settings, intended to be inaccessible by command-line and config file).
Override in subclasses."""
settings_default_overrides = None
"""A dictionary of auxiliary defaults, to override defaults for settings
defined in other components. Override in subclasses."""
relative_path_settings = ()
"""Settings containing filesystem paths. Override in subclasses.
Settings listed here are to be interpreted relative to the current working
directory."""
config_section = None
"""The name of the config file section specific to this component
(lowercase, no brackets). Override in subclasses."""
config_section_dependencies = None
"""A list of names of config file sections that are to be applied before
`config_section`, in order (from general to specific). In other words,
the settings in `config_section` are to be overlaid on top of the settings
from these sections. The "general" section is assumed implicitly.
Override in subclasses."""
class TransformSpec:
"""
Runtime transform specification base class.
TransformSpec subclass objects used by `docutils.transforms.Transformer`.
"""
def get_transforms(self):
"""Transforms required by this class. Override in subclasses."""
if self.default_transforms != ():
import warnings
warnings.warn('default_transforms attribute deprecated.\n'
'Use get_transforms() method instead.',
DeprecationWarning)
return list(self.default_transforms)
return []
# Deprecated; for compatibility.
default_transforms = ()
unknown_reference_resolvers = ()
"""List of functions to try to resolve unknown references. Unknown
references have a 'refname' attribute which doesn't correspond to any
target in the document. Called when the transforms in
`docutils.tranforms.references` are unable to find a correct target. The
list should contain functions which will try to resolve unknown
references, with the following signature::
def reference_resolver(node):
'''Returns boolean: true if resolved, false if not.'''
If the function is able to resolve the reference, it should also remove
the 'refname' attribute and mark the node as resolved::
del node['refname']
node.resolved = 1
Each function must have a "priority" attribute which will affect the order
the unknown_reference_resolvers are run::
reference_resolver.priority = 100
Override in subclasses."""
class Component(SettingsSpec, TransformSpec):
"""Base class for Docutils components."""
component_type = None
"""Name of the component type ('reader', 'parser', 'writer'). Override in
subclasses."""
supported = ()
"""Names for this component. Override in subclasses."""
def supports(self, format):
"""
Is `format` supported by this component?
To be used by transforms to ask the dependent component if it supports
a certain input context or output format.
"""
return format in self.supported
| {
"repo_name": "akiokio/centralfitestoque",
"path": "src/.pycharm_helpers/docutils/__init__.py",
"copies": "1",
"size": "7112",
"license": "bsd-2-clause",
"hash": -7284775350619548000,
"line_mean": 33.862745098,
"line_max": 81,
"alpha_frac": 0.6975534308,
"autogenerated": false,
"ratio": 4.553137003841229,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00040514542845963223,
"num_lines": 204
} |
"""
Open Document Format (ODF) Writer.
"""
VERSION = '1.0a'
__docformat__ = 'reStructuredText'
import StringIO
import copy
import os
import os.path
import re
import tempfile
import time
import zipfile
from xml.dom import minidom
import docutils
from docutils import frontend, nodes, utils, writers
from docutils.readers import standalone
from docutils.transforms import references
WhichElementTree = ''
try:
# 1. Try to use lxml.
#from lxml import etree
#WhichElementTree = 'lxml'
raise ImportError('Ignoring lxml')
except ImportError, e:
try:
# 2. Try to use ElementTree from the Python standard library.
from xml.etree import ElementTree as etree
WhichElementTree = 'elementtree'
except ImportError, e:
try:
# 3. Try to use a version of ElementTree installed as a separate
# product.
from elementtree import ElementTree as etree
WhichElementTree = 'elementtree'
except ImportError, e:
s1 = 'Must install either a version of Python containing ' \
'ElementTree (Python version >=2.5) or install ElementTree.'
raise ImportError(s1)
#
# Import pygments and odtwriter pygments formatters if possible.
try:
import pygments
import pygments.lexers
from pygmentsformatter import OdtPygmentsProgFormatter, \
OdtPygmentsLaTeXFormatter
except ImportError, exp:
pygments = None
#
# Is the PIL imaging library installed?
try:
import Image
except ImportError, exp:
Image = None
## import warnings
## warnings.warn('importing IPShellEmbed', UserWarning)
## from IPython.Shell import IPShellEmbed
## args = ['-pdb', '-pi1', 'In <\\#>: ', '-pi2', ' .\\D.: ',
## '-po', 'Out<\\#>: ', '-nosep']
## ipshell = IPShellEmbed(args,
## banner = 'Entering IPython. Press Ctrl-D to exit.',
## exit_msg = 'Leaving Interpreter, back to program.')
#
# ElementTree does not support getparent method (lxml does).
# This wrapper class and the following support functions provide
# that support for the ability to get the parent of an element.
#
if WhichElementTree == 'elementtree':
class _ElementInterfaceWrapper(etree._ElementInterface):
def __init__(self, tag, attrib=None):
etree._ElementInterface.__init__(self, tag, attrib)
if attrib is None:
attrib = {}
self.parent = None
def setparent(self, parent):
self.parent = parent
def getparent(self):
return self.parent
#
# Constants and globals
SPACES_PATTERN = re.compile(r'( +)')
TABS_PATTERN = re.compile(r'(\t+)')
FILL_PAT1 = re.compile(r'^ +')
FILL_PAT2 = re.compile(r' {2,}')
TABLESTYLEPREFIX = 'rststyle-table-'
TABLENAMEDEFAULT = '%s0' % TABLESTYLEPREFIX
TABLEPROPERTYNAMES = ('border', 'border-top', 'border-left',
'border-right', 'border-bottom', )
GENERATOR_DESC = 'Docutils.org/odf_odt'
NAME_SPACE_1 = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'
CONTENT_NAMESPACE_DICT = CNSD = {
# 'office:version': '1.0',
'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'dom': 'http://www.w3.org/2001/xml-events',
'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'math': 'http://www.w3.org/1998/Math/MathML',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'office': NAME_SPACE_1,
'ooo': 'http://openoffice.org/2004/office',
'oooc': 'http://openoffice.org/2004/calc',
'ooow': 'http://openoffice.org/2004/writer',
'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xforms': 'http://www.w3.org/2002/xforms',
'xlink': 'http://www.w3.org/1999/xlink',
'xsd': 'http://www.w3.org/2001/XMLSchema',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
STYLES_NAMESPACE_DICT = SNSD = {
# 'office:version': '1.0',
'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'dom': 'http://www.w3.org/2001/xml-events',
'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'math': 'http://www.w3.org/1998/Math/MathML',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'office': NAME_SPACE_1,
'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'ooo': 'http://openoffice.org/2004/office',
'oooc': 'http://openoffice.org/2004/calc',
'ooow': 'http://openoffice.org/2004/writer',
'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xlink': 'http://www.w3.org/1999/xlink',
}
MANIFEST_NAMESPACE_DICT = MANNSD = {
'manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}
META_NAMESPACE_DICT = METNSD = {
# 'office:version': '1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'office': NAME_SPACE_1,
'ooo': 'http://openoffice.org/2004/office',
'xlink': 'http://www.w3.org/1999/xlink',
}
#
# Attribute dictionaries for use with ElementTree (not lxml), which
# does not support use of nsmap parameter on Element() and SubElement().
CONTENT_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:dom': 'http://www.w3.org/2001/xml-events',
'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:oooc': 'http://openoffice.org/2004/calc',
'xmlns:ooow': 'http://openoffice.org/2004/writer',
'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xmlns:xforms': 'http://www.w3.org/2002/xforms',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
STYLES_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:dom': 'http://www.w3.org/2001/xml-events',
'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:oooc': 'http://openoffice.org/2004/calc',
'xmlns:ooow': 'http://openoffice.org/2004/writer',
'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}
MANIFEST_NAMESPACE_ATTRIB = {
'xmlns:manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}
META_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}
#
# Functions
#
#
# ElementTree support functions.
# In order to be able to get the parent of elements, must use these
# instead of the functions with same name provided by ElementTree.
#
def Element(tag, attrib=None, nsmap=None, nsdict=CNSD):
if attrib is None:
attrib = {}
tag, attrib = fix_ns(tag, attrib, nsdict)
if WhichElementTree == 'lxml':
el = etree.Element(tag, attrib, nsmap=nsmap)
else:
el = _ElementInterfaceWrapper(tag, attrib)
return el
def SubElement(parent, tag, attrib=None, nsmap=None, nsdict=CNSD):
if attrib is None:
attrib = {}
tag, attrib = fix_ns(tag, attrib, nsdict)
if WhichElementTree == 'lxml':
el = etree.SubElement(parent, tag, attrib, nsmap=nsmap)
else:
el = _ElementInterfaceWrapper(tag, attrib)
parent.append(el)
el.setparent(parent)
return el
def fix_ns(tag, attrib, nsdict):
nstag = add_ns(tag, nsdict)
nsattrib = {}
for key, val in attrib.iteritems():
nskey = add_ns(key, nsdict)
nsattrib[nskey] = val
return nstag, nsattrib
def add_ns(tag, nsdict=CNSD):
if WhichElementTree == 'lxml':
nstag, name = tag.split(':')
ns = nsdict.get(nstag)
if ns is None:
raise RuntimeError, 'Invalid namespace prefix: %s' % nstag
tag = '{%s}%s' % (ns, name,)
return tag
def ToString(et):
outstream = StringIO.StringIO()
et.write(outstream)
s1 = outstream.getvalue()
outstream.close()
return s1
def escape_cdata(text):
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
ascii = ''
for char in text:
if ord(char) >= ord("\x7f"):
ascii += "&#x%X;" % ( ord(char), )
else:
ascii += char
return ascii
WORD_SPLIT_PAT1 = re.compile(r'\b(\w*)\b\W*')
def split_words(line):
# We need whitespace at the end of the string for our regexpr.
line += ' '
words = []
pos1 = 0
mo = WORD_SPLIT_PAT1.search(line, pos1)
while mo is not None:
word = mo.groups()[0]
words.append(word)
pos1 = mo.end()
mo = WORD_SPLIT_PAT1.search(line, pos1)
return words
#
# Classes
#
class TableStyle(object):
def __init__(self, border=None, backgroundcolor=None):
self.border = border
self.backgroundcolor = backgroundcolor
def get_border_(self):
return self.border_
def set_border_(self, border):
self.border_ = border
border = property(get_border_, set_border_)
def get_backgroundcolor_(self):
return self.backgroundcolor_
def set_backgroundcolor_(self, backgroundcolor):
self.backgroundcolor_ = backgroundcolor
backgroundcolor = property(get_backgroundcolor_, set_backgroundcolor_)
BUILTIN_DEFAULT_TABLE_STYLE = TableStyle(
border = '0.0007in solid #000000')
#
# Information about the indentation level for lists nested inside
# other contexts, e.g. dictionary lists.
class ListLevel(object):
def __init__(self, level, sibling_level=True, nested_level=True):
self.level = level
self.sibling_level = sibling_level
self.nested_level = nested_level
def set_sibling(self, sibling_level): self.sibling_level = sibling_level
def get_sibling(self): return self.sibling_level
def set_nested(self, nested_level): self.nested_level = nested_level
def get_nested(self): return self.nested_level
def set_level(self, level): self.level = level
def get_level(self): return self.level
class Writer(writers.Writer):
MIME_TYPE = 'application/vnd.oasis.opendocument.text'
EXTENSION = '.odt'
supported = ('odt', )
"""Formats this writer supports."""
default_stylesheet = 'styles' + EXTENSION
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = (
'ODF-Specific Options',
None,
(
('Specify a stylesheet. '
'Default: "%s"' % default_stylesheet_path,
['--stylesheet'],
{
'default': default_stylesheet_path,
'dest': 'stylesheet'
}),
('Specify a configuration/mapping file relative to the '
'current working '
'directory for additional ODF options. '
'In particular, this file may contain a section named '
'"Formats" that maps default style names to '
'names to be used in the resulting output file allowing for '
'adhering to external standards. '
'For more info and the format of the configuration/mapping file, '
'see the odtwriter doc.',
['--odf-config-file'],
{'metavar': '<file>'}),
('Obfuscate email addresses to confuse harvesters while still '
'keeping email links usable with standards-compliant browsers.',
['--cloak-email-addresses'],
{'default': False,
'action': 'store_true',
'dest': 'cloak_email_addresses',
'validator': frontend.validate_boolean}),
('Do not obfuscate email addresses.',
['--no-cloak-email-addresses'],
{'default': False,
'action': 'store_false',
'dest': 'cloak_email_addresses',
'validator': frontend.validate_boolean}),
('Specify the thickness of table borders in thousands of a cm. '
'Default is 35.',
['--table-border-thickness'],
{'default': None,
'validator': frontend.validate_nonnegative_int}),
('Add syntax highlighting in literal code blocks.',
['--add-syntax-highlighting'],
{'default': False,
'action': 'store_true',
'dest': 'add_syntax_highlighting',
'validator': frontend.validate_boolean}),
('Do not add syntax highlighting in literal code blocks. (default)',
['--no-syntax-highlighting'],
{'default': False,
'action': 'store_false',
'dest': 'add_syntax_highlighting',
'validator': frontend.validate_boolean}),
('Create sections for headers. (default)',
['--create-sections'],
{'default': True,
'action': 'store_true',
'dest': 'create_sections',
'validator': frontend.validate_boolean}),
('Do not create sections for headers.',
['--no-sections'],
{'default': True,
'action': 'store_false',
'dest': 'create_sections',
'validator': frontend.validate_boolean}),
('Create links.',
['--create-links'],
{'default': False,
'action': 'store_true',
'dest': 'create_links',
'validator': frontend.validate_boolean}),
('Do not create links. (default)',
['--no-links'],
{'default': False,
'action': 'store_false',
'dest': 'create_links',
'validator': frontend.validate_boolean}),
('Generate endnotes at end of document, not footnotes '
'at bottom of page.',
['--endnotes-end-doc'],
{'default': False,
'action': 'store_true',
'dest': 'endnotes_end_doc',
'validator': frontend.validate_boolean}),
('Generate footnotes at bottom of page, not endnotes '
'at end of document. (default)',
['--no-endnotes-end-doc'],
{'default': False,
'action': 'store_false',
'dest': 'endnotes_end_doc',
'validator': frontend.validate_boolean}),
('Generate a bullet list table of contents, not '
'an ODF/oowriter table of contents.',
['--generate-list-toc'],
{'default': True,
'action': 'store_false',
'dest': 'generate_oowriter_toc',
'validator': frontend.validate_boolean}),
('Generate an ODF/oowriter table of contents, not '
'a bullet list. (default)',
['--generate-oowriter-toc'],
{'default': True,
'action': 'store_true',
'dest': 'generate_oowriter_toc',
'validator': frontend.validate_boolean}),
('Specify the contents of an custom header line. '
'See odf_odt writer documentation for details '
'about special field character sequences.',
['--custom-odt-header'],
{ 'default': '',
'dest': 'custom_header',
}),
('Specify the contents of an custom footer line. '
'See odf_odt writer documentation for details '
'about special field character sequences.',
['--custom-odt-footer'],
{ 'default': '',
'dest': 'custom_footer',
}),
)
)
settings_defaults = {
'output_encoding_error_handler': 'xmlcharrefreplace',
}
relative_path_settings = (
'stylesheet_path',
)
config_section = 'opendocument odf writer'
config_section_dependencies = (
'writers',
)
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = ODFTranslator
def translate(self):
self.settings = self.document.settings
self.visitor = self.translator_class(self.document)
self.visitor.retrieve_styles(self.EXTENSION)
self.document.walkabout(self.visitor)
self.visitor.add_doc_title()
self.assemble_my_parts()
self.output = self.parts['whole']
def assemble_my_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses.
"""
writers.Writer.assemble_parts(self)
f = tempfile.NamedTemporaryFile()
zfile = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
content = self.visitor.content_astext()
self.write_zip_str(zfile, 'content.xml', content)
self.write_zip_str(zfile, 'mimetype', self.MIME_TYPE)
s1 = self.create_manifest()
self.write_zip_str(zfile, 'META-INF/manifest.xml', s1)
s1 = self.create_meta()
self.write_zip_str(zfile, 'meta.xml', s1)
s1 = self.get_stylesheet()
self.write_zip_str(zfile, 'styles.xml', s1)
s1 = self.get_settings()
self.write_zip_str(zfile, 'settings.xml', s1)
self.store_embedded_files(zfile)
zfile.close()
f.seek(0)
whole = f.read()
f.close()
self.parts['whole'] = whole
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
def write_zip_str(self, zfile, name, bytes):
localtime = time.localtime(time.time())
zinfo = zipfile.ZipInfo(name, localtime)
# Add some standard UNIX file access permissions (-rw-r--r--).
zinfo.external_attr = (0x81a4 & 0xFFFF) << 16L
zinfo.compress_type = zipfile.ZIP_DEFLATED
zfile.writestr(zinfo, bytes)
def store_embedded_files(self, zfile):
embedded_files = self.visitor.get_embedded_file_list()
for source, destination in embedded_files:
if source is None:
continue
try:
# encode/decode
destination1 = destination.decode('latin-1').encode('utf-8')
zfile.write(source, destination1, zipfile.ZIP_STORED)
except OSError, e:
self.document.reporter.warning(
"Can't open file %s." % (source, ))
def get_settings(self):
"""
modeled after get_stylesheet
"""
stylespath = self.settings.stylesheet
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('settings.xml')
zfile.close()
return s1
def get_stylesheet(self):
"""Get the stylesheet from the visitor.
Ask the visitor to setup the page.
"""
s1 = self.visitor.setup_page()
return s1
def assemble_parts(self):
pass
def create_manifest(self):
if WhichElementTree == 'lxml':
root = Element('manifest:manifest',
nsmap=MANIFEST_NAMESPACE_DICT,
nsdict=MANIFEST_NAMESPACE_DICT,
)
else:
root = Element('manifest:manifest',
attrib=MANIFEST_NAMESPACE_ATTRIB,
nsdict=MANIFEST_NAMESPACE_DICT,
)
doc = etree.ElementTree(root)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': self.MIME_TYPE,
'manifest:full-path': '/',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'content.xml',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'styles.xml',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'meta.xml',
}, nsdict=MANNSD)
s1 = ToString(doc)
doc = minidom.parseString(s1)
s1 = doc.toprettyxml(' ')
return s1
def create_meta(self):
if WhichElementTree == 'lxml':
root = Element('office:document-meta',
nsmap=META_NAMESPACE_DICT,
nsdict=META_NAMESPACE_DICT,
)
else:
root = Element('office:document-meta',
attrib=META_NAMESPACE_ATTRIB,
nsdict=META_NAMESPACE_DICT,
)
doc = etree.ElementTree(root)
root = SubElement(root, 'office:meta', nsdict=METNSD)
el1 = SubElement(root, 'meta:generator', nsdict=METNSD)
el1.text = 'Docutils/rst2odf.py/%s' % (VERSION, )
s1 = os.environ.get('USER', '')
el1 = SubElement(root, 'meta:initial-creator', nsdict=METNSD)
el1.text = s1
s2 = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())
el1 = SubElement(root, 'meta:creation-date', nsdict=METNSD)
el1.text = s2
el1 = SubElement(root, 'dc:creator', nsdict=METNSD)
el1.text = s1
el1 = SubElement(root, 'dc:date', nsdict=METNSD)
el1.text = s2
el1 = SubElement(root, 'dc:language', nsdict=METNSD)
el1.text = 'en-US'
el1 = SubElement(root, 'meta:editing-cycles', nsdict=METNSD)
el1.text = '1'
el1 = SubElement(root, 'meta:editing-duration', nsdict=METNSD)
el1.text = 'PT00M01S'
title = self.visitor.get_title()
el1 = SubElement(root, 'dc:title', nsdict=METNSD)
if title:
el1.text = title
else:
el1.text = '[no title]'
meta_dict = self.visitor.get_meta_dict()
keywordstr = meta_dict.get('keywords')
if keywordstr is not None:
keywords = split_words(keywordstr)
for keyword in keywords:
el1 = SubElement(root, 'meta:keyword', nsdict=METNSD)
el1.text = keyword
description = meta_dict.get('description')
if description is not None:
el1 = SubElement(root, 'dc:description', nsdict=METNSD)
el1.text = description
s1 = ToString(doc)
#doc = minidom.parseString(s1)
#s1 = doc.toprettyxml(' ')
return s1
# class ODFTranslator(nodes.SparseNodeVisitor):
class ODFTranslator(nodes.GenericNodeVisitor):
used_styles = (
'attribution', 'blockindent', 'blockquote', 'blockquote-bulletitem',
'blockquote-bulletlist', 'blockquote-enumitem', 'blockquote-enumlist',
'bulletitem', 'bulletlist',
'caption', 'legend',
'centeredtextbody', 'codeblock',
'codeblock-classname', 'codeblock-comment', 'codeblock-functionname',
'codeblock-keyword', 'codeblock-name', 'codeblock-number',
'codeblock-operator', 'codeblock-string', 'emphasis', 'enumitem',
'enumlist', 'epigraph', 'epigraph-bulletitem', 'epigraph-bulletlist',
'epigraph-enumitem', 'epigraph-enumlist', 'footer',
'footnote', 'citation',
'header', 'highlights', 'highlights-bulletitem',
'highlights-bulletlist', 'highlights-enumitem', 'highlights-enumlist',
'horizontalline', 'inlineliteral', 'quotation', 'rubric',
'strong', 'table-title', 'textbody', 'tocbulletlist', 'tocenumlist',
'title',
'subtitle',
'heading1',
'heading2',
'heading3',
'heading4',
'heading5',
'heading6',
'heading7',
'admon-attention-hdr',
'admon-attention-body',
'admon-caution-hdr',
'admon-caution-body',
'admon-danger-hdr',
'admon-danger-body',
'admon-error-hdr',
'admon-error-body',
'admon-generic-hdr',
'admon-generic-body',
'admon-hint-hdr',
'admon-hint-body',
'admon-important-hdr',
'admon-important-body',
'admon-note-hdr',
'admon-note-body',
'admon-tip-hdr',
'admon-tip-body',
'admon-warning-hdr',
'admon-warning-body',
'tableoption',
'tableoption.%c', 'tableoption.%c%d', 'Table%d', 'Table%d.%c',
'Table%d.%c%d',
'lineblock1',
'lineblock2',
'lineblock3',
'lineblock4',
'lineblock5',
'lineblock6',
'image', 'figureframe',
)
def __init__(self, document):
#nodes.SparseNodeVisitor.__init__(self, document)
nodes.GenericNodeVisitor.__init__(self, document)
self.settings = document.settings
self.format_map = { }
if self.settings.odf_config_file:
from ConfigParser import ConfigParser
parser = ConfigParser()
parser.read(self.settings.odf_config_file)
for rststyle, format in parser.items("Formats"):
if rststyle not in self.used_styles:
self.document.reporter.warning(
'Style "%s" is not a style used by odtwriter.' % (
rststyle, ))
self.format_map[rststyle] = format
self.section_level = 0
self.section_count = 0
# Create ElementTree content and styles documents.
if WhichElementTree == 'lxml':
root = Element(
'office:document-content',
nsmap=CONTENT_NAMESPACE_DICT,
)
else:
root = Element(
'office:document-content',
attrib=CONTENT_NAMESPACE_ATTRIB,
)
self.content_tree = etree.ElementTree(element=root)
self.current_element = root
SubElement(root, 'office:scripts')
SubElement(root, 'office:font-face-decls')
el = SubElement(root, 'office:automatic-styles')
self.automatic_styles = el
el = SubElement(root, 'office:body')
el = self.generate_content_element(el)
self.current_element = el
self.body_text_element = el
self.paragraph_style_stack = [self.rststyle('textbody'), ]
self.list_style_stack = []
self.table_count = 0
self.column_count = ord('A') - 1
self.trace_level = -1
self.optiontablestyles_generated = False
self.field_name = None
self.field_element = None
self.title = None
self.image_count = 0
self.image_style_count = 0
self.image_dict = {}
self.embedded_file_list = []
self.syntaxhighlighting = 1
self.syntaxhighlight_lexer = 'python'
self.header_content = []
self.footer_content = []
self.in_header = False
self.in_footer = False
self.blockstyle = ''
self.in_table_of_contents = False
self.table_of_content_index_body = None
self.list_level = 0
self.footnote_ref_dict = {}
self.footnote_list = []
self.footnote_chars_idx = 0
self.footnote_level = 0
self.pending_ids = [ ]
self.in_paragraph = False
self.found_doc_title = False
self.bumped_list_level_stack = []
self.meta_dict = {}
self.line_block_level = 0
self.line_indent_level = 0
self.citation_id = None
self.style_index = 0 # use to form unique style names
self.str_stylesheet = ''
self.str_stylesheetcontent = ''
self.dom_stylesheet = None
self.table_styles = None
def get_str_stylesheet(self):
return self.str_stylesheet
def retrieve_styles(self, extension):
"""Retrieve the stylesheet from either a .xml file or from
a .odt (zip) file. Return the content as a string.
"""
s2 = None
stylespath = self.settings.stylesheet
ext = os.path.splitext(stylespath)[1]
if ext == '.xml':
stylesfile = open(stylespath, 'r')
s1 = stylesfile.read()
stylesfile.close()
elif ext == extension:
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('styles.xml')
s2 = zfile.read('content.xml')
zfile.close()
else:
raise RuntimeError, 'stylesheet path (%s) must be %s or .xml file' %(stylespath, extension)
self.str_stylesheet = s1
self.str_stylesheetcontent = s2
self.dom_stylesheet = etree.fromstring(self.str_stylesheet)
self.dom_stylesheetcontent = etree.fromstring(self.str_stylesheetcontent)
self.table_styles = self.extract_table_styles(s2)
def extract_table_styles(self, styles_str):
root = etree.fromstring(styles_str)
table_styles = {}
auto_styles = root.find(
'{%s}automatic-styles' % (CNSD['office'], ))
for stylenode in auto_styles:
name = stylenode.get('{%s}name' % (CNSD['style'], ))
tablename = name.split('.')[0]
family = stylenode.get('{%s}family' % (CNSD['style'], ))
if name.startswith(TABLESTYLEPREFIX):
tablestyle = table_styles.get(tablename)
if tablestyle is None:
tablestyle = TableStyle()
table_styles[tablename] = tablestyle
if family == 'table':
properties = stylenode.find(
'{%s}table-properties' % (CNSD['style'], ))
property = properties.get('{%s}%s' % (CNSD['fo'],
'background-color', ))
if property is not None and property != 'none':
tablestyle.backgroundcolor = property
elif family == 'table-cell':
properties = stylenode.find(
'{%s}table-cell-properties' % (CNSD['style'], ))
if properties is not None:
border = self.get_property(properties)
if border is not None:
tablestyle.border = border
return table_styles
def get_property(self, stylenode):
border = None
for propertyname in TABLEPROPERTYNAMES:
border = stylenode.get('{%s}%s' % (CNSD['fo'], propertyname, ))
if border is not None and border != 'none':
return border
return border
def add_doc_title(self):
text = self.settings.title
if text:
self.title = text
if not self.found_doc_title:
el = Element('text:p', attrib = {
'text:style-name': self.rststyle('title'),
})
el.text = text
self.body_text_element.insert(0, el)
def rststyle(self, name, parameters=( )):
"""
Returns the style name to use for the given style.
If `parameters` is given `name` must contain a matching number of ``%`` and
is used as a format expression with `parameters` as the value.
"""
name1 = name % parameters
stylename = self.format_map.get(name1, 'rststyle-%s' % name1)
return stylename
def generate_content_element(self, root):
return SubElement(root, 'office:text')
def setup_page(self):
self.setup_paper(self.dom_stylesheet)
if (len(self.header_content) > 0 or len(self.footer_content) > 0 or
self.settings.custom_header or self.settings.custom_footer):
self.add_header_footer(self.dom_stylesheet)
new_content = etree.tostring(self.dom_stylesheet)
return new_content
def setup_paper(self, root_el):
try:
fin = os.popen("paperconf -s 2> /dev/null")
w, h = map(float, fin.read().split())
fin.close()
except:
w, h = 612, 792 # default to Letter
def walk(el):
if el.tag == "{%s}page-layout-properties" % SNSD["style"] and \
not el.attrib.has_key("{%s}page-width" % SNSD["fo"]):
el.attrib["{%s}page-width" % SNSD["fo"]] = "%.3fpt" % w
el.attrib["{%s}page-height" % SNSD["fo"]] = "%.3fpt" % h
el.attrib["{%s}margin-left" % SNSD["fo"]] = \
el.attrib["{%s}margin-right" % SNSD["fo"]] = \
"%.3fpt" % (.1 * w)
el.attrib["{%s}margin-top" % SNSD["fo"]] = \
el.attrib["{%s}margin-bottom" % SNSD["fo"]] = \
"%.3fpt" % (.1 * h)
else:
for subel in el.getchildren(): walk(subel)
walk(root_el)
def add_header_footer(self, root_el):
automatic_styles = root_el.find(
'{%s}automatic-styles' % SNSD['office'])
path = '{%s}master-styles' % (NAME_SPACE_1, )
master_el = root_el.find(path)
if master_el is None:
return
path = '{%s}master-page' % (SNSD['style'], )
master_el = master_el.find(path)
if master_el is None:
return
el1 = master_el
if self.header_content or self.settings.custom_header:
if WhichElementTree == 'lxml':
el2 = SubElement(el1, 'style:header', nsdict=SNSD)
else:
el2 = SubElement(el1, 'style:header',
attrib=STYLES_NAMESPACE_ATTRIB,
nsdict=STYLES_NAMESPACE_DICT,
)
for el in self.header_content:
attrkey = add_ns('text:style-name', nsdict=SNSD)
el.attrib[attrkey] = self.rststyle('header')
el2.append(el)
if self.settings.custom_header:
elcustom = self.create_custom_headfoot(el2,
self.settings.custom_header, 'header', automatic_styles)
if self.footer_content or self.settings.custom_footer:
if WhichElementTree == 'lxml':
el2 = SubElement(el1, 'style:footer', nsdict=SNSD)
else:
el2 = SubElement(el1, 'style:footer',
attrib=STYLES_NAMESPACE_ATTRIB,
nsdict=STYLES_NAMESPACE_DICT,
)
for el in self.footer_content:
attrkey = add_ns('text:style-name', nsdict=SNSD)
el.attrib[attrkey] = self.rststyle('footer')
el2.append(el)
if self.settings.custom_footer:
elcustom = self.create_custom_headfoot(el2,
self.settings.custom_footer, 'footer', automatic_styles)
code_none, code_field, code_text = range(3)
field_pat = re.compile(r'%(..?)%')
def create_custom_headfoot(self, parent, text, style_name, automatic_styles):
current_element = None
field_iter = self.split_field_specifiers_iter(text)
for item in field_iter:
if item[0] == ODFTranslator.code_field:
if item[1] not in ('p', 'P',
't1', 't2', 't3', 't4',
'd1', 'd2', 'd3', 'd4', 'd5',
's', 't', 'a'):
msg = 'bad field spec: %%%s%%' % (item[1], )
raise RuntimeError, msg
if current_element is None:
parent = SubElement(parent, 'text:p', attrib={
'text:style-name': self.rststyle(style_name),
})
el1 = self.make_field_element(parent,
item[1], style_name, automatic_styles)
if el1 is None:
msg = 'bad field spec: %%%s%%' % (item[1], )
raise RuntimeError, msg
else:
current_element = el1
else:
if current_element is None:
parent = SubElement(parent, 'text:p', attrib={
'text:style-name': self.rststyle(style_name),
})
parent.text = item[1]
else:
current_element.tail = item[1]
def make_field_element(self, parent, text, style_name, automatic_styles):
if text == 'p':
el1 = SubElement(parent, 'text:page-number', attrib={
'text:style-name': self.rststyle(style_name),
'text:select-page': 'current',
})
elif text == 'P':
el1 = SubElement(parent, 'text:page-count', attrib={
'text:style-name': self.rststyle(style_name),
})
elif text == 't1':
self.style_index += 1
el1 = SubElement(parent, 'text:time', attrib={
'text:style-name': self.rststyle(style_name),
'text:fixed': 'true',
'style:data-style-name': 'rst-time-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:time-style', attrib={
'style:name': 'rst-time-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:hours', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:minutes', attrib={
'number:style': 'long',
})
elif text == 't2':
self.style_index += 1
el1 = SubElement(parent, 'text:time', attrib={
'text:style-name': self.rststyle(style_name),
'text:fixed': 'true',
'style:data-style-name': 'rst-time-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:time-style', attrib={
'style:name': 'rst-time-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:hours', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:minutes', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:seconds', attrib={
'number:style': 'long',
})
elif text == 't3':
self.style_index += 1
el1 = SubElement(parent, 'text:time', attrib={
'text:style-name': self.rststyle(style_name),
'text:fixed': 'true',
'style:data-style-name': 'rst-time-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:time-style', attrib={
'style:name': 'rst-time-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:hours', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:minutes', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ' '
el3 = SubElement(el2, 'number:am-pm')
elif text == 't4':
self.style_index += 1
el1 = SubElement(parent, 'text:time', attrib={
'text:style-name': self.rststyle(style_name),
'text:fixed': 'true',
'style:data-style-name': 'rst-time-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:time-style', attrib={
'style:name': 'rst-time-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:hours', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:minutes', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:seconds', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ' '
el3 = SubElement(el2, 'number:am-pm')
elif text == 'd1':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'number:automatic-order': 'true',
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:month', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '/'
el3 = SubElement(el2, 'number:day', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '/'
el3 = SubElement(el2, 'number:year')
elif text == 'd2':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'number:automatic-order': 'true',
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:month', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '/'
el3 = SubElement(el2, 'number:day', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '/'
el3 = SubElement(el2, 'number:year', attrib={
'number:style': 'long',
})
elif text == 'd3':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'number:automatic-order': 'true',
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:month', attrib={
'number:textual': 'true',
})
el3 = SubElement(el2, 'number:text')
el3.text = ' '
el3 = SubElement(el2, 'number:day', attrib={
})
el3 = SubElement(el2, 'number:text')
el3.text = ', '
el3 = SubElement(el2, 'number:year', attrib={
'number:style': 'long',
})
elif text == 'd4':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'number:automatic-order': 'true',
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:month', attrib={
'number:textual': 'true',
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ' '
el3 = SubElement(el2, 'number:day', attrib={
})
el3 = SubElement(el2, 'number:text')
el3.text = ', '
el3 = SubElement(el2, 'number:year', attrib={
'number:style': 'long',
})
elif text == 'd5':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:year', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '-'
el3 = SubElement(el2, 'number:month', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '-'
el3 = SubElement(el2, 'number:day', attrib={
'number:style': 'long',
})
elif text == 's':
el1 = SubElement(parent, 'text:subject', attrib={
'text:style-name': self.rststyle(style_name),
})
elif text == 't':
el1 = SubElement(parent, 'text:title', attrib={
'text:style-name': self.rststyle(style_name),
})
elif text == 'a':
el1 = SubElement(parent, 'text:author-name', attrib={
'text:fixed': 'false',
})
else:
el1 = None
return el1
def split_field_specifiers_iter(self, text):
pos1 = 0
pos_end = len(text)
while True:
mo = ODFTranslator.field_pat.search(text, pos1)
if mo:
pos2 = mo.start()
if pos2 > pos1:
yield (ODFTranslator.code_text, text[pos1:pos2])
yield (ODFTranslator.code_field, mo.group(1))
pos1 = mo.end()
else:
break
trailing = text[pos1:]
if trailing:
yield (ODFTranslator.code_text, trailing)
def astext(self):
root = self.content_tree.getroot()
et = etree.ElementTree(root)
s1 = ToString(et)
return s1
def content_astext(self):
return self.astext()
def set_title(self, title): self.title = title
def get_title(self): return self.title
def set_embedded_file_list(self, embedded_file_list):
self.embedded_file_list = embedded_file_list
def get_embedded_file_list(self): return self.embedded_file_list
def get_meta_dict(self): return self.meta_dict
def process_footnotes(self):
for node, el1 in self.footnote_list:
backrefs = node.attributes.get('backrefs', [])
first = True
for ref in backrefs:
el2 = self.footnote_ref_dict.get(ref)
if el2 is not None:
if first:
first = False
el3 = copy.deepcopy(el1)
el2.append(el3)
else:
children = el2.getchildren()
if len(children) > 0: # and 'id' in el2.attrib:
child = children[0]
ref1 = child.text
attribkey = add_ns('text:id', nsdict=SNSD)
id1 = el2.get(attribkey, 'footnote-error')
if id1 is None:
id1 = ''
tag = add_ns('text:note-ref', nsdict=SNSD)
el2.tag = tag
if self.settings.endnotes_end_doc:
note_class = 'endnote'
else:
note_class = 'footnote'
el2.attrib.clear()
attribkey = add_ns('text:note-class', nsdict=SNSD)
el2.attrib[attribkey] = note_class
attribkey = add_ns('text:ref-name', nsdict=SNSD)
el2.attrib[attribkey] = id1
attribkey = add_ns('text:reference-format', nsdict=SNSD)
el2.attrib[attribkey] = 'page'
el2.text = ref1
#
# Utility methods
def append_child(self, tag, attrib=None, parent=None):
if parent is None:
parent = self.current_element
if attrib is None:
el = SubElement(parent, tag)
else:
el = SubElement(parent, tag, attrib)
return el
def append_p(self, style, text=None):
result = self.append_child('text:p', attrib={
'text:style-name': self.rststyle(style)})
self.append_pending_ids(result)
if text is not None:
result.text = text
return result
def append_pending_ids(self, el):
if self.settings.create_links:
for id in self.pending_ids:
SubElement(el, 'text:reference-mark', attrib={
'text:name': id})
self.pending_ids = [ ]
def set_current_element(self, el):
self.current_element = el
def set_to_parent(self):
self.current_element = self.current_element.getparent()
def generate_labeled_block(self, node, label):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
el = self.append_p('blockindent')
return el
def generate_labeled_line(self, node, label):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
el1.tail = node.astext()
return el
def encode(self, text):
text = text.replace(u'\u00a0', " ")
return text
#
# Visitor functions
#
# In alphabetic order, more or less.
# See docutils.docutils.nodes.node_class_names.
#
def dispatch_visit(self, node):
"""Override to catch basic attributes which many nodes have."""
self.handle_basic_atts(node)
nodes.GenericNodeVisitor.dispatch_visit(self, node)
def handle_basic_atts(self, node):
if isinstance(node, nodes.Element) and node['ids']:
self.pending_ids += node['ids']
def default_visit(self, node):
self.document.reporter.warning('missing visit_%s' % (node.tagname, ))
def default_departure(self, node):
self.document.reporter.warning('missing depart_%s' % (node.tagname, ))
def visit_Text(self, node):
# Skip nodes whose text has been processed in parent nodes.
if isinstance(node.parent, docutils.nodes.literal_block):
return
text = node.astext()
# Are we in mixed content? If so, add the text to the
# etree tail of the previous sibling element.
if len(self.current_element.getchildren()) > 0:
if self.current_element.getchildren()[-1].tail:
self.current_element.getchildren()[-1].tail += text
else:
self.current_element.getchildren()[-1].tail = text
else:
if self.current_element.text:
self.current_element.text += text
else:
self.current_element.text = text
def depart_Text(self, node):
pass
#
# Pre-defined fields
#
def visit_address(self, node):
el = self.generate_labeled_block(node, 'Address: ')
self.set_current_element(el)
def depart_address(self, node):
self.set_to_parent()
def visit_author(self, node):
if isinstance(node.parent, nodes.authors):
el = self.append_p('blockindent')
else:
el = self.generate_labeled_block(node, 'Author: ')
self.set_current_element(el)
def depart_author(self, node):
self.set_to_parent()
def visit_authors(self, node):
label = 'Authors:'
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
def depart_authors(self, node):
pass
def visit_contact(self, node):
el = self.generate_labeled_block(node, 'Contact: ')
self.set_current_element(el)
def depart_contact(self, node):
self.set_to_parent()
def visit_copyright(self, node):
el = self.generate_labeled_block(node, 'Copyright: ')
self.set_current_element(el)
def depart_copyright(self, node):
self.set_to_parent()
def visit_date(self, node):
self.generate_labeled_line(node, 'Date: ')
def depart_date(self, node):
pass
def visit_organization(self, node):
el = self.generate_labeled_block(node, 'Organization: ')
self.set_current_element(el)
def depart_organization(self, node):
self.set_to_parent()
def visit_status(self, node):
el = self.generate_labeled_block(node, 'Status: ')
self.set_current_element(el)
def depart_status(self, node):
self.set_to_parent()
def visit_revision(self, node):
self.generate_labeled_line(node, 'Revision: ')
def depart_revision(self, node):
pass
def visit_version(self, node):
el = self.generate_labeled_line(node, 'Version: ')
#self.set_current_element(el)
def depart_version(self, node):
#self.set_to_parent()
pass
def visit_attribution(self, node):
el = self.append_p('attribution', node.astext())
def depart_attribution(self, node):
pass
def visit_block_quote(self, node):
if 'epigraph' in node.attributes['classes']:
self.paragraph_style_stack.append(self.rststyle('epigraph'))
self.blockstyle = self.rststyle('epigraph')
elif 'highlights' in node.attributes['classes']:
self.paragraph_style_stack.append(self.rststyle('highlights'))
self.blockstyle = self.rststyle('highlights')
else:
self.paragraph_style_stack.append(self.rststyle('blockquote'))
self.blockstyle = self.rststyle('blockquote')
self.line_indent_level += 1
def depart_block_quote(self, node):
self.paragraph_style_stack.pop()
self.blockstyle = ''
self.line_indent_level -= 1
def visit_bullet_list(self, node):
self.list_level +=1
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
pass
else:
if node.has_key('classes') and \
'auto-toc' in node.attributes['classes']:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('tocenumlist'),
})
self.list_style_stack.append(self.rststyle('enumitem'))
else:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('tocbulletlist'),
})
self.list_style_stack.append(self.rststyle('bulletitem'))
self.set_current_element(el)
else:
if self.blockstyle == self.rststyle('blockquote'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('blockquote-bulletitem'))
elif self.blockstyle == self.rststyle('highlights'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('highlights-bulletitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('epigraph-bulletitem'))
else:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('bulletlist'),
})
self.list_style_stack.append(self.rststyle('bulletitem'))
self.set_current_element(el)
def depart_bullet_list(self, node):
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
pass
else:
self.set_to_parent()
self.list_style_stack.pop()
else:
self.set_to_parent()
self.list_style_stack.pop()
self.list_level -=1
def visit_caption(self, node):
raise nodes.SkipChildren()
pass
def depart_caption(self, node):
pass
def visit_comment(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'office:annotation', attrib={})
el2 = SubElement(el1, 'text:p', attrib={})
el2.text = node.astext()
def depart_comment(self, node):
pass
def visit_compound(self, node):
# The compound directive currently receives no special treatment.
pass
def depart_compound(self, node):
pass
def visit_container(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
self.paragraph_style_stack.append(self.rststyle(styles[0]))
def depart_container(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
self.paragraph_style_stack.pop()
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
self.paragraph_style_stack.append(self.rststyle('blockindent'))
self.bumped_list_level_stack.append(ListLevel(1))
def depart_definition(self, node):
self.paragraph_style_stack.pop()
self.bumped_list_level_stack.pop()
def visit_definition_list(self, node):
pass
def depart_definition_list(self, node):
pass
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_term(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
#el1.text = node.astext()
self.set_current_element(el1)
def depart_term(self, node):
self.set_to_parent()
self.set_to_parent()
def visit_classifier(self, node):
els = self.current_element.getchildren()
if len(els) > 0:
el = els[-1]
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('emphasis')
})
el1.text = ' (%s)' % (node.astext(), )
def depart_classifier(self, node):
pass
def visit_document(self, node):
pass
def depart_document(self, node):
self.process_footnotes()
def visit_docinfo(self, node):
self.section_level += 1
self.section_count += 1
if self.settings.create_sections:
el = self.append_child('text:section', attrib={
'text:name': 'Section%d' % self.section_count,
'text:style-name': 'Sect%d' % self.section_level,
})
self.set_current_element(el)
def depart_docinfo(self, node):
self.section_level -= 1
if self.settings.create_sections:
self.set_to_parent()
def visit_emphasis(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('emphasis')})
self.set_current_element(el)
def depart_emphasis(self, node):
self.set_to_parent()
def visit_enumerated_list(self, node):
el1 = self.current_element
if self.blockstyle == self.rststyle('blockquote'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-enumlist'),
})
self.list_style_stack.append(self.rststyle('blockquote-enumitem'))
elif self.blockstyle == self.rststyle('highlights'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-enumlist'),
})
self.list_style_stack.append(self.rststyle('highlights-enumitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-enumlist'),
})
self.list_style_stack.append(self.rststyle('epigraph-enumitem'))
else:
liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), )
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle(liststylename),
})
self.list_style_stack.append(self.rststyle('enumitem'))
self.set_current_element(el2)
def depart_enumerated_list(self, node):
self.set_to_parent()
self.list_style_stack.pop()
def visit_list_item(self, node):
# If we are in a "bumped" list level, then wrap this
# list in an outer lists in order to increase the
# indentation level.
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
self.paragraph_style_stack.append(
self.rststyle('contents-%d' % (self.list_level, )))
else:
el1 = self.append_child('text:list-item')
self.set_current_element(el1)
else:
el1 = self.append_child('text:list-item')
el3 = el1
if len(self.bumped_list_level_stack) > 0:
level_obj = self.bumped_list_level_stack[-1]
if level_obj.get_sibling():
level_obj.set_nested(False)
for level_obj1 in self.bumped_list_level_stack:
for idx in range(level_obj1.get_level()):
el2 = self.append_child('text:list', parent=el3)
el3 = self.append_child(
'text:list-item', parent=el2)
self.paragraph_style_stack.append(self.list_style_stack[-1])
self.set_current_element(el3)
def depart_list_item(self, node):
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
self.paragraph_style_stack.pop()
else:
self.set_to_parent()
else:
if len(self.bumped_list_level_stack) > 0:
level_obj = self.bumped_list_level_stack[-1]
if level_obj.get_sibling():
level_obj.set_nested(True)
for level_obj1 in self.bumped_list_level_stack:
for idx in range(level_obj1.get_level()):
self.set_to_parent()
self.set_to_parent()
self.paragraph_style_stack.pop()
self.set_to_parent()
def visit_header(self, node):
self.in_header = True
def depart_header(self, node):
self.in_header = False
def visit_footer(self, node):
self.in_footer = True
def depart_footer(self, node):
self.in_footer = False
def visit_field(self, node):
pass
def depart_field(self, node):
pass
def visit_field_list(self, node):
pass
def depart_field_list(self, node):
pass
def visit_field_name(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = node.astext()
def depart_field_name(self, node):
pass
def visit_field_body(self, node):
self.paragraph_style_stack.append(self.rststyle('blockindent'))
def depart_field_body(self, node):
self.paragraph_style_stack.pop()
def visit_figure(self, node):
pass
def depart_figure(self, node):
pass
def visit_footnote(self, node):
self.footnote_level += 1
self.save_footnote_current = self.current_element
el1 = Element('text:note-body')
self.current_element = el1
self.footnote_list.append((node, el1))
if isinstance(node, docutils.nodes.citation):
self.paragraph_style_stack.append(self.rststyle('citation'))
else:
self.paragraph_style_stack.append(self.rststyle('footnote'))
def depart_footnote(self, node):
self.paragraph_style_stack.pop()
self.current_element = self.save_footnote_current
self.footnote_level -= 1
footnote_chars = [
'*', '**', '***',
'++', '+++',
'##', '###',
'@@', '@@@',
]
def visit_footnote_reference(self, node):
if self.footnote_level <= 0:
id = node.attributes['ids'][0]
refid = node.attributes.get('refid')
if refid is None:
refid = ''
if self.settings.endnotes_end_doc:
note_class = 'endnote'
else:
note_class = 'footnote'
el1 = self.append_child('text:note', attrib={
'text:id': '%s' % (refid, ),
'text:note-class': note_class,
})
note_auto = str(node.attributes.get('auto', 1))
if isinstance(node, docutils.nodes.citation_reference):
citation = '[%s]' % node.astext()
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': citation,
})
el2.text = citation
elif note_auto == '1':
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': node.astext(),
})
el2.text = node.astext()
elif note_auto == '*':
if self.footnote_chars_idx >= len(
ODFTranslator.footnote_chars):
self.footnote_chars_idx = 0
footnote_char = ODFTranslator.footnote_chars[
self.footnote_chars_idx]
self.footnote_chars_idx += 1
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': footnote_char,
})
el2.text = footnote_char
self.footnote_ref_dict[id] = el1
raise nodes.SkipChildren()
def depart_footnote_reference(self, node):
pass
def visit_citation(self, node):
for id in node.attributes['ids']:
self.citation_id = id
break
self.paragraph_style_stack.append(self.rststyle('blockindent'))
self.bumped_list_level_stack.append(ListLevel(1))
def depart_citation(self, node):
self.citation_id = None
self.paragraph_style_stack.pop()
self.bumped_list_level_stack.pop()
def visit_citation_reference(self, node):
if self.settings.create_links:
id = node.attributes['refid']
el = self.append_child('text:reference-ref', attrib={
'text:ref-name': '%s' % (id, ),
'text:reference-format': 'text',
})
el.text = '['
self.set_current_element(el)
elif self.current_element.text is None:
self.current_element.text = '['
else:
self.current_element.text += '['
def depart_citation_reference(self, node):
self.current_element.text += ']'
if self.settings.create_links:
self.set_to_parent()
def visit_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
raise nodes.SkipChildren()
elif self.citation_id is not None:
el = self.append_p('textbody')
self.set_current_element(el)
el.text = '['
if self.settings.create_links:
el1 = self.append_child('text:reference-mark-start', attrib={
'text:name': '%s' % (self.citation_id, ),
})
def depart_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
pass
elif self.citation_id is not None:
self.current_element.text += ']'
if self.settings.create_links:
el = self.append_child('text:reference-mark-end', attrib={
'text:name': '%s' % (self.citation_id, ),
})
self.set_to_parent()
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def check_file_exists(self, path):
if os.path.exists(path):
return 1
else:
return 0
def visit_image(self, node):
# Capture the image file.
if 'uri' in node.attributes:
source = node.attributes['uri']
if not self.check_file_exists(source):
self.document.reporter.warning(
'Cannot find image file %s.' % (source, ))
return
else:
return
if source in self.image_dict:
filename, destination = self.image_dict[source]
else:
self.image_count += 1
filename = os.path.split(source)[1]
destination = 'Pictures/1%08x%s' % (self.image_count, filename, )
spec = (os.path.abspath(source), destination,)
self.embedded_file_list.append(spec)
self.image_dict[source] = (source, destination,)
# Is this a figure (containing an image) or just a plain image?
if self.in_paragraph:
el1 = self.current_element
else:
el1 = SubElement(self.current_element, 'text:p',
attrib={'text:style-name': self.rststyle('textbody')})
el2 = el1
if isinstance(node.parent, docutils.nodes.figure):
el3, el4, el5, caption = self.generate_figure(node, source,
destination, el2)
attrib = {}
el6, width = self.generate_image(node, source, destination,
el5, attrib)
if caption is not None:
el6.tail = caption
else: #if isinstance(node.parent, docutils.nodes.image):
el3 = self.generate_image(node, source, destination, el2)
def depart_image(self, node):
pass
def get_image_width_height(self, node, attr):
size = None
if attr in node.attributes:
size = node.attributes[attr]
unit = size[-2:]
if unit.isalpha():
size = size[:-2]
else:
unit = 'px'
try:
size = float(size)
except ValueError, e:
self.document.reporter.warning(
'Invalid %s for image: "%s"' % (
attr, node.attributes[attr]))
size = [size, unit]
return size
def get_image_scale(self, node):
if 'scale' in node.attributes:
try:
scale = int(node.attributes['scale'])
if scale < 1: # or scale > 100:
self.document.reporter.warning(
'scale out of range (%s), using 1.' % (scale, ))
scale = 1
scale = scale * 0.01
except ValueError, e:
self.document.reporter.warning(
'Invalid scale for image: "%s"' % (
node.attributes['scale'], ))
else:
scale = 1.0
return scale
def get_image_scaled_width_height(self, node, source):
scale = self.get_image_scale(node)
width = self.get_image_width_height(node, 'width')
height = self.get_image_width_height(node, 'height')
dpi = (72, 72)
if Image is not None and source in self.image_dict:
filename, destination = self.image_dict[source]
imageobj = Image.open(filename, 'r')
dpi = imageobj.info.get('dpi', dpi)
# dpi information can be (xdpi, ydpi) or xydpi
try: iter(dpi)
except: dpi = (dpi, dpi)
else:
imageobj = None
if width is None or height is None:
if imageobj is None:
raise RuntimeError(
'image size not fully specified and PIL not installed')
if width is None: width = [imageobj.size[0], 'px']
if height is None: height = [imageobj.size[1], 'px']
width[0] *= scale
height[0] *= scale
if width[1] == 'px': width = [width[0] / dpi[0], 'in']
if height[1] == 'px': height = [height[0] / dpi[1], 'in']
width[0] = str(width[0])
height[0] = str(height[0])
return ''.join(width), ''.join(height)
def generate_figure(self, node, source, destination, current_element):
caption = None
width, height = self.get_image_scaled_width_height(node, source)
for node1 in node.parent.children:
if node1.tagname == 'caption':
caption = node1.astext()
self.image_style_count += 1
#
# Add the style for the caption.
if caption is not None:
attrib = {
'style:class': 'extra',
'style:family': 'paragraph',
'style:name': 'Caption',
'style:parent-style-name': 'Standard',
}
el1 = SubElement(self.automatic_styles, 'style:style',
attrib=attrib, nsdict=SNSD)
attrib = {
'fo:margin-bottom': '0.0835in',
'fo:margin-top': '0.0835in',
'text:line-number': '0',
'text:number-lines': 'false',
}
el2 = SubElement(el1, 'style:paragraph-properties',
attrib=attrib, nsdict=SNSD)
attrib = {
'fo:font-size': '12pt',
'fo:font-style': 'italic',
'style:font-name': 'Times',
'style:font-name-complex': 'Lucidasans1',
'style:font-size-asian': '12pt',
'style:font-size-complex': '12pt',
'style:font-style-asian': 'italic',
'style:font-style-complex': 'italic',
}
el2 = SubElement(el1, 'style:text-properties',
attrib=attrib, nsdict=SNSD)
style_name = 'rstframestyle%d' % self.image_style_count
# Add the styles
attrib = {
'style:name': style_name,
'style:family': 'graphic',
'style:parent-style-name': self.rststyle('figureframe'),
}
el1 = SubElement(self.automatic_styles,
'style:style', attrib=attrib, nsdict=SNSD)
halign = 'center'
valign = 'top'
if 'align' in node.attributes:
align = node.attributes['align'].split()
for val in align:
if val in ('left', 'center', 'right'):
halign = val
elif val in ('top', 'middle', 'bottom'):
valign = val
attrib = {}
wrap = False
classes = node.parent.attributes.get('classes')
if classes and 'wrap' in classes:
wrap = True
if wrap:
attrib['style:wrap'] = 'dynamic'
else:
attrib['style:wrap'] = 'none'
el2 = SubElement(el1,
'style:graphic-properties', attrib=attrib, nsdict=SNSD)
attrib = {
'draw:style-name': style_name,
'draw:name': 'Frame1',
'text:anchor-type': 'paragraph',
'draw:z-index': '0',
}
attrib['svg:width'] = width
# dbg
#attrib['svg:height'] = height
el3 = SubElement(current_element, 'draw:frame', attrib=attrib)
attrib = {}
el4 = SubElement(el3, 'draw:text-box', attrib=attrib)
attrib = {
'text:style-name': self.rststyle('caption'),
}
el5 = SubElement(el4, 'text:p', attrib=attrib)
return el3, el4, el5, caption
def generate_image(self, node, source, destination, current_element,
frame_attrs=None):
width, height = self.get_image_scaled_width_height(node, source)
self.image_style_count += 1
style_name = 'rstframestyle%d' % self.image_style_count
# Add the style.
attrib = {
'style:name': style_name,
'style:family': 'graphic',
'style:parent-style-name': self.rststyle('image'),
}
el1 = SubElement(self.automatic_styles,
'style:style', attrib=attrib, nsdict=SNSD)
halign = None
valign = None
if 'align' in node.attributes:
align = node.attributes['align'].split()
for val in align:
if val in ('left', 'center', 'right'):
halign = val
elif val in ('top', 'middle', 'bottom'):
valign = val
if frame_attrs is None:
attrib = {
'style:vertical-pos': 'top',
'style:vertical-rel': 'paragraph',
'style:horizontal-rel': 'paragraph',
'style:mirror': 'none',
'fo:clip': 'rect(0cm 0cm 0cm 0cm)',
'draw:luminance': '0%',
'draw:contrast': '0%',
'draw:red': '0%',
'draw:green': '0%',
'draw:blue': '0%',
'draw:gamma': '100%',
'draw:color-inversion': 'false',
'draw:image-opacity': '100%',
'draw:color-mode': 'standard',
}
else:
attrib = frame_attrs
if halign is not None:
attrib['style:horizontal-pos'] = halign
if valign is not None:
attrib['style:vertical-pos'] = valign
# If there is a classes/wrap directive or we are
# inside a table, add a no-wrap style.
wrap = False
classes = node.attributes.get('classes')
if classes and 'wrap' in classes:
wrap = True
if wrap:
attrib['style:wrap'] = 'dynamic'
else:
attrib['style:wrap'] = 'none'
# If we are inside a table, add a no-wrap style.
if self.is_in_table(node):
attrib['style:wrap'] = 'none'
el2 = SubElement(el1,
'style:graphic-properties', attrib=attrib, nsdict=SNSD)
# Add the content.
#el = SubElement(current_element, 'text:p',
# attrib={'text:style-name': self.rststyle('textbody')})
attrib={
'draw:style-name': style_name,
'draw:name': 'graphics2',
'draw:z-index': '1',
}
if isinstance(node.parent, nodes.TextElement):
attrib['text:anchor-type'] = 'as-char' #vds
else:
attrib['text:anchor-type'] = 'paragraph'
attrib['svg:width'] = width
attrib['svg:height'] = height
el1 = SubElement(current_element, 'draw:frame', attrib=attrib)
el2 = SubElement(el1, 'draw:image', attrib={
'xlink:href': '%s' % (destination, ),
'xlink:type': 'simple',
'xlink:show': 'embed',
'xlink:actuate': 'onLoad',
})
return el1, width
def is_in_table(self, node):
node1 = node.parent
while node1:
if isinstance(node1, docutils.nodes.entry):
return True
node1 = node1.parent
return False
def visit_legend(self, node):
if isinstance(node.parent, docutils.nodes.figure):
el1 = self.current_element[-1]
el1 = el1[0][0]
self.current_element = el1
self.paragraph_style_stack.append(self.rststyle('legend'))
def depart_legend(self, node):
if isinstance(node.parent, docutils.nodes.figure):
self.paragraph_style_stack.pop()
self.set_to_parent()
self.set_to_parent()
self.set_to_parent()
def visit_line_block(self, node):
self.line_indent_level += 1
self.line_block_level += 1
def depart_line_block(self, node):
self.line_indent_level -= 1
self.line_block_level -= 1
def visit_line(self, node):
style = 'lineblock%d' % self.line_indent_level
el1 = SubElement(self.current_element, 'text:p', attrib={
'text:style-name': self.rststyle(style),
})
self.current_element = el1
def depart_line(self, node):
self.set_to_parent()
def visit_literal(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('inlineliteral')})
self.set_current_element(el)
def depart_literal(self, node):
self.set_to_parent()
def visit_inline(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
inline_style = styles[0]
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle(inline_style)})
self.set_current_element(el)
def depart_inline(self, node):
self.set_to_parent()
def _calculate_code_block_padding(self, line):
count = 0
matchobj = SPACES_PATTERN.match(line)
if matchobj:
pad = matchobj.group()
count = len(pad)
else:
matchobj = TABS_PATTERN.match(line)
if matchobj:
pad = matchobj.group()
count = len(pad) * 8
return count
def _add_syntax_highlighting(self, insource, language):
lexer = pygments.lexers.get_lexer_by_name(language, stripall=True)
if language in ('latex', 'tex'):
fmtr = OdtPygmentsLaTeXFormatter(lambda name, parameters=():
self.rststyle(name, parameters),
escape_function=escape_cdata)
else:
fmtr = OdtPygmentsProgFormatter(lambda name, parameters=():
self.rststyle(name, parameters),
escape_function=escape_cdata)
outsource = pygments.highlight(insource, lexer, fmtr)
return outsource
def fill_line(self, line):
line = FILL_PAT1.sub(self.fill_func1, line)
line = FILL_PAT2.sub(self.fill_func2, line)
return line
def fill_func1(self, matchobj):
spaces = matchobj.group(0)
repl = '<text:s text:c="%d"/>' % (len(spaces), )
return repl
def fill_func2(self, matchobj):
spaces = matchobj.group(0)
repl = ' <text:s text:c="%d"/>' % (len(spaces) - 1, )
return repl
def visit_literal_block(self, node):
wrapper1 = '<text:p text:style-name="%s">%%s</text:p>' % (
self.rststyle('codeblock'), )
source = node.astext()
if (pygments and
self.settings.add_syntax_highlighting
#and
#node.get('hilight', False)
):
language = node.get('language', 'python')
source = self._add_syntax_highlighting(source, language)
else:
source = escape_cdata(source)
lines = source.split('\n')
lines1 = ['<wrappertag1 xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">']
my_lines = []
for my_line in lines:
my_line = self.fill_line(my_line)
my_line = my_line.replace(" ", "\n")
my_lines.append(my_line)
my_lines_str = '<text:line-break/>'.join(my_lines)
my_lines_str2 = wrapper1 % (my_lines_str, )
lines1.append(my_lines_str2)
lines1.append('</wrappertag1>')
s1 = ''.join(lines1)
if WhichElementTree != "lxml":
s1 = s1.encode("utf-8")
el1 = etree.fromstring(s1)
children = el1.getchildren()
for child in children:
self.current_element.append(child)
def depart_literal_block(self, node):
pass
visit_doctest_block = visit_literal_block
depart_doctest_block = depart_literal_block
def visit_meta(self, node):
name = node.attributes.get('name')
content = node.attributes.get('content')
if name is not None and content is not None:
self.meta_dict[name] = content
def depart_meta(self, node):
pass
def visit_option_list(self, node):
table_name = 'tableoption'
#
# Generate automatic styles
if not self.optiontablestyles_generated:
self.optiontablestyles_generated = True
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(table_name),
'style:family': 'table'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-properties', attrib={
'style:width': '17.59cm',
'table:align': 'left',
'style:shadow': 'none'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle('%s.%%c' % table_name, ( 'A', )),
'style:family': 'table-column'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-column-properties', attrib={
'style:column-width': '4.999cm'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle('%s.%%c' % table_name, ( 'B', )),
'style:family': 'table-column'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-column-properties', attrib={
'style:column-width': '12.587cm'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 1, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:background-color': 'transparent',
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': 'none',
'fo:border-top': '0.035cm solid #000000',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
el2 = SubElement(el1, 'style:background-image', nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 1, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border': '0.035cm solid #000000'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 2, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': 'none',
'fo:border-top': 'none',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 2, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': '0.035cm solid #000000',
'fo:border-top': 'none',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
#
# Generate table data
el = self.append_child('table:table', attrib={
'table:name': self.rststyle(table_name),
'table:style-name': self.rststyle(table_name),
})
el1 = SubElement(el, 'table:table-column', attrib={
'table:style-name': self.rststyle(
'%s.%%c' % table_name, ( 'A', ))})
el1 = SubElement(el, 'table:table-column', attrib={
'table:style-name': self.rststyle(
'%s.%%c' % table_name, ( 'B', ))})
el1 = SubElement(el, 'table:table-header-rows')
el2 = SubElement(el1, 'table:table-row')
el3 = SubElement(el2, 'table:table-cell', attrib={
'table:style-name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 1, )),
'office:value-type': 'string'})
el4 = SubElement(el3, 'text:p', attrib={
'text:style-name': 'Table_20_Heading'})
el4.text= 'Option'
el3 = SubElement(el2, 'table:table-cell', attrib={
'table:style-name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 1, )),
'office:value-type': 'string'})
el4 = SubElement(el3, 'text:p', attrib={
'text:style-name': 'Table_20_Heading'})
el4.text= 'Description'
self.set_current_element(el)
def depart_option_list(self, node):
self.set_to_parent()
def visit_option_list_item(self, node):
el = self.append_child('table:table-row')
self.set_current_element(el)
def depart_option_list_item(self, node):
self.set_to_parent()
def visit_option_group(self, node):
el = self.append_child('table:table-cell', attrib={
'table:style-name': 'Table%d.A2' % self.table_count,
'office:value-type': 'string',
})
self.set_current_element(el)
def depart_option_group(self, node):
self.set_to_parent()
def visit_option(self, node):
el = self.append_child('text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el.text = node.astext()
def depart_option(self, node):
pass
def visit_option_string(self, node):
pass
def depart_option_string(self, node):
pass
def visit_option_argument(self, node):
pass
def depart_option_argument(self, node):
pass
def visit_description(self, node):
el = self.append_child('table:table-cell', attrib={
'table:style-name': 'Table%d.B2' % self.table_count,
'office:value-type': 'string',
})
el1 = SubElement(el, 'text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el1.text = node.astext()
raise nodes.SkipChildren()
def depart_description(self, node):
pass
def visit_paragraph(self, node):
self.in_paragraph = True
if self.in_header:
el = self.append_p('header')
elif self.in_footer:
el = self.append_p('footer')
else:
style_name = self.paragraph_style_stack[-1]
el = self.append_child('text:p',
attrib={'text:style-name': style_name})
self.append_pending_ids(el)
self.set_current_element(el)
def depart_paragraph(self, node):
self.in_paragraph = False
self.set_to_parent()
if self.in_header:
self.header_content.append(
self.current_element.getchildren()[-1])
self.current_element.remove(
self.current_element.getchildren()[-1])
elif self.in_footer:
self.footer_content.append(
self.current_element.getchildren()[-1])
self.current_element.remove(
self.current_element.getchildren()[-1])
def visit_problematic(self, node):
pass
def depart_problematic(self, node):
pass
def visit_raw(self, node):
if 'format' in node.attributes:
formats = node.attributes['format']
formatlist = formats.split()
if 'odt' in formatlist:
rawstr = node.astext()
attrstr = ' '.join(['%s="%s"' % (k, v, )
for k,v in CONTENT_NAMESPACE_ATTRIB.items()])
contentstr = '<stuff %s>%s</stuff>' % (attrstr, rawstr, )
if WhichElementTree != "lxml":
contentstr = contentstr.encode("utf-8")
content = etree.fromstring(contentstr)
elements = content.getchildren()
if len(elements) > 0:
el1 = elements[0]
if self.in_header:
pass
elif self.in_footer:
pass
else:
self.current_element.append(el1)
raise nodes.SkipChildren()
def depart_raw(self, node):
if self.in_header:
pass
elif self.in_footer:
pass
else:
pass
def visit_reference(self, node):
text = node.astext()
if self.settings.create_links:
if node.has_key('refuri'):
href = node['refuri']
if ( self.settings.cloak_email_addresses
and href.startswith('mailto:')):
href = self.cloak_mailto(href)
el = self.append_child('text:a', attrib={
'xlink:href': '%s' % href,
'xlink:type': 'simple',
})
self.set_current_element(el)
elif node.has_key('refid'):
if self.settings.create_links:
href = node['refid']
el = self.append_child('text:reference-ref', attrib={
'text:ref-name': '%s' % href,
'text:reference-format': 'text',
})
else:
self.document.reporter.warning(
'References must have "refuri" or "refid" attribute.')
if (self.in_table_of_contents and
len(node.children) >= 1 and
isinstance(node.children[0], docutils.nodes.generated)):
node.remove(node.children[0])
def depart_reference(self, node):
if self.settings.create_links:
if node.has_key('refuri'):
self.set_to_parent()
def visit_rubric(self, node):
style_name = self.rststyle('rubric')
classes = node.get('classes')
if classes:
class1 = classes[0]
if class1:
style_name = class1
el = SubElement(self.current_element, 'text:h', attrib = {
#'text:outline-level': '%d' % section_level,
#'text:style-name': 'Heading_20_%d' % section_level,
'text:style-name': style_name,
})
text = node.astext()
el.text = self.encode(text)
def depart_rubric(self, node):
pass
def visit_section(self, node, move_ids=1):
self.section_level += 1
self.section_count += 1
if self.settings.create_sections:
el = self.append_child('text:section', attrib={
'text:name': 'Section%d' % self.section_count,
'text:style-name': 'Sect%d' % self.section_level,
})
self.set_current_element(el)
def depart_section(self, node):
self.section_level -= 1
if self.settings.create_sections:
self.set_to_parent()
def visit_strong(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
self.set_current_element(el)
def depart_strong(self, node):
self.set_to_parent()
def visit_substitution_definition(self, node):
raise nodes.SkipChildren()
def depart_substitution_definition(self, node):
pass
def visit_system_message(self, node):
pass
def depart_system_message(self, node):
pass
def get_table_style(self, node):
table_style = None
table_name = None
use_predefined_table_style = False
str_classes = node.get('classes')
if str_classes is not None:
for str_class in str_classes:
if str_class.startswith(TABLESTYLEPREFIX):
table_name = str_class
use_predefined_table_style = True
break
if table_name is not None:
table_style = self.table_styles.get(table_name)
if table_style is None:
# If we can't find the table style, issue warning
# and use the default table style.
self.document.reporter.warning(
'Can\'t find table style "%s". Using default.' % (
table_name, ))
table_name = TABLENAMEDEFAULT
table_style = self.table_styles.get(table_name)
if table_style is None:
# If we can't find the default table style, issue a warning
# and use a built-in default style.
self.document.reporter.warning(
'Can\'t find default table style "%s". Using built-in default.' % (
table_name, ))
table_style = BUILTIN_DEFAULT_TABLE_STYLE
else:
table_name = TABLENAMEDEFAULT
table_style = self.table_styles.get(table_name)
if table_style is None:
# If we can't find the default table style, issue a warning
# and use a built-in default style.
self.document.reporter.warning(
'Can\'t find default table style "%s". Using built-in default.' % (
table_name, ))
table_style = BUILTIN_DEFAULT_TABLE_STYLE
return table_style
def visit_table(self, node):
self.table_count += 1
table_style = self.get_table_style(node)
table_name = '%s%%d' % TABLESTYLEPREFIX
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
'style:family': 'table',
}, nsdict=SNSD)
if table_style.backgroundcolor is None:
el1_1 = SubElement(el1, 'style:table-properties', attrib={
#'style:width': '17.59cm',
'table:align': 'margins',
'fo:margin-top': '0in',
'fo:margin-bottom': '0.10in',
}, nsdict=SNSD)
else:
el1_1 = SubElement(el1, 'style:table-properties', attrib={
#'style:width': '17.59cm',
'table:align': 'margins',
'fo:margin-top': '0in',
'fo:margin-bottom': '0.10in',
'fo:background-color': table_style.backgroundcolor,
}, nsdict=SNSD)
# We use a single cell style for all cells in this table.
# That's probably not correct, but seems to work.
el2 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( self.table_count, 'A', 1, )),
'style:family': 'table-cell',
}, nsdict=SNSD)
thickness = self.settings.table_border_thickness
if thickness is None:
line_style1 = table_style.border
else:
line_style1 = '0.%03dcm solid #000000' % (thickness, )
el2_1 = SubElement(el2, 'style:table-cell-properties', attrib={
'fo:padding': '0.049cm',
'fo:border-left': line_style1,
'fo:border-right': line_style1,
'fo:border-top': line_style1,
'fo:border-bottom': line_style1,
}, nsdict=SNSD)
title = None
for child in node.children:
if child.tagname == 'title':
title = child.astext()
break
if title is not None:
el3 = self.append_p('table-title', title)
else:
pass
el4 = SubElement(self.current_element, 'table:table', attrib={
'table:name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
'table:style-name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
})
self.set_current_element(el4)
self.current_table_style = el1
self.table_width = 0
def depart_table(self, node):
attribkey = add_ns('style:width', nsdict=SNSD)
attribval = '%dcm' % self.table_width
self.current_table_style.attrib[attribkey] = attribval
self.set_to_parent()
def visit_tgroup(self, node):
self.column_count = ord('A') - 1
def depart_tgroup(self, node):
pass
def visit_colspec(self, node):
self.column_count += 1
colspec_name = self.rststyle(
'%s%%d.%%s' % TABLESTYLEPREFIX,
(self.table_count, chr(self.column_count), )
)
colwidth = node['colwidth']
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': colspec_name,
'style:family': 'table-column',
}, nsdict=SNSD)
el1_1 = SubElement(el1, 'style:table-column-properties', attrib={
'style:column-width': '%dcm' % colwidth }, nsdict=SNSD)
el2 = self.append_child('table:table-column', attrib={
'table:style-name': colspec_name,
})
self.table_width += colwidth
def depart_colspec(self, node):
pass
def visit_thead(self, node):
el = self.append_child('table:table-header-rows')
self.set_current_element(el)
self.in_thead = True
self.paragraph_style_stack.append('Table_20_Heading')
def depart_thead(self, node):
self.set_to_parent()
self.in_thead = False
self.paragraph_style_stack.pop()
def visit_row(self, node):
self.column_count = ord('A') - 1
el = self.append_child('table:table-row')
self.set_current_element(el)
def depart_row(self, node):
self.set_to_parent()
def visit_entry(self, node):
self.column_count += 1
cellspec_name = self.rststyle(
'%s%%d.%%c%%d' % TABLESTYLEPREFIX,
(self.table_count, 'A', 1, )
)
attrib={
'table:style-name': cellspec_name,
'office:value-type': 'string',
}
morecols = node.get('morecols', 0)
if morecols > 0:
attrib['table:number-columns-spanned'] = '%d' % (morecols + 1,)
self.column_count += morecols
morerows = node.get('morerows', 0)
if morerows > 0:
attrib['table:number-rows-spanned'] = '%d' % (morerows + 1,)
el1 = self.append_child('table:table-cell', attrib=attrib)
self.set_current_element(el1)
def depart_entry(self, node):
self.set_to_parent()
def visit_tbody(self, node):
pass
def depart_tbody(self, node):
pass
def visit_target(self, node):
#
# I don't know how to implement targets in ODF.
# How do we create a target in oowriter? A cross-reference?
if not (node.has_key('refuri') or node.has_key('refid')
or node.has_key('refname')):
pass
else:
pass
def depart_target(self, node):
pass
def visit_title(self, node, move_ids=1, title_type='title'):
if isinstance(node.parent, docutils.nodes.section):
section_level = self.section_level
if section_level > 7:
self.document.reporter.warning(
'Heading/section levels greater than 7 not supported.')
self.document.reporter.warning(
' Reducing to heading level 7 for heading: "%s"' % (
node.astext(), ))
section_level = 7
el1 = self.append_child('text:h', attrib = {
'text:outline-level': '%d' % section_level,
#'text:style-name': 'Heading_20_%d' % section_level,
'text:style-name': self.rststyle(
'heading%d', (section_level, )),
})
self.append_pending_ids(el1)
self.set_current_element(el1)
elif isinstance(node.parent, docutils.nodes.document):
# text = self.settings.title
#else:
# text = node.astext()
el1 = SubElement(self.current_element, 'text:p', attrib = {
'text:style-name': self.rststyle(title_type),
})
self.append_pending_ids(el1)
text = node.astext()
self.title = text
self.found_doc_title = True
self.set_current_element(el1)
def depart_title(self, node):
if (isinstance(node.parent, docutils.nodes.section) or
isinstance(node.parent, docutils.nodes.document)):
self.set_to_parent()
def visit_subtitle(self, node, move_ids=1):
self.visit_title(node, move_ids, title_type='subtitle')
def depart_subtitle(self, node):
self.depart_title(node)
def visit_title_reference(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': self.rststyle('quotation')})
el.text = self.encode(node.astext())
raise nodes.SkipChildren()
def depart_title_reference(self, node):
pass
def generate_table_of_content_entry_template(self, el1):
for idx in range(1, 11):
el2 = SubElement(el1,
'text:table-of-content-entry-template',
attrib={
'text:outline-level': "%d" % (idx, ),
'text:style-name': self.rststyle('contents-%d' % (idx, )),
})
el3 = SubElement(el2, 'text:index-entry-chapter')
el3 = SubElement(el2, 'text:index-entry-text')
el3 = SubElement(el2, 'text:index-entry-tab-stop', attrib={
'style:leader-char': ".",
'style:type': "right",
})
el3 = SubElement(el2, 'text:index-entry-page-number')
def visit_topic(self, node):
if 'classes' in node.attributes:
if 'contents' in node.attributes['classes']:
if self.settings.generate_oowriter_toc:
el1 = self.append_child('text:table-of-content', attrib={
'text:name': 'Table of Contents1',
'text:protected': 'true',
'text:style-name': 'Sect1',
})
el2 = SubElement(el1,
'text:table-of-content-source',
attrib={
'text:outline-level': '10',
})
el3 =SubElement(el2, 'text:index-title-template', attrib={
'text:style-name': 'Contents_20_Heading',
})
el3.text = 'Table of Contents'
self.generate_table_of_content_entry_template(el2)
el4 = SubElement(el1, 'text:index-body')
el5 = SubElement(el4, 'text:index-title')
el6 = SubElement(el5, 'text:p', attrib={
'text:style-name': self.rststyle('contents-heading'),
})
el6.text = 'Table of Contents'
self.save_current_element = self.current_element
self.table_of_content_index_body = el4
self.set_current_element(el4)
else:
el = self.append_p('horizontalline')
el = self.append_p('centeredtextbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = 'Contents'
self.in_table_of_contents = True
elif 'abstract' in node.attributes['classes']:
el = self.append_p('horizontalline')
el = self.append_p('centeredtextbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = 'Abstract'
def depart_topic(self, node):
if 'classes' in node.attributes:
if 'contents' in node.attributes['classes']:
if self.settings.generate_oowriter_toc:
self.update_toc_page_numbers(
self.table_of_content_index_body)
self.set_current_element(self.save_current_element)
else:
el = self.append_p('horizontalline')
self.in_table_of_contents = False
def update_toc_page_numbers(self, el):
collection = []
self.update_toc_collect(el, 0, collection)
self.update_toc_add_numbers(collection)
def update_toc_collect(self, el, level, collection):
collection.append((level, el))
level += 1
for child_el in el.getchildren():
if child_el.tag != 'text:index-body':
self.update_toc_collect(child_el, level, collection)
def update_toc_add_numbers(self, collection):
for level, el1 in collection:
if (el1.tag == 'text:p' and
el1.text != 'Table of Contents'):
el2 = SubElement(el1, 'text:tab')
el2.tail = '9999'
def visit_transition(self, node):
el = self.append_p('horizontalline')
def depart_transition(self, node):
pass
#
# Admonitions
#
def visit_warning(self, node):
self.generate_admonition(node, 'warning')
def depart_warning(self, node):
self.paragraph_style_stack.pop()
def visit_attention(self, node):
self.generate_admonition(node, 'attention')
depart_attention = depart_warning
def visit_caution(self, node):
self.generate_admonition(node, 'caution')
depart_caution = depart_warning
def visit_danger(self, node):
self.generate_admonition(node, 'danger')
depart_danger = depart_warning
def visit_error(self, node):
self.generate_admonition(node, 'error')
depart_error = depart_warning
def visit_hint(self, node):
self.generate_admonition(node, 'hint')
depart_hint = depart_warning
def visit_important(self, node):
self.generate_admonition(node, 'important')
depart_important = depart_warning
def visit_note(self, node):
self.generate_admonition(node, 'note')
depart_note = depart_warning
def visit_tip(self, node):
self.generate_admonition(node, 'tip')
depart_tip = depart_warning
def visit_admonition(self, node):
title = None
for child in node.children:
if child.tagname == 'title':
title = child.astext()
if title is None:
classes1 = node.get('classes')
if classes1:
title = classes1[0]
self.generate_admonition(node, 'generic', title)
depart_admonition = depart_warning
def generate_admonition(self, node, label, title=None):
el1 = SubElement(self.current_element, 'text:p', attrib = {
'text:style-name': self.rststyle('admon-%s-hdr', ( label, )),
})
if title:
el1.text = title
else:
el1.text = '%s!' % (label.capitalize(), )
s1 = self.rststyle('admon-%s-body', ( label, ))
self.paragraph_style_stack.append(s1)
#
# Roles (e.g. subscript, superscript, strong, ...
#
def visit_subscript(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': 'rststyle-subscript',
})
self.set_current_element(el)
def depart_subscript(self, node):
self.set_to_parent()
def visit_superscript(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': 'rststyle-superscript',
})
self.set_current_element(el)
def depart_superscript(self, node):
self.set_to_parent()
# Use an own reader to modify transformations done.
class Reader(standalone.Reader):
def get_transforms(self):
default = standalone.Reader.get_transforms(self)
if self.settings.create_links:
return default
return [ i
for i in default
if i is not references.DanglingReferences ]
| {
"repo_name": "kdwink/intellij-community",
"path": "python/helpers/py2only/docutils/writers/odf_odt/__init__.py",
"copies": "5",
"size": "119224",
"license": "apache-2.0",
"hash": -2157689204296556500,
"line_mean": 37.1394753679,
"line_max": 103,
"alpha_frac": 0.536259478,
"autogenerated": false,
"ratio": 3.8108997922326995,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002479478078370687,
"num_lines": 3126
} |
"""
Open Document Format (ODF) Writer.
"""
VERSION = '1.0a'
__docformat__ = 'reStructuredText'
import sys
import os
import os.path
import tempfile
import zipfile
from xml.dom import minidom
import time
import re
import StringIO
import inspect
import imp
import copy
import docutils
from docutils import frontend, nodes, utils, writers, languages
from docutils.parsers import rst
from docutils.readers import standalone
from docutils.transforms import references
WhichElementTree = ''
try:
# 1. Try to use lxml.
#from lxml import etree
#WhichElementTree = 'lxml'
raise ImportError('Ignoring lxml')
except ImportError, e:
try:
# 2. Try to use ElementTree from the Python standard library.
from xml.etree import ElementTree as etree
WhichElementTree = 'elementtree'
except ImportError, e:
try:
# 3. Try to use a version of ElementTree installed as a separate
# product.
from elementtree import ElementTree as etree
WhichElementTree = 'elementtree'
except ImportError, e:
s1 = 'Must install either a version of Python containing ' \
'ElementTree (Python version >=2.5) or install ElementTree.'
raise ImportError(s1)
#
# Import pygments and odtwriter pygments formatters if possible.
try:
import pygments
import pygments.lexers
from pygmentsformatter import OdtPygmentsProgFormatter, \
OdtPygmentsLaTeXFormatter
except ImportError, exp:
pygments = None
#
# Is the PIL imaging library installed?
try:
import Image
except ImportError, exp:
Image = None
## import warnings
## warnings.warn('importing IPShellEmbed', UserWarning)
## from IPython.Shell import IPShellEmbed
## args = ['-pdb', '-pi1', 'In <\\#>: ', '-pi2', ' .\\D.: ',
## '-po', 'Out<\\#>: ', '-nosep']
## ipshell = IPShellEmbed(args,
## banner = 'Entering IPython. Press Ctrl-D to exit.',
## exit_msg = 'Leaving Interpreter, back to program.')
#
# ElementTree does not support getparent method (lxml does).
# This wrapper class and the following support functions provide
# that support for the ability to get the parent of an element.
#
if WhichElementTree == 'elementtree':
class _ElementInterfaceWrapper(etree._ElementInterface):
def __init__(self, tag, attrib=None):
etree._ElementInterface.__init__(self, tag, attrib)
if attrib is None:
attrib = {}
self.parent = None
def setparent(self, parent):
self.parent = parent
def getparent(self):
return self.parent
#
# Constants and globals
SPACES_PATTERN = re.compile(r'( +)')
TABS_PATTERN = re.compile(r'(\t+)')
FILL_PAT1 = re.compile(r'^ +')
FILL_PAT2 = re.compile(r' {2,}')
TABLESTYLEPREFIX = 'rststyle-table-'
TABLENAMEDEFAULT = '%s0' % TABLESTYLEPREFIX
TABLEPROPERTYNAMES = ('border', 'border-top', 'border-left',
'border-right', 'border-bottom', )
GENERATOR_DESC = 'Docutils.org/odf_odt'
NAME_SPACE_1 = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'
CONTENT_NAMESPACE_DICT = CNSD = {
# 'office:version': '1.0',
'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'dom': 'http://www.w3.org/2001/xml-events',
'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'math': 'http://www.w3.org/1998/Math/MathML',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'office': NAME_SPACE_1,
'ooo': 'http://openoffice.org/2004/office',
'oooc': 'http://openoffice.org/2004/calc',
'ooow': 'http://openoffice.org/2004/writer',
'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xforms': 'http://www.w3.org/2002/xforms',
'xlink': 'http://www.w3.org/1999/xlink',
'xsd': 'http://www.w3.org/2001/XMLSchema',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
STYLES_NAMESPACE_DICT = SNSD = {
# 'office:version': '1.0',
'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'dom': 'http://www.w3.org/2001/xml-events',
'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'math': 'http://www.w3.org/1998/Math/MathML',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'office': NAME_SPACE_1,
'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'ooo': 'http://openoffice.org/2004/office',
'oooc': 'http://openoffice.org/2004/calc',
'ooow': 'http://openoffice.org/2004/writer',
'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xlink': 'http://www.w3.org/1999/xlink',
}
MANIFEST_NAMESPACE_DICT = MANNSD = {
'manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}
META_NAMESPACE_DICT = METNSD = {
# 'office:version': '1.0',
'dc': 'http://purl.org/dc/elements/1.1/',
'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'office': NAME_SPACE_1,
'ooo': 'http://openoffice.org/2004/office',
'xlink': 'http://www.w3.org/1999/xlink',
}
#
# Attribute dictionaries for use with ElementTree (not lxml), which
# does not support use of nsmap parameter on Element() and SubElement().
CONTENT_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:dom': 'http://www.w3.org/2001/xml-events',
'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:oooc': 'http://openoffice.org/2004/calc',
'xmlns:ooow': 'http://openoffice.org/2004/writer',
'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xmlns:xforms': 'http://www.w3.org/2002/xforms',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
}
STYLES_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:dom': 'http://www.w3.org/2001/xml-events',
'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:oooc': 'http://openoffice.org/2004/calc',
'xmlns:ooow': 'http://openoffice.org/2004/writer',
'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}
MANIFEST_NAMESPACE_ATTRIB = {
'xmlns:manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}
META_NAMESPACE_ATTRIB = {
'office:version': '1.0',
'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
'xmlns:office': NAME_SPACE_1,
'xmlns:ooo': 'http://openoffice.org/2004/office',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}
#
# Functions
#
#
# ElementTree support functions.
# In order to be able to get the parent of elements, must use these
# instead of the functions with same name provided by ElementTree.
#
def Element(tag, attrib=None, nsmap=None, nsdict=CNSD):
if attrib is None:
attrib = {}
tag, attrib = fix_ns(tag, attrib, nsdict)
if WhichElementTree == 'lxml':
el = etree.Element(tag, attrib, nsmap=nsmap)
else:
el = _ElementInterfaceWrapper(tag, attrib)
return el
def SubElement(parent, tag, attrib=None, nsmap=None, nsdict=CNSD):
if attrib is None:
attrib = {}
tag, attrib = fix_ns(tag, attrib, nsdict)
if WhichElementTree == 'lxml':
el = etree.SubElement(parent, tag, attrib, nsmap=nsmap)
else:
el = _ElementInterfaceWrapper(tag, attrib)
parent.append(el)
el.setparent(parent)
return el
def fix_ns(tag, attrib, nsdict):
nstag = add_ns(tag, nsdict)
nsattrib = {}
for key, val in attrib.iteritems():
nskey = add_ns(key, nsdict)
nsattrib[nskey] = val
return nstag, nsattrib
def add_ns(tag, nsdict=CNSD):
if WhichElementTree == 'lxml':
nstag, name = tag.split(':')
ns = nsdict.get(nstag)
if ns is None:
raise RuntimeError, 'Invalid namespace prefix: %s' % nstag
tag = '{%s}%s' % (ns, name,)
return tag
def ToString(et):
outstream = StringIO.StringIO()
et.write(outstream)
s1 = outstream.getvalue()
outstream.close()
return s1
def escape_cdata(text):
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
ascii = ''
for char in text:
if ord(char) >= ord("\x7f"):
ascii += "&#x%X;" % ( ord(char), )
else:
ascii += char
return ascii
WORD_SPLIT_PAT1 = re.compile(r'\b(\w*)\b\W*')
def split_words(line):
# We need whitespace at the end of the string for our regexpr.
line += ' '
words = []
pos1 = 0
mo = WORD_SPLIT_PAT1.search(line, pos1)
while mo is not None:
word = mo.groups()[0]
words.append(word)
pos1 = mo.end()
mo = WORD_SPLIT_PAT1.search(line, pos1)
return words
#
# Classes
#
class TableStyle(object):
def __init__(self, border=None, backgroundcolor=None):
self.border = border
self.backgroundcolor = backgroundcolor
def get_border_(self):
return self.border_
def set_border_(self, border):
self.border_ = border
border = property(get_border_, set_border_)
def get_backgroundcolor_(self):
return self.backgroundcolor_
def set_backgroundcolor_(self, backgroundcolor):
self.backgroundcolor_ = backgroundcolor
backgroundcolor = property(get_backgroundcolor_, set_backgroundcolor_)
BUILTIN_DEFAULT_TABLE_STYLE = TableStyle(
border = '0.0007in solid #000000')
#
# Information about the indentation level for lists nested inside
# other contexts, e.g. dictionary lists.
class ListLevel(object):
def __init__(self, level, sibling_level=True, nested_level=True):
self.level = level
self.sibling_level = sibling_level
self.nested_level = nested_level
def set_sibling(self, sibling_level): self.sibling_level = sibling_level
def get_sibling(self): return self.sibling_level
def set_nested(self, nested_level): self.nested_level = nested_level
def get_nested(self): return self.nested_level
def set_level(self, level): self.level = level
def get_level(self): return self.level
class Writer(writers.Writer):
MIME_TYPE = 'application/vnd.oasis.opendocument.text'
EXTENSION = '.odt'
supported = ('odt', )
"""Formats this writer supports."""
default_stylesheet = 'styles' + EXTENSION
default_stylesheet_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_stylesheet))
default_template = 'template.txt'
default_template_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = (
'ODF-Specific Options',
None,
(
('Specify a stylesheet. '
'Default: "%s"' % default_stylesheet_path,
['--stylesheet'],
{
'default': default_stylesheet_path,
'dest': 'stylesheet'
}),
('Specify a configuration/mapping file relative to the '
'current working '
'directory for additional ODF options. '
'In particular, this file may contain a section named '
'"Formats" that maps default style names to '
'names to be used in the resulting output file allowing for '
'adhering to external standards. '
'For more info and the format of the configuration/mapping file, '
'see the odtwriter doc.',
['--odf-config-file'],
{'metavar': '<file>'}),
('Obfuscate email addresses to confuse harvesters while still '
'keeping email links usable with standards-compliant browsers.',
['--cloak-email-addresses'],
{'default': False,
'action': 'store_true',
'dest': 'cloak_email_addresses',
'validator': frontend.validate_boolean}),
('Do not obfuscate email addresses.',
['--no-cloak-email-addresses'],
{'default': False,
'action': 'store_false',
'dest': 'cloak_email_addresses',
'validator': frontend.validate_boolean}),
('Specify the thickness of table borders in thousands of a cm. '
'Default is 35.',
['--table-border-thickness'],
{'default': None,
'validator': frontend.validate_nonnegative_int}),
('Add syntax highlighting in literal code blocks.',
['--add-syntax-highlighting'],
{'default': False,
'action': 'store_true',
'dest': 'add_syntax_highlighting',
'validator': frontend.validate_boolean}),
('Do not add syntax highlighting in literal code blocks. (default)',
['--no-syntax-highlighting'],
{'default': False,
'action': 'store_false',
'dest': 'add_syntax_highlighting',
'validator': frontend.validate_boolean}),
('Create sections for headers. (default)',
['--create-sections'],
{'default': True,
'action': 'store_true',
'dest': 'create_sections',
'validator': frontend.validate_boolean}),
('Do not create sections for headers.',
['--no-sections'],
{'default': True,
'action': 'store_false',
'dest': 'create_sections',
'validator': frontend.validate_boolean}),
('Create links.',
['--create-links'],
{'default': False,
'action': 'store_true',
'dest': 'create_links',
'validator': frontend.validate_boolean}),
('Do not create links. (default)',
['--no-links'],
{'default': False,
'action': 'store_false',
'dest': 'create_links',
'validator': frontend.validate_boolean}),
('Generate endnotes at end of document, not footnotes '
'at bottom of page.',
['--endnotes-end-doc'],
{'default': False,
'action': 'store_true',
'dest': 'endnotes_end_doc',
'validator': frontend.validate_boolean}),
('Generate footnotes at bottom of page, not endnotes '
'at end of document. (default)',
['--no-endnotes-end-doc'],
{'default': False,
'action': 'store_false',
'dest': 'endnotes_end_doc',
'validator': frontend.validate_boolean}),
('Generate a bullet list table of contents, not '
'an ODF/oowriter table of contents.',
['--generate-list-toc'],
{'default': True,
'action': 'store_false',
'dest': 'generate_oowriter_toc',
'validator': frontend.validate_boolean}),
('Generate an ODF/oowriter table of contents, not '
'a bullet list. (default)',
['--generate-oowriter-toc'],
{'default': True,
'action': 'store_true',
'dest': 'generate_oowriter_toc',
'validator': frontend.validate_boolean}),
('Specify the contents of an custom header line. '
'See odf_odt writer documentation for details '
'about special field character sequences.',
['--custom-odt-header'],
{ 'default': '',
'dest': 'custom_header',
}),
('Specify the contents of an custom footer line. '
'See odf_odt writer documentation for details '
'about special field character sequences.',
['--custom-odt-footer'],
{ 'default': '',
'dest': 'custom_footer',
}),
)
)
settings_defaults = {
'output_encoding_error_handler': 'xmlcharrefreplace',
}
relative_path_settings = (
'stylesheet_path',
)
config_section = 'opendocument odf writer'
config_section_dependencies = (
'writers',
)
def __init__(self):
writers.Writer.__init__(self)
self.translator_class = ODFTranslator
def translate(self):
self.settings = self.document.settings
self.visitor = self.translator_class(self.document)
self.visitor.retrieve_styles(self.EXTENSION)
self.document.walkabout(self.visitor)
self.visitor.add_doc_title()
self.assemble_my_parts()
self.output = self.parts['whole']
def assemble_my_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses.
"""
writers.Writer.assemble_parts(self)
f = tempfile.NamedTemporaryFile()
zfile = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
content = self.visitor.content_astext()
self.write_zip_str(zfile, 'content.xml', content)
self.write_zip_str(zfile, 'mimetype', self.MIME_TYPE)
s1 = self.create_manifest()
self.write_zip_str(zfile, 'META-INF/manifest.xml', s1)
s1 = self.create_meta()
self.write_zip_str(zfile, 'meta.xml', s1)
s1 = self.get_stylesheet()
self.write_zip_str(zfile, 'styles.xml', s1)
s1 = self.get_settings()
self.write_zip_str(zfile, 'settings.xml', s1)
self.store_embedded_files(zfile)
zfile.close()
f.seek(0)
whole = f.read()
f.close()
self.parts['whole'] = whole
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
def write_zip_str(self, zfile, name, bytes):
localtime = time.localtime(time.time())
zinfo = zipfile.ZipInfo(name, localtime)
# Add some standard UNIX file access permissions (-rw-r--r--).
zinfo.external_attr = (0x81a4 & 0xFFFF) << 16L
zinfo.compress_type = zipfile.ZIP_DEFLATED
zfile.writestr(zinfo, bytes)
def store_embedded_files(self, zfile):
embedded_files = self.visitor.get_embedded_file_list()
for source, destination in embedded_files:
if source is None:
continue
try:
# encode/decode
destination1 = destination.decode('latin-1').encode('utf-8')
zfile.write(source, destination1, zipfile.ZIP_STORED)
except OSError, e:
self.document.reporter.warning(
"Can't open file %s." % (source, ))
def get_settings(self):
"""
modeled after get_stylesheet
"""
stylespath = self.settings.stylesheet
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('settings.xml')
zfile.close()
return s1
def get_stylesheet(self):
"""Get the stylesheet from the visitor.
Ask the visitor to setup the page.
"""
s1 = self.visitor.setup_page()
return s1
def assemble_parts(self):
pass
def create_manifest(self):
if WhichElementTree == 'lxml':
root = Element('manifest:manifest',
nsmap=MANIFEST_NAMESPACE_DICT,
nsdict=MANIFEST_NAMESPACE_DICT,
)
else:
root = Element('manifest:manifest',
attrib=MANIFEST_NAMESPACE_ATTRIB,
nsdict=MANIFEST_NAMESPACE_DICT,
)
doc = etree.ElementTree(root)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': self.MIME_TYPE,
'manifest:full-path': '/',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'content.xml',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'styles.xml',
}, nsdict=MANNSD)
SubElement(root, 'manifest:file-entry', attrib={
'manifest:media-type': 'text/xml',
'manifest:full-path': 'meta.xml',
}, nsdict=MANNSD)
s1 = ToString(doc)
doc = minidom.parseString(s1)
s1 = doc.toprettyxml(' ')
return s1
def create_meta(self):
if WhichElementTree == 'lxml':
root = Element('office:document-meta',
nsmap=META_NAMESPACE_DICT,
nsdict=META_NAMESPACE_DICT,
)
else:
root = Element('office:document-meta',
attrib=META_NAMESPACE_ATTRIB,
nsdict=META_NAMESPACE_DICT,
)
doc = etree.ElementTree(root)
root = SubElement(root, 'office:meta', nsdict=METNSD)
el1 = SubElement(root, 'meta:generator', nsdict=METNSD)
el1.text = 'Docutils/rst2odf.py/%s' % (VERSION, )
s1 = os.environ.get('USER', '')
el1 = SubElement(root, 'meta:initial-creator', nsdict=METNSD)
el1.text = s1
s2 = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())
el1 = SubElement(root, 'meta:creation-date', nsdict=METNSD)
el1.text = s2
el1 = SubElement(root, 'dc:creator', nsdict=METNSD)
el1.text = s1
el1 = SubElement(root, 'dc:date', nsdict=METNSD)
el1.text = s2
el1 = SubElement(root, 'dc:language', nsdict=METNSD)
el1.text = 'en-US'
el1 = SubElement(root, 'meta:editing-cycles', nsdict=METNSD)
el1.text = '1'
el1 = SubElement(root, 'meta:editing-duration', nsdict=METNSD)
el1.text = 'PT00M01S'
title = self.visitor.get_title()
el1 = SubElement(root, 'dc:title', nsdict=METNSD)
if title:
el1.text = title
else:
el1.text = '[no title]'
meta_dict = self.visitor.get_meta_dict()
keywordstr = meta_dict.get('keywords')
if keywordstr is not None:
keywords = split_words(keywordstr)
for keyword in keywords:
el1 = SubElement(root, 'meta:keyword', nsdict=METNSD)
el1.text = keyword
description = meta_dict.get('description')
if description is not None:
el1 = SubElement(root, 'dc:description', nsdict=METNSD)
el1.text = description
s1 = ToString(doc)
#doc = minidom.parseString(s1)
#s1 = doc.toprettyxml(' ')
return s1
# class ODFTranslator(nodes.SparseNodeVisitor):
class ODFTranslator(nodes.GenericNodeVisitor):
used_styles = (
'attribution', 'blockindent', 'blockquote', 'blockquote-bulletitem',
'blockquote-bulletlist', 'blockquote-enumitem', 'blockquote-enumlist',
'bulletitem', 'bulletlist',
'caption', 'legend',
'centeredtextbody', 'codeblock',
'codeblock-classname', 'codeblock-comment', 'codeblock-functionname',
'codeblock-keyword', 'codeblock-name', 'codeblock-number',
'codeblock-operator', 'codeblock-string', 'emphasis', 'enumitem',
'enumlist', 'epigraph', 'epigraph-bulletitem', 'epigraph-bulletlist',
'epigraph-enumitem', 'epigraph-enumlist', 'footer',
'footnote', 'citation',
'header', 'highlights', 'highlights-bulletitem',
'highlights-bulletlist', 'highlights-enumitem', 'highlights-enumlist',
'horizontalline', 'inlineliteral', 'quotation', 'rubric',
'strong', 'table-title', 'textbody', 'tocbulletlist', 'tocenumlist',
'title',
'subtitle',
'heading1',
'heading2',
'heading3',
'heading4',
'heading5',
'heading6',
'heading7',
'admon-attention-hdr',
'admon-attention-body',
'admon-caution-hdr',
'admon-caution-body',
'admon-danger-hdr',
'admon-danger-body',
'admon-error-hdr',
'admon-error-body',
'admon-generic-hdr',
'admon-generic-body',
'admon-hint-hdr',
'admon-hint-body',
'admon-important-hdr',
'admon-important-body',
'admon-note-hdr',
'admon-note-body',
'admon-tip-hdr',
'admon-tip-body',
'admon-warning-hdr',
'admon-warning-body',
'tableoption',
'tableoption.%c', 'tableoption.%c%d', 'Table%d', 'Table%d.%c',
'Table%d.%c%d',
'lineblock1',
'lineblock2',
'lineblock3',
'lineblock4',
'lineblock5',
'lineblock6',
'image', 'figureframe',
)
def __init__(self, document):
#nodes.SparseNodeVisitor.__init__(self, document)
nodes.GenericNodeVisitor.__init__(self, document)
self.settings = document.settings
self.format_map = { }
if self.settings.odf_config_file:
from ConfigParser import ConfigParser
parser = ConfigParser()
parser.read(self.settings.odf_config_file)
for rststyle, format in parser.items("Formats"):
if rststyle not in self.used_styles:
self.document.reporter.warning(
'Style "%s" is not a style used by odtwriter.' % (
rststyle, ))
self.format_map[rststyle] = format
self.section_level = 0
self.section_count = 0
# Create ElementTree content and styles documents.
if WhichElementTree == 'lxml':
root = Element(
'office:document-content',
nsmap=CONTENT_NAMESPACE_DICT,
)
else:
root = Element(
'office:document-content',
attrib=CONTENT_NAMESPACE_ATTRIB,
)
self.content_tree = etree.ElementTree(element=root)
self.current_element = root
SubElement(root, 'office:scripts')
SubElement(root, 'office:font-face-decls')
el = SubElement(root, 'office:automatic-styles')
self.automatic_styles = el
el = SubElement(root, 'office:body')
el = self.generate_content_element(el)
self.current_element = el
self.body_text_element = el
self.paragraph_style_stack = [self.rststyle('textbody'), ]
self.list_style_stack = []
self.table_count = 0
self.column_count = ord('A') - 1
self.trace_level = -1
self.optiontablestyles_generated = False
self.field_name = None
self.field_element = None
self.title = None
self.image_count = 0
self.image_style_count = 0
self.image_dict = {}
self.embedded_file_list = []
self.syntaxhighlighting = 1
self.syntaxhighlight_lexer = 'python'
self.header_content = []
self.footer_content = []
self.in_header = False
self.in_footer = False
self.blockstyle = ''
self.in_table_of_contents = False
self.table_of_content_index_body = None
self.list_level = 0
self.footnote_ref_dict = {}
self.footnote_list = []
self.footnote_chars_idx = 0
self.footnote_level = 0
self.pending_ids = [ ]
self.in_paragraph = False
self.found_doc_title = False
self.bumped_list_level_stack = []
self.meta_dict = {}
self.line_block_level = 0
self.line_indent_level = 0
self.citation_id = None
self.style_index = 0 # use to form unique style names
self.str_stylesheet = ''
self.str_stylesheetcontent = ''
self.dom_stylesheet = None
self.table_styles = None
def get_str_stylesheet(self):
return self.str_stylesheet
def retrieve_styles(self, extension):
"""Retrieve the stylesheet from either a .xml file or from
a .odt (zip) file. Return the content as a string.
"""
s2 = None
stylespath = self.settings.stylesheet
ext = os.path.splitext(stylespath)[1]
if ext == '.xml':
stylesfile = open(stylespath, 'r')
s1 = stylesfile.read()
stylesfile.close()
elif ext == extension:
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('styles.xml')
s2 = zfile.read('content.xml')
zfile.close()
else:
raise RuntimeError, 'stylesheet path (%s) must be %s or .xml file' %(stylespath, extension)
self.str_stylesheet = s1
self.str_stylesheetcontent = s2
self.dom_stylesheet = etree.fromstring(self.str_stylesheet)
self.dom_stylesheetcontent = etree.fromstring(self.str_stylesheetcontent)
self.table_styles = self.extract_table_styles(s2)
def extract_table_styles(self, styles_str):
root = etree.fromstring(styles_str)
table_styles = {}
auto_styles = root.find(
'{%s}automatic-styles' % (CNSD['office'], ))
for stylenode in auto_styles:
name = stylenode.get('{%s}name' % (CNSD['style'], ))
tablename = name.split('.')[0]
family = stylenode.get('{%s}family' % (CNSD['style'], ))
if name.startswith(TABLESTYLEPREFIX):
tablestyle = table_styles.get(tablename)
if tablestyle is None:
tablestyle = TableStyle()
table_styles[tablename] = tablestyle
if family == 'table':
properties = stylenode.find(
'{%s}table-properties' % (CNSD['style'], ))
property = properties.get('{%s}%s' % (CNSD['fo'],
'background-color', ))
if property is not None and property != 'none':
tablestyle.backgroundcolor = property
elif family == 'table-cell':
properties = stylenode.find(
'{%s}table-cell-properties' % (CNSD['style'], ))
if properties is not None:
border = self.get_property(properties)
if border is not None:
tablestyle.border = border
return table_styles
def get_property(self, stylenode):
border = None
for propertyname in TABLEPROPERTYNAMES:
border = stylenode.get('{%s}%s' % (CNSD['fo'], propertyname, ))
if border is not None and border != 'none':
return border
return border
def add_doc_title(self):
text = self.settings.title
if text:
self.title = text
if not self.found_doc_title:
el = Element('text:p', attrib = {
'text:style-name': self.rststyle('title'),
})
el.text = text
self.body_text_element.insert(0, el)
def rststyle(self, name, parameters=( )):
"""
Returns the style name to use for the given style.
If `parameters` is given `name` must contain a matching number of ``%`` and
is used as a format expression with `parameters` as the value.
"""
name1 = name % parameters
stylename = self.format_map.get(name1, 'rststyle-%s' % name1)
return stylename
def generate_content_element(self, root):
return SubElement(root, 'office:text')
def setup_page(self):
self.setup_paper(self.dom_stylesheet)
if (len(self.header_content) > 0 or len(self.footer_content) > 0 or
self.settings.custom_header or self.settings.custom_footer):
self.add_header_footer(self.dom_stylesheet)
new_content = etree.tostring(self.dom_stylesheet)
return new_content
def setup_paper(self, root_el):
try:
fin = os.popen("paperconf -s 2> /dev/null")
w, h = map(float, fin.read().split())
fin.close()
except:
w, h = 612, 792 # default to Letter
def walk(el):
if el.tag == "{%s}page-layout-properties" % SNSD["style"] and \
not el.attrib.has_key("{%s}page-width" % SNSD["fo"]):
el.attrib["{%s}page-width" % SNSD["fo"]] = "%.3fpt" % w
el.attrib["{%s}page-height" % SNSD["fo"]] = "%.3fpt" % h
el.attrib["{%s}margin-left" % SNSD["fo"]] = \
el.attrib["{%s}margin-right" % SNSD["fo"]] = \
"%.3fpt" % (.1 * w)
el.attrib["{%s}margin-top" % SNSD["fo"]] = \
el.attrib["{%s}margin-bottom" % SNSD["fo"]] = \
"%.3fpt" % (.1 * h)
else:
for subel in el.getchildren(): walk(subel)
walk(root_el)
def add_header_footer(self, root_el):
automatic_styles = root_el.find(
'{%s}automatic-styles' % SNSD['office'])
path = '{%s}master-styles' % (NAME_SPACE_1, )
master_el = root_el.find(path)
if master_el is None:
return
path = '{%s}master-page' % (SNSD['style'], )
master_el = master_el.find(path)
if master_el is None:
return
el1 = master_el
if self.header_content or self.settings.custom_header:
if WhichElementTree == 'lxml':
el2 = SubElement(el1, 'style:header', nsdict=SNSD)
else:
el2 = SubElement(el1, 'style:header',
attrib=STYLES_NAMESPACE_ATTRIB,
nsdict=STYLES_NAMESPACE_DICT,
)
for el in self.header_content:
attrkey = add_ns('text:style-name', nsdict=SNSD)
el.attrib[attrkey] = self.rststyle('header')
el2.append(el)
if self.settings.custom_header:
elcustom = self.create_custom_headfoot(el2,
self.settings.custom_header, 'header', automatic_styles)
if self.footer_content or self.settings.custom_footer:
if WhichElementTree == 'lxml':
el2 = SubElement(el1, 'style:footer', nsdict=SNSD)
else:
el2 = SubElement(el1, 'style:footer',
attrib=STYLES_NAMESPACE_ATTRIB,
nsdict=STYLES_NAMESPACE_DICT,
)
for el in self.footer_content:
attrkey = add_ns('text:style-name', nsdict=SNSD)
el.attrib[attrkey] = self.rststyle('footer')
el2.append(el)
if self.settings.custom_footer:
elcustom = self.create_custom_headfoot(el2,
self.settings.custom_footer, 'footer', automatic_styles)
code_none, code_field, code_text = range(3)
field_pat = re.compile(r'%(..?)%')
def create_custom_headfoot(self, parent, text, style_name, automatic_styles):
current_element = None
field_iter = self.split_field_specifiers_iter(text)
for item in field_iter:
if item[0] == ODFTranslator.code_field:
if item[1] not in ('p', 'P',
't1', 't2', 't3', 't4',
'd1', 'd2', 'd3', 'd4', 'd5',
's', 't', 'a'):
msg = 'bad field spec: %%%s%%' % (item[1], )
raise RuntimeError, msg
if current_element is None:
parent = SubElement(parent, 'text:p', attrib={
'text:style-name': self.rststyle(style_name),
})
el1 = self.make_field_element(parent,
item[1], style_name, automatic_styles)
if el1 is None:
msg = 'bad field spec: %%%s%%' % (item[1], )
raise RuntimeError, msg
else:
current_element = el1
else:
if current_element is None:
parent = SubElement(parent, 'text:p', attrib={
'text:style-name': self.rststyle(style_name),
})
parent.text = item[1]
else:
current_element.tail = item[1]
def make_field_element(self, parent, text, style_name, automatic_styles):
if text == 'p':
el1 = SubElement(parent, 'text:page-number', attrib={
'text:style-name': self.rststyle(style_name),
'text:select-page': 'current',
})
elif text == 'P':
el1 = SubElement(parent, 'text:page-count', attrib={
'text:style-name': self.rststyle(style_name),
})
elif text == 't1':
self.style_index += 1
el1 = SubElement(parent, 'text:time', attrib={
'text:style-name': self.rststyle(style_name),
'text:fixed': 'true',
'style:data-style-name': 'rst-time-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:time-style', attrib={
'style:name': 'rst-time-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:hours', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:minutes', attrib={
'number:style': 'long',
})
elif text == 't2':
self.style_index += 1
el1 = SubElement(parent, 'text:time', attrib={
'text:style-name': self.rststyle(style_name),
'text:fixed': 'true',
'style:data-style-name': 'rst-time-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:time-style', attrib={
'style:name': 'rst-time-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:hours', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:minutes', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:seconds', attrib={
'number:style': 'long',
})
elif text == 't3':
self.style_index += 1
el1 = SubElement(parent, 'text:time', attrib={
'text:style-name': self.rststyle(style_name),
'text:fixed': 'true',
'style:data-style-name': 'rst-time-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:time-style', attrib={
'style:name': 'rst-time-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:hours', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:minutes', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ' '
el3 = SubElement(el2, 'number:am-pm')
elif text == 't4':
self.style_index += 1
el1 = SubElement(parent, 'text:time', attrib={
'text:style-name': self.rststyle(style_name),
'text:fixed': 'true',
'style:data-style-name': 'rst-time-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:time-style', attrib={
'style:name': 'rst-time-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:hours', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:minutes', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ':'
el3 = SubElement(el2, 'number:seconds', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ' '
el3 = SubElement(el2, 'number:am-pm')
elif text == 'd1':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'number:automatic-order': 'true',
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:month', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '/'
el3 = SubElement(el2, 'number:day', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '/'
el3 = SubElement(el2, 'number:year')
elif text == 'd2':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'number:automatic-order': 'true',
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:month', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '/'
el3 = SubElement(el2, 'number:day', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '/'
el3 = SubElement(el2, 'number:year', attrib={
'number:style': 'long',
})
elif text == 'd3':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'number:automatic-order': 'true',
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:month', attrib={
'number:textual': 'true',
})
el3 = SubElement(el2, 'number:text')
el3.text = ' '
el3 = SubElement(el2, 'number:day', attrib={
})
el3 = SubElement(el2, 'number:text')
el3.text = ', '
el3 = SubElement(el2, 'number:year', attrib={
'number:style': 'long',
})
elif text == 'd4':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'number:automatic-order': 'true',
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:month', attrib={
'number:textual': 'true',
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = ' '
el3 = SubElement(el2, 'number:day', attrib={
})
el3 = SubElement(el2, 'number:text')
el3.text = ', '
el3 = SubElement(el2, 'number:year', attrib={
'number:style': 'long',
})
elif text == 'd5':
self.style_index += 1
el1 = SubElement(parent, 'text:date', attrib={
'text:style-name': self.rststyle(style_name),
'style:data-style-name': 'rst-date-style-%d' % self.style_index,
})
el2 = SubElement(automatic_styles, 'number:date-style', attrib={
'style:name': 'rst-date-style-%d' % self.style_index,
'xmlns:number': SNSD['number'],
'xmlns:style': SNSD['style'],
})
el3 = SubElement(el2, 'number:year', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '-'
el3 = SubElement(el2, 'number:month', attrib={
'number:style': 'long',
})
el3 = SubElement(el2, 'number:text')
el3.text = '-'
el3 = SubElement(el2, 'number:day', attrib={
'number:style': 'long',
})
elif text == 's':
el1 = SubElement(parent, 'text:subject', attrib={
'text:style-name': self.rststyle(style_name),
})
elif text == 't':
el1 = SubElement(parent, 'text:title', attrib={
'text:style-name': self.rststyle(style_name),
})
elif text == 'a':
el1 = SubElement(parent, 'text:author-name', attrib={
'text:fixed': 'false',
})
else:
el1 = None
return el1
def split_field_specifiers_iter(self, text):
pos1 = 0
pos_end = len(text)
while True:
mo = ODFTranslator.field_pat.search(text, pos1)
if mo:
pos2 = mo.start()
if pos2 > pos1:
yield (ODFTranslator.code_text, text[pos1:pos2])
yield (ODFTranslator.code_field, mo.group(1))
pos1 = mo.end()
else:
break
trailing = text[pos1:]
if trailing:
yield (ODFTranslator.code_text, trailing)
def astext(self):
root = self.content_tree.getroot()
et = etree.ElementTree(root)
s1 = ToString(et)
return s1
def content_astext(self):
return self.astext()
def set_title(self, title): self.title = title
def get_title(self): return self.title
def set_embedded_file_list(self, embedded_file_list):
self.embedded_file_list = embedded_file_list
def get_embedded_file_list(self): return self.embedded_file_list
def get_meta_dict(self): return self.meta_dict
def process_footnotes(self):
for node, el1 in self.footnote_list:
backrefs = node.attributes.get('backrefs', [])
first = True
for ref in backrefs:
el2 = self.footnote_ref_dict.get(ref)
if el2 is not None:
if first:
first = False
el3 = copy.deepcopy(el1)
el2.append(el3)
else:
children = el2.getchildren()
if len(children) > 0: # and 'id' in el2.attrib:
child = children[0]
ref1 = child.text
attribkey = add_ns('text:id', nsdict=SNSD)
id1 = el2.get(attribkey, 'footnote-error')
if id1 is None:
id1 = ''
tag = add_ns('text:note-ref', nsdict=SNSD)
el2.tag = tag
if self.settings.endnotes_end_doc:
note_class = 'endnote'
else:
note_class = 'footnote'
el2.attrib.clear()
attribkey = add_ns('text:note-class', nsdict=SNSD)
el2.attrib[attribkey] = note_class
attribkey = add_ns('text:ref-name', nsdict=SNSD)
el2.attrib[attribkey] = id1
attribkey = add_ns('text:reference-format', nsdict=SNSD)
el2.attrib[attribkey] = 'page'
el2.text = ref1
#
# Utility methods
def append_child(self, tag, attrib=None, parent=None):
if parent is None:
parent = self.current_element
if attrib is None:
el = SubElement(parent, tag)
else:
el = SubElement(parent, tag, attrib)
return el
def append_p(self, style, text=None):
result = self.append_child('text:p', attrib={
'text:style-name': self.rststyle(style)})
self.append_pending_ids(result)
if text is not None:
result.text = text
return result
def append_pending_ids(self, el):
if self.settings.create_links:
for id in self.pending_ids:
SubElement(el, 'text:reference-mark', attrib={
'text:name': id})
self.pending_ids = [ ]
def set_current_element(self, el):
self.current_element = el
def set_to_parent(self):
self.current_element = self.current_element.getparent()
def generate_labeled_block(self, node, label):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
el = self.append_p('blockindent')
return el
def generate_labeled_line(self, node, label):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
el1.tail = node.astext()
return el
def encode(self, text):
text = text.replace(u'\u00a0', " ")
return text
#
# Visitor functions
#
# In alphabetic order, more or less.
# See docutils.docutils.nodes.node_class_names.
#
def dispatch_visit(self, node):
"""Override to catch basic attributes which many nodes have."""
self.handle_basic_atts(node)
nodes.GenericNodeVisitor.dispatch_visit(self, node)
def handle_basic_atts(self, node):
if isinstance(node, nodes.Element) and node['ids']:
self.pending_ids += node['ids']
def default_visit(self, node):
self.document.reporter.warning('missing visit_%s' % (node.tagname, ))
def default_departure(self, node):
self.document.reporter.warning('missing depart_%s' % (node.tagname, ))
def visit_Text(self, node):
# Skip nodes whose text has been processed in parent nodes.
if isinstance(node.parent, docutils.nodes.literal_block):
return
text = node.astext()
# Are we in mixed content? If so, add the text to the
# etree tail of the previous sibling element.
if len(self.current_element.getchildren()) > 0:
if self.current_element.getchildren()[-1].tail:
self.current_element.getchildren()[-1].tail += text
else:
self.current_element.getchildren()[-1].tail = text
else:
if self.current_element.text:
self.current_element.text += text
else:
self.current_element.text = text
def depart_Text(self, node):
pass
#
# Pre-defined fields
#
def visit_address(self, node):
el = self.generate_labeled_block(node, 'Address: ')
self.set_current_element(el)
def depart_address(self, node):
self.set_to_parent()
def visit_author(self, node):
if isinstance(node.parent, nodes.authors):
el = self.append_p('blockindent')
else:
el = self.generate_labeled_block(node, 'Author: ')
self.set_current_element(el)
def depart_author(self, node):
self.set_to_parent()
def visit_authors(self, node):
label = 'Authors:'
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = label
def depart_authors(self, node):
pass
def visit_contact(self, node):
el = self.generate_labeled_block(node, 'Contact: ')
self.set_current_element(el)
def depart_contact(self, node):
self.set_to_parent()
def visit_copyright(self, node):
el = self.generate_labeled_block(node, 'Copyright: ')
self.set_current_element(el)
def depart_copyright(self, node):
self.set_to_parent()
def visit_date(self, node):
self.generate_labeled_line(node, 'Date: ')
def depart_date(self, node):
pass
def visit_organization(self, node):
el = self.generate_labeled_block(node, 'Organization: ')
self.set_current_element(el)
def depart_organization(self, node):
self.set_to_parent()
def visit_status(self, node):
el = self.generate_labeled_block(node, 'Status: ')
self.set_current_element(el)
def depart_status(self, node):
self.set_to_parent()
def visit_revision(self, node):
self.generate_labeled_line(node, 'Revision: ')
def depart_revision(self, node):
pass
def visit_version(self, node):
el = self.generate_labeled_line(node, 'Version: ')
#self.set_current_element(el)
def depart_version(self, node):
#self.set_to_parent()
pass
def visit_attribution(self, node):
el = self.append_p('attribution', node.astext())
def depart_attribution(self, node):
pass
def visit_block_quote(self, node):
if 'epigraph' in node.attributes['classes']:
self.paragraph_style_stack.append(self.rststyle('epigraph'))
self.blockstyle = self.rststyle('epigraph')
elif 'highlights' in node.attributes['classes']:
self.paragraph_style_stack.append(self.rststyle('highlights'))
self.blockstyle = self.rststyle('highlights')
else:
self.paragraph_style_stack.append(self.rststyle('blockquote'))
self.blockstyle = self.rststyle('blockquote')
self.line_indent_level += 1
def depart_block_quote(self, node):
self.paragraph_style_stack.pop()
self.blockstyle = ''
self.line_indent_level -= 1
def visit_bullet_list(self, node):
self.list_level +=1
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
pass
else:
if node.has_key('classes') and \
'auto-toc' in node.attributes['classes']:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('tocenumlist'),
})
self.list_style_stack.append(self.rststyle('enumitem'))
else:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('tocbulletlist'),
})
self.list_style_stack.append(self.rststyle('bulletitem'))
self.set_current_element(el)
else:
if self.blockstyle == self.rststyle('blockquote'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('blockquote-bulletitem'))
elif self.blockstyle == self.rststyle('highlights'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('highlights-bulletitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-bulletlist'),
})
self.list_style_stack.append(
self.rststyle('epigraph-bulletitem'))
else:
el = SubElement(self.current_element, 'text:list', attrib={
'text:style-name': self.rststyle('bulletlist'),
})
self.list_style_stack.append(self.rststyle('bulletitem'))
self.set_current_element(el)
def depart_bullet_list(self, node):
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
pass
else:
self.set_to_parent()
self.list_style_stack.pop()
else:
self.set_to_parent()
self.list_style_stack.pop()
self.list_level -=1
def visit_caption(self, node):
raise nodes.SkipChildren()
pass
def depart_caption(self, node):
pass
def visit_comment(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'office:annotation', attrib={})
el2 = SubElement(el1, 'text:p', attrib={})
el2.text = node.astext()
def depart_comment(self, node):
pass
def visit_compound(self, node):
# The compound directive currently receives no special treatment.
pass
def depart_compound(self, node):
pass
def visit_container(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
self.paragraph_style_stack.append(self.rststyle(styles[0]))
def depart_container(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
self.paragraph_style_stack.pop()
def visit_decoration(self, node):
pass
def depart_decoration(self, node):
pass
def visit_definition(self, node):
self.paragraph_style_stack.append(self.rststyle('blockindent'))
self.bumped_list_level_stack.append(ListLevel(1))
def depart_definition(self, node):
self.paragraph_style_stack.pop()
self.bumped_list_level_stack.pop()
def visit_definition_list(self, node):
pass
def depart_definition_list(self, node):
pass
def visit_definition_list_item(self, node):
pass
def depart_definition_list_item(self, node):
pass
def visit_term(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
#el1.text = node.astext()
self.set_current_element(el1)
def depart_term(self, node):
self.set_to_parent()
self.set_to_parent()
def visit_classifier(self, node):
els = self.current_element.getchildren()
if len(els) > 0:
el = els[-1]
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('emphasis')
})
el1.text = ' (%s)' % (node.astext(), )
def depart_classifier(self, node):
pass
def visit_document(self, node):
pass
def depart_document(self, node):
self.process_footnotes()
def visit_docinfo(self, node):
self.section_level += 1
self.section_count += 1
if self.settings.create_sections:
el = self.append_child('text:section', attrib={
'text:name': 'Section%d' % self.section_count,
'text:style-name': 'Sect%d' % self.section_level,
})
self.set_current_element(el)
def depart_docinfo(self, node):
self.section_level -= 1
if self.settings.create_sections:
self.set_to_parent()
def visit_emphasis(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('emphasis')})
self.set_current_element(el)
def depart_emphasis(self, node):
self.set_to_parent()
def visit_enumerated_list(self, node):
el1 = self.current_element
if self.blockstyle == self.rststyle('blockquote'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('blockquote-enumlist'),
})
self.list_style_stack.append(self.rststyle('blockquote-enumitem'))
elif self.blockstyle == self.rststyle('highlights'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('highlights-enumlist'),
})
self.list_style_stack.append(self.rststyle('highlights-enumitem'))
elif self.blockstyle == self.rststyle('epigraph'):
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle('epigraph-enumlist'),
})
self.list_style_stack.append(self.rststyle('epigraph-enumitem'))
else:
liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), )
el2 = SubElement(el1, 'text:list', attrib={
'text:style-name': self.rststyle(liststylename),
})
self.list_style_stack.append(self.rststyle('enumitem'))
self.set_current_element(el2)
def depart_enumerated_list(self, node):
self.set_to_parent()
self.list_style_stack.pop()
def visit_list_item(self, node):
# If we are in a "bumped" list level, then wrap this
# list in an outer lists in order to increase the
# indentation level.
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
self.paragraph_style_stack.append(
self.rststyle('contents-%d' % (self.list_level, )))
else:
el1 = self.append_child('text:list-item')
self.set_current_element(el1)
else:
el1 = self.append_child('text:list-item')
el3 = el1
if len(self.bumped_list_level_stack) > 0:
level_obj = self.bumped_list_level_stack[-1]
if level_obj.get_sibling():
level_obj.set_nested(False)
for level_obj1 in self.bumped_list_level_stack:
for idx in range(level_obj1.get_level()):
el2 = self.append_child('text:list', parent=el3)
el3 = self.append_child(
'text:list-item', parent=el2)
self.paragraph_style_stack.append(self.list_style_stack[-1])
self.set_current_element(el3)
def depart_list_item(self, node):
if self.in_table_of_contents:
if self.settings.generate_oowriter_toc:
self.paragraph_style_stack.pop()
else:
self.set_to_parent()
else:
if len(self.bumped_list_level_stack) > 0:
level_obj = self.bumped_list_level_stack[-1]
if level_obj.get_sibling():
level_obj.set_nested(True)
for level_obj1 in self.bumped_list_level_stack:
for idx in range(level_obj1.get_level()):
self.set_to_parent()
self.set_to_parent()
self.paragraph_style_stack.pop()
self.set_to_parent()
def visit_header(self, node):
self.in_header = True
def depart_header(self, node):
self.in_header = False
def visit_footer(self, node):
self.in_footer = True
def depart_footer(self, node):
self.in_footer = False
def visit_field(self, node):
pass
def depart_field(self, node):
pass
def visit_field_list(self, node):
pass
def depart_field_list(self, node):
pass
def visit_field_name(self, node):
el = self.append_p('textbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = node.astext()
def depart_field_name(self, node):
pass
def visit_field_body(self, node):
self.paragraph_style_stack.append(self.rststyle('blockindent'))
def depart_field_body(self, node):
self.paragraph_style_stack.pop()
def visit_figure(self, node):
pass
def depart_figure(self, node):
pass
def visit_footnote(self, node):
self.footnote_level += 1
self.save_footnote_current = self.current_element
el1 = Element('text:note-body')
self.current_element = el1
self.footnote_list.append((node, el1))
if isinstance(node, docutils.nodes.citation):
self.paragraph_style_stack.append(self.rststyle('citation'))
else:
self.paragraph_style_stack.append(self.rststyle('footnote'))
def depart_footnote(self, node):
self.paragraph_style_stack.pop()
self.current_element = self.save_footnote_current
self.footnote_level -= 1
footnote_chars = [
'*', '**', '***',
'++', '+++',
'##', '###',
'@@', '@@@',
]
def visit_footnote_reference(self, node):
if self.footnote_level <= 0:
id = node.attributes['ids'][0]
refid = node.attributes.get('refid')
if refid is None:
refid = ''
if self.settings.endnotes_end_doc:
note_class = 'endnote'
else:
note_class = 'footnote'
el1 = self.append_child('text:note', attrib={
'text:id': '%s' % (refid, ),
'text:note-class': note_class,
})
note_auto = str(node.attributes.get('auto', 1))
if isinstance(node, docutils.nodes.citation_reference):
citation = '[%s]' % node.astext()
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': citation,
})
el2.text = citation
elif note_auto == '1':
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': node.astext(),
})
el2.text = node.astext()
elif note_auto == '*':
if self.footnote_chars_idx >= len(
ODFTranslator.footnote_chars):
self.footnote_chars_idx = 0
footnote_char = ODFTranslator.footnote_chars[
self.footnote_chars_idx]
self.footnote_chars_idx += 1
el2 = SubElement(el1, 'text:note-citation', attrib={
'text:label': footnote_char,
})
el2.text = footnote_char
self.footnote_ref_dict[id] = el1
raise nodes.SkipChildren()
def depart_footnote_reference(self, node):
pass
def visit_citation(self, node):
for id in node.attributes['ids']:
self.citation_id = id
break
self.paragraph_style_stack.append(self.rststyle('blockindent'))
self.bumped_list_level_stack.append(ListLevel(1))
def depart_citation(self, node):
self.citation_id = None
self.paragraph_style_stack.pop()
self.bumped_list_level_stack.pop()
def visit_citation_reference(self, node):
if self.settings.create_links:
id = node.attributes['refid']
el = self.append_child('text:reference-ref', attrib={
'text:ref-name': '%s' % (id, ),
'text:reference-format': 'text',
})
el.text = '['
self.set_current_element(el)
elif self.current_element.text is None:
self.current_element.text = '['
else:
self.current_element.text += '['
def depart_citation_reference(self, node):
self.current_element.text += ']'
if self.settings.create_links:
self.set_to_parent()
def visit_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
raise nodes.SkipChildren()
elif self.citation_id is not None:
el = self.append_p('textbody')
self.set_current_element(el)
el.text = '['
if self.settings.create_links:
el1 = self.append_child('text:reference-mark-start', attrib={
'text:name': '%s' % (self.citation_id, ),
})
def depart_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
pass
elif self.citation_id is not None:
self.current_element.text += ']'
if self.settings.create_links:
el = self.append_child('text:reference-mark-end', attrib={
'text:name': '%s' % (self.citation_id, ),
})
self.set_to_parent()
def visit_generated(self, node):
pass
def depart_generated(self, node):
pass
def check_file_exists(self, path):
if os.path.exists(path):
return 1
else:
return 0
def visit_image(self, node):
# Capture the image file.
if 'uri' in node.attributes:
source = node.attributes['uri']
if not self.check_file_exists(source):
self.document.reporter.warning(
'Cannot find image file %s.' % (source, ))
return
else:
return
if source in self.image_dict:
filename, destination = self.image_dict[source]
else:
self.image_count += 1
filename = os.path.split(source)[1]
destination = 'Pictures/1%08x%s' % (self.image_count, filename, )
spec = (os.path.abspath(source), destination,)
self.embedded_file_list.append(spec)
self.image_dict[source] = (source, destination,)
# Is this a figure (containing an image) or just a plain image?
if self.in_paragraph:
el1 = self.current_element
else:
el1 = SubElement(self.current_element, 'text:p',
attrib={'text:style-name': self.rststyle('textbody')})
el2 = el1
if isinstance(node.parent, docutils.nodes.figure):
el3, el4, el5, caption = self.generate_figure(node, source,
destination, el2)
attrib = {}
el6, width = self.generate_image(node, source, destination,
el5, attrib)
if caption is not None:
el6.tail = caption
else: #if isinstance(node.parent, docutils.nodes.image):
el3 = self.generate_image(node, source, destination, el2)
def depart_image(self, node):
pass
def get_image_width_height(self, node, attr):
size = None
if attr in node.attributes:
size = node.attributes[attr]
unit = size[-2:]
if unit.isalpha():
size = size[:-2]
else:
unit = 'px'
try:
size = float(size)
except ValueError, e:
self.document.reporter.warning(
'Invalid %s for image: "%s"' % (
attr, node.attributes[attr]))
size = [size, unit]
return size
def get_image_scale(self, node):
if 'scale' in node.attributes:
try:
scale = int(node.attributes['scale'])
if scale < 1: # or scale > 100:
self.document.reporter.warning(
'scale out of range (%s), using 1.' % (scale, ))
scale = 1
scale = scale * 0.01
except ValueError, e:
self.document.reporter.warning(
'Invalid scale for image: "%s"' % (
node.attributes['scale'], ))
else:
scale = 1.0
return scale
def get_image_scaled_width_height(self, node, source):
scale = self.get_image_scale(node)
width = self.get_image_width_height(node, 'width')
height = self.get_image_width_height(node, 'height')
dpi = (72, 72)
if Image is not None and source in self.image_dict:
filename, destination = self.image_dict[source]
imageobj = Image.open(filename, 'r')
dpi = imageobj.info.get('dpi', dpi)
# dpi information can be (xdpi, ydpi) or xydpi
try: iter(dpi)
except: dpi = (dpi, dpi)
else:
imageobj = None
if width is None or height is None:
if imageobj is None:
raise RuntimeError(
'image size not fully specified and PIL not installed')
if width is None: width = [imageobj.size[0], 'px']
if height is None: height = [imageobj.size[1], 'px']
width[0] *= scale
height[0] *= scale
if width[1] == 'px': width = [width[0] / dpi[0], 'in']
if height[1] == 'px': height = [height[0] / dpi[1], 'in']
width[0] = str(width[0])
height[0] = str(height[0])
return ''.join(width), ''.join(height)
def generate_figure(self, node, source, destination, current_element):
caption = None
width, height = self.get_image_scaled_width_height(node, source)
for node1 in node.parent.children:
if node1.tagname == 'caption':
caption = node1.astext()
self.image_style_count += 1
#
# Add the style for the caption.
if caption is not None:
attrib = {
'style:class': 'extra',
'style:family': 'paragraph',
'style:name': 'Caption',
'style:parent-style-name': 'Standard',
}
el1 = SubElement(self.automatic_styles, 'style:style',
attrib=attrib, nsdict=SNSD)
attrib = {
'fo:margin-bottom': '0.0835in',
'fo:margin-top': '0.0835in',
'text:line-number': '0',
'text:number-lines': 'false',
}
el2 = SubElement(el1, 'style:paragraph-properties',
attrib=attrib, nsdict=SNSD)
attrib = {
'fo:font-size': '12pt',
'fo:font-style': 'italic',
'style:font-name': 'Times',
'style:font-name-complex': 'Lucidasans1',
'style:font-size-asian': '12pt',
'style:font-size-complex': '12pt',
'style:font-style-asian': 'italic',
'style:font-style-complex': 'italic',
}
el2 = SubElement(el1, 'style:text-properties',
attrib=attrib, nsdict=SNSD)
style_name = 'rstframestyle%d' % self.image_style_count
# Add the styles
attrib = {
'style:name': style_name,
'style:family': 'graphic',
'style:parent-style-name': self.rststyle('figureframe'),
}
el1 = SubElement(self.automatic_styles,
'style:style', attrib=attrib, nsdict=SNSD)
halign = 'center'
valign = 'top'
if 'align' in node.attributes:
align = node.attributes['align'].split()
for val in align:
if val in ('left', 'center', 'right'):
halign = val
elif val in ('top', 'middle', 'bottom'):
valign = val
attrib = {}
wrap = False
classes = node.parent.attributes.get('classes')
if classes and 'wrap' in classes:
wrap = True
if wrap:
attrib['style:wrap'] = 'dynamic'
else:
attrib['style:wrap'] = 'none'
el2 = SubElement(el1,
'style:graphic-properties', attrib=attrib, nsdict=SNSD)
attrib = {
'draw:style-name': style_name,
'draw:name': 'Frame1',
'text:anchor-type': 'paragraph',
'draw:z-index': '0',
}
attrib['svg:width'] = width
# dbg
#attrib['svg:height'] = height
el3 = SubElement(current_element, 'draw:frame', attrib=attrib)
attrib = {}
el4 = SubElement(el3, 'draw:text-box', attrib=attrib)
attrib = {
'text:style-name': self.rststyle('caption'),
}
el5 = SubElement(el4, 'text:p', attrib=attrib)
return el3, el4, el5, caption
def generate_image(self, node, source, destination, current_element,
frame_attrs=None):
width, height = self.get_image_scaled_width_height(node, source)
self.image_style_count += 1
style_name = 'rstframestyle%d' % self.image_style_count
# Add the style.
attrib = {
'style:name': style_name,
'style:family': 'graphic',
'style:parent-style-name': self.rststyle('image'),
}
el1 = SubElement(self.automatic_styles,
'style:style', attrib=attrib, nsdict=SNSD)
halign = None
valign = None
if 'align' in node.attributes:
align = node.attributes['align'].split()
for val in align:
if val in ('left', 'center', 'right'):
halign = val
elif val in ('top', 'middle', 'bottom'):
valign = val
if frame_attrs is None:
attrib = {
'style:vertical-pos': 'top',
'style:vertical-rel': 'paragraph',
'style:horizontal-rel': 'paragraph',
'style:mirror': 'none',
'fo:clip': 'rect(0cm 0cm 0cm 0cm)',
'draw:luminance': '0%',
'draw:contrast': '0%',
'draw:red': '0%',
'draw:green': '0%',
'draw:blue': '0%',
'draw:gamma': '100%',
'draw:color-inversion': 'false',
'draw:image-opacity': '100%',
'draw:color-mode': 'standard',
}
else:
attrib = frame_attrs
if halign is not None:
attrib['style:horizontal-pos'] = halign
if valign is not None:
attrib['style:vertical-pos'] = valign
# If there is a classes/wrap directive or we are
# inside a table, add a no-wrap style.
wrap = False
classes = node.attributes.get('classes')
if classes and 'wrap' in classes:
wrap = True
if wrap:
attrib['style:wrap'] = 'dynamic'
else:
attrib['style:wrap'] = 'none'
# If we are inside a table, add a no-wrap style.
if self.is_in_table(node):
attrib['style:wrap'] = 'none'
el2 = SubElement(el1,
'style:graphic-properties', attrib=attrib, nsdict=SNSD)
# Add the content.
#el = SubElement(current_element, 'text:p',
# attrib={'text:style-name': self.rststyle('textbody')})
attrib={
'draw:style-name': style_name,
'draw:name': 'graphics2',
'draw:z-index': '1',
}
if isinstance(node.parent, nodes.TextElement):
attrib['text:anchor-type'] = 'as-char' #vds
else:
attrib['text:anchor-type'] = 'paragraph'
attrib['svg:width'] = width
attrib['svg:height'] = height
el1 = SubElement(current_element, 'draw:frame', attrib=attrib)
el2 = SubElement(el1, 'draw:image', attrib={
'xlink:href': '%s' % (destination, ),
'xlink:type': 'simple',
'xlink:show': 'embed',
'xlink:actuate': 'onLoad',
})
return el1, width
def is_in_table(self, node):
node1 = node.parent
while node1:
if isinstance(node1, docutils.nodes.entry):
return True
node1 = node1.parent
return False
def visit_legend(self, node):
if isinstance(node.parent, docutils.nodes.figure):
el1 = self.current_element[-1]
el1 = el1[0][0]
self.current_element = el1
self.paragraph_style_stack.append(self.rststyle('legend'))
def depart_legend(self, node):
if isinstance(node.parent, docutils.nodes.figure):
self.paragraph_style_stack.pop()
self.set_to_parent()
self.set_to_parent()
self.set_to_parent()
def visit_line_block(self, node):
self.line_indent_level += 1
self.line_block_level += 1
def depart_line_block(self, node):
self.line_indent_level -= 1
self.line_block_level -= 1
def visit_line(self, node):
style = 'lineblock%d' % self.line_indent_level
el1 = SubElement(self.current_element, 'text:p', attrib={
'text:style-name': self.rststyle(style),
})
self.current_element = el1
def depart_line(self, node):
self.set_to_parent()
def visit_literal(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('inlineliteral')})
self.set_current_element(el)
def depart_literal(self, node):
self.set_to_parent()
def visit_inline(self, node):
styles = node.attributes.get('classes', ())
if len(styles) > 0:
inline_style = styles[0]
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle(inline_style)})
self.set_current_element(el)
def depart_inline(self, node):
self.set_to_parent()
def _calculate_code_block_padding(self, line):
count = 0
matchobj = SPACES_PATTERN.match(line)
if matchobj:
pad = matchobj.group()
count = len(pad)
else:
matchobj = TABS_PATTERN.match(line)
if matchobj:
pad = matchobj.group()
count = len(pad) * 8
return count
def _add_syntax_highlighting(self, insource, language):
lexer = pygments.lexers.get_lexer_by_name(language, stripall=True)
if language in ('latex', 'tex'):
fmtr = OdtPygmentsLaTeXFormatter(lambda name, parameters=():
self.rststyle(name, parameters),
escape_function=escape_cdata)
else:
fmtr = OdtPygmentsProgFormatter(lambda name, parameters=():
self.rststyle(name, parameters),
escape_function=escape_cdata)
outsource = pygments.highlight(insource, lexer, fmtr)
return outsource
def fill_line(self, line):
line = FILL_PAT1.sub(self.fill_func1, line)
line = FILL_PAT2.sub(self.fill_func2, line)
return line
def fill_func1(self, matchobj):
spaces = matchobj.group(0)
repl = '<text:s text:c="%d"/>' % (len(spaces), )
return repl
def fill_func2(self, matchobj):
spaces = matchobj.group(0)
repl = ' <text:s text:c="%d"/>' % (len(spaces) - 1, )
return repl
def visit_literal_block(self, node):
wrapper1 = '<text:p text:style-name="%s">%%s</text:p>' % (
self.rststyle('codeblock'), )
source = node.astext()
if (pygments and
self.settings.add_syntax_highlighting
#and
#node.get('hilight', False)
):
language = node.get('language', 'python')
source = self._add_syntax_highlighting(source, language)
else:
source = escape_cdata(source)
lines = source.split('\n')
lines1 = ['<wrappertag1 xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">']
my_lines = []
for my_line in lines:
my_line = self.fill_line(my_line)
my_line = my_line.replace(" ", "\n")
my_lines.append(my_line)
my_lines_str = '<text:line-break/>'.join(my_lines)
my_lines_str2 = wrapper1 % (my_lines_str, )
lines1.append(my_lines_str2)
lines1.append('</wrappertag1>')
s1 = ''.join(lines1)
if WhichElementTree != "lxml":
s1 = s1.encode("utf-8")
el1 = etree.fromstring(s1)
children = el1.getchildren()
for child in children:
self.current_element.append(child)
def depart_literal_block(self, node):
pass
visit_doctest_block = visit_literal_block
depart_doctest_block = depart_literal_block
def visit_meta(self, node):
name = node.attributes.get('name')
content = node.attributes.get('content')
if name is not None and content is not None:
self.meta_dict[name] = content
def depart_meta(self, node):
pass
def visit_option_list(self, node):
table_name = 'tableoption'
#
# Generate automatic styles
if not self.optiontablestyles_generated:
self.optiontablestyles_generated = True
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(table_name),
'style:family': 'table'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-properties', attrib={
'style:width': '17.59cm',
'table:align': 'left',
'style:shadow': 'none'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle('%s.%%c' % table_name, ( 'A', )),
'style:family': 'table-column'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-column-properties', attrib={
'style:column-width': '4.999cm'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle('%s.%%c' % table_name, ( 'B', )),
'style:family': 'table-column'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-column-properties', attrib={
'style:column-width': '12.587cm'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 1, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:background-color': 'transparent',
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': 'none',
'fo:border-top': '0.035cm solid #000000',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
el2 = SubElement(el1, 'style:background-image', nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 1, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border': '0.035cm solid #000000'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 2, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': 'none',
'fo:border-top': 'none',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
el = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 2, )),
'style:family': 'table-cell'}, nsdict=SNSD)
el1 = SubElement(el, 'style:table-cell-properties', attrib={
'fo:padding': '0.097cm',
'fo:border-left': '0.035cm solid #000000',
'fo:border-right': '0.035cm solid #000000',
'fo:border-top': 'none',
'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
#
# Generate table data
el = self.append_child('table:table', attrib={
'table:name': self.rststyle(table_name),
'table:style-name': self.rststyle(table_name),
})
el1 = SubElement(el, 'table:table-column', attrib={
'table:style-name': self.rststyle(
'%s.%%c' % table_name, ( 'A', ))})
el1 = SubElement(el, 'table:table-column', attrib={
'table:style-name': self.rststyle(
'%s.%%c' % table_name, ( 'B', ))})
el1 = SubElement(el, 'table:table-header-rows')
el2 = SubElement(el1, 'table:table-row')
el3 = SubElement(el2, 'table:table-cell', attrib={
'table:style-name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'A', 1, )),
'office:value-type': 'string'})
el4 = SubElement(el3, 'text:p', attrib={
'text:style-name': 'Table_20_Heading'})
el4.text= 'Option'
el3 = SubElement(el2, 'table:table-cell', attrib={
'table:style-name': self.rststyle(
'%s.%%c%%d' % table_name, ( 'B', 1, )),
'office:value-type': 'string'})
el4 = SubElement(el3, 'text:p', attrib={
'text:style-name': 'Table_20_Heading'})
el4.text= 'Description'
self.set_current_element(el)
def depart_option_list(self, node):
self.set_to_parent()
def visit_option_list_item(self, node):
el = self.append_child('table:table-row')
self.set_current_element(el)
def depart_option_list_item(self, node):
self.set_to_parent()
def visit_option_group(self, node):
el = self.append_child('table:table-cell', attrib={
'table:style-name': 'Table%d.A2' % self.table_count,
'office:value-type': 'string',
})
self.set_current_element(el)
def depart_option_group(self, node):
self.set_to_parent()
def visit_option(self, node):
el = self.append_child('text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el.text = node.astext()
def depart_option(self, node):
pass
def visit_option_string(self, node):
pass
def depart_option_string(self, node):
pass
def visit_option_argument(self, node):
pass
def depart_option_argument(self, node):
pass
def visit_description(self, node):
el = self.append_child('table:table-cell', attrib={
'table:style-name': 'Table%d.B2' % self.table_count,
'office:value-type': 'string',
})
el1 = SubElement(el, 'text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el1.text = node.astext()
raise nodes.SkipChildren()
def depart_description(self, node):
pass
def visit_paragraph(self, node):
self.in_paragraph = True
if self.in_header:
el = self.append_p('header')
elif self.in_footer:
el = self.append_p('footer')
else:
style_name = self.paragraph_style_stack[-1]
el = self.append_child('text:p',
attrib={'text:style-name': style_name})
self.append_pending_ids(el)
self.set_current_element(el)
def depart_paragraph(self, node):
self.in_paragraph = False
self.set_to_parent()
if self.in_header:
self.header_content.append(
self.current_element.getchildren()[-1])
self.current_element.remove(
self.current_element.getchildren()[-1])
elif self.in_footer:
self.footer_content.append(
self.current_element.getchildren()[-1])
self.current_element.remove(
self.current_element.getchildren()[-1])
def visit_problematic(self, node):
pass
def depart_problematic(self, node):
pass
def visit_raw(self, node):
if 'format' in node.attributes:
formats = node.attributes['format']
formatlist = formats.split()
if 'odt' in formatlist:
rawstr = node.astext()
attrstr = ' '.join(['%s="%s"' % (k, v, )
for k,v in CONTENT_NAMESPACE_ATTRIB.items()])
contentstr = '<stuff %s>%s</stuff>' % (attrstr, rawstr, )
if WhichElementTree != "lxml":
contentstr = contentstr.encode("utf-8")
content = etree.fromstring(contentstr)
elements = content.getchildren()
if len(elements) > 0:
el1 = elements[0]
if self.in_header:
pass
elif self.in_footer:
pass
else:
self.current_element.append(el1)
raise nodes.SkipChildren()
def depart_raw(self, node):
if self.in_header:
pass
elif self.in_footer:
pass
else:
pass
def visit_reference(self, node):
text = node.astext()
if self.settings.create_links:
if node.has_key('refuri'):
href = node['refuri']
if ( self.settings.cloak_email_addresses
and href.startswith('mailto:')):
href = self.cloak_mailto(href)
el = self.append_child('text:a', attrib={
'xlink:href': '%s' % href,
'xlink:type': 'simple',
})
self.set_current_element(el)
elif node.has_key('refid'):
if self.settings.create_links:
href = node['refid']
el = self.append_child('text:reference-ref', attrib={
'text:ref-name': '%s' % href,
'text:reference-format': 'text',
})
else:
self.document.reporter.warning(
'References must have "refuri" or "refid" attribute.')
if (self.in_table_of_contents and
len(node.children) >= 1 and
isinstance(node.children[0], docutils.nodes.generated)):
node.remove(node.children[0])
def depart_reference(self, node):
if self.settings.create_links:
if node.has_key('refuri'):
self.set_to_parent()
def visit_rubric(self, node):
style_name = self.rststyle('rubric')
classes = node.get('classes')
if classes:
class1 = classes[0]
if class1:
style_name = class1
el = SubElement(self.current_element, 'text:h', attrib = {
#'text:outline-level': '%d' % section_level,
#'text:style-name': 'Heading_20_%d' % section_level,
'text:style-name': style_name,
})
text = node.astext()
el.text = self.encode(text)
def depart_rubric(self, node):
pass
def visit_section(self, node, move_ids=1):
self.section_level += 1
self.section_count += 1
if self.settings.create_sections:
el = self.append_child('text:section', attrib={
'text:name': 'Section%d' % self.section_count,
'text:style-name': 'Sect%d' % self.section_level,
})
self.set_current_element(el)
def depart_section(self, node):
self.section_level -= 1
if self.settings.create_sections:
self.set_to_parent()
def visit_strong(self, node):
el = SubElement(self.current_element, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
self.set_current_element(el)
def depart_strong(self, node):
self.set_to_parent()
def visit_substitution_definition(self, node):
raise nodes.SkipChildren()
def depart_substitution_definition(self, node):
pass
def visit_system_message(self, node):
pass
def depart_system_message(self, node):
pass
def get_table_style(self, node):
table_style = None
table_name = None
use_predefined_table_style = False
str_classes = node.get('classes')
if str_classes is not None:
for str_class in str_classes:
if str_class.startswith(TABLESTYLEPREFIX):
table_name = str_class
use_predefined_table_style = True
break
if table_name is not None:
table_style = self.table_styles.get(table_name)
if table_style is None:
# If we can't find the table style, issue warning
# and use the default table style.
self.document.reporter.warning(
'Can\'t find table style "%s". Using default.' % (
table_name, ))
table_name = TABLENAMEDEFAULT
table_style = self.table_styles.get(table_name)
if table_style is None:
# If we can't find the default table style, issue a warning
# and use a built-in default style.
self.document.reporter.warning(
'Can\'t find default table style "%s". Using built-in default.' % (
table_name, ))
table_style = BUILTIN_DEFAULT_TABLE_STYLE
else:
table_name = TABLENAMEDEFAULT
table_style = self.table_styles.get(table_name)
if table_style is None:
# If we can't find the default table style, issue a warning
# and use a built-in default style.
self.document.reporter.warning(
'Can\'t find default table style "%s". Using built-in default.' % (
table_name, ))
table_style = BUILTIN_DEFAULT_TABLE_STYLE
return table_style
def visit_table(self, node):
self.table_count += 1
table_style = self.get_table_style(node)
table_name = '%s%%d' % TABLESTYLEPREFIX
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
'style:family': 'table',
}, nsdict=SNSD)
if table_style.backgroundcolor is None:
el1_1 = SubElement(el1, 'style:table-properties', attrib={
#'style:width': '17.59cm',
'table:align': 'margins',
'fo:margin-top': '0in',
'fo:margin-bottom': '0.10in',
}, nsdict=SNSD)
else:
el1_1 = SubElement(el1, 'style:table-properties', attrib={
#'style:width': '17.59cm',
'table:align': 'margins',
'fo:margin-top': '0in',
'fo:margin-bottom': '0.10in',
'fo:background-color': table_style.backgroundcolor,
}, nsdict=SNSD)
# We use a single cell style for all cells in this table.
# That's probably not correct, but seems to work.
el2 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': self.rststyle(
'%s.%%c%%d' % table_name, ( self.table_count, 'A', 1, )),
'style:family': 'table-cell',
}, nsdict=SNSD)
thickness = self.settings.table_border_thickness
if thickness is None:
line_style1 = table_style.border
else:
line_style1 = '0.%03dcm solid #000000' % (thickness, )
el2_1 = SubElement(el2, 'style:table-cell-properties', attrib={
'fo:padding': '0.049cm',
'fo:border-left': line_style1,
'fo:border-right': line_style1,
'fo:border-top': line_style1,
'fo:border-bottom': line_style1,
}, nsdict=SNSD)
title = None
for child in node.children:
if child.tagname == 'title':
title = child.astext()
break
if title is not None:
el3 = self.append_p('table-title', title)
else:
pass
el4 = SubElement(self.current_element, 'table:table', attrib={
'table:name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
'table:style-name': self.rststyle(
'%s' % table_name, ( self.table_count, )),
})
self.set_current_element(el4)
self.current_table_style = el1
self.table_width = 0
def depart_table(self, node):
attribkey = add_ns('style:width', nsdict=SNSD)
attribval = '%dcm' % self.table_width
self.current_table_style.attrib[attribkey] = attribval
self.set_to_parent()
def visit_tgroup(self, node):
self.column_count = ord('A') - 1
def depart_tgroup(self, node):
pass
def visit_colspec(self, node):
self.column_count += 1
colspec_name = self.rststyle(
'%s%%d.%%s' % TABLESTYLEPREFIX,
(self.table_count, chr(self.column_count), )
)
colwidth = node['colwidth']
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': colspec_name,
'style:family': 'table-column',
}, nsdict=SNSD)
el1_1 = SubElement(el1, 'style:table-column-properties', attrib={
'style:column-width': '%dcm' % colwidth }, nsdict=SNSD)
el2 = self.append_child('table:table-column', attrib={
'table:style-name': colspec_name,
})
self.table_width += colwidth
def depart_colspec(self, node):
pass
def visit_thead(self, node):
el = self.append_child('table:table-header-rows')
self.set_current_element(el)
self.in_thead = True
self.paragraph_style_stack.append('Table_20_Heading')
def depart_thead(self, node):
self.set_to_parent()
self.in_thead = False
self.paragraph_style_stack.pop()
def visit_row(self, node):
self.column_count = ord('A') - 1
el = self.append_child('table:table-row')
self.set_current_element(el)
def depart_row(self, node):
self.set_to_parent()
def visit_entry(self, node):
self.column_count += 1
cellspec_name = self.rststyle(
'%s%%d.%%c%%d' % TABLESTYLEPREFIX,
(self.table_count, 'A', 1, )
)
attrib={
'table:style-name': cellspec_name,
'office:value-type': 'string',
}
morecols = node.get('morecols', 0)
if morecols > 0:
attrib['table:number-columns-spanned'] = '%d' % (morecols + 1,)
self.column_count += morecols
morerows = node.get('morerows', 0)
if morerows > 0:
attrib['table:number-rows-spanned'] = '%d' % (morerows + 1,)
el1 = self.append_child('table:table-cell', attrib=attrib)
self.set_current_element(el1)
def depart_entry(self, node):
self.set_to_parent()
def visit_tbody(self, node):
pass
def depart_tbody(self, node):
pass
def visit_target(self, node):
#
# I don't know how to implement targets in ODF.
# How do we create a target in oowriter? A cross-reference?
if not (node.has_key('refuri') or node.has_key('refid')
or node.has_key('refname')):
pass
else:
pass
def depart_target(self, node):
pass
def visit_title(self, node, move_ids=1, title_type='title'):
if isinstance(node.parent, docutils.nodes.section):
section_level = self.section_level
if section_level > 7:
self.document.reporter.warning(
'Heading/section levels greater than 7 not supported.')
self.document.reporter.warning(
' Reducing to heading level 7 for heading: "%s"' % (
node.astext(), ))
section_level = 7
el1 = self.append_child('text:h', attrib = {
'text:outline-level': '%d' % section_level,
#'text:style-name': 'Heading_20_%d' % section_level,
'text:style-name': self.rststyle(
'heading%d', (section_level, )),
})
self.append_pending_ids(el1)
self.set_current_element(el1)
elif isinstance(node.parent, docutils.nodes.document):
# text = self.settings.title
#else:
# text = node.astext()
el1 = SubElement(self.current_element, 'text:p', attrib = {
'text:style-name': self.rststyle(title_type),
})
self.append_pending_ids(el1)
text = node.astext()
self.title = text
self.found_doc_title = True
self.set_current_element(el1)
def depart_title(self, node):
if (isinstance(node.parent, docutils.nodes.section) or
isinstance(node.parent, docutils.nodes.document)):
self.set_to_parent()
def visit_subtitle(self, node, move_ids=1):
self.visit_title(node, move_ids, title_type='subtitle')
def depart_subtitle(self, node):
self.depart_title(node)
def visit_title_reference(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': self.rststyle('quotation')})
el.text = self.encode(node.astext())
raise nodes.SkipChildren()
def depart_title_reference(self, node):
pass
def generate_table_of_content_entry_template(self, el1):
for idx in range(1, 11):
el2 = SubElement(el1,
'text:table-of-content-entry-template',
attrib={
'text:outline-level': "%d" % (idx, ),
'text:style-name': self.rststyle('contents-%d' % (idx, )),
})
el3 = SubElement(el2, 'text:index-entry-chapter')
el3 = SubElement(el2, 'text:index-entry-text')
el3 = SubElement(el2, 'text:index-entry-tab-stop', attrib={
'style:leader-char': ".",
'style:type': "right",
})
el3 = SubElement(el2, 'text:index-entry-page-number')
def visit_topic(self, node):
if 'classes' in node.attributes:
if 'contents' in node.attributes['classes']:
if self.settings.generate_oowriter_toc:
el1 = self.append_child('text:table-of-content', attrib={
'text:name': 'Table of Contents1',
'text:protected': 'true',
'text:style-name': 'Sect1',
})
el2 = SubElement(el1,
'text:table-of-content-source',
attrib={
'text:outline-level': '10',
})
el3 =SubElement(el2, 'text:index-title-template', attrib={
'text:style-name': 'Contents_20_Heading',
})
el3.text = 'Table of Contents'
self.generate_table_of_content_entry_template(el2)
el4 = SubElement(el1, 'text:index-body')
el5 = SubElement(el4, 'text:index-title')
el6 = SubElement(el5, 'text:p', attrib={
'text:style-name': self.rststyle('contents-heading'),
})
el6.text = 'Table of Contents'
self.save_current_element = self.current_element
self.table_of_content_index_body = el4
self.set_current_element(el4)
else:
el = self.append_p('horizontalline')
el = self.append_p('centeredtextbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = 'Contents'
self.in_table_of_contents = True
elif 'abstract' in node.attributes['classes']:
el = self.append_p('horizontalline')
el = self.append_p('centeredtextbody')
el1 = SubElement(el, 'text:span',
attrib={'text:style-name': self.rststyle('strong')})
el1.text = 'Abstract'
def depart_topic(self, node):
if 'classes' in node.attributes:
if 'contents' in node.attributes['classes']:
if self.settings.generate_oowriter_toc:
self.update_toc_page_numbers(
self.table_of_content_index_body)
self.set_current_element(self.save_current_element)
else:
el = self.append_p('horizontalline')
self.in_table_of_contents = False
def update_toc_page_numbers(self, el):
collection = []
self.update_toc_collect(el, 0, collection)
self.update_toc_add_numbers(collection)
def update_toc_collect(self, el, level, collection):
collection.append((level, el))
level += 1
for child_el in el.getchildren():
if child_el.tag != 'text:index-body':
self.update_toc_collect(child_el, level, collection)
def update_toc_add_numbers(self, collection):
for level, el1 in collection:
if (el1.tag == 'text:p' and
el1.text != 'Table of Contents'):
el2 = SubElement(el1, 'text:tab')
el2.tail = '9999'
def visit_transition(self, node):
el = self.append_p('horizontalline')
def depart_transition(self, node):
pass
#
# Admonitions
#
def visit_warning(self, node):
self.generate_admonition(node, 'warning')
def depart_warning(self, node):
self.paragraph_style_stack.pop()
def visit_attention(self, node):
self.generate_admonition(node, 'attention')
depart_attention = depart_warning
def visit_caution(self, node):
self.generate_admonition(node, 'caution')
depart_caution = depart_warning
def visit_danger(self, node):
self.generate_admonition(node, 'danger')
depart_danger = depart_warning
def visit_error(self, node):
self.generate_admonition(node, 'error')
depart_error = depart_warning
def visit_hint(self, node):
self.generate_admonition(node, 'hint')
depart_hint = depart_warning
def visit_important(self, node):
self.generate_admonition(node, 'important')
depart_important = depart_warning
def visit_note(self, node):
self.generate_admonition(node, 'note')
depart_note = depart_warning
def visit_tip(self, node):
self.generate_admonition(node, 'tip')
depart_tip = depart_warning
def visit_admonition(self, node):
title = None
for child in node.children:
if child.tagname == 'title':
title = child.astext()
if title is None:
classes1 = node.get('classes')
if classes1:
title = classes1[0]
self.generate_admonition(node, 'generic', title)
depart_admonition = depart_warning
def generate_admonition(self, node, label, title=None):
el1 = SubElement(self.current_element, 'text:p', attrib = {
'text:style-name': self.rststyle('admon-%s-hdr', ( label, )),
})
if title:
el1.text = title
else:
el1.text = '%s!' % (label.capitalize(), )
s1 = self.rststyle('admon-%s-body', ( label, ))
self.paragraph_style_stack.append(s1)
#
# Roles (e.g. subscript, superscript, strong, ...
#
def visit_subscript(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': 'rststyle-subscript',
})
self.set_current_element(el)
def depart_subscript(self, node):
self.set_to_parent()
def visit_superscript(self, node):
el = self.append_child('text:span', attrib={
'text:style-name': 'rststyle-superscript',
})
self.set_current_element(el)
def depart_superscript(self, node):
self.set_to_parent()
# Use an own reader to modify transformations done.
class Reader(standalone.Reader):
def get_transforms(self):
default = standalone.Reader.get_transforms(self)
if self.settings.create_links:
return default
return [ i
for i in default
if i is not references.DanglingReferences ]
| {
"repo_name": "robovm/robovm-studio",
"path": "python/helpers/docutils/writers/odf_odt/__init__.py",
"copies": "41",
"size": "119306",
"license": "apache-2.0",
"hash": 8468282245481710000,
"line_mean": 37.104758863,
"line_max": 103,
"alpha_frac": 0.5364608653,
"autogenerated": false,
"ratio": 3.8114497476199602,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002563523930771748,
"num_lines": 3131
} |
# Internationalization details are documented in
# <http://docutils.sf.net/docs/howto/i18n.html>.
"""
This package contains modules for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
from docutils.utils import normalize_language_tag
_languages = {}
def get_language(language_code, reporter):
"""Return module with language localizations.
`language_code` is a "BCP 47" language tag.
If there is no matching module, warn and fall back to English.
"""
# TODO: use a dummy module returning emtpy strings?, configurable?
for tag in normalize_language_tag(language_code):
if tag in _languages:
return _languages[tag]
try:
module = __import__(tag, globals(), locals())
except ImportError:
continue
_languages[tag] = module
return module
reporter.warning(
'language "%s" not supported: ' % language_code +
'Docutils-generated text will be in English.')
module = __import__('en', globals(), locals())
_languages[tag] = module # warn only one time!
return module
| {
"repo_name": "johngian/remo",
"path": "vendor-local/lib/python/docutils/languages/__init__.py",
"copies": "6",
"size": "1286",
"license": "bsd-3-clause",
"hash": -638516370537126900,
"line_mean": 31.9743589744,
"line_max": 74,
"alpha_frac": 0.6617418351,
"autogenerated": false,
"ratio": 3.9691358024691357,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7630877637569136,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils Writer modules.
"""
__docformat__ = 'reStructuredText'
import os.path
import docutils
from docutils import languages, Component
from docutils.transforms import universal
class Writer(Component):
"""
Abstract base class for docutils Writers.
Each writer module or package must export a subclass also called 'Writer'.
Each writer must support all standard node types listed in
`docutils.nodes.node_class_names`.
The `write()` method is the main entry point.
"""
component_type = 'writer'
config_section = 'writers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Messages,
universal.FilterMessages,
universal.StripClassesAndElements,]
document = None
"""The document to write (Docutils doctree); set by `write`."""
output = None
"""Final translated form of `document` (Unicode string for text, binary
string for other forms); set by `translate`."""
language = None
"""Language module for the document; set by `write`."""
destination = None
"""`docutils.io` Output object; where to write the document.
Set by `write`."""
def __init__(self):
# Used by HTML and LaTex writer for output fragments:
self.parts = {}
"""Mapping of document part names to fragments of `self.output`.
Values are Unicode strings; encoding is up to the client. The 'whole'
key should contain the entire document output.
"""
def write(self, document, destination):
"""
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.
"""
self.document = document
self.language = languages.get_language(
document.settings.language_code,
document.reporter)
self.destination = destination
self.translate()
output = self.destination.write(self.output)
return output
def translate(self):
"""
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.
"""
raise NotImplementedError('subclass must override this method')
def assemble_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses."""
self.parts['whole'] = self.output
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
class UnfilteredWriter(Writer):
"""
A writer that passes the document tree on unchanged (e.g. a
serializer.)
Documents written by UnfilteredWriters are typically reused at a
later date using a subclass of `readers.ReReader`.
"""
def get_transforms(self):
# Do not add any transforms. When the document is reused
# later, the then-used writer will add the appropriate
# transforms.
return Component.get_transforms(self)
_writer_aliases = {
'html': 'html4css1',
'latex': 'latex2e',
'pprint': 'pseudoxml',
'pformat': 'pseudoxml',
'pdf': 'rlpdf',
'xml': 'docutils_xml',
's5': 's5_html'}
def get_writer_class(writer_name):
"""Return the Writer class from the `writer_name` module."""
writer_name = writer_name.lower()
if writer_name in _writer_aliases:
writer_name = _writer_aliases[writer_name]
module = __import__(writer_name, globals(), locals())
return module.Writer
| {
"repo_name": "abdullah2891/remo",
"path": "vendor-local/lib/python/docutils/writers/__init__.py",
"copies": "6",
"size": "4283",
"license": "bsd-3-clause",
"hash": -6788696736269331000,
"line_mean": 30.9626865672,
"line_max": 78,
"alpha_frac": 0.6495447117,
"autogenerated": false,
"ratio": 4.348223350253807,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7997768061953806,
"avg_score": null,
"num_lines": null
} |
"""
This package contains modules for standard tree transforms available
to Docutils components. Tree transforms serve a variety of purposes:
- To tie up certain syntax-specific "loose ends" that remain after the
initial parsing of the input plaintext. These transforms are used to
supplement a limited syntax.
- To automate the internal linking of the document tree (hyperlink
references, footnote references, etc.).
- To extract useful information from the document tree. These
transforms may be used to construct (for example) indexes and tables
of contents.
Each transform is an optional step that a Docutils component may
choose to perform on the parsed document.
"""
__docformat__ = 'reStructuredText'
from docutils import languages, ApplicationError, TransformSpec
class TransformError(ApplicationError): pass
class Transform:
"""
Docutils transform component abstract base class.
"""
default_priority = None
"""Numerical priority of this transform, 0 through 999 (override)."""
def __init__(self, document, startnode=None):
"""
Initial setup for in-place document transforms.
"""
self.document = document
"""The document tree to transform."""
self.startnode = startnode
"""Node from which to begin the transform. For many transforms which
apply to the document as a whole, `startnode` is not set (i.e. its
value is `None`)."""
self.language = languages.get_language(
document.settings.language_code, document.reporter)
"""Language module local to this document."""
def apply(self, **kwargs):
"""Override to apply the transform to the document tree."""
raise NotImplementedError('subclass must override this method')
class Transformer(TransformSpec):
"""
Stores transforms (`Transform` classes) and applies them to document
trees. Also keeps track of components by component type name.
"""
def __init__(self, document):
self.transforms = []
"""List of transforms to apply. Each item is a 3-tuple:
``(priority string, transform class, pending node or None)``."""
self.unknown_reference_resolvers = []
"""List of hook functions which assist in resolving references"""
self.document = document
"""The `nodes.document` object this Transformer is attached to."""
self.applied = []
"""Transforms already applied, in order."""
self.sorted = 0
"""Boolean: is `self.tranforms` sorted?"""
self.components = {}
"""Mapping of component type name to component object. Set by
`self.populate_from_components()`."""
self.serialno = 0
"""Internal serial number to keep track of the add order of
transforms."""
def add_transform(self, transform_class, priority=None, **kwargs):
"""
Store a single transform. Use `priority` to override the default.
`kwargs` is a dictionary whose contents are passed as keyword
arguments to the `apply` method of the transform. This can be used to
pass application-specific data to the transform instance.
"""
if priority is None:
priority = transform_class.default_priority
priority_string = self.get_priority_string(priority)
self.transforms.append(
(priority_string, transform_class, None, kwargs))
self.sorted = 0
def add_transforms(self, transform_list):
"""Store multiple transforms, with default priorities."""
for transform_class in transform_list:
priority_string = self.get_priority_string(
transform_class.default_priority)
self.transforms.append(
(priority_string, transform_class, None, {}))
self.sorted = 0
def add_pending(self, pending, priority=None):
"""Store a transform with an associated `pending` node."""
transform_class = pending.transform
if priority is None:
priority = transform_class.default_priority
priority_string = self.get_priority_string(priority)
self.transforms.append(
(priority_string, transform_class, pending, {}))
self.sorted = 0
def get_priority_string(self, priority):
"""
Return a string, `priority` combined with `self.serialno`.
This ensures FIFO order on transforms with identical priority.
"""
self.serialno += 1
return '%03d-%03d' % (priority, self.serialno)
def populate_from_components(self, components):
"""
Store each component's default transforms, with default priorities.
Also, store components by type name in a mapping for later lookup.
"""
for component in components:
if component is None:
continue
self.add_transforms(component.get_transforms())
self.components[component.component_type] = component
self.sorted = 0
# Set up all of the reference resolvers for this transformer. Each
# component of this transformer is able to register its own helper
# functions to help resolve references.
unknown_reference_resolvers = []
for i in components:
unknown_reference_resolvers.extend(i.unknown_reference_resolvers)
decorated_list = [(f.priority, f) for f in unknown_reference_resolvers]
decorated_list.sort()
self.unknown_reference_resolvers.extend([f[1] for f in decorated_list])
def apply_transforms(self):
"""Apply all of the stored transforms, in priority order."""
self.document.reporter.attach_observer(
self.document.note_transform_message)
while self.transforms:
if not self.sorted:
# Unsorted initially, and whenever a transform is added.
self.transforms.sort()
self.transforms.reverse()
self.sorted = 1
priority, transform_class, pending, kwargs = self.transforms.pop()
transform = transform_class(self.document, startnode=pending)
transform.apply(**kwargs)
self.applied.append((priority, transform_class, pending, kwargs))
| {
"repo_name": "mglukhikh/intellij-community",
"path": "python/helpers/py2only/docutils/transforms/__init__.py",
"copies": "186",
"size": "6505",
"license": "apache-2.0",
"hash": -719012436074697700,
"line_mean": 36.8197674419,
"line_max": 79,
"alpha_frac": 0.6505764796,
"autogenerated": false,
"ratio": 4.673132183908046,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
# Internationalization details are documented in
# <http://docutils.sf.net/docs/howto/i18n.html>.
"""
This package contains modules for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
from docutils.utils import normalize_language_tag
_languages = {}
def get_language(language_code, reporter):
"""Return module with language localizations.
`language_code` is a "BCP 47" language tag.
If there is no matching module, warn and fall back to English.
"""
# TODO: use a dummy module returning emtpy strings?, configurable?
for tag in normalize_language_tag(language_code):
if tag in _languages:
return _languages[tag]
try:
module = __import__(tag, globals(), locals())
except ImportError:
continue
_languages[tag] = module
return module
reporter.warning(
'language "%s" not supported: ' % language_code +
'Docutils-generated text will be in English.')
module = __import__('en', globals(), locals())
_languages[tag] = module # warn only one time!
return module
| {
"repo_name": "cuongthai/cuongthai-s-blog",
"path": "docutils/languages/__init__.py",
"copies": "2",
"size": "1325",
"license": "bsd-3-clause",
"hash": 4072111173108203000,
"line_mean": 31.9743589744,
"line_max": 74,
"alpha_frac": 0.6422641509,
"autogenerated": false,
"ratio": 4.027355623100304,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5669619774000304,
"avg_score": null,
"num_lines": null
} |
"""
This package contains Docutils Writer modules.
"""
__docformat__ = 'reStructuredText'
import os.path
import docutils
from docutils import languages, Component
from docutils.transforms import universal
class Writer(Component):
"""
Abstract base class for docutils Writers.
Each writer module or package must export a subclass also called 'Writer'.
Each writer must support all standard node types listed in
`docutils.nodes.node_class_names`.
The `write()` method is the main entry point.
"""
component_type = 'writer'
config_section = 'writers'
def get_transforms(self):
return Component.get_transforms(self) + [
universal.Messages,
universal.FilterMessages,
universal.StripClassesAndElements,]
document = None
"""The document to write (Docutils doctree); set by `write`."""
output = None
"""Final translated form of `document` (Unicode string for text, binary
string for other forms); set by `translate`."""
language = None
"""Language module for the document; set by `write`."""
destination = None
"""`docutils.io` Output object; where to write the document.
Set by `write`."""
def __init__(self):
# Used by HTML and LaTex writer for output fragments:
self.parts = {}
"""Mapping of document part names to fragments of `self.output`.
Values are Unicode strings; encoding is up to the client. The 'whole'
key should contain the entire document output.
"""
def write(self, document, destination):
"""
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.
"""
self.document = document
self.language = languages.get_language(
document.settings.language_code,
document.reporter)
self.destination = destination
self.translate()
output = self.destination.write(self.output)
return output
def translate(self):
"""
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.
"""
raise NotImplementedError('subclass must override this method')
def assemble_parts(self):
"""Assemble the `self.parts` dictionary. Extend in subclasses."""
self.parts['whole'] = self.output
self.parts['encoding'] = self.document.settings.output_encoding
self.parts['version'] = docutils.__version__
class UnfilteredWriter(Writer):
"""
A writer that passes the document tree on unchanged (e.g. a
serializer.)
Documents written by UnfilteredWriters are typically reused at a
later date using a subclass of `readers.ReReader`.
"""
def get_transforms(self):
# Do not add any transforms. When the document is reused
# later, the then-used writer will add the appropriate
# transforms.
return Component.get_transforms(self)
_writer_aliases = {
'html': 'html4css1',
'latex': 'latex2e',
'pprint': 'pseudoxml',
'pformat': 'pseudoxml',
'pdf': 'rlpdf',
'xml': 'docutils_xml',
's5': 's5_html'}
def get_writer_class(writer_name):
"""Return the Writer class from the `writer_name` module."""
writer_name = writer_name.lower()
if writer_name in _writer_aliases:
writer_name = _writer_aliases[writer_name]
module = __import__(writer_name, globals(), locals())
return module.Writer
| {
"repo_name": "ajaxsys/dict-admin",
"path": "docutils/writers/__init__.py",
"copies": "2",
"size": "4417",
"license": "bsd-3-clause",
"hash": 6816592545464800000,
"line_mean": 30.9626865672,
"line_max": 78,
"alpha_frac": 0.6298392574,
"autogenerated": false,
"ratio": 4.452620967741935,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00035959657494838724,
"num_lines": 134
} |
"""
This package contains modules for standard tree transforms available
to Docutils components. Tree transforms serve a variety of purposes:
- To tie up certain syntax-specific "loose ends" that remain after the
initial parsing of the input plaintext. These transforms are used to
supplement a limited syntax.
- To automate the internal linking of the document tree (hyperlink
references, footnote references, etc.).
- To extract useful information from the document tree. These
transforms may be used to construct (for example) indexes and tables
of contents.
Each transform is an optional step that a Docutils component may
choose to perform on the parsed document.
"""
__docformat__ = 'reStructuredText'
from docutils import languages, ApplicationError, TransformSpec
class TransformError(ApplicationError): pass
class Transform:
"""
Docutils transform component abstract base class.
"""
default_priority = None
"""Numerical priority of this transform, 0 through 999 (override)."""
def __init__(self, document, startnode=None):
"""
Initial setup for in-place document transforms.
"""
self.document = document
"""The document tree to transform."""
self.startnode = startnode
"""Node from which to begin the transform. For many transforms which
apply to the document as a whole, `startnode` is not set (i.e. its
value is `None`)."""
self.language = languages.get_language(
document.settings.language_code, document.reporter)
"""Language module local to this document."""
def apply(self, **kwargs):
"""Override to apply the transform to the document tree."""
raise NotImplementedError('subclass must override this method')
class Transformer(TransformSpec):
"""
Stores transforms (`Transform` classes) and applies them to document
trees. Also keeps track of components by component type name.
"""
def __init__(self, document):
self.transforms = []
"""List of transforms to apply. Each item is a 3-tuple:
``(priority string, transform class, pending node or None)``."""
self.unknown_reference_resolvers = []
"""List of hook functions which assist in resolving references"""
self.document = document
"""The `nodes.document` object this Transformer is attached to."""
self.applied = []
"""Transforms already applied, in order."""
self.sorted = 0
"""Boolean: is `self.tranforms` sorted?"""
self.components = {}
"""Mapping of component type name to component object. Set by
`self.populate_from_components()`."""
self.serialno = 0
"""Internal serial number to keep track of the add order of
transforms."""
def add_transform(self, transform_class, priority=None, **kwargs):
"""
Store a single transform. Use `priority` to override the default.
`kwargs` is a dictionary whose contents are passed as keyword
arguments to the `apply` method of the transform. This can be used to
pass application-specific data to the transform instance.
"""
if priority is None:
priority = transform_class.default_priority
priority_string = self.get_priority_string(priority)
self.transforms.append(
(priority_string, transform_class, None, kwargs))
self.sorted = 0
def add_transforms(self, transform_list):
"""Store multiple transforms, with default priorities."""
for transform_class in transform_list:
priority_string = self.get_priority_string(
transform_class.default_priority)
self.transforms.append(
(priority_string, transform_class, None, {}))
self.sorted = 0
def add_pending(self, pending, priority=None):
"""Store a transform with an associated `pending` node."""
transform_class = pending.transform
if priority is None:
priority = transform_class.default_priority
priority_string = self.get_priority_string(priority)
self.transforms.append(
(priority_string, transform_class, pending, {}))
self.sorted = 0
def get_priority_string(self, priority):
"""
Return a string, `priority` combined with `self.serialno`.
This ensures FIFO order on transforms with identical priority.
"""
self.serialno += 1
return '%03d-%03d' % (priority, self.serialno)
def populate_from_components(self, components):
"""
Store each component's default transforms, with default priorities.
Also, store components by type name in a mapping for later lookup.
"""
for component in components:
if component is None:
continue
self.add_transforms(component.get_transforms())
self.components[component.component_type] = component
self.sorted = 0
# Set up all of the reference resolvers for this transformer. Each
# component of this transformer is able to register its own helper
# functions to help resolve references.
unknown_reference_resolvers = []
for i in components:
unknown_reference_resolvers.extend(i.unknown_reference_resolvers)
decorated_list = [(f.priority, f) for f in unknown_reference_resolvers]
decorated_list.sort()
self.unknown_reference_resolvers.extend([f[1] for f in decorated_list])
def apply_transforms(self):
"""Apply all of the stored transforms, in priority order."""
self.document.reporter.attach_observer(
self.document.note_transform_message)
while self.transforms:
if not self.sorted:
# Unsorted initially, and whenever a transform is added.
self.transforms.sort()
self.transforms.reverse()
self.sorted = 1
priority, transform_class, pending, kwargs = self.transforms.pop()
transform = transform_class(self.document, startnode=pending)
transform.apply(**kwargs)
self.applied.append((priority, transform_class, pending, kwargs))
| {
"repo_name": "cuongthai/cuongthai-s-blog",
"path": "docutils/transforms/__init__.py",
"copies": "2",
"size": "6677",
"license": "bsd-3-clause",
"hash": 3336815722050036000,
"line_mean": 36.8197674419,
"line_max": 79,
"alpha_frac": 0.6338175827,
"autogenerated": false,
"ratio": 4.776108726752503,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0001263902932254803,
"num_lines": 172
} |
"""
This package contains directive implementation modules.
"""
__docformat__ = 'reStructuredText'
import re
import codecs
from docutils import nodes
from docutils.parsers.rst.languages import en as _fallback_language_module
_directive_registry = {
'attention': ('admonitions', 'Attention'),
'caution': ('admonitions', 'Caution'),
'danger': ('admonitions', 'Danger'),
'error': ('admonitions', 'Error'),
'important': ('admonitions', 'Important'),
'note': ('admonitions', 'Note'),
'tip': ('admonitions', 'Tip'),
'hint': ('admonitions', 'Hint'),
'warning': ('admonitions', 'Warning'),
'admonition': ('admonitions', 'Admonition'),
'sidebar': ('body', 'Sidebar'),
'topic': ('body', 'Topic'),
'line-block': ('body', 'LineBlock'),
'parsed-literal': ('body', 'ParsedLiteral'),
'math': ('body', 'MathBlock'),
'rubric': ('body', 'Rubric'),
'epigraph': ('body', 'Epigraph'),
'highlights': ('body', 'Highlights'),
'pull-quote': ('body', 'PullQuote'),
'compound': ('body', 'Compound'),
'container': ('body', 'Container'),
#'questions': ('body', 'question_list'),
'table': ('tables', 'RSTTable'),
'csv-table': ('tables', 'CSVTable'),
'list-table': ('tables', 'ListTable'),
'image': ('images', 'Image'),
'figure': ('images', 'Figure'),
'contents': ('parts', 'Contents'),
'sectnum': ('parts', 'Sectnum'),
'header': ('parts', 'Header'),
'footer': ('parts', 'Footer'),
#'footnotes': ('parts', 'footnotes'),
#'citations': ('parts', 'citations'),
'target-notes': ('references', 'TargetNotes'),
'meta': ('html', 'Meta'),
#'imagemap': ('html', 'imagemap'),
'raw': ('misc', 'Raw'),
'include': ('misc', 'Include'),
'replace': ('misc', 'Replace'),
'unicode': ('misc', 'Unicode'),
'class': ('misc', 'Class'),
'role': ('misc', 'Role'),
'default-role': ('misc', 'DefaultRole'),
'title': ('misc', 'Title'),
'date': ('misc', 'Date'),
'restructuredtext-test-directive': ('misc', 'TestDirective'),}
"""Mapping of directive name to (module name, class name). The
directive name is canonical & must be lowercase. Language-dependent
names are defined in the ``language`` subpackage."""
_directives = {}
"""Cache of imported directives."""
def directive(directive_name, language_module, document):
"""
Locate and return a directive function from its language-dependent name.
If not found in the current language, check English. Return None if the
named directive cannot be found.
"""
normname = directive_name.lower()
messages = []
msg_text = []
if normname in _directives:
return _directives[normname], messages
canonicalname = None
try:
canonicalname = language_module.directives[normname]
except AttributeError, error:
msg_text.append('Problem retrieving directive entry from language '
'module %r: %s.' % (language_module, error))
except KeyError:
msg_text.append('No directive entry for "%s" in module "%s".'
% (directive_name, language_module.__name__))
if not canonicalname:
try:
canonicalname = _fallback_language_module.directives[normname]
msg_text.append('Using English fallback for directive "%s".'
% directive_name)
except KeyError:
msg_text.append('Trying "%s" as canonical directive name.'
% directive_name)
# The canonical name should be an English name, but just in case:
canonicalname = normname
if msg_text:
message = document.reporter.info(
'\n'.join(msg_text), line=document.current_line)
messages.append(message)
try:
modulename, classname = _directive_registry[canonicalname]
except KeyError:
# Error handling done by caller.
return None, messages
try:
module = __import__(modulename, globals(), locals())
except ImportError, detail:
messages.append(document.reporter.error(
'Error importing directive module "%s" (directive "%s"):\n%s'
% (modulename, directive_name, detail),
line=document.current_line))
return None, messages
try:
directive = getattr(module, classname)
_directives[normname] = directive
except AttributeError:
messages.append(document.reporter.error(
'No directive class "%s" in module "%s" (directive "%s").'
% (classname, modulename, directive_name),
line=document.current_line))
return None, messages
return directive, messages
def register_directive(name, directive):
"""
Register a nonstandard application-defined directive function.
Language lookups are not needed for such functions.
"""
_directives[name] = directive
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
else:
return None
def unchanged_required(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
return argument # unchanged!
def unchanged(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
No argument implies empty string ("").
"""
if argument is None:
return u''
else:
return argument # unchanged!
def path(argument):
"""
Return the path argument unwrapped (with newlines removed).
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
path = ''.join([s.strip() for s in argument.splitlines()])
return path
def uri(argument):
"""
Return the URI argument with whitespace removed.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
uri = ''.join(argument.split())
return uri
def nonnegative_int(argument):
"""
Check for a nonnegative integer argument; raise ``ValueError`` if not.
(Directive option conversion function.)
"""
value = int(argument)
if value < 0:
raise ValueError('negative value; must be positive or zero')
return value
def percentage(argument):
"""
Check for an integer percentage value with optional percent sign.
"""
try:
argument = argument.rstrip(' %')
except AttributeError:
pass
return nonnegative_int(argument)
length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc']
def get_measure(argument, units):
"""
Check for a positive argument of one of the units and return a
normalized string of the form "<value><unit>" (without space in
between).
To be called from directive option conversion functions.
"""
match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument)
try:
assert match is not None
float(match.group(1))
except (AssertionError, ValueError):
raise ValueError(
'not a positive measure of one of the following units:\n%s'
% ' '.join(['"%s"' % i for i in units]))
return match.group(1) + match.group(2)
def length_or_unitless(argument):
return get_measure(argument, length_units + [''])
def length_or_percentage_or_unitless(argument, default=''):
"""
Return normalized string of a length or percentage unit.
Add <default> if there is no unit. Raise ValueError if the argument is not
a positive measure of one of the valid CSS units (or without unit).
>>> length_or_percentage_or_unitless('3 pt')
'3pt'
>>> length_or_percentage_or_unitless('3%', 'em')
'3%'
>>> length_or_percentage_or_unitless('3')
'3'
>>> length_or_percentage_or_unitless('3', 'px')
'3px'
"""
try:
return get_measure(argument, length_units + ['%'])
except ValueError:
return get_measure(argument, ['']) + default
def class_option(argument):
"""
Convert the argument into a list of ID-compatible strings and return it.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
names = argument.split()
class_names = []
for name in names:
class_name = nodes.make_id(name)
if not class_name:
raise ValueError('cannot make "%s" into a class name' % name)
class_names.append(class_name)
return class_names
unicode_pattern = re.compile(
r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE)
def unicode_code(code):
r"""
Convert a Unicode character code to a Unicode character.
(Directive option conversion function.)
Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``,
``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style
numeric character entities (e.g. ``☮``). Other text remains as-is.
Raise ValueError for illegal Unicode code values.
"""
try:
if code.isdigit(): # decimal number
return unichr(int(code))
else:
match = unicode_pattern.match(code)
if match: # hex number
value = match.group(1) or match.group(2)
return unichr(int(value, 16))
else: # other text
return code
except OverflowError, detail:
raise ValueError('code too large (%s)' % detail)
def single_char_or_unicode(argument):
"""
A single character is returned as-is. Unicode characters codes are
converted as in `unicode_code`. (Directive option conversion function.)
"""
char = unicode_code(argument)
if len(char) > 1:
raise ValueError('%r invalid; must be a single character or '
'a Unicode code' % char)
return char
def single_char_or_whitespace_or_unicode(argument):
"""
As with `single_char_or_unicode`, but "tab" and "space" are also supported.
(Directive option conversion function.)
"""
if argument == 'tab':
char = '\t'
elif argument == 'space':
char = ' '
else:
char = single_char_or_unicode(argument)
return char
def positive_int(argument):
"""
Converts the argument into an integer. Raises ValueError for negative,
zero, or non-integer values. (Directive option conversion function.)
"""
value = int(argument)
if value < 1:
raise ValueError('negative or zero value; must be positive')
return value
def positive_int_list(argument):
"""
Converts a space- or comma-separated list of values into a Python list
of integers.
(Directive option conversion function.)
Raises ValueError for non-positive-integer values.
"""
if ',' in argument:
entries = argument.split(',')
else:
entries = argument.split()
return [positive_int(entry) for entry in entries]
def encoding(argument):
"""
Verfies the encoding argument by lookup.
(Directive option conversion function.)
Raises ValueError for unknown encodings.
"""
try:
codecs.lookup(argument)
except LookupError:
raise ValueError('unknown encoding: "%s"' % argument)
return argument
def choice(argument, values):
"""
Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
example::
from docutils.parsers.rst import directives
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
Raise ``ValueError`` if no argument is found or if the argument's value is
not valid (not an entry in the supplied list).
"""
try:
value = argument.lower().strip()
except AttributeError:
raise ValueError('must supply an argument; choose from %s'
% format_values(values))
if value in values:
return value
else:
raise ValueError('"%s" unknown; choose from %s'
% (argument, format_values(values)))
def format_values(values):
return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]),
values[-1])
| {
"repo_name": "alekseyev/wheatleycms",
"path": "docutils/parsers/rst/directives/__init__.py",
"copies": "6",
"size": "13349",
"license": "bsd-3-clause",
"hash": -9177735072327124000,
"line_mean": 32.7095959596,
"line_max": 79,
"alpha_frac": 0.6067870252,
"autogenerated": false,
"ratio": 4.175477009696591,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7782264034896591,
"avg_score": null,
"num_lines": null
} |
"""
This package contains directive implementation modules.
"""
__docformat__ = 'reStructuredText'
import re
import codecs
from docutils import nodes
from docutils.parsers.rst.languages import en as _fallback_language_module
_directive_registry = {
'attention': ('admonitions', 'Attention'),
'caution': ('admonitions', 'Caution'),
'danger': ('admonitions', 'Danger'),
'error': ('admonitions', 'Error'),
'important': ('admonitions', 'Important'),
'note': ('admonitions', 'Note'),
'tip': ('admonitions', 'Tip'),
'hint': ('admonitions', 'Hint'),
'warning': ('admonitions', 'Warning'),
'admonition': ('admonitions', 'Admonition'),
'sidebar': ('body', 'Sidebar'),
'topic': ('body', 'Topic'),
'line-block': ('body', 'LineBlock'),
'parsed-literal': ('body', 'ParsedLiteral'),
'math': ('body', 'MathBlock'),
'rubric': ('body', 'Rubric'),
'epigraph': ('body', 'Epigraph'),
'highlights': ('body', 'Highlights'),
'pull-quote': ('body', 'PullQuote'),
'compound': ('body', 'Compound'),
'container': ('body', 'Container'),
#'questions': ('body', 'question_list'),
'table': ('tables', 'RSTTable'),
'csv-table': ('tables', 'CSVTable'),
'list-table': ('tables', 'ListTable'),
'image': ('images', 'Image'),
'figure': ('images', 'Figure'),
'contents': ('parts', 'Contents'),
'sectnum': ('parts', 'Sectnum'),
'header': ('parts', 'Header'),
'footer': ('parts', 'Footer'),
#'footnotes': ('parts', 'footnotes'),
#'citations': ('parts', 'citations'),
'target-notes': ('references', 'TargetNotes'),
'meta': ('html', 'Meta'),
#'imagemap': ('html', 'imagemap'),
'raw': ('misc', 'Raw'),
'include': ('misc', 'Include'),
'replace': ('misc', 'Replace'),
'unicode': ('misc', 'Unicode'),
'class': ('misc', 'Class'),
'role': ('misc', 'Role'),
'default-role': ('misc', 'DefaultRole'),
'title': ('misc', 'Title'),
'date': ('misc', 'Date'),
'restructuredtext-test-directive': ('misc', 'TestDirective'),}
"""Mapping of directive name to (module name, class name). The
directive name is canonical & must be lowercase. Language-dependent
names are defined in the ``language`` subpackage."""
_directives = {}
"""Cache of imported directives."""
def directive(directive_name, language_module, document):
"""
Locate and return a directive function from its language-dependent name.
If not found in the current language, check English. Return None if the
named directive cannot be found.
"""
normname = directive_name.lower()
messages = []
msg_text = []
if normname in _directives:
return _directives[normname], messages
canonicalname = None
try:
canonicalname = language_module.directives[normname]
except AttributeError, error:
msg_text.append('Problem retrieving directive entry from language '
'module %r: %s.' % (language_module, error))
except KeyError:
msg_text.append('No directive entry for "%s" in module "%s".'
% (directive_name, language_module.__name__))
if not canonicalname:
try:
canonicalname = _fallback_language_module.directives[normname]
msg_text.append('Using English fallback for directive "%s".'
% directive_name)
except KeyError:
msg_text.append('Trying "%s" as canonical directive name.'
% directive_name)
# The canonical name should be an English name, but just in case:
canonicalname = normname
if msg_text:
message = document.reporter.info(
'\n'.join(msg_text), line=document.current_line)
messages.append(message)
try:
modulename, classname = _directive_registry[canonicalname]
except KeyError:
# Error handling done by caller.
return None, messages
try:
module = __import__(modulename, globals(), locals())
except ImportError, detail:
messages.append(document.reporter.error(
'Error importing directive module "%s" (directive "%s"):\n%s'
% (modulename, directive_name, detail),
line=document.current_line))
return None, messages
try:
directive = getattr(module, classname)
_directives[normname] = directive
except AttributeError:
messages.append(document.reporter.error(
'No directive class "%s" in module "%s" (directive "%s").'
% (classname, modulename, directive_name),
line=document.current_line))
return None, messages
return directive, messages
def register_directive(name, directive):
"""
Register a nonstandard application-defined directive function.
Language lookups are not needed for such functions.
"""
_directives[name] = directive
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
else:
return None
def unchanged_required(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
return argument # unchanged!
def unchanged(argument):
"""
Return the argument text, unchanged.
(Directive option conversion function.)
No argument implies empty string ("").
"""
if argument is None:
return u''
else:
return argument # unchanged!
def path(argument):
"""
Return the path argument unwrapped (with newlines removed).
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
path = ''.join([s.strip() for s in argument.splitlines()])
return path
def uri(argument):
"""
Return the URI argument with whitespace removed.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
else:
uri = ''.join(argument.split())
return uri
def nonnegative_int(argument):
"""
Check for a nonnegative integer argument; raise ``ValueError`` if not.
(Directive option conversion function.)
"""
value = int(argument)
if value < 0:
raise ValueError('negative value; must be positive or zero')
return value
def percentage(argument):
"""
Check for an integer percentage value with optional percent sign.
"""
try:
argument = argument.rstrip(' %')
except AttributeError:
pass
return nonnegative_int(argument)
length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc']
def get_measure(argument, units):
"""
Check for a positive argument of one of the units and return a
normalized string of the form "<value><unit>" (without space in
between).
To be called from directive option conversion functions.
"""
match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument)
try:
assert match is not None
float(match.group(1))
except (AssertionError, ValueError):
raise ValueError(
'not a positive measure of one of the following units:\n%s'
% ' '.join(['"%s"' % i for i in units]))
return match.group(1) + match.group(2)
def length_or_unitless(argument):
return get_measure(argument, length_units + [''])
def length_or_percentage_or_unitless(argument, default=''):
"""
Return normalized string of a length or percentage unit.
Add <default> if there is no unit. Raise ValueError if the argument is not
a positive measure of one of the valid CSS units (or without unit).
>>> length_or_percentage_or_unitless('3 pt')
'3pt'
>>> length_or_percentage_or_unitless('3%', 'em')
'3%'
>>> length_or_percentage_or_unitless('3')
'3'
>>> length_or_percentage_or_unitless('3', 'px')
'3px'
"""
try:
return get_measure(argument, length_units + ['%'])
except ValueError:
return get_measure(argument, ['']) + default
def class_option(argument):
"""
Convert the argument into a list of ID-compatible strings and return it.
(Directive option conversion function.)
Raise ``ValueError`` if no argument is found.
"""
if argument is None:
raise ValueError('argument required but none supplied')
names = argument.split()
class_names = []
for name in names:
class_name = nodes.make_id(name)
if not class_name:
raise ValueError('cannot make "%s" into a class name' % name)
class_names.append(class_name)
return class_names
unicode_pattern = re.compile(
r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE)
def unicode_code(code):
r"""
Convert a Unicode character code to a Unicode character.
(Directive option conversion function.)
Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``,
``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style
numeric character entities (e.g. ``☮``). Other text remains as-is.
Raise ValueError for illegal Unicode code values.
"""
try:
if code.isdigit(): # decimal number
return unichr(int(code))
else:
match = unicode_pattern.match(code)
if match: # hex number
value = match.group(1) or match.group(2)
return unichr(int(value, 16))
else: # other text
return code
except OverflowError, detail:
raise ValueError('code too large (%s)' % detail)
def single_char_or_unicode(argument):
"""
A single character is returned as-is. Unicode characters codes are
converted as in `unicode_code`. (Directive option conversion function.)
"""
char = unicode_code(argument)
if len(char) > 1:
raise ValueError('%r invalid; must be a single character or '
'a Unicode code' % char)
return char
def single_char_or_whitespace_or_unicode(argument):
"""
As with `single_char_or_unicode`, but "tab" and "space" are also supported.
(Directive option conversion function.)
"""
if argument == 'tab':
char = '\t'
elif argument == 'space':
char = ' '
else:
char = single_char_or_unicode(argument)
return char
def positive_int(argument):
"""
Converts the argument into an integer. Raises ValueError for negative,
zero, or non-integer values. (Directive option conversion function.)
"""
value = int(argument)
if value < 1:
raise ValueError('negative or zero value; must be positive')
return value
def positive_int_list(argument):
"""
Converts a space- or comma-separated list of values into a Python list
of integers.
(Directive option conversion function.)
Raises ValueError for non-positive-integer values.
"""
if ',' in argument:
entries = argument.split(',')
else:
entries = argument.split()
return [positive_int(entry) for entry in entries]
def encoding(argument):
"""
Verfies the encoding argument by lookup.
(Directive option conversion function.)
Raises ValueError for unknown encodings.
"""
try:
codecs.lookup(argument)
except LookupError:
raise ValueError('unknown encoding: "%s"' % argument)
return argument
def choice(argument, values):
"""
Directive option utility function, supplied to enable options whose
argument must be a member of a finite set of possible values (must be
lower case). A custom conversion function must be written to use it. For
example::
from docutils.parsers.rst import directives
def yesno(argument):
return directives.choice(argument, ('yes', 'no'))
Raise ``ValueError`` if no argument is found or if the argument's value is
not valid (not an entry in the supplied list).
"""
try:
value = argument.lower().strip()
except AttributeError:
raise ValueError('must supply an argument; choose from %s'
% format_values(values))
if value in values:
return value
else:
raise ValueError('"%s" unknown; choose from %s'
% (argument, format_values(values)))
def format_values(values):
return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]),
values[-1])
| {
"repo_name": "ajaxsys/dict-admin",
"path": "docutils/parsers/rst/directives/__init__.py",
"copies": "2",
"size": "13745",
"license": "bsd-3-clause",
"hash": -5591970400355042000,
"line_mean": 32.7095959596,
"line_max": 79,
"alpha_frac": 0.5893052019,
"autogenerated": false,
"ratio": 4.280597944565556,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5869903146465556,
"avg_score": null,
"num_lines": null
} |
"""$Id: __init__.py 699 2006-09-25 02:01:18Z rubys $"""
__author__ = "Sam Ruby <http://intertwingly.net/> and Mark Pilgrim <http://diveintomark.org/>"
__version__ = "$Revision: 699 $"
__date__ = "$Date: 2006-09-25 02:01:18 +0000 (Mon, 25 Sep 2006) $"
__copyright__ = "Copyright (c) 2002 Sam Ruby and Mark Pilgrim"
import socket
if hasattr(socket, 'setdefaulttimeout'):
socket.setdefaulttimeout(10)
Timeout = socket.timeout
else:
import timeoutsocket
timeoutsocket.setDefaultSocketTimeout(10)
Timeout = timeoutsocket.Timeout
import urllib2
import logging
from logging import *
from xml.sax import SAXException
from xml.sax.xmlreader import InputSource
import re
import xmlEncoding
import mediaTypes
from httplib import BadStatusLine
MAXDATALENGTH = 200000
def _validate(aString, firstOccurrenceOnly, loggedEvents, base, encoding, selfURIs=None):
"""validate RSS from string, returns validator object"""
from xml.sax import make_parser, handler
from base import SAXDispatcher
from exceptions import UnicodeError
from cStringIO import StringIO
# By now, aString should be Unicode
source = InputSource()
source.setByteStream(StringIO(xmlEncoding.asUTF8(aString)))
validator = SAXDispatcher(base, selfURIs or [base], encoding)
validator.setFirstOccurrenceOnly(firstOccurrenceOnly)
validator.loggedEvents += loggedEvents
# experimental RSS-Profile draft 1.06 support
validator.setLiterals(re.findall('&(\w+);',aString))
xmlver = re.match("^<\?\s*xml\s+version\s*=\s*['\"]([-a-zA-Z0-9_.:]*)['\"]",aString)
if xmlver and xmlver.group(1)<>'1.0':
validator.log(logging.BadXmlVersion({"version":xmlver.group(1)}))
try:
from xml.sax.expatreader import ExpatParser
class fake_dtd_parser(ExpatParser):
def reset(self):
ExpatParser.reset(self)
self._parser.UseForeignDTD(1)
parser = fake_dtd_parser()
except:
parser = make_parser()
parser.setFeature(handler.feature_namespaces, 1)
parser.setContentHandler(validator)
parser.setErrorHandler(validator)
parser.setEntityResolver(validator)
if hasattr(parser, '_ns_stack'):
# work around bug in built-in SAX parser (doesn't recognize xml: namespace)
# PyXML doesn't have this problem, and it doesn't have _ns_stack either
parser._ns_stack.append({'http://www.w3.org/XML/1998/namespace':'xml'})
def xmlvalidate(log):
import libxml2
from StringIO import StringIO
from random import random
prefix="...%s..." % str(random()).replace('0.','')
msg=[]
libxml2.registerErrorHandler(lambda msg,str: msg.append(str), msg)
input = libxml2.inputBuffer(StringIO(xmlEncoding.asUTF8(aString)))
reader = input.newTextReader(prefix)
reader.SetParserProp(libxml2.PARSER_VALIDATE, 1)
ret = reader.Read()
while ret == 1: ret = reader.Read()
msg=''.join(msg)
for line in msg.splitlines():
if line.startswith(prefix): log(line.split(':',4)[-1].strip())
validator.xmlvalidator=xmlvalidate
try:
parser.parse(source)
except SAXException:
pass
except UnicodeError:
import sys
exctype, value = sys.exc_info()[:2]
validator.log(logging.UnicodeError({"exception":value}))
if validator.getFeedType() == TYPE_RSS1:
try:
from rdflib.syntax.parsers.RDFXMLHandler import RDFXMLHandler
class Handler(RDFXMLHandler):
ns_prefix_map = {}
prefix_ns_map = {}
def add(self, triple): pass
def __init__(self, dispatcher):
RDFXMLHandler.__init__(self, self)
self.dispatcher=dispatcher
def error(self, message):
self.dispatcher.log(InvalidRDF({"message": message}))
source.getByteStream().reset()
parser.reset()
parser.setContentHandler(Handler(parser.getContentHandler()))
parser.setErrorHandler(handler.ErrorHandler())
parser.parse(source)
except:
pass
return validator
def validateStream(aFile, firstOccurrenceOnly=0, contentType=None, base=""):
loggedEvents = []
if contentType:
(mediaType, charset) = mediaTypes.checkValid(contentType, loggedEvents)
else:
(mediaType, charset) = (None, None)
rawdata = aFile.read(MAXDATALENGTH)
if aFile.read(1):
raise ValidationFailure(logging.ValidatorLimit({'limit': 'feed length > ' + str(MAXDATALENGTH) + ' bytes'}))
encoding, rawdata = xmlEncoding.decode(mediaType, charset, rawdata, loggedEvents, fallback='utf-8')
validator = _validate(rawdata, firstOccurrenceOnly, loggedEvents, base, encoding)
if mediaType and validator.feedType:
mediaTypes.checkAgainstFeedType(mediaType, validator.feedType, validator.loggedEvents)
return {"feedType":validator.feedType, "loggedEvents":validator.loggedEvents}
def validateString(aString, firstOccurrenceOnly=0, fallback=None, base=""):
loggedEvents = []
if type(aString) != unicode:
encoding, aString = xmlEncoding.decode("", None, aString, loggedEvents, fallback)
else:
encoding = "utf-8" # setting a sane (?) default
if aString is not None:
validator = _validate(aString, firstOccurrenceOnly, loggedEvents, base, encoding)
return {"feedType":validator.feedType, "loggedEvents":validator.loggedEvents}
else:
return {"loggedEvents": loggedEvents}
def validateURL(url, firstOccurrenceOnly=1, wantRawData=0):
"""validate RSS from URL, returns events list, or (events, rawdata) tuple"""
loggedEvents = []
request = urllib2.Request(url)
request.add_header("Accept-encoding", "gzip, deflate")
request.add_header("User-Agent", "FeedValidator/1.3")
usock = None
try:
try:
usock = urllib2.urlopen(request)
rawdata = usock.read(MAXDATALENGTH)
if usock.read(1):
raise ValidationFailure(logging.ValidatorLimit({'limit': 'feed length > ' + str(MAXDATALENGTH) + ' bytes'}))
# check for temporary redirects
if usock.geturl()<>request.get_full_url():
from httplib import HTTPConnection
spliturl=url.split('/',3)
if spliturl[0]=="http:":
conn=HTTPConnection(spliturl[2])
conn.request("GET",'/'+spliturl[3].split("#",1)[0])
resp=conn.getresponse()
if resp.status<>301:
loggedEvents.append(TempRedirect({}))
except BadStatusLine, status:
raise ValidationFailure(logging.HttpError({'status': status.__class__}))
except urllib2.HTTPError, status:
rawdata = status.read()
lastline = rawdata.strip().split('\n')[-1].strip()
if lastline in ['</rss>','</feed>','</rdf:RDF>']:
loggedEvents.append(logging.HttpError({'status': status}))
usock = status
else:
raise ValidationFailure(logging.HttpError({'status': status}))
except urllib2.URLError, x:
raise ValidationFailure(logging.HttpError({'status': x.reason}))
except Timeout, x:
raise ValidationFailure(logging.IOError({"message": 'Server timed out', "exception":x}))
if usock.headers.get('content-encoding', None) == None:
loggedEvents.append(Uncompressed({}))
if usock.headers.get('content-encoding', None) == 'gzip':
import gzip, StringIO
try:
rawdata = gzip.GzipFile(fileobj=StringIO.StringIO(rawdata)).read()
except:
import sys
exctype, value = sys.exc_info()[:2]
event=logging.IOError({"message": 'Server response declares Content-Encoding: gzip', "exception":value})
raise ValidationFailure(event)
if usock.headers.get('content-encoding', None) == 'deflate':
import zlib
try:
rawdata = zlib.decompress(rawdata, -zlib.MAX_WBITS)
except:
import sys
exctype, value = sys.exc_info()[:2]
event=logging.IOError({"message": 'Server response declares Content-Encoding: deflate', "exception":value})
raise ValidationFailure(event)
mediaType = None
charset = None
# Is the Content-Type correct?
contentType = usock.headers.get('content-type', None)
if contentType:
(mediaType, charset) = mediaTypes.checkValid(contentType, loggedEvents)
# Check for malformed HTTP headers
for (h, v) in usock.headers.items():
if (h.find(' ') >= 0):
loggedEvents.append(HttpProtocolError({'header': h}))
selfURIs = [request.get_full_url()]
baseURI = usock.geturl()
if not baseURI in selfURIs: selfURIs.append(baseURI)
# Get baseURI from content-location and/or redirect information
if usock.headers.get('content-location', None):
from urlparse import urljoin
baseURI=urljoin(baseURI,usock.headers.get('content-location', ""))
elif usock.headers.get('location', None):
from urlparse import urljoin
baseURI=urljoin(baseURI,usock.headers.get('location', ""))
if not baseURI in selfURIs: selfURIs.append(baseURI)
usock.close()
usock = None
mediaTypes.contentSniffing(mediaType, rawdata, loggedEvents)
encoding, rawdata = xmlEncoding.decode(mediaType, charset, rawdata, loggedEvents, fallback='utf-8')
if rawdata is None:
return {'loggedEvents': loggedEvents}
rawdata = rawdata.replace('\r\n', '\n').replace('\r', '\n') # normalize EOL
validator = _validate(rawdata, firstOccurrenceOnly, loggedEvents, baseURI, encoding, selfURIs)
# Warn about mismatches between media type and feed version
if mediaType and validator.feedType:
mediaTypes.checkAgainstFeedType(mediaType, validator.feedType, validator.loggedEvents)
params = {"feedType":validator.feedType, "loggedEvents":validator.loggedEvents}
if wantRawData:
params['rawdata'] = rawdata
return params
finally:
try:
if usock: usock.close()
except:
pass
__all__ = ['base',
'channel',
'compatibility',
'image',
'item',
'logging',
'rdf',
'root',
'rss',
'skipHours',
'textInput',
'util',
'validators',
'validateURL',
'validateString']
| {
"repo_name": "canwe/NewsBlur",
"path": "vendor/feedvalidator/__init__.py",
"copies": "16",
"size": "10034",
"license": "mit",
"hash": -1342115423131937300,
"line_mean": 33.6,
"line_max": 116,
"alpha_frac": 0.6720151485,
"autogenerated": false,
"ratio": 3.7665165165165164,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": null,
"num_lines": null
} |
"""
S5/HTML Slideshow Writer.
"""
__docformat__ = 'reStructuredText'
import sys
import os
import re
import docutils
from docutils import frontend, nodes, utils
from docutils.writers import html4css1
from docutils.parsers.rst import directives
from docutils._compat import b
themes_dir_path = utils.relative_path(
os.path.join(os.getcwd(), 'dummy'),
os.path.join(os.path.dirname(__file__), 'themes'))
def find_theme(name):
# Where else to look for a theme?
# Check working dir? Destination dir? Config dir? Plugins dir?
path = os.path.join(themes_dir_path, name)
if not os.path.isdir(path):
raise docutils.ApplicationError(
'Theme directory not found: %r (path: %r)' % (name, path))
return path
class Writer(html4css1.Writer):
settings_spec = html4css1.Writer.settings_spec + (
'S5 Slideshow Specific Options',
'For the S5/HTML writer, the --no-toc-backlinks option '
'(defined in General Docutils Options above) is the default, '
'and should not be changed.',
(('Specify an installed S5 theme by name. Overrides --theme-url. '
'The default theme name is "default". The theme files will be '
'copied into a "ui/<theme>" directory, in the same directory as the '
'destination file (output HTML). Note that existing theme files '
'will not be overwritten (unless --overwrite-theme-files is used).',
['--theme'],
{'default': 'default', 'metavar': '<name>',
'overrides': 'theme_url'}),
('Specify an S5 theme URL. The destination file (output HTML) will '
'link to this theme; nothing will be copied. Overrides --theme.',
['--theme-url'],
{'metavar': '<URL>', 'overrides': 'theme'}),
('Allow existing theme files in the ``ui/<theme>`` directory to be '
'overwritten. The default is not to overwrite theme files.',
['--overwrite-theme-files'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Keep existing theme files in the ``ui/<theme>`` directory; do not '
'overwrite any. This is the default.',
['--keep-theme-files'],
{'dest': 'overwrite_theme_files', 'action': 'store_false'}),
('Set the initial view mode to "slideshow" [default] or "outline".',
['--view-mode'],
{'choices': ['slideshow', 'outline'], 'default': 'slideshow',
'metavar': '<mode>'}),
('Normally hide the presentation controls in slideshow mode. '
'This is the default.',
['--hidden-controls'],
{'action': 'store_true', 'default': True,
'validator': frontend.validate_boolean}),
('Always show the presentation controls in slideshow mode. '
'The default is to hide the controls.',
['--visible-controls'],
{'dest': 'hidden_controls', 'action': 'store_false'}),
('Enable the current slide indicator ("1 / 15"). '
'The default is to disable it.',
['--current-slide'],
{'action': 'store_true', 'validator': frontend.validate_boolean}),
('Disable the current slide indicator. This is the default.',
['--no-current-slide'],
{'dest': 'current_slide', 'action': 'store_false'}),))
settings_default_overrides = {'toc_backlinks': 0}
config_section = 's5_html writer'
config_section_dependencies = ('writers', 'html4css1 writer')
def __init__(self):
html4css1.Writer.__init__(self)
self.translator_class = S5HTMLTranslator
class S5HTMLTranslator(html4css1.HTMLTranslator):
s5_stylesheet_template = """\
<!-- configuration parameters -->
<meta name="defaultView" content="%(view_mode)s" />
<meta name="controlVis" content="%(control_visibility)s" />
<!-- style sheet links -->
<script src="%(path)s/slides.js" type="text/javascript"></script>
<link rel="stylesheet" href="%(path)s/slides.css"
type="text/css" media="projection" id="slideProj" />
<link rel="stylesheet" href="%(path)s/outline.css"
type="text/css" media="screen" id="outlineStyle" />
<link rel="stylesheet" href="%(path)s/print.css"
type="text/css" media="print" id="slidePrint" />
<link rel="stylesheet" href="%(path)s/opera.css"
type="text/css" media="projection" id="operaFix" />\n"""
# The script element must go in front of the link elements to
# avoid a flash of unstyled content (FOUC), reproducible with
# Firefox.
disable_current_slide = """
<style type="text/css">
#currentSlide {display: none;}
</style>\n"""
layout_template = """\
<div class="layout">
<div id="controls"></div>
<div id="currentSlide"></div>
<div id="header">
%(header)s
</div>
<div id="footer">
%(title)s%(footer)s
</div>
</div>\n"""
# <div class="topleft"></div>
# <div class="topright"></div>
# <div class="bottomleft"></div>
# <div class="bottomright"></div>
default_theme = 'default'
"""Name of the default theme."""
base_theme_file = '__base__'
"""Name of the file containing the name of the base theme."""
direct_theme_files = (
'slides.css', 'outline.css', 'print.css', 'opera.css', 'slides.js')
"""Names of theme files directly linked to in the output HTML"""
indirect_theme_files = (
's5-core.css', 'framing.css', 'pretty.css', 'blank.gif', 'iepngfix.htc')
"""Names of files used indirectly; imported or used by files in
`direct_theme_files`."""
required_theme_files = indirect_theme_files + direct_theme_files
"""Names of mandatory theme files."""
def __init__(self, *args):
html4css1.HTMLTranslator.__init__(self, *args)
#insert S5-specific stylesheet and script stuff:
self.theme_file_path = None
self.setup_theme()
view_mode = self.document.settings.view_mode
control_visibility = ('visible', 'hidden')[self.document.settings
.hidden_controls]
self.stylesheet.append(self.s5_stylesheet_template
% {'path': self.theme_file_path,
'view_mode': view_mode,
'control_visibility': control_visibility})
if not self.document.settings.current_slide:
self.stylesheet.append(self.disable_current_slide)
self.add_meta('<meta name="version" content="S5 1.1" />\n')
self.s5_footer = []
self.s5_header = []
self.section_count = 0
self.theme_files_copied = None
def setup_theme(self):
if self.document.settings.theme:
self.copy_theme()
elif self.document.settings.theme_url:
self.theme_file_path = self.document.settings.theme_url
else:
raise docutils.ApplicationError(
'No theme specified for S5/HTML writer.')
def copy_theme(self):
"""
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'.
"""
settings = self.document.settings
path = find_theme(settings.theme)
theme_paths = [path]
self.theme_files_copied = {}
required_files_copied = {}
# This is a link (URL) in HTML, so we use "/", not os.sep:
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:
# no destination, so we can't copy the theme
return
default = 0
while path:
for f in os.listdir(path): # copy all files from each theme
if f == self.base_theme_file:
continue # ... except the "__base__" file
if ( self.copy_file(f, path, dest)
and f in self.required_theme_files):
required_files_copied[f] = 1
if default:
break # "default" theme has no base theme
# Find the "__base__" file in theme directory:
base_theme_file = os.path.join(path, self.base_theme_file)
# If it exists, read it and record the theme path:
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: # check for duplicates (cycles)
path = None # if found, use default base
else:
theme_paths.append(path)
break
else: # no theme name found
path = None # use default base
else: # no base theme file found
path = None # use default base
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):
# Some required files weren't found & couldn't be copied.
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]))
files_to_skip_pattern = re.compile(r'~$|\.bak$|#$|\.cvsignore$')
def copy_file(self, name, source_dir, dest_dir):
"""
Copy file `name` from `source_dir` to `dest_dir`.
Return 1 if the file exists in either `source_dir` or `dest_dir`.
"""
source = os.path.join(source_dir, name)
dest = os.path.join(dest_dir, name)
if dest in self.theme_files_copied:
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(
b('ui/default'),
dest_dir[dest_dir.rfind('ui/'):].encode(
sys.getfilesystemencoding())))
dest_file.close()
settings.record_dependencies.add(source)
return 1
if os.path.isfile(dest):
return 1
def depart_document(self, node):
self.head_prefix.extend([self.doctype,
self.head_prefix_template %
{'lang': self.settings.language_code}])
self.html_prolog.append(self.doctype)
self.meta.insert(0, self.content_type % self.settings.output_encoding)
self.head.insert(0, self.content_type % self.settings.output_encoding)
header = ''.join(self.s5_header)
footer = ''.join(self.s5_footer)
title = ''.join(self.html_title).replace('<h1 class="title">', '<h1>')
layout = self.layout_template % {'header': header,
'title': title,
'footer': footer}
self.fragment.extend(self.body)
self.body_prefix.extend(layout)
self.body_prefix.append('<div class="presentation">\n')
self.body_prefix.append(
self.starttag({'classes': ['slide'], 'ids': ['slide0']}, 'div'))
if not self.section_count:
self.body.append('</div>\n')
self.body_suffix.insert(0, '</div>\n')
# skip content-type meta tag with interpolated charset value:
self.html_head.extend(self.head[1:])
self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo
+ self.docinfo + self.body
+ self.body_suffix[:-1])
def depart_footer(self, node):
start = self.context.pop()
self.s5_footer.append('<h2>')
self.s5_footer.extend(self.body[start:])
self.s5_footer.append('</h2>')
del self.body[start:]
def depart_header(self, node):
start = self.context.pop()
header = ['<div id="header">\n']
header.extend(self.body[start:])
header.append('\n</div>\n')
del self.body[start:]
self.s5_header.extend(header)
def visit_section(self, node):
if not self.section_count:
self.body.append('\n</div>\n')
self.section_count += 1
self.section_level += 1
if self.section_level > 1:
# dummy for matching div's
self.body.append(self.starttag(node, 'div', CLASS='section'))
else:
self.body.append(self.starttag(node, 'div', CLASS='slide'))
def visit_subtitle(self, node):
if isinstance(node.parent, nodes.section):
level = self.section_level + self.initial_header_level - 1
if level == 1:
level = 2
tag = 'h%s' % level
self.body.append(self.starttag(node, tag, ''))
self.context.append('</%s>\n' % tag)
else:
html4css1.HTMLTranslator.visit_subtitle(self, node)
def visit_title(self, node):
html4css1.HTMLTranslator.visit_title(self, node)
| {
"repo_name": "johngian/remo",
"path": "vendor-local/lib/python/docutils/writers/s5_html/__init__.py",
"copies": "6",
"size": "14387",
"license": "bsd-3-clause",
"hash": 8786394808145313000,
"line_mean": 40.4610951009,
"line_max": 80,
"alpha_frac": 0.5616876347,
"autogenerated": false,
"ratio": 3.975407571152252,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.7537095205852252,
"avg_score": null,
"num_lines": null
} |