Skip to content

Styles

Representation of the “styles.xml” part.

Classes:

Name Description
Styles

Representation of the “styles.xml” part of an ODF document.

Attributes:

Name Type Description
CONTEXT_MAPPING

CONTEXT_MAPPING module-attribute

CONTEXT_MAPPING = {
    "paragraph": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "text": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "graphic": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "page-layout": ("//office:automatic-styles",),
    "master-page": ("//office:master-styles",),
    "font-face": ("//office:font-face-decls",),
    "outline": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "date": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "list": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "presentation": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "drawing-page": ("//office:automatic-styles",),
    "presentation-page-layout": ("//office:styles",),
    "marker": ("//office:styles",),
    "fill-image": ("//office:styles",),
    "table": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "table-cell": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "table-row": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "table-column": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "section": (
        "//office:styles",
        "//office:automatic-styles",
    ),
    "chart": (
        "//office:styles",
        "//office:automatic-styles",
    ),
}

Styles

Bases: XmlPart

Representation of the “styles.xml” part of an ODF document.

This class provides an interface to the styles defined in the “styles.xml” part of an ODF document, which includes automatic styles, master styles, and default styles.

Methods:

Name Description
get_master_page

Get a master page by its position.

get_style

Return the style uniquely identified by its family and name.

get_styles

Return the list of styles in the Styles part.

set_default_styles_language_country

Set the default language and country in styles.

Attributes:

Name Type Description
default_language str

Get or set the default language from styles, in “en-US” format.

default_styles list[StyleBase]

Return the list of default styles (“style:default-style”).

master_pages list[StyleMasterPage]

Get the list of master pages.

office_automatic_styles OfficeAutomaticStyles | None

Get or set the “office:automatic-styles” element.

office_master_styles OfficeMasterStyles | None

Get or set the “office:master-styles” element.

Source code in odfdo/styles.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
class Styles(XmlPart):
    """Representation of the "styles.xml" part of an ODF document.

    This class provides an interface to the styles defined in the "styles.xml"
    part of an ODF document, which includes automatic styles, master styles,
    and default styles.
    """

    def _get_style_contexts(
        self, family: str, automatic: bool = False
    ) -> list[Element]:
        """Get the XML contexts where styles are stored.

        Args:
            family: The style family to search for.
            automatic: Whether to only search in automatic styles.

        Returns:
            list[Element]: A list of XML elements that are contexts for styles.
        """
        if automatic:
            elems = [self.get_element("//office:automatic-styles")]
        elif family:
            queries = CONTEXT_MAPPING.get(family) or (
                "//office:styles",
                "//office:automatic-styles",
            )
            elems = [self.get_element(query) for query in queries]
        else:
            # All possibilities
            elems = [
                self.get_element("//office:automatic-styles"),
                self.get_element("//office:styles"),
                self.get_element("//office:master-styles"),
                self.get_element("//office:font-face-decls"),
            ]
        return [e for e in elems if isinstance(e, Element)]

    def get_styles(
        self, family: str = "", automatic: bool = False
    ) -> list[StyleBase | DrawFillImage | DrawMarker]:
        """Return the list of styles in the Styles part.

        Optionally, the results can be limited to a specific family and/or
        to automatic styles.

        Args:
            family: The style family to filter by (e.g.,
                'paragraph', 'text').
            automatic: If True, only automatic styles are
                returned. Defaults to False.

        Returns:
            list[StyleBase|DrawFillImage|DrawMarker]: A list of style-like
            instances matching the criteria..
        """
        result = []
        for context in self._get_style_contexts(family, automatic=automatic):
            if context is None:  # pragma: nocover
                continue
            # print('-ctx----', automatic)
            # print(context.tag)
            # print(context.__class__)
            # print(context.serialize())
            result.extend(context.get_styles(family=family))
        return result

    @property
    def default_styles(self) -> list[StyleBase]:
        """Return the list of default styles ("style:default-style").

        Returns:
            list[StyleBase]: A list of default Style elements.
        """
        return cast(list[StyleBase], self.get_elements("//style:default-style"))

    def set_default_styles_language_country(self, value: str) -> None:
        """Set the default language and country in styles.

        Args:
            value: The language/country code in RFC3066 format (e.g., "en-US").

        Raises:
            TypeError: If the language code format is invalid.
        """
        language = str(value)
        if not is_RFC3066(language):
            msg = 'Language must be "xx" lang or "xx-YY" lang-COUNTRY code (RFC3066)'
            raise TypeError(msg)
        lc = language.split("-")
        if len(lc) == 2:
            lang, country = lc
        else:
            lang = lc[0]
            country = ""
        styles = [
            s for s in self.default_styles if s.family in {"graphic", "paragraph"}
        ]
        for style in styles:
            style.set_properties(area="text", language=lang, country=country)

    @property
    def default_language(self) -> str:
        """Get or set the default language from styles, in "en-US" format."""
        styles = [s for s in self.default_styles if s.family == "paragraph"]
        if not styles:
            return ""
        style = styles[0]
        props = style.get_properties(area="text") or {}
        lang = str(props.get("fo:language", ""))
        country = str(props.get("fo:country", ""))
        if lang and country:
            return f"{lang}-{country}"
        return lang or country

    @default_language.setter
    def default_language(self, value: str) -> None:
        return self.set_default_styles_language_country(value)

    def get_style(
        self,
        family: str,
        name_or_element: str | StyleBase | None = None,
        display_name: str | None = None,
    ) -> StyleBase | DrawFillImage | DrawMarker | None:
        """Return the style uniquely identified by its family and name.

        If the `name_or_element` argument is already a Style object, it will be
        returned. If `name_or_element` is None, the default style for the given
        family is fetched. If the name provided is a display name, use the
        `display_name` argument instead.

        Args:
            family: The style family (e.g., 'paragraph', 'text', 'graphic').
            name_or_element: The internal name of the
                style or a Style object itself.
            display_name: The display name of the style as seen in an
                office application.

        Returns:
            StyleBase | DrawFillImage | DrawMarker | None: A style-like
                instance, or None if not found.
        """
        for context in self._get_style_contexts(family):
            if context is None:
                continue  # pragma: nocover
            style = context.get_style(
                family,
                name_or_element=name_or_element,
                display_name=display_name,
            )
            if style is not None:
                return style
        return None

    @property
    def office_master_styles(self) -> OfficeMasterStyles | None:
        """Get or set the "office:master-styles" element.

        Returns:
            OfficeMasterStyles | None: The "office:master-styles" element, or None if not found.
        """
        return cast(
            None | OfficeMasterStyles, self.get_element("//office:master-styles")
        )

    @office_master_styles.setter
    def office_master_styles(self, office_master_styles: OfficeMasterStyles) -> None:
        """Set the "office:master-styles" element.

        Args:
            office_master_styles: The "office:master-styles" element to set.
        """
        current = self.office_master_styles
        if isinstance(current, OfficeMasterStyles):
            current.delete()
        self.root.append(office_master_styles)

    @property
    def master_pages(self) -> list[StyleMasterPage]:
        """Get the list of master pages.

        Returns:
            list[StyleMasterPage]: A list of StyleMasterPage elements.
        """
        master_styles = self.office_master_styles
        if master_styles is None:
            return []
        return [
            e  # type: ignore[misc]
            for e in master_styles.children
            if isinstance(e, StyleBase) and e.tag == "style:master-page"
        ]

    def get_master_page(self, position: int = 0) -> StyleMasterPage | None:
        """Get a master page by its position.

        Args:
            position: The position (index) of the master page. Defaults to 0.

        Returns:
            StyleMasterPage | None: The StyleMasterPage element at the given position,
            or None if not found.
        """
        results = self.master_pages
        try:
            return results[position]
        except IndexError:
            return None

    @property
    def office_automatic_styles(self) -> OfficeAutomaticStyles | None:
        """Get or set the "office:automatic-styles" element.

        Returns:
            OfficeAutomaticStyles | None: The "office:automatic-styles" element,
            or None if not found.
        """
        return cast(
            None | OfficeAutomaticStyles,
            self.get_element("//office:automatic-styles"),
        )

    @office_automatic_styles.setter
    def office_automatic_styles(
        self, office_automatic_styles: OfficeAutomaticStyles
    ) -> None:
        """Set the "office:automatic-styles" element.

        Args:
            office_automatic_styles: The "office:automatic-styles"
                element to set.
        """
        current = self.office_automatic_styles
        if isinstance(current, OfficeAutomaticStyles):
            current.delete()
        self.root.append(office_automatic_styles)

default_language property writable

default_language: str

Get or set the default language from styles, in “en-US” format.

default_styles property

default_styles: list[StyleBase]

Return the list of default styles (“style:default-style”).

Returns:

Type Description
list[StyleBase]

list[StyleBase]: A list of default Style elements.

master_pages property

master_pages: list[StyleMasterPage]

Get the list of master pages.

Returns:

Type Description
list[StyleMasterPage]

list[StyleMasterPage]: A list of StyleMasterPage elements.

office_automatic_styles property writable

office_automatic_styles: OfficeAutomaticStyles | None

Get or set the “office:automatic-styles” element.

Returns:

Type Description
OfficeAutomaticStyles | None

OfficeAutomaticStyles | None: The “office:automatic-styles” element,

OfficeAutomaticStyles | None

or None if not found.

office_master_styles property writable

office_master_styles: OfficeMasterStyles | None

Get or set the “office:master-styles” element.

Returns:

Type Description
OfficeMasterStyles | None

OfficeMasterStyles | None: The “office:master-styles” element, or None if not found.

_get_style_contexts

_get_style_contexts(
    family: str, automatic: bool = False
) -> list[Element]

Get the XML contexts where styles are stored.

Parameters:

Name Type Description Default
family str

The style family to search for.

required
automatic bool

Whether to only search in automatic styles.

False

Returns:

Type Description
list[Element]

list[Element]: A list of XML elements that are contexts for styles.

Source code in odfdo/styles.py
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def _get_style_contexts(
    self, family: str, automatic: bool = False
) -> list[Element]:
    """Get the XML contexts where styles are stored.

    Args:
        family: The style family to search for.
        automatic: Whether to only search in automatic styles.

    Returns:
        list[Element]: A list of XML elements that are contexts for styles.
    """
    if automatic:
        elems = [self.get_element("//office:automatic-styles")]
    elif family:
        queries = CONTEXT_MAPPING.get(family) or (
            "//office:styles",
            "//office:automatic-styles",
        )
        elems = [self.get_element(query) for query in queries]
    else:
        # All possibilities
        elems = [
            self.get_element("//office:automatic-styles"),
            self.get_element("//office:styles"),
            self.get_element("//office:master-styles"),
            self.get_element("//office:font-face-decls"),
        ]
    return [e for e in elems if isinstance(e, Element)]

get_master_page

get_master_page(
    position: int = 0,
) -> StyleMasterPage | None

Get a master page by its position.

Parameters:

Name Type Description Default
position int

The position (index) of the master page. Defaults to 0.

0

Returns:

Type Description
StyleMasterPage | None

StyleMasterPage | None: The StyleMasterPage element at the given position,

StyleMasterPage | None

or None if not found.

Source code in odfdo/styles.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def get_master_page(self, position: int = 0) -> StyleMasterPage | None:
    """Get a master page by its position.

    Args:
        position: The position (index) of the master page. Defaults to 0.

    Returns:
        StyleMasterPage | None: The StyleMasterPage element at the given position,
        or None if not found.
    """
    results = self.master_pages
    try:
        return results[position]
    except IndexError:
        return None

get_style

get_style(
    family: str,
    name_or_element: str | StyleBase | None = None,
    display_name: str | None = None,
) -> StyleBase | DrawFillImage | DrawMarker | None

Return the style uniquely identified by its family and name.

If the name_or_element argument is already a Style object, it will be returned. If name_or_element is None, the default style for the given family is fetched. If the name provided is a display name, use the display_name argument instead.

Parameters:

Name Type Description Default
family str

The style family (e.g., ‘paragraph’, ‘text’, ‘graphic’).

required
name_or_element str | StyleBase | None

The internal name of the style or a Style object itself.

None
display_name str | None

The display name of the style as seen in an office application.

None

Returns:

Type Description
StyleBase | DrawFillImage | DrawMarker | None

StyleBase | DrawFillImage | DrawMarker | None: A style-like instance, or None if not found.

Source code in odfdo/styles.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def get_style(
    self,
    family: str,
    name_or_element: str | StyleBase | None = None,
    display_name: str | None = None,
) -> StyleBase | DrawFillImage | DrawMarker | None:
    """Return the style uniquely identified by its family and name.

    If the `name_or_element` argument is already a Style object, it will be
    returned. If `name_or_element` is None, the default style for the given
    family is fetched. If the name provided is a display name, use the
    `display_name` argument instead.

    Args:
        family: The style family (e.g., 'paragraph', 'text', 'graphic').
        name_or_element: The internal name of the
            style or a Style object itself.
        display_name: The display name of the style as seen in an
            office application.

    Returns:
        StyleBase | DrawFillImage | DrawMarker | None: A style-like
            instance, or None if not found.
    """
    for context in self._get_style_contexts(family):
        if context is None:
            continue  # pragma: nocover
        style = context.get_style(
            family,
            name_or_element=name_or_element,
            display_name=display_name,
        )
        if style is not None:
            return style
    return None

get_styles

get_styles(
    family: str = "", automatic: bool = False
) -> list[StyleBase | DrawFillImage | DrawMarker]

Return the list of styles in the Styles part.

Optionally, the results can be limited to a specific family and/or to automatic styles.

Parameters:

Name Type Description Default
family str

The style family to filter by (e.g., ‘paragraph’, ‘text’).

''
automatic bool

If True, only automatic styles are returned. Defaults to False.

False

Returns:

Type Description
list[StyleBase | DrawFillImage | DrawMarker]

list[StyleBase|DrawFillImage|DrawMarker]: A list of style-like

list[StyleBase | DrawFillImage | DrawMarker]

instances matching the criteria..

Source code in odfdo/styles.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def get_styles(
    self, family: str = "", automatic: bool = False
) -> list[StyleBase | DrawFillImage | DrawMarker]:
    """Return the list of styles in the Styles part.

    Optionally, the results can be limited to a specific family and/or
    to automatic styles.

    Args:
        family: The style family to filter by (e.g.,
            'paragraph', 'text').
        automatic: If True, only automatic styles are
            returned. Defaults to False.

    Returns:
        list[StyleBase|DrawFillImage|DrawMarker]: A list of style-like
        instances matching the criteria..
    """
    result = []
    for context in self._get_style_contexts(family, automatic=automatic):
        if context is None:  # pragma: nocover
            continue
        # print('-ctx----', automatic)
        # print(context.tag)
        # print(context.__class__)
        # print(context.serialize())
        result.extend(context.get_styles(family=family))
    return result

set_default_styles_language_country

set_default_styles_language_country(value: str) -> None

Set the default language and country in styles.

Parameters:

Name Type Description Default
value str

The language/country code in RFC3066 format (e.g., “en-US”).

required

Raises:

Type Description
TypeError

If the language code format is invalid.

Source code in odfdo/styles.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def set_default_styles_language_country(self, value: str) -> None:
    """Set the default language and country in styles.

    Args:
        value: The language/country code in RFC3066 format (e.g., "en-US").

    Raises:
        TypeError: If the language code format is invalid.
    """
    language = str(value)
    if not is_RFC3066(language):
        msg = 'Language must be "xx" lang or "xx-YY" lang-COUNTRY code (RFC3066)'
        raise TypeError(msg)
    lc = language.split("-")
    if len(lc) == 2:
        lang, country = lc
    else:
        lang = lc[0]
        country = ""
    styles = [
        s for s in self.default_styles if s.family in {"graphic", "paragraph"}
    ]
    for style in styles:
        style.set_properties(area="text", language=lang, country=country)