desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Cause new child element specified by *child_bldr* to be appended to the children of this element.'
def with_child(self, child_bldr):
self._child_bldrs.append(child_bldr) return self
'Cause *text* to be placed between the start and end tags of this element. Not robust enough for mixed elements, intended only for elements having no child elements.'
def with_text(self, text):
self._text = text return self
'Cause the element to contain namespace declarations. By default, the namespace prefixes defined in the Builder class are used. These can be overridden by providing exlicit prefixes, e.g. ``with_nsdecls(\'a\', \'r\')``.'
def with_nsdecls(self, *nspfxs):
if (not nspfxs): nspfxs = self.__nspfxs__ self._nsdecls = (u' %s' % nsdecls(*nspfxs)) return self
'Return element XML based on attribute settings'
def xml(self, indent=0):
indent_str = (u' ' * indent) if self._is_empty: xml = (u'%s%s\n' % (indent_str, self._empty_element_tag)) else: xml = (u'%s\n' % self._non_empty_element_xml(indent)) return xml
'Return all element attributes as a string, like \' foo="bar" x="1"\'.'
@property def _xmlattrs_str(self):
return u''.join(self._xmlattrs)
'Scenarios are: 1) no pHYs chunk in PNG stream, 2) units specifier other than 1; 3) px_per_unit is 0; 4) px_per_unit is None'
@pytest.fixture(params=[((-1), (-1)), (0, 1000), (None, 1000), (1, 0), (1, None)]) def no_dpi_fixture(self, request, chunks_):
(units_specifier, px_per_unit) = request.param if (units_specifier == (-1)): chunks_.pHYs = None else: chunks_.pHYs.horz_px_per_unit = px_per_unit chunks_.pHYs.vert_px_per_unit = px_per_unit chunks_.pHYs.units_specifier = units_specifier png_parser = _PngParser(chunks_) return png_parser
'Return XML for a [Content_Types].xml based on items in *entries*.'
def _xml_from(self, entries):
types_bldr = a_Types().with_nsdecls() for entry in entries: if (entry[0] == u'Default'): (ext, content_type) = entry[1:] default_bldr = a_Default() default_bldr.with_Extension(ext) default_bldr.with_ContentType(content_type) types_bldr.with_child(default_bldr) elif (entry[0] == u'Override'): (partname, content_type) = entry[1:] override_bldr = an_Override() override_bldr.with_PartName(partname) override_bldr.with_ContentType(content_type) types_bldr.with_child(override_bldr) return types_bldr.xml()
'Internal relationships (TargetMode == \'Internal\' in the XML) should have a relative ref, e.g. \'../slideLayouts/slideLayout1.xml\', for the target_ref attribute.'
def it_should_have_relative_ref_for_internal_rel(self):
part = Mock(name=u'part', partname=PackURI(u'/ppt/media/image1.png')) baseURI = u'/ppt/slides' rel = _Relationship(None, None, part, baseURI) assert (rel.target_ref == u'../media/image1.png')
'Populated Relationships instance that will exercise the rels.xml property.'
@pytest.fixture def rels(self):
rels = Relationships(u'/baseURI') rels.add_relationship(reltype=u'http://rt-hyperlink', target=u'http://some/link', rId=u'rId1', is_external=True) part = Mock(name=u'part') part.partname.relative_ref.return_value = u'../media/image1.png' rels.add_relationship(reltype=u'http://rt-image', target=part, rId=u'rId2') return rels
'Return a rels_elm mock that will be returned from CT_Relationships.new()'
@pytest.fixture def rels_elm(self, request):
rels_elm = Mock(name=u'rels_elm') xml = PropertyMock(name=u'xml') type(rels_elm).xml = xml rels_elm.attach_mock(xml, u'xml') rels_elm.reset_mock() patch_ = patch.object(CT_Relationships, u'new', return_value=rels_elm) patch_.start() request.addfinalizer(patch_.stop) return rels_elm
'Return list of tuples zipped from uri_str cases and *expected_values*. Raise if lengths don\'t match.'
def cases(self, expected_values):
uri_str_cases = ['/', '/ppt/presentation.xml', '/ppt/slides/slide1.xml'] if (len(expected_values) != len(uri_str_cases)): msg = 'len(expected_values) differs from len(uri_str_cases)' raise AssertionError(msg) pack_uris = [PackURI(uri_str) for uri_str in uri_str_cases] return zip(pack_uris, expected_values)
'Mock that patches all the _write_* methods of PackageWriter'
@pytest.fixture def _write_methods(self, request):
root_mock = Mock(name='PackageWriter') patch1 = patch.object(PackageWriter, '_write_content_types_stream') patch2 = patch.object(PackageWriter, '_write_pkg_rels') patch3 = patch.object(PackageWriter, '_write_parts') root_mock.attach_mock(patch1.start(), '_write_content_types_stream') root_mock.attach_mock(patch2.start(), '_write_pkg_rels') root_mock.attach_mock(patch3.start(), '_write_parts') def fin(): patch1.stop() patch2.stop() patch3.stop() request.addfinalizer(fin) return root_mock
'Return element based on XML generated by builder'
@property def element(self):
return parse_xml(self.xml)
'Add integer *indent* spaces at beginning of element XML'
def with_indent(self, indent):
self._indent = indent return self
'Establish instance variables with default values'
def __init__(self):
self._content_type = 'application/xml' self._extension = 'xml' self._indent = 0 self._namespace = (' xmlns="%s"' % NS.OPC_CONTENT_TYPES)
'Set ContentType attribute to *content_type*'
def with_content_type(self, content_type):
self._content_type = content_type return self
'Set Extension attribute to *extension*'
def with_extension(self, extension):
self._extension = extension return self
'Don\'t include an \'xmlns=\' attribute'
def without_namespace(self):
self._namespace = '' return self
'Return Default element'
@property def xml(self):
tmpl = '%s<Default%s Extension="%s" ContentType="%s"/>\n' indent = (' ' * self._indent) return (tmpl % (indent, self._namespace, self._extension, self._content_type))
'Establish instance variables with default values'
def __init__(self):
self._content_type = 'app/vnd.type' self._indent = 0 self._namespace = (' xmlns="%s"' % NS.OPC_CONTENT_TYPES) self._partname = '/part/name.xml'
'Set ContentType attribute to *content_type*'
def with_content_type(self, content_type):
self._content_type = content_type return self
'Set PartName attribute to *partname*'
def with_partname(self, partname):
self._partname = partname return self
'Don\'t include an \'xmlns=\' attribute'
def without_namespace(self):
self._namespace = '' return self
'Return Override element'
@property def xml(self):
tmpl = '%s<Override%s PartName="%s" ContentType="%s"/>\n' indent = (' ' * self._indent) return (tmpl % (indent, self._namespace, self._partname, self._content_type))
'Establish instance variables with default values'
def __init__(self):
self._rId = 'rId9' self._reltype = 'ReLtYpE' self._target = 'docProps/core.xml' self._target_mode = None self._indent = 0 self._namespace = (' xmlns="%s"' % NS.OPC_RELATIONSHIPS)
'Set Id attribute to *rId*'
def with_rId(self, rId):
self._rId = rId return self
'Set Type attribute to *reltype*'
def with_reltype(self, reltype):
self._reltype = reltype return self
'Set XXX attribute to *target*'
def with_target(self, target):
self._target = target return self
'Set TargetMode attribute to *target_mode*'
def with_target_mode(self, target_mode):
self._target_mode = (None if (target_mode == 'Internal') else target_mode) return self
'Don\'t include an \'xmlns=\' attribute'
def without_namespace(self):
self._namespace = '' return self
'Return Relationship element'
@property def xml(self):
tmpl = '%s<Relationship%s Id="%s" Type="%s" Target="%s"%s/>\n' indent = (' ' * self._indent) return (tmpl % (indent, self._namespace, self._rId, self._reltype, self._target, self.target_mode))
'Establish instance variables with default values'
def __init__(self):
self._rels = (('rId1', 'http://reltype1', 'docProps/core.xml', 'Internal'), ('rId2', 'http://linktype', 'http://some/link', 'External'), ('rId3', 'http://reltype2', '../slides/slide1.xml', 'Internal'))
'Return XML string based on settings accumulated via method calls.'
@property def xml(self):
xml = ('<Relationships xmlns="%s">\n' % NS.OPC_RELATIONSHIPS) for (rId, reltype, target, target_mode) in self._rels: xml += a_Relationship().with_rId(rId).with_reltype(reltype).with_target(target).with_target_mode(target_mode).with_indent(2).without_namespace().xml xml += '</Relationships>\n' return xml
'Establish instance variables with default values'
def __init__(self):
self._defaults = (('xml', 'application/xml'), ('jpeg', 'image/jpeg')) self._empty = False self._overrides = (('/docProps/core.xml', 'app/vnd.type1'), ('/ppt/presentation.xml', 'app/vnd.type2'), ('/docProps/thumbnail.jpeg', 'image/jpeg'))
'Return XML string based on settings accumulated via method calls'
@property def xml(self):
if self._empty: return ('<Types xmlns="%s"/>\n' % NS.OPC_CONTENT_TYPES) xml = ('<Types xmlns="%s">\n' % NS.OPC_CONTENT_TYPES) for (extension, content_type) in self._defaults: xml += a_Default().with_extension(extension).with_content_type(content_type).with_indent(2).without_namespace().xml for (partname, content_type) in self._overrides: xml += an_Override().with_partname(partname).with_content_type(content_type).with_indent(2).without_namespace().xml xml += '</Types>\n' return xml
'Return a mock patching property OpcPackage.parts, reversing the patch after each use.'
@pytest.fixture def parts(self, request, parts_):
_patch = patch.object(OpcPackage, 'parts', new_callable=PropertyMock, return_value=parts_) request.addfinalizer(_patch.stop) return _patch.start()
'Provide a more meaningful repr value for an Element object, one that displays the tagname as a simple empty element, e.g. ``<w:pPr/>``.'
def __repr__(self):
return ('<%s/>' % self._tagname)
'Make each of the elements appearing in *child_node_list* a child of this element.'
def connect_children(self, child_node_list):
for node in child_node_list: child = node.element self._children.append(child)
'Return an ``Element`` object constructed from a parser element token.'
@classmethod def from_token(cls, token):
tagname = token.tagname attrs = [(name, value) for (name, value) in token.attr_list] text = token.text return cls(tagname, attrs, text)
'|True| if this element is the root of the tree and should include the namespace prefixes. |False| otherwise.'
@property def is_root(self):
return self._is_root
'The namespace prefix of this element, the empty string (``\'\'``) if the tag is in the default namespace.'
@property def nspfx(self):
tagname = self._tagname idx = tagname.find(':') if (idx == (-1)): return '' return tagname[:idx]
'A sequence containing each of the namespace prefixes appearing in this tree. Each prefix appears once and only once, and in document order.'
@property def nspfxs(self):
def merge(seq, seq_2): for item in seq_2: if (item in seq): continue seq.append(item) nspfxs = [self.nspfx] for child in self._children: merge(nspfxs, child.nspfxs) return nspfxs
'The XML corresponding to the tree rooted at this element, pretty-printed using 2-spaces indentation at each level and with a trailing \''
@property def xml(self):
return self._xml(indent=0)
'Return a string containing the XML of this element and all its children with a starting indent of *indent* spaces.'
def _xml(self, indent):
self._indent_str = (' ' * indent) xml = self._start_tag for child in self._children: xml += child._xml((indent + 2)) xml += self._end_tag return xml
'The text of the opening tag of this element, including attributes. If this is the root element, a namespace declaration for each of the namespace prefixes that occur in this tree is added in front of any attributes. If this element contains text, that text follows the start tag. If not, and this element has no children, an empty tag is returned. Otherwise, an opening tag is returned, followed by a newline. The tag is indented by this element\'s indent value in all cases.'
@property def _start_tag(self):
_nsdecls = (nsdecls(*self.nspfxs) if self.is_root else '') tag = ('%s<%s%s' % (self._indent_str, self._tagname, _nsdecls)) for attr in self._attrs: (name, value) = attr tag += (' %s="%s"' % (name, value)) if self._text: tag += ('>%s' % self._text) elif self._children: tag += '>\n' else: tag += '/>\n' return tag
'The text of the closing tag of this element, if there is one. If the element contains text, no leading indentation is included.'
@property def _end_tag(self):
if self._text: tag = ('</%s>\n' % self._tagname) elif self._children: tag = ('%s</%s>\n' % (self._indent_str, self._tagname)) else: tag = '' return tag
'Return a |_Column| object of *width*, newly added rightmost to the table.'
def add_column(self, width):
tblGrid = self._tbl.tblGrid gridCol = tblGrid.add_gridCol() gridCol.w = width for tr in self._tbl.tr_lst: tc = tr.add_tc() tc.width = width return _Column(gridCol, self)
'Return a |_Row| instance, newly added bottom-most to the table.'
def add_row(self):
tbl = self._tbl tr = tbl.add_tr() for gridCol in tbl.tblGrid.gridCol_lst: tc = tr.add_tc() tc.width = gridCol.w return _Row(tr, self)
'Read/write. A member of :ref:`WdRowAlignment` or None, specifying the positioning of this table between the page margins. |None| if no setting is specified, causing the effective value to be inherited from the style hierarchy.'
@property def alignment(self):
return self._tblPr.alignment
'|True| if column widths can be automatically adjusted to improve the fit of cell contents. |False| if table layout is fixed. Column widths are adjusted in either case if total column width exceeds page width. Read/write boolean.'
@property def autofit(self):
return self._tblPr.autofit
'Return |_Cell| instance correponding to table cell at *row_idx*, *col_idx* intersection, where (0, 0) is the top, left-most cell.'
def cell(self, row_idx, col_idx):
cell_idx = (col_idx + (row_idx * self._column_count)) return self._cells[cell_idx]
'Sequence of cells in the column at *column_idx* in this table.'
def column_cells(self, column_idx):
cells = self._cells idxs = range(column_idx, len(cells), self._column_count) return [cells[idx] for idx in idxs]
'|_Columns| instance representing the sequence of columns in this table.'
@lazyproperty def columns(self):
return _Columns(self._tbl, self)
'Sequence of cells in the row at *row_idx* in this table.'
def row_cells(self, row_idx):
column_count = self._column_count start = (row_idx * column_count) end = (start + column_count) return self._cells[start:end]
'|_Rows| instance containing the sequence of rows in this table.'
@lazyproperty def rows(self):
return _Rows(self._tbl, self)
'Read/write. A |_TableStyle| object representing the style applied to this table. The default table style for the document (often `Normal Table`) is returned if the table has no directly-applied style. Assigning |None| to this property removes any directly-applied table style causing it to inherit the default table style of the document. Note that the style name of a table style differs slightly from that displayed in the user interface; a hyphen, if it appears, must be removed. For example, `Light Shading - Accent 1` becomes `Light Shading Accent 1`.'
@property def style(self):
style_id = self._tbl.tblStyle_val return self.part.get_style(style_id, WD_STYLE_TYPE.TABLE)
'Provide child objects with reference to the |Table| object they belong to, without them having to know their direct parent is a |Table| object. This is the terminus of a series of `parent._table` calls from an arbitrary child through its ancestors.'
@property def table(self):
return self
'A member of :ref:`WdTableDirection` indicating the direction in which the table cells are ordered, e.g. `WD_TABLE_DIRECTION.LTR`. |None| indicates the value is inherited from the style hierarchy.'
@property def table_direction(self):
return self._element.bidiVisual_val
'A sequence of |_Cell| objects, one for each cell of the layout grid. If the table contains a span, one or more |_Cell| object references are repeated.'
@property def _cells(self):
col_count = self._column_count cells = [] for tc in self._tbl.iter_tcs(): for grid_span_idx in range(tc.grid_span): if (tc.vMerge == ST_Merge.CONTINUE): cells.append(cells[(- col_count)]) elif (grid_span_idx > 0): cells.append(cells[(-1)]) else: cells.append(_Cell(tc, self)) return cells
'The number of grid columns in this table.'
@property def _column_count(self):
return self._tbl.col_count
'Return a paragraph newly added to the end of the content in this cell. If present, *text* is added to the paragraph in a single run. If specified, the paragraph style *style* is applied. If *style* is not specified or is |None|, the result is as though the \'Normal\' style was applied. Note that the formatting of text in a cell can be influenced by the table style. *text* can contain tab (``\t``) characters, which are converted to the appropriate XML form for a tab. *text* can also include newline (``\n``) or carriage return (``\r``) characters, each of which is converted to a line break.'
def add_paragraph(self, text=u'', style=None):
return super(_Cell, self).add_paragraph(text, style)
'Return a table newly added to this cell after any existing cell content, having *rows* rows and *cols* columns. An empty paragraph is added after the table because Word requires a paragraph element as the last element in every cell.'
def add_table(self, rows, cols):
width = (self.width if (self.width is not None) else Inches(1)) table = super(_Cell, self).add_table(rows, cols, width) self.add_paragraph() return table
'Return a merged cell created by spanning the rectangular region having this cell and *other_cell* as diagonal corners. Raises |InvalidSpanError| if the cells do not define a rectangular region.'
def merge(self, other_cell):
(tc, tc_2) = (self._tc, other_cell._tc) merged_tc = tc.merge(tc_2) return _Cell(merged_tc, self._parent)
'List of paragraphs in the cell. A table cell is required to contain at least one block-level element and end with a paragraph. By default, a new cell contains a single paragraph. Read-only'
@property def paragraphs(self):
return super(_Cell, self).paragraphs
'List of tables in the cell, in the order they appear. Read-only.'
@property def tables(self):
return super(_Cell, self).tables
'The entire contents of this cell as a string of text. Assigning a string to this property replaces all existing content with a single paragraph containing the assigned text in a single run.'
@property def text(self):
return u'\n'.join((p.text for p in self.paragraphs))
'Write-only. Set entire contents of cell to the string *text*. Any existing content or revisions are replaced.'
@text.setter def text(self, text):
tc = self._tc tc.clear_content() p = tc.add_p() r = p.add_r() r.text = text
'The width of this cell in EMU, or |None| if no explicit width is set.'
@property def width(self):
return self._tc.width
'Sequence of |_Cell| instances corresponding to cells in this column.'
@property def cells(self):
return tuple(self.table.column_cells(self._index))
'Reference to the |Table| object this column belongs to.'
@property def table(self):
return self._parent.table
'The width of this column in EMU, or |None| if no explicit width is set.'
@property def width(self):
return self._gridCol.w
'Index of this column in its table, starting from zero.'
@property def _index(self):
return self._gridCol.gridCol_idx
'Provide indexed access, e.g. \'columns[0]\''
def __getitem__(self, idx):
try: gridCol = self._gridCol_lst[idx] except IndexError: msg = (u'column index [%d] is out of range' % idx) raise IndexError(msg) return _Column(gridCol, self)
'Reference to the |Table| object this column collection belongs to.'
@property def table(self):
return self._parent.table
'Sequence containing ``<w:gridCol>`` elements for this table, each representing a table column.'
@property def _gridCol_lst(self):
tblGrid = self._tbl.tblGrid return tblGrid.gridCol_lst
'Sequence of |_Cell| instances corresponding to cells in this row.'
@property def cells(self):
return tuple(self.table.row_cells(self._index))
'Reference to the |Table| object this row belongs to.'
@property def table(self):
return self._parent.table
'Index of this row in its table, starting from zero.'
@property def _index(self):
return self._tr.tr_idx
'Provide indexed access, (e.g. \'rows[0]\')'
def __getitem__(self, idx):
return list(self)[idx]
'Reference to the |Table| object this row collection belongs to.'
@property def table(self):
return self._parent.table
'Return newly created empty numbering part, containing only the root ``<w:numbering>`` element.'
@classmethod def new(cls):
raise NotImplementedError
'The |_NumberingDefinitions| instance containing the numbering definitions (<w:num> element proxies) for this numbering part.'
@lazyproperty def numbering_definitions(self):
return _NumberingDefinitions(self._element)
'Return a newly created settings part, containing a default `w:settings` element tree.'
@classmethod def default(cls, package):
partname = PackURI(u'/word/settings.xml') content_type = CT.WML_SETTINGS element = parse_xml(cls._default_settings_xml()) return cls(partname, content_type, element, package)
'A |Settings| proxy object for the `w:settings` element in this part, containing the document-level settings for this document.'
@property def settings(self):
return Settings(self.element)
'Return a bytestream containing XML for a default settings part.'
@classmethod def _default_settings_xml(cls):
path = os.path.join(os.path.split(__file__)[0], u'..', u'templates', u'default-settings.xml') with open(path, u'rb') as f: xml_bytes = f.read() return xml_bytes
'Return a newly created styles part, containing a default set of elements.'
@classmethod def default(cls, package):
partname = PackURI(u'/word/styles.xml') content_type = CT.WML_STYLES element = parse_xml(cls._default_styles_xml()) return cls(partname, content_type, element, package)
'The |_Styles| instance containing the styles (<w:style> element proxies) for this styles part.'
@property def styles(self):
return Styles(self.element)
'Return a bytestream containing XML for a default styles part.'
@classmethod def _default_styles_xml(cls):
path = os.path.join(os.path.split(__file__)[0], u'..', u'templates', u'default-styles.xml') with open(path, u'rb') as f: xml_bytes = f.read() return xml_bytes
'A |CoreProperties| object providing read/write access to the core properties of this document.'
@property def core_properties(self):
return self.package.core_properties
'A |Document| object providing access to the content of this document.'
@property def document(self):
return Document(self._element, self)
'Return an (rId, image) 2-tuple for the image identified by *image_descriptor*. *image* is an |Image| instance providing access to the properties of the image, such as dimensions and image type. *rId* is the key for the relationship between this document part and the image part, reused if already present, newly created if not.'
def get_or_add_image(self, image_descriptor):
image_part = self._package.image_parts.get_or_add_image_part(image_descriptor) rId = self.relate_to(image_part, RT.IMAGE) return (rId, image_part.image)
'Return the style in this document matching *style_id*. Returns the default style for *style_type* if *style_id* is |None| or does not match a defined style of *style_type*.'
def get_style(self, style_id, style_type):
return self.styles.get_by_id(style_id, style_type)
'Return the style_id (|str|) of the style of *style_type* matching *style_or_name*. Returns |None| if the style resolves to the default style for *style_type* or if *style_or_name* is itself |None|. Raises if *style_or_name* is a style of the wrong type or names a style not present in the document.'
def get_style_id(self, style_or_name, style_type):
return self.styles.get_style_id(style_or_name, style_type)
'The |InlineShapes| instance containing the inline shapes in the document.'
@lazyproperty def inline_shapes(self):
return InlineShapes(self._element.body, self)
'Return a newly-created `w:inline` element containing the image specified by *image_descriptor* and scaled based on the values of *width* and *height*.'
def new_pic_inline(self, image_descriptor, width, height):
(rId, image) = self.get_or_add_image(image_descriptor) (cx, cy) = image.scaled_dimensions(width, height) (shape_id, filename) = (self.next_id, image.filename) return CT_Inline.new_pic_inline(shape_id, rId, filename, cx, cy)
'The next available positive integer id value in this document. Gaps in id sequence are filled. The id attribute value is unique in the document, without regard to the element type it appears on.'
@property def next_id(self):
id_str_lst = self._element.xpath(u'//@id') used_ids = [int(id_str) for id_str in id_str_lst if id_str.isdigit()] for n in range(1, (len(used_ids) + 2)): if (n not in used_ids): return n
'A |NumberingPart| object providing access to the numbering definitions for this document. Creates an empty numbering part if one is not present.'
@lazyproperty def numbering_part(self):
try: return self.part_related_by(RT.NUMBERING) except KeyError: numbering_part = NumberingPart.new() self.relate_to(numbering_part, RT.NUMBERING) return numbering_part
'Save this document to *path_or_stream*, which can be either a path to a filesystem location (a string) or a file-like object.'
def save(self, path_or_stream):
self.package.save(path_or_stream)
'A |Settings| object providing access to the settings in the settings part of this document.'
@property def settings(self):
return self._settings_part.settings
'A |Styles| object providing access to the styles in the styles part of this document.'
@property def styles(self):
return self._styles_part.styles