code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def __getitem__(self, partname: PackURI) -> str:
"""Return content-type (MIME-type) for part identified by *partname*."""
if not isinstance(partname, PackURI): # pyright: ignore[reportUnnecessaryIsInstance]
raise TypeError(
"_ContentTypeMap key must be <type 'PackURI'>, got %s" % type(partname).__name__
)
if partname in self._overrides:
return self._overrides[partname]
if partname.ext in self._defaults:
return self._defaults[partname.ext]
raise KeyError("no content-type for partname '%s' in [Content_Types].xml" % partname)
|
Return content-type (MIME-type) for part identified by *partname*.
|
__getitem__
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def __getitem__(self, rId: str) -> _Relationship:
"""Implement relationship lookup by rId using indexed access, like rels[rId]."""
try:
return self._rels[rId]
except KeyError:
raise KeyError("no relationship with key '%s'" % rId)
|
Implement relationship lookup by rId using indexed access, like rels[rId].
|
__getitem__
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def get_or_add(self, reltype: str, target_part: Part) -> str:
"""Return str rId of `reltype` to `target_part`.
The rId of an existing matching relationship is used if present. Otherwise, a new
relationship is added and that rId is returned.
"""
existing_rId = self._get_matching(reltype, target_part)
return (
self._add_relationship(reltype, target_part) if existing_rId is None else existing_rId
)
|
Return str rId of `reltype` to `target_part`.
The rId of an existing matching relationship is used if present. Otherwise, a new
relationship is added and that rId is returned.
|
get_or_add
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def get_or_add_ext_rel(self, reltype: str, target_ref: str) -> str:
"""Return str rId of external relationship of `reltype` to `target_ref`.
The rId of an existing matching relationship is used if present. Otherwise, a new
relationship is added and that rId is returned.
"""
existing_rId = self._get_matching(reltype, target_ref, is_external=True)
return (
self._add_relationship(reltype, target_ref, is_external=True)
if existing_rId is None
else existing_rId
)
|
Return str rId of external relationship of `reltype` to `target_ref`.
The rId of an existing matching relationship is used if present. Otherwise, a new
relationship is added and that rId is returned.
|
get_or_add_ext_rel
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def load_from_xml(
self, base_uri: str, xml_rels: CT_Relationships, parts: dict[PackURI, Part]
) -> None:
"""Replace any relationships in this collection with those from `xml_rels`."""
def iter_valid_rels():
"""Filter out broken relationships such as those pointing to NULL."""
for rel_elm in xml_rels.relationship_lst:
# --- Occasionally a PowerPoint plugin or other client will "remove"
# --- a relationship simply by "voiding" its Target value, like making
# --- it "/ppt/slides/NULL". Skip any relationships linking to a
# --- partname that is not present in the package.
if rel_elm.targetMode == RTM.INTERNAL:
partname = PackURI.from_rel_ref(base_uri, rel_elm.target_ref)
if partname not in parts:
continue
yield _Relationship.from_xml(base_uri, rel_elm, parts)
self._rels.clear()
self._rels.update((rel.rId, rel) for rel in iter_valid_rels())
|
Replace any relationships in this collection with those from `xml_rels`.
|
load_from_xml
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def iter_valid_rels():
"""Filter out broken relationships such as those pointing to NULL."""
for rel_elm in xml_rels.relationship_lst:
# --- Occasionally a PowerPoint plugin or other client will "remove"
# --- a relationship simply by "voiding" its Target value, like making
# --- it "/ppt/slides/NULL". Skip any relationships linking to a
# --- partname that is not present in the package.
if rel_elm.targetMode == RTM.INTERNAL:
partname = PackURI.from_rel_ref(base_uri, rel_elm.target_ref)
if partname not in parts:
continue
yield _Relationship.from_xml(base_uri, rel_elm, parts)
|
Filter out broken relationships such as those pointing to NULL.
|
iter_valid_rels
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def part_with_reltype(self, reltype: str) -> Part:
"""Return target part of relationship with matching `reltype`.
Raises |KeyError| if not found and |ValueError| if more than one matching relationship is
found.
"""
rels_of_reltype = self._rels_by_reltype[reltype]
if len(rels_of_reltype) == 0:
raise KeyError("no relationship of type '%s' in collection" % reltype)
if len(rels_of_reltype) > 1:
raise ValueError("multiple relationships of type '%s' in collection" % reltype)
return rels_of_reltype[0].target_part
|
Return target part of relationship with matching `reltype`.
Raises |KeyError| if not found and |ValueError| if more than one matching relationship is
found.
|
part_with_reltype
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def xml(self):
"""bytes XML serialization of this relationship collection.
This value is suitable for storage as a .rels file in an OPC package. Includes a `<?xml..`
declaration header with encoding as UTF-8.
"""
rels_elm = CT_Relationships.new()
# -- Sequence <Relationship> elements deterministically (in numerical order) to
# -- simplify testing and manual inspection.
def iter_rels_in_numerical_order():
sorted_num_rId_pairs = sorted(
(
int(rId[3:]) if rId.startswith("rId") and rId[3:].isdigit() else 0,
rId,
)
for rId in self.keys()
)
return (self[rId] for _, rId in sorted_num_rId_pairs)
for rel in iter_rels_in_numerical_order():
rels_elm.add_rel(rel.rId, rel.reltype, rel.target_ref, rel.is_external)
return rels_elm.xml_file_bytes
|
bytes XML serialization of this relationship collection.
This value is suitable for storage as a .rels file in an OPC package. Includes a `<?xml..`
declaration header with encoding as UTF-8.
|
xml
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def _add_relationship(self, reltype: str, target: Part | str, is_external: bool = False) -> str:
"""Return str rId of |_Relationship| newly added to spec."""
rId = self._next_rId
self._rels[rId] = _Relationship(
self._base_uri,
rId,
reltype,
target_mode=RTM.EXTERNAL if is_external else RTM.INTERNAL,
target=target,
)
return rId
|
Return str rId of |_Relationship| newly added to spec.
|
_add_relationship
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def _get_matching(
self, reltype: str, target: Part | str, is_external: bool = False
) -> str | None:
"""Return optional str rId of rel of `reltype`, `target`, and `is_external`.
Returns `None` on no matching relationship
"""
for rel in self._rels_by_reltype[reltype]:
if rel.is_external != is_external:
continue
rel_target = rel.target_ref if rel.is_external else rel.target_part
if rel_target == target:
return rel.rId
return None
|
Return optional str rId of rel of `reltype`, `target`, and `is_external`.
Returns `None` on no matching relationship
|
_get_matching
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def _next_rId(self) -> str:
"""Next str rId available in collection.
The next rId is the first unused key starting from "rId1" and making use of any gaps in
numbering, e.g. 'rId2' for rIds ['rId1', 'rId3'].
"""
# --- The common case is where all sequential numbers starting at "rId1" are
# --- used and the next available rId is "rId%d" % (len(rels)+1). So we start
# --- there and count down to produce the best performance.
for n in range(len(self) + 1, 0, -1):
rId_candidate = "rId%d" % n # like 'rId19'
if rId_candidate not in self._rels:
return rId_candidate
raise Exception(
"ProgrammingError: Impossible to have more distinct rIds than relationships"
)
|
Next str rId available in collection.
The next rId is the first unused key starting from "rId1" and making use of any gaps in
numbering, e.g. 'rId2' for rIds ['rId1', 'rId3'].
|
_next_rId
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def _rels_by_reltype(self) -> dict[str, list[_Relationship]]:
"""defaultdict {reltype: [rels]} for all relationships in collection."""
D: DefaultDict[str, list[_Relationship]] = collections.defaultdict(list)
for rel in self.values():
D[rel.reltype].append(rel)
return D
|
defaultdict {reltype: [rels]} for all relationships in collection.
|
_rels_by_reltype
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def from_xml(
cls, base_uri: str, rel: CT_Relationship, parts: dict[PackURI, Part]
) -> _Relationship:
"""Return |_Relationship| object based on CT_Relationship element `rel`."""
target = (
rel.target_ref
if rel.targetMode == RTM.EXTERNAL
else parts[PackURI.from_rel_ref(base_uri, rel.target_ref)]
)
return cls(base_uri, rel.rId, rel.reltype, rel.targetMode, target)
|
Return |_Relationship| object based on CT_Relationship element `rel`.
|
from_xml
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def target_part(self) -> Part:
"""|Part| or subtype referred to by this relationship."""
if self.is_external:
raise ValueError(
"`.target_part` property on _Relationship is undefined when "
"target-mode is external"
)
assert isinstance(self._target, Part)
return self._target
|
|Part| or subtype referred to by this relationship.
|
target_part
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def target_partname(self) -> PackURI:
"""|PackURI| instance containing partname targeted by this relationship.
Raises `ValueError` on reference if target_mode is external. Use :attr:`target_mode` to
check before referencing.
"""
if self.is_external:
raise ValueError(
"`.target_partname` property on _Relationship is undefined when "
"target-mode is external"
)
assert isinstance(self._target, Part)
return self._target.partname
|
|PackURI| instance containing partname targeted by this relationship.
Raises `ValueError` on reference if target_mode is external. Use :attr:`target_mode` to
check before referencing.
|
target_partname
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def target_ref(self) -> str:
"""str reference to relationship target.
For internal relationships this is the relative partname, suitable for serialization
purposes. For an external relationship it is typically a URL.
"""
if self.is_external:
assert isinstance(self._target, str)
return self._target
return self.target_partname.relative_ref(self._base_uri)
|
str reference to relationship target.
For internal relationships this is the relative partname, suitable for serialization
purposes. For an external relationship it is typically a URL.
|
target_ref
|
python
|
scanny/python-pptx
|
src/pptx/opc/package.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/package.py
|
MIT
|
def from_rel_ref(baseURI: str, relative_ref: str) -> PackURI:
"""Construct an absolute pack URI formed by translating `relative_ref` onto `baseURI`."""
joined_uri = posixpath.join(baseURI, relative_ref)
abs_uri = posixpath.abspath(joined_uri)
return PackURI(abs_uri)
|
Construct an absolute pack URI formed by translating `relative_ref` onto `baseURI`.
|
from_rel_ref
|
python
|
scanny/python-pptx
|
src/pptx/opc/packuri.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/packuri.py
|
MIT
|
def ext(self) -> str:
"""The extension portion of this pack URI.
E.g. `"xml"` for `"/ppt/slides/slide1.xml"`. Note the leading period is not included.
"""
# -- raw_ext is either empty string or starts with period, e.g. ".xml" --
raw_ext = posixpath.splitext(self)[1]
return raw_ext[1:] if raw_ext.startswith(".") else raw_ext
|
The extension portion of this pack URI.
E.g. `"xml"` for `"/ppt/slides/slide1.xml"`. Note the leading period is not included.
|
ext
|
python
|
scanny/python-pptx
|
src/pptx/opc/packuri.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/packuri.py
|
MIT
|
def idx(self) -> int | None:
"""Optional int partname index.
Value is an integer for an "array" partname or None for singleton partname, e.g. `21` for
`"/ppt/slides/slide21.xml"` and |None| for `"/ppt/presentation.xml"`.
"""
filename = self.filename
if not filename:
return None
name_part = posixpath.splitext(filename)[0] # filename w/ext removed
match = self._filename_re.match(name_part)
if match is None:
return None
if match.group(2):
return int(match.group(2))
return None
|
Optional int partname index.
Value is an integer for an "array" partname or None for singleton partname, e.g. `21` for
`"/ppt/slides/slide21.xml"` and |None| for `"/ppt/presentation.xml"`.
|
idx
|
python
|
scanny/python-pptx
|
src/pptx/opc/packuri.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/packuri.py
|
MIT
|
def relative_ref(self, baseURI: str) -> str:
"""Return string containing relative reference to package item from `baseURI`.
E.g. PackURI("/ppt/slideLayouts/slideLayout1.xml") would return
"../slideLayouts/slideLayout1.xml" for baseURI "/ppt/slides".
"""
# workaround for posixpath bug in 2.6, doesn't generate correct
# relative path when `start` (second) parameter is root ("/")
return self[1:] if baseURI == "/" else posixpath.relpath(self, baseURI)
|
Return string containing relative reference to package item from `baseURI`.
E.g. PackURI("/ppt/slideLayouts/slideLayout1.xml") would return
"../slideLayouts/slideLayout1.xml" for baseURI "/ppt/slides".
|
relative_ref
|
python
|
scanny/python-pptx
|
src/pptx/opc/packuri.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/packuri.py
|
MIT
|
def rels_uri(self) -> PackURI:
"""The pack URI of the .rels part corresponding to the current pack URI.
Only produces sensible output if the pack URI is a partname or the package pseudo-partname
"/".
"""
rels_filename = "%s.rels" % self.filename
rels_uri_str = posixpath.join(self.baseURI, "_rels", rels_filename)
return PackURI(rels_uri_str)
|
The pack URI of the .rels part corresponding to the current pack URI.
Only produces sensible output if the pack URI is a partname or the package pseudo-partname
"/".
|
rels_uri
|
python
|
scanny/python-pptx
|
src/pptx/opc/packuri.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/packuri.py
|
MIT
|
def rels_xml_for(self, partname: PackURI) -> bytes | None:
"""Return optional rels item XML for `partname`.
Returns `None` if no rels item is present for `partname`. `partname` is a |PackURI|
instance.
"""
blob_reader, uri = self._blob_reader, partname.rels_uri
return blob_reader[uri] if uri in blob_reader else None
|
Return optional rels item XML for `partname`.
Returns `None` if no rels item is present for `partname`. `partname` is a |PackURI|
instance.
|
rels_xml_for
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def write(
cls, pkg_file: str | IO[bytes], pkg_rels: _Relationships, parts: Sequence[Part]
) -> None:
"""Write a physical package (.pptx file) to `pkg_file`.
The serialized package contains `pkg_rels` and `parts`, a content-types stream based on
the content type of each part, and a .rels file for each part that has relationships.
"""
cls(pkg_file, pkg_rels, parts)._write()
|
Write a physical package (.pptx file) to `pkg_file`.
The serialized package contains `pkg_rels` and `parts`, a content-types stream based on
the content type of each part, and a .rels file for each part that has relationships.
|
write
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def _write_content_types_stream(self, phys_writer: _PhysPkgWriter) -> None:
"""Write `[Content_Types].xml` part to the physical package.
This part must contain an appropriate content type lookup target for each part in the
package.
"""
phys_writer.write(
CONTENT_TYPES_URI,
serialize_part_xml(_ContentTypesItem.xml_for(self._parts)),
)
|
Write `[Content_Types].xml` part to the physical package.
This part must contain an appropriate content type lookup target for each part in the
package.
|
_write_content_types_stream
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def _write_parts(self, phys_writer: _PhysPkgWriter) -> None:
"""Write blob of each part in `parts` to the package.
A rels item for each part is also written when the part has relationships.
"""
for part in self._parts:
phys_writer.write(part.partname, part.blob)
if part._rels: # pyright: ignore[reportPrivateUsage]
phys_writer.write(part.partname.rels_uri, part.rels.xml)
|
Write blob of each part in `parts` to the package.
A rels item for each part is also written when the part has relationships.
|
_write_parts
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def __contains__(self, item: object) -> bool:
"""Must be implemented by each subclass."""
raise NotImplementedError( # pragma: no cover
"`%s` must implement `.__contains__()`" % type(self).__name__
)
|
Must be implemented by each subclass.
|
__contains__
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def __contains__(self, pack_uri: object) -> bool:
"""Return True when part identified by `pack_uri` is present in zip archive."""
if not isinstance(pack_uri, PackURI):
return False
return os.path.exists(posixpath.join(self._path, pack_uri.membername))
|
Return True when part identified by `pack_uri` is present in zip archive.
|
__contains__
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def __getitem__(self, pack_uri: PackURI) -> bytes:
"""Return bytes of file corresponding to `pack_uri` in package directory."""
path = os.path.join(self._path, pack_uri.membername)
try:
with open(path, "rb") as f:
return f.read()
except IOError:
raise KeyError("no member '%s' in package" % pack_uri)
|
Return bytes of file corresponding to `pack_uri` in package directory.
|
__getitem__
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def __getitem__(self, pack_uri: PackURI) -> bytes:
"""Return bytes for part corresponding to `pack_uri`.
Raises |KeyError| if no matching member is present in zip archive.
"""
if pack_uri not in self._blobs:
raise KeyError("no member '%s' in package" % pack_uri)
return self._blobs[pack_uri]
|
Return bytes for part corresponding to `pack_uri`.
Raises |KeyError| if no matching member is present in zip archive.
|
__getitem__
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def _blobs(self) -> dict[PackURI, bytes]:
"""dict mapping partname to package part binaries."""
with zipfile.ZipFile(self._pkg_file, "r") as z:
return {PackURI("/%s" % name): z.read(name) for name in z.namelist()}
|
dict mapping partname to package part binaries.
|
_blobs
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def write(self, pack_uri: PackURI, blob: bytes) -> None:
"""Write `blob` to package with membername corresponding to `pack_uri`."""
raise NotImplementedError( # pragma: no cover
f"`{type(self).__name__}` must implement `.write()`"
)
|
Write `blob` to package with membername corresponding to `pack_uri`.
|
write
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def _xml(self) -> CT_Types:
"""lxml.etree._Element containing the content-types item.
This XML object is suitable for serialization to the `[Content_Types].xml` item for an OPC
package. Although the sequence of elements is not strictly significant, as an aid to
testing and readability Default elements are sorted by extension and Override elements are
sorted by partname.
"""
defaults, overrides = self._defaults_and_overrides
_types_elm = CT_Types.new()
for ext, content_type in sorted(defaults.items()):
_types_elm.add_default(ext, content_type)
for partname, content_type in sorted(overrides.items()):
_types_elm.add_override(partname, content_type)
return _types_elm
|
lxml.etree._Element containing the content-types item.
This XML object is suitable for serialization to the `[Content_Types].xml` item for an OPC
package. Although the sequence of elements is not strictly significant, as an aid to
testing and readability Default elements are sorted by extension and Override elements are
sorted by partname.
|
_xml
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def _defaults_and_overrides(self) -> tuple[dict[str, str], dict[PackURI, str]]:
"""pair of dict (defaults, overrides) accounting for all parts.
`defaults` is {ext: content_type} and overrides is {partname: content_type}.
"""
defaults = CaseInsensitiveDict(rels=CT.OPC_RELATIONSHIPS, xml=CT.XML)
overrides: dict[PackURI, str] = {}
for part in self._parts:
partname, content_type = part.partname, part.content_type
ext = partname.ext
if (ext.lower(), content_type) in default_content_types:
defaults[ext] = content_type
else:
overrides[partname] = content_type
return defaults, overrides
|
pair of dict (defaults, overrides) accounting for all parts.
`defaults` is {ext: content_type} and overrides is {partname: content_type}.
|
_defaults_and_overrides
|
python
|
scanny/python-pptx
|
src/pptx/opc/serialized.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/opc/serialized.py
|
MIT
|
def action_fields(self) -> dict[str, str]:
"""Query portion of the `ppaction://` URL as dict.
For example `{'id':'0', 'return':'true'}` in 'ppaction://customshow?id=0&return=true'.
Returns an empty dict if the URL contains no query string or if no action attribute is
present.
"""
url = self.action
if url is None:
return {}
halves = url.split("?")
if len(halves) == 1:
return {}
key_value_pairs = halves[1].split("&")
return dict([pair.split("=") for pair in key_value_pairs])
|
Query portion of the `ppaction://` URL as dict.
For example `{'id':'0', 'return':'true'}` in 'ppaction://customshow?id=0&return=true'.
Returns an empty dict if the URL contains no query string or if no action attribute is
present.
|
action_fields
|
python
|
scanny/python-pptx
|
src/pptx/oxml/action.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/action.py
|
MIT
|
def action_verb(self) -> str | None:
"""The host portion of the `ppaction://` URL contained in the action attribute.
For example 'customshow' in 'ppaction://customshow?id=0&return=true'. Returns |None| if no
action attribute is present.
"""
url = self.action
if url is None:
return None
protocol_and_host = url.split("?")[0]
host = protocol_and_host[11:]
return host
|
The host portion of the `ppaction://` URL contained in the action attribute.
For example 'customshow' in 'ppaction://customshow?id=0&return=true'. Returns |None| if no
action attribute is present.
|
action_verb
|
python
|
scanny/python-pptx
|
src/pptx/oxml/action.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/action.py
|
MIT
|
def revision_number(self, value: int):
"""Set revision property to string value of integer `value`."""
if not isinstance(value, int) or value < 1: # pyright: ignore[reportUnnecessaryIsInstance]
tmpl = "revision property requires positive int, got '%s'"
raise ValueError(tmpl % value)
revision = self.get_or_add_revision()
revision.text = str(value)
|
Set revision property to string value of integer `value`.
|
revision_number
|
python
|
scanny/python-pptx
|
src/pptx/oxml/coreprops.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/coreprops.py
|
MIT
|
def _get_or_add(self, prop_name: str):
"""Return element returned by 'get_or_add_' method for `prop_name`."""
get_or_add_method_name = "get_or_add_%s" % prop_name
get_or_add_method = getattr(self, get_or_add_method_name)
element = get_or_add_method()
return element
|
Return element returned by 'get_or_add_' method for `prop_name`.
|
_get_or_add
|
python
|
scanny/python-pptx
|
src/pptx/oxml/coreprops.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/coreprops.py
|
MIT
|
def _offset_dt(cls, datetime: dt.datetime, offset_str: str):
"""Return |datetime| instance offset from `datetime` by offset specified in `offset_str`.
`offset_str` is a string like `'-07:00'`.
"""
match = cls._offset_pattern.match(offset_str)
if match is None:
raise ValueError(f"{repr(offset_str)} is not a valid offset string")
sign, hours_str, minutes_str = match.groups()
sign_factor = -1 if sign == "+" else 1
hours = int(hours_str) * sign_factor
minutes = int(minutes_str) * sign_factor
td = dt.timedelta(hours=hours, minutes=minutes)
return datetime + td
|
Return |datetime| instance offset from `datetime` by offset specified in `offset_str`.
`offset_str` is a string like `'-07:00'`.
|
_offset_dt
|
python
|
scanny/python-pptx
|
src/pptx/oxml/coreprops.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/coreprops.py
|
MIT
|
def _set_element_datetime(self, prop_name: str, value: dt.datetime) -> None:
"""Set date/time value of child element having `prop_name` to `value`."""
if not isinstance(value, dt.datetime): # pyright: ignore[reportUnnecessaryIsInstance]
tmpl = "property requires <type 'datetime.datetime'> object, got %s"
raise ValueError(tmpl % type(value))
element = self._get_or_add(prop_name)
dt_str = value.strftime("%Y-%m-%dT%H:%M:%SZ")
element.text = dt_str
if prop_name in ("created", "modified"):
# These two require an explicit 'xsi:type="dcterms:W3CDTF"'
# attribute. The first and last line are a hack required to add
# the xsi namespace to the root element rather than each child
# element in which it is referenced
self.set(qn("xsi:foo"), "bar")
element.set(qn("xsi:type"), "dcterms:W3CDTF")
del self.attrib[qn("xsi:foo")]
|
Set date/time value of child element having `prop_name` to `value`.
|
_set_element_datetime
|
python
|
scanny/python-pptx
|
src/pptx/oxml/coreprops.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/coreprops.py
|
MIT
|
def _set_element_text(self, prop_name: str, value: str) -> None:
"""Set string value of `name` property to `value`."""
value = str(value)
if len(value) > 255:
tmpl = "exceeded 255 char limit for property, got:\n\n'%s'"
raise ValueError(tmpl % value)
element = self._get_or_add(prop_name)
element.text = value
|
Set string value of `name` property to `value`.
|
_set_element_text
|
python
|
scanny/python-pptx
|
src/pptx/oxml/coreprops.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/coreprops.py
|
MIT
|
def _next_id(self) -> int:
"""The next available slide ID as an `int`.
Valid slide IDs start at 256. The next integer value greater than the max value in use is
chosen, which minimizes that chance of reusing the id of a deleted slide.
"""
MIN_SLIDE_ID = 256
MAX_SLIDE_ID = 2147483647
used_ids = [int(s) for s in cast("list[str]", self.xpath("./p:sldId/@id"))]
simple_next = max([MIN_SLIDE_ID - 1] + used_ids) + 1
if simple_next <= MAX_SLIDE_ID:
return simple_next
# -- fall back to search for next unused from bottom --
valid_used_ids = sorted(id for id in used_ids if (MIN_SLIDE_ID <= id <= MAX_SLIDE_ID))
return (
next(
candidate_id
for candidate_id, used_id in enumerate(valid_used_ids, start=MIN_SLIDE_ID)
if candidate_id != used_id
)
if valid_used_ids
else 256
)
|
The next available slide ID as an `int`.
Valid slide IDs start at 256. The next integer value greater than the max value in use is
chosen, which minimizes that chance of reusing the id of a deleted slide.
|
_next_id
|
python
|
scanny/python-pptx
|
src/pptx/oxml/presentation.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/presentation.py
|
MIT
|
def validate_float(cls, value: Any):
"""Note that int values are accepted."""
if not isinstance(value, (int, float)):
raise TypeError("value must be a number, got %s" % type(value))
|
Note that int values are accepted.
|
validate_float
|
python
|
scanny/python-pptx
|
src/pptx/oxml/simpletypes.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/simpletypes.py
|
MIT
|
def convert_to_xml(cls, value):
"""
Convert signed angle float like -42.42 to int 60000 per degree,
normalized to positive value.
"""
# modulo normalizes negative and >360 degree values
rot = int(round(value * cls.DEGREE_INCREMENTS)) % cls.THREE_SIXTY
return str(rot)
|
Convert signed angle float like -42.42 to int 60000 per degree,
normalized to positive value.
|
convert_to_xml
|
python
|
scanny/python-pptx
|
src/pptx/oxml/simpletypes.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/simpletypes.py
|
MIT
|
def convert_to_xml(cls, degrees):
"""Convert signed angle float like -427.42 to int 60000 per degree.
Value is normalized to a positive value less than 360 degrees.
"""
if degrees < 0.0:
degrees %= -360
degrees += 360
elif degrees > 0.0:
degrees %= 360
return str(int(round(degrees * cls.DEGREE_INCREMENTS)))
|
Convert signed angle float like -427.42 to int 60000 per degree.
Value is normalized to a positive value less than 360 degrees.
|
convert_to_xml
|
python
|
scanny/python-pptx
|
src/pptx/oxml/simpletypes.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/simpletypes.py
|
MIT
|
def add_noFill_bgPr(self):
"""Return a new `p:bgPr` element with noFill properties."""
xml = "<p:bgPr %s>\n" " <a:noFill/>\n" " <a:effectLst/>\n" "</p:bgPr>" % nsdecls("a", "p")
bgPr = cast(CT_BackgroundProperties, parse_xml(xml))
self._insert_bgPr(bgPr)
return bgPr
|
Return a new `p:bgPr` element with noFill properties.
|
add_noFill_bgPr
|
python
|
scanny/python-pptx
|
src/pptx/oxml/slide.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/slide.py
|
MIT
|
def get_or_add_bgPr(self) -> CT_BackgroundProperties:
"""Return `p:bg/p:bgPr` grandchild.
If no such grandchild is present, any existing `p:bg` child is first removed and a new
default `p:bg` with noFill settings is added.
"""
bg = self.bg
if bg is None or bg.bgPr is None:
bg = self._change_to_noFill_bg()
return cast(CT_BackgroundProperties, bg.bgPr)
|
Return `p:bg/p:bgPr` grandchild.
If no such grandchild is present, any existing `p:bg` child is first removed and a new
default `p:bg` with noFill settings is added.
|
get_or_add_bgPr
|
python
|
scanny/python-pptx
|
src/pptx/oxml/slide.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/slide.py
|
MIT
|
def _change_to_noFill_bg(self) -> CT_Background:
"""Establish a `p:bg` child with no-fill settings.
Any existing `p:bg` child is first removed.
"""
self._remove_bg()
bg = self.get_or_add_bg()
bg.add_noFill_bgPr()
return bg
|
Establish a `p:bg` child with no-fill settings.
Any existing `p:bg` child is first removed.
|
_change_to_noFill_bg
|
python
|
scanny/python-pptx
|
src/pptx/oxml/slide.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/slide.py
|
MIT
|
def get_or_add_childTnLst(self):
"""Return parent element for a new `p:video` child element.
The `p:video` element causes play controls to appear under a video
shape (pic shape containing video). There can be more than one video
shape on a slide, which causes the precondition to vary. It needs to
handle the case when there is no `p:sld/p:timing` element and when
that element already exists. If the case isn't simple, it just nukes
what's there and adds a fresh one. This could theoretically remove
desired existing timing information, but there isn't any evidence
available to me one way or the other, so I've taken the simple
approach.
"""
childTnLst = self._childTnLst
if childTnLst is None:
childTnLst = self._add_childTnLst()
return childTnLst
|
Return parent element for a new `p:video` child element.
The `p:video` element causes play controls to appear under a video
shape (pic shape containing video). There can be more than one video
shape on a slide, which causes the precondition to vary. It needs to
handle the case when there is no `p:sld/p:timing` element and when
that element already exists. If the case isn't simple, it just nukes
what's there and adds a fresh one. This could theoretically remove
desired existing timing information, but there isn't any evidence
available to me one way or the other, so I've taken the simple
approach.
|
get_or_add_childTnLst
|
python
|
scanny/python-pptx
|
src/pptx/oxml/slide.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/slide.py
|
MIT
|
def _add_childTnLst(self):
"""Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Any existing `p:timing` child element is ruthlessly removed and
replaced.
"""
self.remove(self.get_or_add_timing())
timing = parse_xml(self._childTnLst_timing_xml())
self._insert_timing(timing)
return timing.xpath("./p:tnLst/p:par/p:cTn/p:childTnLst")[0]
|
Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Any existing `p:timing` child element is ruthlessly removed and
replaced.
|
_add_childTnLst
|
python
|
scanny/python-pptx
|
src/pptx/oxml/slide.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/slide.py
|
MIT
|
def _childTnLst(self):
"""Return `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Return None if that element is not present.
"""
childTnLsts = self.xpath("./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst")
if not childTnLsts:
return None
return childTnLsts[0]
|
Return `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Return None if that element is not present.
|
_childTnLst
|
python
|
scanny/python-pptx
|
src/pptx/oxml/slide.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/slide.py
|
MIT
|
def add_video(self, shape_id):
"""Add a new `p:video` child element for movie having *shape_id*."""
video_xml = (
"<p:video %s>\n"
' <p:cMediaNode vol="80000">\n'
' <p:cTn id="%d" fill="hold" display="0">\n'
" <p:stCondLst>\n"
' <p:cond delay="indefinite"/>\n'
" </p:stCondLst>\n"
" </p:cTn>\n"
" <p:tgtEl>\n"
' <p:spTgt spid="%d"/>\n'
" </p:tgtEl>\n"
" </p:cMediaNode>\n"
"</p:video>\n" % (nsdecls("p"), self._next_cTn_id, shape_id)
)
video = parse_xml(video_xml)
self.append(video)
|
Add a new `p:video` child element for movie having *shape_id*.
|
add_video
|
python
|
scanny/python-pptx
|
src/pptx/oxml/slide.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/slide.py
|
MIT
|
def _next_cTn_id(self):
"""Return the next available unique ID (int) for p:cTn element."""
cTn_id_strs = self.xpath("/p:sld/p:timing//p:cTn/@id")
ids = [int(id_str) for id_str in cTn_id_strs]
return max(ids) + 1
|
Return the next available unique ID (int) for p:cTn element.
|
_next_cTn_id
|
python
|
scanny/python-pptx
|
src/pptx/oxml/slide.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/slide.py
|
MIT
|
def _get_boolean_property(self, propname: str) -> bool:
"""Generalized getter for the boolean properties on the `a:tblPr` child element.
Defaults to False if `propname` attribute is missing or `a:tblPr` element itself is not
present.
"""
tblPr = self.tblPr
if tblPr is None:
return False
propval = getattr(tblPr, propname)
return {True: True, False: False, None: False}[propval]
|
Generalized getter for the boolean properties on the `a:tblPr` child element.
Defaults to False if `propname` attribute is missing or `a:tblPr` element itself is not
present.
|
_get_boolean_property
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def _set_boolean_property(self, propname: str, value: bool) -> None:
"""Generalized setter for boolean properties on the `a:tblPr` child element.
Sets `propname` attribute appropriately based on `value`. If `value` is True, the
attribute is set to "1"; a tblPr child element is added if necessary. If `value` is False,
the `propname` attribute is removed if present, allowing its default value of False to be
its effective value.
"""
if value not in (True, False):
raise ValueError("assigned value must be either True or False, got %s" % value)
tblPr = self.get_or_add_tblPr()
setattr(tblPr, propname, value)
|
Generalized setter for boolean properties on the `a:tblPr` child element.
Sets `propname` attribute appropriately based on `value`. If `value` is True, the
attribute is set to "1"; a tblPr child element is added if necessary. If `value` is False,
the `propname` attribute is removed if present, allowing its default value of False to be
its effective value.
|
_set_boolean_property
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def anchor(self) -> MSO_VERTICAL_ANCHOR | None:
"""String held in `anchor` attribute of `a:tcPr` child element of this `a:tc` element."""
if self.tcPr is None:
return None
return self.tcPr.anchor
|
String held in `anchor` attribute of `a:tcPr` child element of this `a:tc` element.
|
anchor
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def anchor(self, anchor_enum_idx: MSO_VERTICAL_ANCHOR | None):
"""Set value of anchor attribute on `a:tcPr` child element."""
if anchor_enum_idx is None and self.tcPr is None:
return
tcPr = self.get_or_add_tcPr()
tcPr.anchor = anchor_enum_idx
|
Set value of anchor attribute on `a:tcPr` child element.
|
anchor
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def append_ps_from(self, spanned_tc: CT_TableCell):
"""Append `a:p` elements taken from `spanned_tc`.
Any non-empty paragraph elements in `spanned_tc` are removed and appended to the
text-frame of this cell. If `spanned_tc` is left with no content after this process, a
single empty `a:p` element is added to ensure the cell is compliant with the spec.
"""
source_txBody = spanned_tc.get_or_add_txBody()
target_txBody = self.get_or_add_txBody()
# ---if source is empty, there's nothing to do---
if source_txBody.is_empty:
return
# ---a single empty paragraph in target is overwritten---
if target_txBody.is_empty:
target_txBody.clear_content()
for p in source_txBody.p_lst:
target_txBody.append(p)
# ---neither source nor target can be left without ps---
source_txBody.unclear_content()
target_txBody.unclear_content()
|
Append `a:p` elements taken from `spanned_tc`.
Any non-empty paragraph elements in `spanned_tc` are removed and appended to the
text-frame of this cell. If `spanned_tc` is left with no content after this process, a
single empty `a:p` element is added to ensure the cell is compliant with the spec.
|
append_ps_from
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def col_idx(self) -> int:
"""Offset of this cell's column in its table."""
# ---tc elements come before any others in `a:tr` element---
return cast(CT_TableRow, self.getparent()).index(self)
|
Offset of this cell's column in its table.
|
col_idx
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def is_merge_origin(self) -> bool:
"""True if cell is top-left in merged cell range."""
if self.gridSpan > 1 and not self.vMerge:
return True
return self.rowSpan > 1 and not self.hMerge
|
True if cell is top-left in merged cell range.
|
is_merge_origin
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def _get_marX(self, attr_name: str, default: Length) -> Length:
"""Generalized method to get margin values."""
if self.tcPr is None:
return Emu(default)
return Emu(int(self.tcPr.get(attr_name, default)))
|
Generalized method to get margin values.
|
_get_marX
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def _set_marX(self, marX: str, value: Length | None) -> None:
"""Set value of marX attribute on `a:tcPr` child element.
If `marX` is |None|, the marX attribute is removed. `marX` is a string, one of `('marL',
'marR', 'marT', 'marB')`.
"""
if value is None and self.tcPr is None:
return
tcPr = self.get_or_add_tcPr()
setattr(tcPr, marX, value)
|
Set value of marX attribute on `a:tcPr` child element.
If `marX` is |None|, the marX attribute is removed. `marX` is a string, one of `('marL',
'marR', 'marT', 'marB')`.
|
_set_marX
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def from_merge_origin(cls, tc: CT_TableCell):
"""Return instance created from merge-origin tc element."""
other_tc = tc.tbl.tc(
tc.row_idx + tc.rowSpan - 1, # ---other_row_idx
tc.col_idx + tc.gridSpan - 1, # ---other_col_idx
)
return cls(tc, other_tc)
|
Return instance created from merge-origin tc element.
|
from_merge_origin
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def contains_merged_cell(self) -> bool:
"""True if one or more cells in range are part of a merged cell."""
for tc in self.iter_tcs():
if tc.gridSpan > 1:
return True
if tc.rowSpan > 1:
return True
if tc.hMerge:
return True
if tc.vMerge:
return True
return False
|
True if one or more cells in range are part of a merged cell.
|
contains_merged_cell
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def in_same_table(self):
"""True if both cells provided to constructor are in same table."""
if self._tc.tbl is self._other_tc.tbl:
return True
return False
|
True if both cells provided to constructor are in same table.
|
in_same_table
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def iter_except_left_col_tcs(self):
"""Generate each `a:tc` element not in leftmost column of range."""
for tr in self._tbl.tr_lst[self._top : self._bottom]:
for tc in tr.tc_lst[self._left + 1 : self._right]:
yield tc
|
Generate each `a:tc` element not in leftmost column of range.
|
iter_except_left_col_tcs
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def iter_except_top_row_tcs(self):
"""Generate each `a:tc` element in non-first rows of range."""
for tr in self._tbl.tr_lst[self._top + 1 : self._bottom]:
for tc in tr.tc_lst[self._left : self._right]:
yield tc
|
Generate each `a:tc` element in non-first rows of range.
|
iter_except_top_row_tcs
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def iter_left_col_tcs(self):
"""Generate each `a:tc` element in leftmost column of range."""
col_idx = self._left
for tr in self._tbl.tr_lst[self._top : self._bottom]:
yield tr.tc_lst[col_idx]
|
Generate each `a:tc` element in leftmost column of range.
|
iter_left_col_tcs
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def iter_tcs(self):
"""Generate each `a:tc` element in this range.
Cell elements are generated left-to-right, top-to-bottom.
"""
return (
tc
for tr in self._tbl.tr_lst[self._top : self._bottom]
for tc in tr.tc_lst[self._left : self._right]
)
|
Generate each `a:tc` element in this range.
Cell elements are generated left-to-right, top-to-bottom.
|
iter_tcs
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def iter_top_row_tcs(self):
"""Generate each `a:tc` element in topmost row of range."""
tr = self._tbl.tr_lst[self._top]
for tc in tr.tc_lst[self._left : self._right]:
yield tc
|
Generate each `a:tc` element in topmost row of range.
|
iter_top_row_tcs
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def move_content_to_origin(self):
"""Move all paragraphs in range to origin cell."""
tcs = list(self.iter_tcs())
origin_tc = tcs[0]
for spanned_tc in tcs[1:]:
origin_tc.append_ps_from(spanned_tc)
|
Move all paragraphs in range to origin cell.
|
move_content_to_origin
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def _bottom(self):
"""Index of row following last row of range"""
_, top, _, height = self._extents
return top + height
|
Index of row following last row of range
|
_bottom
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def _extents(self) -> tuple[int, int, int, int]:
"""A (left, top, width, height) tuple describing range extents.
Note this is normalized to accommodate the various orderings of the corner cells provided
on construction, which may be in any of four configurations such as (top-left,
bottom-right), (bottom-left, top-right), etc.
"""
def start_and_size(idx: int, other_idx: int) -> tuple[int, int]:
"""Return beginning and length of range based on two indexes."""
return min(idx, other_idx), abs(idx - other_idx) + 1
tc, other_tc = self._tc, self._other_tc
left, width = start_and_size(tc.col_idx, other_tc.col_idx)
top, height = start_and_size(tc.row_idx, other_tc.row_idx)
return left, top, width, height
|
A (left, top, width, height) tuple describing range extents.
Note this is normalized to accommodate the various orderings of the corner cells provided
on construction, which may be in any of four configurations such as (top-left,
bottom-right), (bottom-left, top-right), etc.
|
_extents
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def _right(self):
"""Index of column following the last column in range."""
left, _, width, _ = self._extents
return left + width
|
Index of column following the last column in range.
|
_right
|
python
|
scanny/python-pptx
|
src/pptx/oxml/table.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/table.py
|
MIT
|
def defRPr(self) -> CT_TextCharacterProperties:
"""`a:defRPr` element of required first `p` child, added with its ancestors if not present.
Used when element is a ``c:txPr`` in a chart and the `p` element is used only to specify
formatting, not content.
"""
p = self.p_lst[0]
pPr = p.get_or_add_pPr()
defRPr = pPr.get_or_add_defRPr()
return defRPr
|
`a:defRPr` element of required first `p` child, added with its ancestors if not present.
Used when element is a ``c:txPr`` in a chart and the `p` element is used only to specify
formatting, not content.
|
defRPr
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def is_empty(self) -> bool:
"""True if only a single empty `a:p` element is present."""
ps = self.p_lst
if len(ps) > 1:
return False
if not ps:
raise InvalidXmlError("p:txBody must have at least one a:p")
if ps[0].text != "":
return False
return True
|
True if only a single empty `a:p` element is present.
|
is_empty
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def new_a_txBody(cls) -> CT_TextBody:
"""Return a new `a:txBody` element tree.
Suitable for use in a table cell and possibly other situations.
"""
xml = cls._a_txBody_tmpl()
txBody = cast(CT_TextBody, parse_xml(xml))
return txBody
|
Return a new `a:txBody` element tree.
Suitable for use in a table cell and possibly other situations.
|
new_a_txBody
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def new_txPr(cls):
"""Return a `c:txPr` element tree.
Suitable for use in a chart object like data labels or tick labels.
"""
xml = (
"<c:txPr %s>\n"
" <a:bodyPr/>\n"
" <a:lstStyle/>\n"
" <a:p>\n"
" <a:pPr>\n"
" <a:defRPr/>\n"
" </a:pPr>\n"
" </a:p>\n"
"</c:txPr>\n"
) % nsdecls("c", "a")
txPr = parse_xml(xml)
return txPr
|
Return a `c:txPr` element tree.
Suitable for use in a chart object like data labels or tick labels.
|
new_txPr
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def autofit(self):
"""The autofit setting for the text frame, a member of the `MSO_AUTO_SIZE` enumeration."""
if self.noAutofit is not None:
return MSO_AUTO_SIZE.NONE
if self.normAutofit is not None:
return MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE
if self.spAutoFit is not None:
return MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT
return None
|
The autofit setting for the text frame, a member of the `MSO_AUTO_SIZE` enumeration.
|
autofit
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def add_hlinkClick(self, rId: str) -> CT_Hyperlink:
"""Add an `a:hlinkClick` child element with r:id attribute set to `rId`."""
hlinkClick = self.get_or_add_hlinkClick()
hlinkClick.rId = rId
return hlinkClick
|
Add an `a:hlinkClick` child element with r:id attribute set to `rId`.
|
add_hlinkClick
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def text(self) -> str: # pyright: ignore[reportIncompatibleMethodOverride]
"""The text of the `a:t` child element."""
t = self.t
if t is None:
return ""
return t.text or ""
|
The text of the `a:t` child element.
|
text
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def content_children(self) -> tuple[CT_RegularTextRun | CT_TextLineBreak | CT_TextField, ...]:
"""Sequence containing text-container child elements of this `a:p` element.
These include `a:r`, `a:br`, and `a:fld`.
"""
return tuple(
e for e in self if isinstance(e, (CT_RegularTextRun, CT_TextLineBreak, CT_TextField))
)
|
Sequence containing text-container child elements of this `a:p` element.
These include `a:r`, `a:br`, and `a:fld`.
|
content_children
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def text(self) -> str: # pyright: ignore[reportIncompatibleMethodOverride]
"""str text contained in this paragraph."""
# ---note this shadows the lxml _Element.text---
return "".join([child.text for child in self.content_children])
|
str text contained in this paragraph.
|
text
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def line_spacing(self) -> float | Length | None:
"""The spacing between baselines of successive lines in this paragraph.
A float value indicates a number of lines. A |Length| value indicates a fixed spacing.
Value is contained in `./a:lnSpc/a:spcPts/@val` or `./a:lnSpc/a:spcPct/@val`. Value is
|None| if no element is present.
"""
lnSpc = self.lnSpc
if lnSpc is None:
return None
if lnSpc.spcPts is not None:
return lnSpc.spcPts.val
return cast(CT_TextSpacingPercent, lnSpc.spcPct).val
|
The spacing between baselines of successive lines in this paragraph.
A float value indicates a number of lines. A |Length| value indicates a fixed spacing.
Value is contained in `./a:lnSpc/a:spcPts/@val` or `./a:lnSpc/a:spcPct/@val`. Value is
|None| if no element is present.
|
line_spacing
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def space_after(self) -> Length | None:
"""The EMU equivalent of the centipoints value in `./a:spcAft/a:spcPts/@val`."""
spcAft = self.spcAft
if spcAft is None:
return None
spcPts = spcAft.spcPts
if spcPts is None:
return None
return spcPts.val
|
The EMU equivalent of the centipoints value in `./a:spcAft/a:spcPts/@val`.
|
space_after
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def space_before(self):
"""The EMU equivalent of the centipoints value in `./a:spcBef/a:spcPts/@val`."""
spcBef = self.spcBef
if spcBef is None:
return None
spcPts = spcBef.spcPts
if spcPts is None:
return None
return spcPts.val
|
The EMU equivalent of the centipoints value in `./a:spcBef/a:spcPts/@val`.
|
space_before
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def set_spcPct(self, value: float):
"""Set spacing to `value` lines, e.g. 1.75 lines.
A ./a:spcPts child is removed if present.
"""
self._remove_spcPts()
spcPct = self.get_or_add_spcPct()
spcPct.val = value
|
Set spacing to `value` lines, e.g. 1.75 lines.
A ./a:spcPts child is removed if present.
|
set_spcPct
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def set_spcPts(self, value: Length):
"""Set spacing to `value` points. A ./a:spcPct child is removed if present."""
self._remove_spcPct()
spcPts = self.get_or_add_spcPts()
spcPts.val = value
|
Set spacing to `value` points. A ./a:spcPct child is removed if present.
|
set_spcPts
|
python
|
scanny/python-pptx
|
src/pptx/oxml/text.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/text.py
|
MIT
|
def OxmlElement(nsptag_str: str, nsmap: dict[str, str] | None = None) -> BaseOxmlElement:
"""Return a "loose" lxml element having the tag specified by `nsptag_str`.
`nsptag_str` must contain the standard namespace prefix, e.g. 'a:tbl'. The resulting element is
an instance of the custom element class for this tag name if one is defined.
"""
nsptag = NamespacePrefixedTag(nsptag_str)
nsmap = nsmap if nsmap is not None else nsptag.nsmap
return oxml_parser.makeelement(nsptag.clark_name, nsmap=nsmap)
|
Return a "loose" lxml element having the tag specified by `nsptag_str`.
`nsptag_str` must contain the standard namespace prefix, e.g. 'a:tbl'. The resulting element is
an instance of the custom element class for this tag name if one is defined.
|
OxmlElement
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _attr_seq(self, attrs: str) -> list[str]:
"""Return a sequence of attribute strings parsed from *attrs*.
Each attribute string is stripped of whitespace on both ends.
"""
attrs = attrs.strip()
attr_lst = attrs.split()
return sorted(attr_lst)
|
Return a sequence of attribute strings parsed from *attrs*.
Each attribute string is stripped of whitespace on both ends.
|
_attr_seq
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _eq_elm_strs(self, line: str, line_2: str) -> bool:
"""True if the element in `line_2` is XML-equivalent to the element in `line`.
In particular, the order of attributes in XML is not significant.
"""
front, attrs, close, text = self._parse_line(line)
front_2, attrs_2, close_2, text_2 = self._parse_line(line_2)
if front != front_2:
return False
if self._attr_seq(attrs) != self._attr_seq(attrs_2):
return False
if close != close_2:
return False
if text != text_2:
return False
return True
|
True if the element in `line_2` is XML-equivalent to the element in `line`.
In particular, the order of attributes in XML is not significant.
|
_eq_elm_strs
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _parse_line(self, line: str):
"""Return front, attrs, close, text 4-tuple result of parsing XML element string `line`."""
match = self._xml_elm_line_patt.match(line)
if match is None:
raise ValueError("`line` does not match pattern for an XML element")
front, attrs, close, text = [match.group(n) for n in range(1, 5)]
return front, attrs, close, text
|
Return front, attrs, close, text 4-tuple result of parsing XML element string `line`.
|
_parse_line
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _add_attr_property(self):
"""Add a read/write `{prop_name}` property to the element class.
The property returns the interpreted value of this attribute on access and changes the
attribute value to its ST_* counterpart on assignment.
"""
property_ = property(self._getter, self._setter, None)
# assign unconditionally to overwrite element name definition
setattr(self._element_cls, self._prop_name, property_)
|
Add a read/write `{prop_name}` property to the element class.
The property returns the interpreted value of this attribute on access and changes the
attribute value to its ST_* counterpart on assignment.
|
_add_attr_property
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _docstring(self):
"""
Return the string to use as the ``__doc__`` attribute of the property
for this attribute.
"""
return (
"%s type-converted value of ``%s`` attribute, or |None| (or spec"
"ified default value) if not present. Assigning the default valu"
"e causes the attribute to be removed from the element."
% (self._simple_type.__name__, self._attr_name)
)
|
Return the string to use as the ``__doc__`` attribute of the property
for this attribute.
|
_docstring
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _getter(self) -> Callable[[BaseOxmlElement], Any]:
"""Callable suitable for the "get" side of the attribute property descriptor."""
def get_attr_value(obj: BaseOxmlElement) -> Any:
attr_str_value = obj.get(self._clark_name)
if attr_str_value is None:
return self._default
return self._simple_type.from_xml(attr_str_value)
get_attr_value.__doc__ = self._docstring
return get_attr_value
|
Callable suitable for the "get" side of the attribute property descriptor.
|
_getter
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _setter(self) -> Callable[[BaseOxmlElement, Any], None]:
"""Callable suitable for the "set" side of the attribute property descriptor."""
def set_attr_value(obj: BaseOxmlElement, value: Any) -> None:
# -- when an XML attribute has a default value, setting it to that default removes the
# -- attribute from the element (when it is present)
if value == self._default:
if self._clark_name in obj.attrib:
del obj.attrib[self._clark_name]
return
str_value = self._simple_type.to_xml(value)
obj.set(self._clark_name, str_value)
return set_attr_value
|
Callable suitable for the "set" side of the attribute property descriptor.
|
_setter
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _getter(self) -> Callable[[BaseOxmlElement], Any]:
"""Callable suitable for the "get" side of the attribute property descriptor."""
def get_attr_value(obj: BaseOxmlElement) -> Any:
attr_str_value = obj.get(self._clark_name)
if attr_str_value is None:
raise InvalidXmlError(
"required '%s' attribute not present on element %s" % (self._attr_name, obj.tag)
)
return self._simple_type.from_xml(attr_str_value)
get_attr_value.__doc__ = self._docstring
return get_attr_value
|
Callable suitable for the "get" side of the attribute property descriptor.
|
_getter
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _docstring(self):
"""
Return the string to use as the ``__doc__`` attribute of the property
for this attribute.
"""
return "%s type-converted value of ``%s`` attribute." % (
self._simple_type.__name__,
self._attr_name,
)
|
Return the string to use as the ``__doc__`` attribute of the property
for this attribute.
|
_docstring
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _setter(self) -> Callable[[BaseOxmlElement, Any], None]:
"""Callable suitable for the "set" side of the attribute property descriptor."""
def set_attr_value(obj: BaseOxmlElement, value: Any) -> None:
str_value = self._simple_type.to_xml(value)
obj.set(self._clark_name, str_value)
return set_attr_value
|
Callable suitable for the "set" side of the attribute property descriptor.
|
_setter
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str):
"""Baseline behavior for adding the appropriate methods to `element_cls`."""
self._element_cls = element_cls
self._prop_name = prop_name
|
Baseline behavior for adding the appropriate methods to `element_cls`.
|
populate_class_members
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
def _add_adder(self):
"""Add an ``_add_x()`` method to the element class for this child element."""
def _add_child(obj: BaseOxmlElement, **attrs: Any):
new_method = getattr(obj, self._new_method_name)
child = new_method()
for key, value in attrs.items():
setattr(child, key, value)
insert_method = getattr(obj, self._insert_method_name)
insert_method(child)
return child
_add_child.__doc__ = (
"Add a new ``<%s>`` child element unconditionally, inserted in t"
"he correct sequence." % self._nsptagname
)
self._add_to_class(self._add_method_name, _add_child)
|
Add an ``_add_x()`` method to the element class for this child element.
|
_add_adder
|
python
|
scanny/python-pptx
|
src/pptx/oxml/xmlchemy.py
|
https://github.com/scanny/python-pptx/blob/master/src/pptx/oxml/xmlchemy.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.