|
From: <mi...@us...> - 2024-10-20 18:57:53
|
Revision: 9955
http://sourceforge.net/p/docutils/code/9955
Author: milde
Date: 2024-10-20 18:57:49 +0000 (Sun, 20 Oct 2024)
Log Message:
-----------
Small fixes and additions.
Be more specific in FAQ answer.
Don't list minor fix (bug #287) in HISTORY.
Shorten some docstrings to adhere to documentation policy
(multi-line docstrings should be summary line, blank line, details).
Better name for function factory that returns a keyword validating function.
(cf. https://stackoverflow.com/questions/3368830/how-to-name-factory-like-methods).
Fix attribute name mismatch "autonum" -> "auto".
Explain F401 noqa comment.
Fix typo in "writers/html5_polyglot/minimal.css" stylesheet.
Avoid confusing variable name ``twidth`` in latex writer.
Modified Paths:
--------------
trunk/docutils/FAQ.rst
trunk/docutils/HISTORY.rst
trunk/docutils/docutils/nodes.py
trunk/docutils/docutils/transforms/parts.py
trunk/docutils/docutils/utils/__init__.py
trunk/docutils/docutils/writers/html5_polyglot/minimal.css
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/test/functional/tests/standalone_rst_docutils_xml.py
trunk/docutils/test/test_nodes.py
Modified: trunk/docutils/FAQ.rst
===================================================================
--- trunk/docutils/FAQ.rst 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/FAQ.rst 2024-10-20 18:57:49 UTC (rev 9955)
@@ -1051,8 +1051,8 @@
Why do enumerated lists only use numbers (no letters or roman numerals)?
------------------------------------------------------------------------
-The rendering of enumerators (the numbers or letters acting as list
-markers) is completely governed by the stylesheet, so either the
+In HTML, the rendering of enumerators (the numbers or letters acting as
+list markers) is completely governed by the stylesheet, so either the
browser can't find the stylesheet (try enabling the
`embed_stylesheet`_ setting [``--embed-stylesheet`` option]), or the
browser can't understand it (try a not too old Firefox, Chrome, Opera,
Modified: trunk/docutils/HISTORY.rst
===================================================================
--- trunk/docutils/HISTORY.rst 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/HISTORY.rst 2024-10-20 18:57:49 UTC (rev 9955)
@@ -29,8 +29,6 @@
Python >= 3.10 is required with active type hints
(``typing.TYPE_CHECKING == True``).
- - Fix license issue (bug #487).
-
* docs/ref/docutils.dtd
- Allow multiple <term> elements in a <definition_list_item>.
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/docutils/nodes.py 2024-10-20 18:57:49 UTC (rev 9955)
@@ -1772,8 +1772,7 @@
"""Mapping of substitution names to substitution_definition nodes."""
self.substitution_names: dict[str, str] = {}
- """Mapping of case-normalized substitution names to case-sensitive
- names."""
+ """Mapping of case-normalized to case-sensitive substitution names."""
self.refnames: dict[str, list[Element]] = {}
"""Mapping of names to lists of referencing nodes."""
@@ -1785,8 +1784,8 @@
"""Mapping of names to unique id's."""
self.nametypes: dict[str, bool] = {}
- """Mapping of names to hyperlink type (boolean: True => explicit,
- False => implicit."""
+ """Mapping of names to hyperlink type. True: explicit, False: implicit.
+ """
self.ids: dict[str, Element] = {}
"""Mapping of ids to nodes."""
@@ -3112,7 +3111,7 @@
# __ https://docutils.sourceforge.io/docs/ref/doctree.html#attribute-reference
# __ https://docutils.sourceforge.io/docs/ref/doctree.html#attribute-types
-def validate_enumerated_type(*keywords: str) -> Callable[[str], str]:
+def create_keyword_validator(*keywords: str) -> Callable[[str], str]:
"""
Return a function that validates a `str` against given `keywords`.
@@ -3248,12 +3247,12 @@
'colwidth': int, # sic! CALS: CDATA (measure or number+'*')
'content': str, # <meta>
'delimiter': str,
- 'dir': validate_enumerated_type('ltr', 'rtl', 'auto'), # <meta>
+ 'dir': create_keyword_validator('ltr', 'rtl', 'auto'), # <meta>
'dupnames': validate_refname_list,
- 'enumtype': validate_enumerated_type('arabic', 'loweralpha', 'lowerroman',
+ 'enumtype': create_keyword_validator('arabic', 'loweralpha', 'lowerroman',
'upperalpha', 'upperroman'),
'format': str, # CDATA (space separated format names)
- 'frame': validate_enumerated_type('top', 'bottom', 'topbot', 'all',
+ 'frame': create_keyword_validator('top', 'bottom', 'topbot', 'all',
'sides', 'none'), # from CALS, ignored
'height': validate_measure,
'http-equiv': str, # <meta>
@@ -3262,7 +3261,7 @@
'level': int,
'line': int,
'ltrim': validate_yesorno,
- 'loading': validate_enumerated_type('embed', 'link', 'lazy'),
+ 'loading': create_keyword_validator('embed', 'link', 'lazy'),
'media': str, # <meta>
'morecols': int,
'morerows': int,
@@ -3287,9 +3286,9 @@
'title': str,
'type': validate_NMTOKEN,
'uri': str,
- 'valign': validate_enumerated_type('top', 'middle', 'bottom'), # from CALS
+ 'valign': create_keyword_validator('top', 'middle', 'bottom'), # from CALS
'width': validate_measure,
- 'xml:space': validate_enumerated_type('default', 'preserve'),
+ 'xml:space': create_keyword_validator('default', 'preserve'),
}
"""
Mapping of `attribute names`__ to validating functions.
Modified: trunk/docutils/docutils/transforms/parts.py
===================================================================
--- trunk/docutils/docutils/transforms/parts.py 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/docutils/transforms/parts.py 2024-10-20 18:57:49 UTC (rev 9955)
@@ -20,7 +20,7 @@
Automatically assigns numbers to the titles of document sections.
It is possible to limit the maximum section level for which the numbers
- are added. For those sections that are auto-numbered, the "autonum"
+ are added. For those sections that are auto-numbered, the "auto"
attribute is set, informing the contents table generator that a different
form of the TOC should be used.
"""
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/docutils/utils/__init__.py 2024-10-20 18:57:49 UTC (rev 9955)
@@ -23,7 +23,7 @@
from docutils import ApplicationError, DataError
from docutils import io, nodes
# for backwards compatibility
-from docutils.nodes import unescape # noqa: F401
+from docutils.nodes import unescape # noqa: F401 (imported but unused)
if TYPE_CHECKING:
from collections.abc import Callable, Sequence, Iterable
Modified: trunk/docutils/docutils/writers/html5_polyglot/minimal.css
===================================================================
--- trunk/docutils/docutils/writers/html5_polyglot/minimal.css 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/docutils/writers/html5_polyglot/minimal.css 2024-10-20 18:57:49 UTC (rev 9955)
@@ -1,4 +1,4 @@
-t/* Minimal style sheet for the HTML output of Docutils. */
+/* Minimal style sheet for the HTML output of Docutils. */
/* */
/* :Author: Günter Milde, based on html4css1.css by David Goodger */
/* :Id: $Id$ */
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-10-20 18:57:49 UTC (rev 9955)
@@ -1067,8 +1067,8 @@
n_c = len(self._col_specs)
a.append('\\endhead\n')
# footer on all but last page (if it fits):
- twidth = sum(node['colwidth']+2 for node in self._col_specs)
- if twidth > 30 or (twidth > 12 and not self.colwidths_auto):
+ t_width = sum(node['colwidth']+2 for node in self._col_specs)
+ if t_width > 30 or (t_width > 12 and not self.colwidths_auto):
a.append(r'\multicolumn{%d}{%s}'
% (n_c, self.get_multicolumn_width(0, n_c))
+ r'{\raggedleft\ldots continued on next page}\\'
Modified: trunk/docutils/test/functional/tests/standalone_rst_docutils_xml.py
===================================================================
--- trunk/docutils/test/functional/tests/standalone_rst_docutils_xml.py 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/test/functional/tests/standalone_rst_docutils_xml.py 2024-10-20 18:57:49 UTC (rev 9955)
@@ -6,7 +6,6 @@
writer = "docutils_xml"
settings_overrides = {
'sectsubtitle_xform': True,
- # format output with indents and newlines
- 'indents': True,
+ 'indents': True, # format output with indents and newlines
'validate': True, # check conformance to Docutils Generic DTD
}
Modified: trunk/docutils/test/test_nodes.py
===================================================================
--- trunk/docutils/test/test_nodes.py 2024-10-20 17:47:14 UTC (rev 9954)
+++ trunk/docutils/test/test_nodes.py 2024-10-20 18:57:49 UTC (rev 9955)
@@ -1140,9 +1140,9 @@
__ https://docutils.sourceforge.io/docs/ref/doctree.html#attribute-types
"""
- def test_validate_enumerated_type(self):
+ def test_create_keyword_validator(self):
# function factory for "choice validators"
- food = nodes.validate_enumerated_type('ham', 'spam')
+ food = nodes.create_keyword_validator('ham', 'spam')
self.assertEqual(food('ham'), 'ham')
with self.assertRaisesRegex(ValueError,
'"bacon" is not one of "ham", "spam".'):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <gr...@us...> - 2024-10-21 20:48:55
|
Revision: 9960
http://sourceforge.net/p/docutils/code/9960
Author: grubert
Date: 2024-10-21 20:48:53 +0000 (Mon, 21 Oct 2024)
Log Message:
-----------
manpage image handling redo
Modified Paths:
--------------
trunk/docutils/docutils/writers/manpage.py
trunk/docutils/test/test_writers/test_manpage.py
Modified: trunk/docutils/docutils/writers/manpage.py
===================================================================
--- trunk/docutils/docutils/writers/manpage.py 2024-10-21 19:26:26 UTC (rev 9959)
+++ trunk/docutils/docutils/writers/manpage.py 2024-10-21 20:48:53 UTC (rev 9960)
@@ -822,14 +822,20 @@
self.body.append('\n')
def visit_image(self, node):
- self.document.reporter.warning('"image" not supported',
+ msg = '"image" not supported by "manpage" writer.'
+ if 'alt' in node.attributes:
+ self.document.reporter.info(msg,
+ base_node=node)
+ self.body.append('.sp\n %s\n' % (
+ node.attributes['alt']))
+ elif 'uri' in node.attributes:
+ self.body.append('.sp\n image: %s\n' % (
+ node.attributes['uri']))
+ self.document.reporter.warning(
+ f'''{msg}
+Please provide an "alt" attribute with textual replacement.''',
base_node=node)
- text = []
- if 'alt' in node.attributes:
- text.append(node.attributes['alt'])
- if 'uri' in node.attributes:
- text.append(node.attributes['uri'])
- self.body.append('[image: %s]\n' % ('/'.join(text)))
+ # else 0 arguments to image not allowed
raise nodes.SkipNode
def visit_important(self, node) -> None:
Modified: trunk/docutils/test/test_writers/test_manpage.py
===================================================================
--- trunk/docutils/test/test_writers/test_manpage.py 2024-10-21 19:26:26 UTC (rev 9959)
+++ trunk/docutils/test/test_writers/test_manpage.py 2024-10-21 20:48:53 UTC (rev 9960)
@@ -89,7 +89,7 @@
warnings.seek(0)
self.assertEqual(
case_warning,
- warnings.readline())
+ warnings.readlines())
@@ -587,7 +587,7 @@
# test defintion
# [ input, expect, expected_warning ]
totest_system_msgs ={}
-# TODO check we get an INFO not a WARNING
+# check we get an INFO not a WARNING
totest_system_msgs['image'] = [
["""\
text
@@ -601,29 +601,18 @@
.SH Name
\\- \n\
text
-[image: an image of something/gibsnich.png]
.sp
+ an image of something
+.sp
more text
.\\" End of generated man page.
""",
-"""\
-<string>:3: (WARNING/2) "image" not supported
-"""],
-# TODO make alt text a quote like
-#
-# text
-#
-# an image of something
-#
-# more text
-]
+[]
+# TODO check INFO text
+# INFO not in warning_stream #<string>:3: (INFO/1) "image" not supported\"""
+],
-# TODO check we get a WARNING
-#
-# (WARNING/2) "image" not supported by "manpage" writer.
-# Please provide an "alt" attribute with textual replacement.
-#
-totest_system_msgs['image-without-alt'] = [
+# check we get a WARNING if no alt text
["""text
.. image:: gibsnich.png
@@ -634,16 +623,16 @@
.SH Name
\\- \n\
text
-[image: gibsnich.png]
.sp
+ image: gibsnich.png
+.sp
more text
.\\" End of generated man page.
""",
-"""\
-<string>:3: (WARNING/2) "image" not supported
-"""],
-# TODO there should be nothing of the image in the manpage, might be decorative
+[ '<string>:3: (WARNING/2) "image" not supported by "manpage" writer.\n',
+'Please provide an "alt" attribute with textual replacement.\n']
]
+]
if __name__ == '__main__':
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-10-21 21:47:19
|
Revision: 9961
http://sourceforge.net/p/docutils/code/9961
Author: milde
Date: 2024-10-21 21:47:17 +0000 (Mon, 21 Oct 2024)
Log Message:
-----------
Store attribute values with datatype "yesorno" as `bool` values.
Use `bool` instead of `int` to store values of "yesorno" attributes in
Python doctree element instances.
This is the "natural" choice for "yesorno" and restores consistency
with the validating function `nodes.validate_yesorno()`.
In XML and pseudoxml output, the value is serialized as "0" or "1"
for backwards compatibility.
Modified Paths:
--------------
trunk/docutils/docs/ref/doctree.rst
trunk/docutils/docutils/nodes.py
trunk/docutils/docutils/parsers/rst/directives/tables.py
trunk/docutils/docutils/parsers/rst/states.py
Modified: trunk/docutils/docs/ref/doctree.rst
===================================================================
--- trunk/docutils/docs/ref/doctree.rst 2024-10-21 20:48:53 UTC (rev 9960)
+++ trunk/docutils/docs/ref/doctree.rst 2024-10-21 21:47:17 UTC (rev 9961)
@@ -4102,7 +4102,7 @@
Resolves to NMTOKEN_.
| Used in the anonymous_, colsep_, ltrim_, rtrim_, rowsep_,
and `stub`_ attributes.
- Python data type: ``int``.
+ Python data type: ``bool``.
__ ../index.html#introductory-tutorial-material-for-end-users
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-10-21 20:48:53 UTC (rev 9960)
+++ trunk/docutils/docutils/nodes.py 2024-10-21 21:47:17 UTC (rev 9961)
@@ -3205,7 +3205,14 @@
return [whitespace_normalize_name(name) for name in value]
-def validate_yesorno(value: bool | Literal['0', '1']) -> bool:
+def validate_yesorno(value: str | int | bool) -> bool:
+ """Validate a `%yesorno`__ (flag) value.
+
+ The string literal "0" evaluates to ``False``, all other
+ values are converterd with `bool()`.
+
+ __ https://docutils.sourceforge.io/docs/ref/doctree.html#yesorno
+ """
if value == "0":
return False
return bool(value)
Modified: trunk/docutils/docutils/parsers/rst/directives/tables.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/tables.py 2024-10-21 20:48:53 UTC (rev 9960)
+++ trunk/docutils/docutils/parsers/rst/directives/tables.py 2024-10-21 21:47:17 UTC (rev 9961)
@@ -501,7 +501,7 @@
if col_width is not None:
colspec.attributes['colwidth'] = col_width
if stub_columns:
- colspec.attributes['stub'] = 1
+ colspec.attributes['stub'] = True
stub_columns -= 1
tgroup += colspec
rows = []
Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py 2024-10-21 20:48:53 UTC (rev 9960)
+++ trunk/docutils/docutils/parsers/rst/states.py 2024-10-21 21:47:17 UTC (rev 9961)
@@ -861,7 +861,7 @@
elif target and (aliastype == 'uri'):
reference['refuri'] = alias
else:
- reference['anonymous'] = 1
+ reference['anonymous'] = True
else:
if target:
target['names'].append(refname)
@@ -929,7 +929,7 @@
reference_node = nodes.reference(
'|%s%s' % (subref_text, endstring), '')
if endstring[-2:] == '__':
- reference_node['anonymous'] = 1
+ reference_node['anonymous'] = True
else:
reference_node['refname'] = normalize_name(subref_text)
self.document.note_refname(reference_node)
@@ -980,7 +980,7 @@
name=whitespace_normalize_name(referencename))
referencenode[0].rawsource = referencename
if anonymous:
- referencenode['anonymous'] = 1
+ referencenode['anonymous'] = True
else:
referencenode['refname'] = refname
self.document.note_refname(referencenode)
@@ -1807,7 +1807,7 @@
for colwidth in colwidths:
colspec = nodes.colspec(colwidth=colwidth)
if stub_columns:
- colspec.attributes['stub'] = 1
+ colspec.attributes['stub'] = True
stub_columns -= 1
tgroup += colspec
if headrows:
@@ -2021,7 +2021,7 @@
else: # anonymous target
if refuri:
target['refuri'] = refuri
- target['anonymous'] = 1
+ target['anonymous'] = True
self.document.note_anonymous_target(target)
def substitution_def(self, match):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <gr...@us...> - 2024-10-22 16:45:29
|
Revision: 9962
http://sourceforge.net/p/docutils/code/9962
Author: grubert
Date: 2024-10-22 16:45:26 +0000 (Tue, 22 Oct 2024)
Log Message:
-----------
Fix formatting
Modified Paths:
--------------
trunk/docutils/docutils/writers/manpage.py
trunk/docutils/test/test_writers/test_manpage.py
Modified: trunk/docutils/docutils/writers/manpage.py
===================================================================
--- trunk/docutils/docutils/writers/manpage.py 2024-10-21 21:47:17 UTC (rev 9961)
+++ trunk/docutils/docutils/writers/manpage.py 2024-10-22 16:45:26 UTC (rev 9962)
@@ -832,9 +832,8 @@
self.body.append('.sp\n image: %s\n' % (
node.attributes['uri']))
self.document.reporter.warning(
- f'''{msg}
-Please provide an "alt" attribute with textual replacement.''',
- base_node=node)
+ f'{msg}\nPlease provide an "alt" attribute with textual'
+ ' replacement.', base_node=node)
# else 0 arguments to image not allowed
raise nodes.SkipNode
Modified: trunk/docutils/test/test_writers/test_manpage.py
===================================================================
--- trunk/docutils/test/test_writers/test_manpage.py 2024-10-21 21:47:17 UTC (rev 9961)
+++ trunk/docutils/test/test_writers/test_manpage.py 2024-10-22 16:45:26 UTC (rev 9962)
@@ -11,7 +11,6 @@
import sys
import unittest
from io import StringIO
-import docutils
if __name__ == '__main__':
# prepend the "docutils root" to the Python library path
@@ -92,7 +91,6 @@
warnings.readlines())
-
document_start = r""".\" Man page generated from reStructuredText by manpage writer
.\" from docutils 0.22b.dev.
.
@@ -586,7 +584,7 @@
# test defintion
# [ input, expect, expected_warning ]
-totest_system_msgs ={}
+totest_system_msgs = {}
# check we get an INFO not a WARNING
totest_system_msgs['image'] = [
["""\
@@ -629,7 +627,7 @@
more text
.\\" End of generated man page.
""",
-[ '<string>:3: (WARNING/2) "image" not supported by "manpage" writer.\n',
+['<string>:3: (WARNING/2) "image" not supported by "manpage" writer.\n',
'Please provide an "alt" attribute with textual replacement.\n']
]
]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-10-24 21:05:03
|
Revision: 9967
http://sourceforge.net/p/docutils/code/9967
Author: milde
Date: 2024-10-24 21:05:01 +0000 (Thu, 24 Oct 2024)
Log Message:
-----------
Start reconciling "colwidth" attribute definition and use.
First, backwards compatible changes get the handling of the
`<colspec>` element's "colwidth" attribute in line with the
definition in the Exchange Table Model.
The "colwidth" attribute is defined in the "Exchange Table Model"
as either a *proportional measure* or a *fixed measure*.
Currently, Docutils supports only unitless values and interpets them
as proportional measures while the Exchange Table Model interprets
unitless values as fixed measures with default unit {U+201C}pt{U+201D}!
The new optional argument "unit_pattern" for `nodes.parse_measure()`
allows configuring what is recognized as a unit.
The new validation function `nodes.validate_proportional()`
for the "colwidth" attribute also accepts conformant values like
"5.2*" (for 5.2 times the "unit proportion").
For backwards compatibility reasons, the attribute is still stored
as numerical value in Python doctree element instances.
New auxiliary method `nodes.colspec.propwith()`:
returns the "colwidth" attribute as number if it is a
proportional measure.
Announce future changes in the RELEASE_NOTES
Add/modify test cases.
Modified Paths:
--------------
trunk/docutils/RELEASE-NOTES.rst
trunk/docutils/docutils/nodes.py
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/html4css1/__init__.py
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/docutils/writers/odf_odt/__init__.py
trunk/docutils/test/test_nodes.py
trunk/docutils/test/test_parsers/test_docutils_xml/test_parse_element.py
Modified: trunk/docutils/RELEASE-NOTES.rst
===================================================================
--- trunk/docutils/RELEASE-NOTES.rst 2024-10-22 21:41:26 UTC (rev 9966)
+++ trunk/docutils/RELEASE-NOTES.rst 2024-10-24 21:05:01 UTC (rev 9967)
@@ -46,7 +46,7 @@
Document Tree / Docutils DTD
----------------------------
-* Do not lowercase reference names in the `refname attribute`_
+* Do not lowercase reference names in the `"refname" attribute`_
(matching hyperlinks, footnotes, and citations remains case insensitive),
and drop the ``name`` attribute from <reference> nodes
in Docutils 1.0.
@@ -57,8 +57,16 @@
* The <footnote> element's first child (<label>) will become mandatory
in Docutils 1.0.
-.. _refname attribute: docs/ref/doctree.html#refname
+* Values of the `"colwidth" attribute`_ will be stored in Python
+ element instances as `str` (with unit "*" for proportional values)
+ in Docutils 1.0. (The method `nodes.colspec.propwidth()` provides
+ a stable means to extract a proportionional value as number.)
+ The default unit will change to "pt" in Docutils 2.0.
+
+.. _"refname" attribute: docs/ref/doctree.html#refname
+.. _"colwidth" attribute: docs/ref/doctree.html#colwidth
+
Writers
-------
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-10-22 21:41:26 UTC (rev 9966)
+++ trunk/docutils/docutils/nodes.py 2024-10-24 21:05:01 UTC (rev 9967)
@@ -37,7 +37,6 @@
# import docutils.transforms # -> delayed import in document.__init__()
if TYPE_CHECKING:
- import numbers
from collections.abc import (Callable, Iterable, Iterator,
Mapping, Sequence)
from types import ModuleType
@@ -2414,7 +2413,20 @@
'align', 'char', 'charoff', 'colname', 'colnum',
'colsep', 'colwidth', 'rowsep', 'stub')
+ def propwidth(self) -> int|float:
+ """Return numerical value of "colwidth__" attribute. Default 1.
+ Raise ValueError if "colwidth" is zero, negative, or a *fixed value*.
+
+ Provisional.
+
+ __ https://docutils.sourceforge.io/docs/ref/doctree.html#colwidth
+ """
+ # Move current implementation of validate_colwidth() here
+ # in Docutils 1.0
+ return validate_colwidth(self.get('colwidth', ''))
+
+
class thead(Part, Element):
"""Row(s) that form the head of a `tgroup`."""
valid_attributes: Final = Element.valid_attributes + ('valign',)
@@ -3059,14 +3071,20 @@
return '"%s"' % value
-def parse_measure(measure: str) -> tuple[numbers.Rational, str]:
- """Parse a measure__, return value + optional unit.
+def parse_measure(measure: str, unit_pattern: str = '[a-zA-Zµ]*|%?'
+ ) -> tuple[int|float, str]:
+ """Parse a measure__, return value + unit.
+ `unit_pattern` is a regular expression describing recognized units.
+ The default is suited for (but not limited to) CSS3 units and SI units.
+ It matches runs of ASCII letters or Greek mu, a single percent sign,
+ or no unit.
+
__ https://docutils.sourceforge.io/docs/ref/doctree.html#measure
Provisional.
"""
- match = re.fullmatch('(-?[0-9.]+) *([a-zA-Zµ]*|%?)', measure)
+ match = re.fullmatch(f'(-?[0-9.]+) *({unit_pattern})', measure)
try:
try:
value = int(match.group(1))
@@ -3149,7 +3167,8 @@
See `parse_measure()` for a function returning a "number + unit" tuple.
- The unit may be any run of letters or a percent sign.
+ The unit may be a run of ASCII letters or Greek mu, a single percent sign,
+ or the empty string. Case is preserved.
Provisional.
@@ -3159,6 +3178,31 @@
return f'{value}{unit}'
+def validate_colwidth(measure: str|int|float) -> int|float:
+ """Validate the "colwidth__" attribute.
+
+ Provisional:
+ `measure` must be a `str` and will be returned as normalized `str`
+ (with unit "*" for proportional values) in Docutils 1.0.
+
+ The default unit will change to "pt" in Docutils 2.0.
+
+ __ https://docutils.sourceforge.io/docs/ref/doctree.html#colwidth
+ """
+ if isinstance(measure, (int, float)):
+ value = measure
+ elif measure in ('*', ''): # short for '1*'
+ value = 1
+ else:
+ try:
+ value, unit = parse_measure(measure, unit_pattern='[*]?')
+ except ValueError:
+ value = -1
+ if value <= 0:
+ raise ValueError(f'"{measure}" is no proportional measure.')
+ return value
+
+
def validate_NMTOKEN(value: str) -> str:
"""
Validate a "name token": a `str` of ASCII letters, digits, and [-._].
@@ -3232,7 +3276,7 @@
'colnum': int, # from CALS, currently ignored
'cols': int, # from CALS: "NMTOKEN, […] must be an integer > 0".
'colsep': validate_yesorno,
- 'colwidth': int, # sic! CALS: CDATA (measure or number+'*')
+ 'colwidth': validate_colwidth, # see docstring for pending changes
'content': str, # <meta>
'delimiter': str,
'dir': create_keyword_validator('ltr', 'rtl', 'auto'), # <meta>
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2024-10-22 21:41:26 UTC (rev 9966)
+++ trunk/docutils/docutils/writers/_html_base.py 2024-10-24 21:05:01 UTC (rev 9967)
@@ -846,9 +846,9 @@
and 'colwidths-given' not in node.parent.parent['classes']):
return
self.body.append(self.starttag(node, 'colgroup'))
- total_width = sum(node['colwidth'] for node in self.colspecs)
+ total_width = sum(node.propwidth() for node in self.colspecs)
for node in self.colspecs:
- colwidth = node['colwidth'] / total_width
+ colwidth = node.propwidth() / total_width
self.body.append(self.emptytag(node, 'col',
style=f'width: {colwidth:.1%}'))
self.body.append('</colgroup>\n')
Modified: trunk/docutils/docutils/writers/html4css1/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/html4css1/__init__.py 2024-10-22 21:41:26 UTC (rev 9966)
+++ trunk/docutils/docutils/writers/html4css1/__init__.py 2024-10-24 21:05:01 UTC (rev 9967)
@@ -231,10 +231,10 @@
or ('colwidths-auto' in self.settings.table_style
and 'colwidths-given' not in node.parent.parent['classes'])):
return
- total_width = sum(node['colwidth'] for node in self.colspecs)
+ total_width = sum(node.propwidth() for node in self.colspecs)
self.body.append(self.starttag(node, 'colgroup'))
for node in self.colspecs:
- colwidth = int(node['colwidth'] * 100.0 / total_width + 0.5)
+ colwidth = node.propwidth() * 100.0 / total_width + 0.5
self.body.append(self.emptytag(node, 'col',
width='%i%%' % colwidth))
self.body.append('</colgroup>\n')
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-10-22 21:41:26 UTC (rev 9966)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-10-24 21:05:01 UTC (rev 9967)
@@ -989,11 +989,11 @@
width = 80 # assumed standard line length
factor = 0.93 # do not make it full linewidth
# first see if we get too wide.
- total_width = sum(node['colwidth']+1 for node in self._col_specs)
+ total_width = sum(node.propwidth()+1 for node in self._col_specs)
if total_width > width:
factor *= width / total_width
- self._colwidths = [(factor * (node['colwidth']+1)/width)
- + 0.005 for node in self._col_specs]
+ self._colwidths = [(factor * (node.propwidth()+1)/width) + 0.005
+ for node in self._col_specs]
latex_colspecs = ['p{%.3f\\DUtablewidth}' % colwidth
for colwidth in self._colwidths]
else:
@@ -1010,7 +1010,7 @@
allowance = 1
else:
allowance = 0 # "widths" option specified, use exact ratio
- self._colwidths = [(node['colwidth']+allowance)/norm_length
+ self._colwidths = [(node.propwidth()+allowance)/norm_length
for node in self._col_specs]
total_width = sum(self._colwidths)
# Limit to 100%, force 100% if table width is specified:
@@ -1067,7 +1067,7 @@
n_c = len(self._col_specs)
a.append('\\endhead\n')
# footer on all but last page (if it fits):
- t_width = sum(node['colwidth']+2 for node in self._col_specs)
+ t_width = sum(node.propwidth()+2 for node in self._col_specs)
if t_width > 30 or (t_width > 12 and not self.colwidths_auto):
a.append(r'\multicolumn{%d}{%s}'
% (n_c, self.get_multicolumn_width(0, n_c))
Modified: trunk/docutils/docutils/writers/odf_odt/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-10-22 21:41:26 UTC (rev 9966)
+++ trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-10-24 21:05:01 UTC (rev 9967)
@@ -3085,7 +3085,7 @@
'%s%%d.%%s' % TABLESTYLEPREFIX,
(self.table_count, chr(self.column_count), )
)
- colwidth = node['colwidth'] / 12.0
+ colwidth = node.propwidth() / 12.0
el1 = SubElement(self.automatic_styles, 'style:style', attrib={
'style:name': colspec_name,
'style:family': 'table-column',
Modified: trunk/docutils/test/test_nodes.py
===================================================================
--- trunk/docutils/test/test_nodes.py 2024-10-22 21:41:26 UTC (rev 9966)
+++ trunk/docutils/test/test_nodes.py 2024-10-24 21:05:01 UTC (rev 9967)
@@ -465,6 +465,31 @@
self.assertEqual(len(parent), 5)
+class ColspecTests(unittest.TestCase):
+
+ def test_propwidth(self):
+ # Return colwidth attribute value if it is a proportional measure.
+ colspec = nodes.colspec()
+ colspec['colwidth'] = '8.2*' # value + '*'
+ self.assertEqual(colspec.propwidth(), 8.2)
+ colspec['colwidth'] = '2' # in Docutils < 2.0, default unit is '*'
+ self.assertEqual(colspec.propwidth(), 2)
+ colspec['colwidth'] = '20%' # percentual values not supported
+ with self.assertRaisesRegex(ValueError, '"20%" is no proportional me'):
+ colspec.propwidth()
+ colspec['colwidth'] = '2em' # fixed values not supported
+ with self.assertRaisesRegex(ValueError, '"2em" is no proportional me'):
+ colspec.propwidth()
+ colspec['colwidth'] = '0*' # value must be positive
+ with self.assertRaisesRegex(ValueError, r'"0\*" is no proportional '):
+ colspec.propwidth()
+ # for backwards compatibility, numerical values are accepted
+ colspec['colwidth'] = 8.2
+ self.assertEqual(colspec.propwidth(), 8.2)
+ colspec['colwidth'] = 2
+ self.assertEqual(colspec.propwidth(), 2)
+
+
class ElementValidationTests(unittest.TestCase):
def test_validate(self):
@@ -1114,22 +1139,33 @@
['a name', 'two\\', r'n\ames'])
def test_parse_measure(self):
- # measure is number + optional unit (letter(s) or percentage)
+ # measure is number + unit
+ # By default, a run of ASCII letters or µ, a single percent sign,
+ # or the empty string are recognized as unit.
self.assertEqual(nodes.parse_measure('8ex'), (8, 'ex'))
self.assertEqual(nodes.parse_measure('2.5'), (2.5, ''))
self.assertEqual(nodes.parse_measure('-2s'), (-2, 's'))
+ # Spaces between number and unit are tolerated, case is preserved:
self.assertEqual(nodes.parse_measure('2 µF'), (2, 'µF'))
self.assertEqual(nodes.parse_measure('10 EUR'), (10, 'EUR'))
self.assertEqual(nodes.parse_measure('.5 %'), (.5, '%'))
- # scientific notation not supported
+ # Only a single percent sign is allowed:
+ with self.assertRaisesRegex(ValueError, '"2%%" is no valid measure'):
+ nodes.parse_measure('2%%')
+ # Scientific notation is not supported:
with self.assertRaisesRegex(ValueError, '"3e-4 mm" is no valid '):
nodes.parse_measure('3e-4 mm')
- # unit must follow the number
+ # Units must follow the number:
with self.assertRaisesRegex(ValueError, '"EUR 23" is no valid '):
nodes.parse_measure('EUR 23')
- # only single percent sign allowed
- with self.assertRaisesRegex(ValueError, '"2%%" is no valid measure'):
- nodes.parse_measure('2%%')
+ # Supported units can be configured with a "unit regexp pattern":
+ self.assertEqual(nodes.parse_measure('10 EUR', 'EUR|€'), (10, 'EUR'))
+ self.assertEqual(nodes.parse_measure('10 €', 'EUR|€'), (10, '€'))
+ with self.assertRaisesRegex(ValueError, '"20 DM" is no valid measure'):
+ nodes.parse_measure('20 DM', 'EUR|€')
+ # Measures without unit are only supported, if the pattern says so:
+ with self.assertRaisesRegex(ValueError, '"20" is no valid measure'):
+ nodes.parse_measure('20', 'EUR|€')
class AttributeTypeTests(unittest.TestCase):
@@ -1171,7 +1207,7 @@
nodes.validate_identifier_list(s2)
def test_validate_measure(self):
- # number (may be decimal fraction) + optional unit
+ # measure == number (int or decimal fraction) + optional unit
# internal whitespace is removed
self.assertEqual(nodes.validate_measure('8 ex'), '8ex')
self.assertEqual(nodes.validate_measure('2'), '2')
@@ -1199,6 +1235,7 @@
def test_validate_NMTOKEN(self):
# str with ASCII-letters, digits, hyphen, underscore, and full-stop.
self.assertEqual(nodes.validate_NMTOKEN('-8x_.'), '-8x_.')
+ # internal space is not allowed
with self.assertRaises(ValueError):
nodes.validate_NMTOKEN('why me')
Modified: trunk/docutils/test/test_parsers/test_docutils_xml/test_parse_element.py
===================================================================
--- trunk/docutils/test/test_parsers/test_docutils_xml/test_parse_element.py 2024-10-22 21:41:26 UTC (rev 9966)
+++ trunk/docutils/test/test_parsers/test_docutils_xml/test_parse_element.py 2024-10-24 21:05:01 UTC (rev 9967)
@@ -141,7 +141,8 @@
node = docutils_xml.parse_element(xml)
self.assertEqual(node.attributes, self.common_attributes | expected)
- def test_auto(self): # CDATA (str) number sequence: '1' or '*'
+ def test_auto(self): # CDATA (str)
+ # also encodes footnote label type: '1': numbered, '*': symbols
xml = '<footnote auto="*" backrefs="footnote-reference-2" />'
expected = {'auto': '*',
'backrefs': ['footnote-reference-2']}
@@ -159,7 +160,15 @@
# 'classes': classnames.type (list[str]) → test_bullet
- def test_colwidth(self): # CDATA (int) sic!
+ def test_colwidth(self): # CDATA (int)
+ # Provisional. Currently, Docutils handles "colwidth" differently
+ # from the Exchange Table Model. This will eventually change
+ # (see https://docutils.sourceforge.io/docs/ref/doctree.html#colwidth).
+ xml = '<colspec colwidth="33*" stub="1" />'
+ expected = {'colwidth': 33, 'stub': 1}
+ node = docutils_xml.parse_element(xml)
+ self.assertEqual(node.attributes, self.common_attributes | expected)
+ # Note: the upstream default unit is "pt", not "*".
xml = '<colspec colwidth="33" stub="1" />'
expected = {'colwidth': 33, 'stub': 1}
node = docutils_xml.parse_element(xml)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-10-26 09:15:21
|
Revision: 9970
http://sourceforge.net/p/docutils/code/9970
Author: milde
Date: 2024-10-26 09:15:18 +0000 (Sat, 26 Oct 2024)
Log Message:
-----------
Fix recursion in `nodes.Element.get_language_code()`.
Because of a typo, `Element.get_language_code()` did not find language
tags in parent elements but just return the fallback value.
Thanks to Marcello Perathoner for the report.
http://permalink.gmane.org/gmane.text.docutils.devel/10544
Modified Paths:
--------------
trunk/docutils/HISTORY.rst
trunk/docutils/docutils/nodes.py
trunk/docutils/test/test_nodes.py
Modified: trunk/docutils/HISTORY.rst
===================================================================
--- trunk/docutils/HISTORY.rst 2024-10-25 22:46:34 UTC (rev 9969)
+++ trunk/docutils/HISTORY.rst 2024-10-26 09:15:18 UTC (rev 9970)
@@ -68,6 +68,7 @@
- New function `parse_measure()`.
- Removed `Element.set_class()`.
- Downgrade "duplicate ID" message level from SERIOUS to ERROR.
+ - Fix recursion in `Element.get_language_code()`.
* docutils/parsers/docutils_xml.py
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-10-25 22:46:34 UTC (rev 9969)
+++ trunk/docutils/docutils/nodes.py 2024-10-26 09:15:18 UTC (rev 9970)
@@ -813,7 +813,7 @@
if cls.startswith('language-'):
return cls.removeprefix('language-')
try:
- return self.parent.get_language(fallback)
+ return self.parent.get_language_code(fallback)
except AttributeError:
return fallback
Modified: trunk/docutils/test/test_nodes.py
===================================================================
--- trunk/docutils/test/test_nodes.py 2024-10-25 22:46:34 UTC (rev 9969)
+++ trunk/docutils/test/test_nodes.py 2024-10-26 09:15:18 UTC (rev 9970)
@@ -240,6 +240,15 @@
element.clear()
self.assertTrue(not len(element))
+ def test_get_language_code(self):
+ # Return language tag from node or parents
+ parent = nodes.Element(classes=['parental', 'language-pt-BR'])
+ self.assertEqual(parent.get_language_code('en'), 'pt-BR')
+ child = nodes.Element(classes=['small'])
+ self.assertEqual(child.get_language_code('en'), 'en')
+ parent.append(child)
+ self.assertEqual(child.get_language_code('en'), 'pt-BR')
+
def test_normal_attributes(self):
element = nodes.Element()
self.assertTrue('foo' not in element)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-11-09 23:36:52
|
Revision: 9977
http://sourceforge.net/p/docutils/code/9977
Author: milde
Date: 2024-11-09 23:36:49 +0000 (Sat, 09 Nov 2024)
Log Message:
-----------
Remove `docutils/utils/roman.py`.
Obsoleted by ``docutils/utils/_roman_numerals.py``.
Modified Paths:
--------------
trunk/docutils/COPYING.rst
trunk/docutils/HISTORY.rst
trunk/docutils/RELEASE-NOTES.rst
Removed Paths:
-------------
trunk/docutils/docutils/utils/roman.py
trunk/docutils/licenses/ZPL-2-1.rst
Modified: trunk/docutils/COPYING.rst
===================================================================
--- trunk/docutils/COPYING.rst 2024-10-30 23:34:50 UTC (rev 9976)
+++ trunk/docutils/COPYING.rst 2024-11-09 23:36:49 UTC (rev 9977)
@@ -128,13 +128,6 @@
Released under the terms of the `BSD 2-Clause License`_
(`local copy <licenses/BSD-2-Clause.rst>`__).
-* docutils/utils/roman.py
-
- copyright by Mark Pilgrim, released under the
- `Zope Public License Version 2.1`_ (`local copy`__).
-
- __ licenses/ZPL-2-1.rst
-
* tools/editors/emacs/rst.el
copyright by Free Software Foundation, Inc.,
@@ -153,7 +146,6 @@
.. _GNU General Public License: https://www.gnu.org/copyleft/gpl.html
.. _BSD 2-Clause License: http://opensource.org/licenses/BSD-2-Clause
.. _BSD 3-Clause License: https://opensource.org/licenses/BSD-3-Clause
-.. _Zope Public License Version 2.1: https://opensource.org/license/zpl-2-1/
.. _OSI-approved: http://opensource.org/licenses/
.. _license-list:
.. _GPL-compatible: https://www.gnu.org/licenses/license-list.html
Modified: trunk/docutils/HISTORY.rst
===================================================================
--- trunk/docutils/HISTORY.rst 2024-10-30 23:34:50 UTC (rev 9976)
+++ trunk/docutils/HISTORY.rst 2024-11-09 23:36:49 UTC (rev 9977)
@@ -139,7 +139,8 @@
* docutils/utils/_roman_numerals.py
- - Added new implementation.
+ - New implementation or Roman numeral support.
+ Replaces the local copy of docutils/utils/roman.py.
* docutils/utils/error_reporting.py
@@ -203,7 +204,7 @@
- Fix conversion factor of "pc" (pica) to "cm".
- Fix conversion of image width in "%" if the height is specified.
- Adjust fallback DPI value (currently not used) to match CSS units.
- - Fix errors with "*.xml" style files (bug #494).
+ - Fix errors with ``*.xml`` style files (bug #494).
* pyproject.toml
Modified: trunk/docutils/RELEASE-NOTES.rst
===================================================================
--- trunk/docutils/RELEASE-NOTES.rst 2024-10-30 23:34:50 UTC (rev 9976)
+++ trunk/docutils/RELEASE-NOTES.rst 2024-11-09 23:36:49 UTC (rev 9977)
@@ -288,6 +288,8 @@
Removed files
``tools/rst2odt_prepstyles.py``
Obsoleted by `docutils.writers.odf_odt.prepstyles`.
+ ``docutils/utils/roman.py``
+ Obsoleted by ``docutils/utils/_roman_numerals.py``
Bugfixes and improvements (see HISTORY_).
Deleted: trunk/docutils/docutils/utils/roman.py
===================================================================
--- trunk/docutils/docutils/utils/roman.py 2024-10-30 23:34:50 UTC (rev 9976)
+++ trunk/docutils/docutils/utils/roman.py 2024-11-09 23:36:49 UTC (rev 9977)
@@ -1,154 +0,0 @@
-##############################################################################
-#
-# Copyright (c) 2001 Mark Pilgrim and Contributors.
-# All Rights Reserved.
-#
-# This software is subject to the provisions of the Zope Public License,
-# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
-# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
-# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
-# FOR A PARTICULAR PURPOSE.
-#
-##############################################################################
-"""Convert to and from Roman numerals"""
-
-__author__ = "Mark Pilgrim (f8...@di...)"
-__version__ = "1.4"
-__date__ = "8 August 2001"
-__copyright__ = """Copyright (c) 2001 Mark Pilgrim
-
-This program is part of "Dive Into Python", a free Python tutorial for
-experienced programmers. Visit http://diveintopython.org/ for the
-latest version.
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the Python 2.1.1 license, available at
-http://www.python.org/2.1.1/license.html
-"""
-
-import argparse
-import re
-import sys
-
-
-# Define exceptions
-class RomanError(Exception):
- pass
-
-
-class OutOfRangeError(RomanError):
- pass
-
-
-class NotIntegerError(RomanError):
- pass
-
-
-class InvalidRomanNumeralError(RomanError):
- pass
-
-
-# Define digit mapping
-romanNumeralMap = (('M', 1000),
- ('CM', 900),
- ('D', 500),
- ('CD', 400),
- ('C', 100),
- ('XC', 90),
- ('L', 50),
- ('XL', 40),
- ('X', 10),
- ('IX', 9),
- ('V', 5),
- ('IV', 4),
- ('I', 1))
-
-
-def toRoman(n):
- """convert integer to Roman numeral"""
- if not isinstance(n, int):
- raise NotIntegerError("decimals can not be converted")
- if not (-1 < n < 5000):
- raise OutOfRangeError("number out of range (must be 0..4999)")
-
- # special case
- if n == 0:
- return 'N'
-
- result = ""
- for numeral, integer in romanNumeralMap:
- while n >= integer:
- result += numeral
- n -= integer
- return result
-
-
-# Define pattern to detect valid Roman numerals
-romanNumeralPattern = re.compile("""
- ^ # beginning of string
- M{0,4} # thousands - 0 to 4 M's
- (CM|CD|D?C{0,3}) # hundreds - 900 (CM), 400 (CD), 0-300 (0 to 3 C's),
- # or 500-800 (D, followed by 0 to 3 C's)
- (XC|XL|L?X{0,3}) # tens - 90 (XC), 40 (XL), 0-30 (0 to 3 X's),
- # or 50-80 (L, followed by 0 to 3 X's)
- (IX|IV|V?I{0,3}) # ones - 9 (IX), 4 (IV), 0-3 (0 to 3 I's),
- # or 5-8 (V, followed by 0 to 3 I's)
- $ # end of string
- """, re.VERBOSE)
-
-
-def fromRoman(s):
- """convert Roman numeral to integer"""
- if not s:
- raise InvalidRomanNumeralError('Input can not be blank')
-
- # special case
- if s == 'N':
- return 0
-
- if not romanNumeralPattern.search(s):
- raise InvalidRomanNumeralError('Invalid Roman numeral: %s' % s)
-
- result = 0
- index = 0
- for numeral, integer in romanNumeralMap:
- while s[index:index + len(numeral)] == numeral:
- result += integer
- index += len(numeral)
- return result
-
-
-def parse_args():
- parser = argparse.ArgumentParser(
- prog='roman',
- description='convert between roman and arabic numerals'
- )
- parser.add_argument('number', help='the value to convert')
- parser.add_argument(
- '-r', '--reverse',
- action='store_true',
- default=False,
- help='convert roman to numeral (case insensitive) [default: False]')
-
- args = parser.parse_args()
- args.number = args.number
- return args
-
-
-def main() -> int:
- args = parse_args()
- if args.reverse:
- u = args.number.upper()
- r = fromRoman(u)
- print(r)
- else:
- i = int(args.number)
- n = toRoman(i)
- print(n)
-
- return 0
-
-
-if __name__ == "__main__": # pragma: no cover
- sys.exit(main()) # pragma: no cover
Deleted: trunk/docutils/licenses/ZPL-2-1.rst
===================================================================
--- trunk/docutils/licenses/ZPL-2-1.rst 2024-10-30 23:34:50 UTC (rev 9976)
+++ trunk/docutils/licenses/ZPL-2-1.rst 2024-11-09 23:36:49 UTC (rev 9977)
@@ -1,44 +0,0 @@
-Zope Public License (ZPL) Version 2.1
-
-A copyright notice accompanies this license document that identifies the
-copyright holders.
-
-This license has been certified as open source. It has also been designated as
-GPL compatible by the Free Software Foundation (FSF).
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-1. Redistributions in source code must retain the accompanying copyright
-notice, this list of conditions, and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the accompanying copyright
-notice, this list of conditions, and the following disclaimer in the
-documentation and/or other materials provided with the distribution.
-
-3. Names of the copyright holders must not be used to endorse or promote
-products derived from this software without prior written permission from the
-copyright holders.
-
-4. The right to distribute this software or to use it for any purpose does not
-give you the right to use Servicemarks (sm) or Trademarks (tm) of the
-copyright
-holders. Use of them is covered by separate agreement with the copyright
-holders.
-
-5. If any files are modified, you must cause the modified files to carry
-prominent notices stating that you changed the files and the date of any
-change.
-
-Disclaimer
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
-OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
-EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
-EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-11-12 10:34:16
|
Revision: 9980
http://sourceforge.net/p/docutils/code/9980
Author: milde
Date: 2024-11-12 10:34:13 +0000 (Tue, 12 Nov 2024)
Log Message:
-----------
Announce upcoming change in "doctest block" handling.
Parse doctest blocks as "code" with language "pycon" (pygment name for
Python console).
+1 syntax highlight in line with other "code" elements.
+1 the `<doctest_block>` doctree element can be retired.
Modified Paths:
--------------
trunk/docutils/RELEASE-NOTES.rst
trunk/docutils/docs/ref/doctree.rst
trunk/docutils/docutils/parsers/rst/states.py
Modified: trunk/docutils/RELEASE-NOTES.rst
===================================================================
--- trunk/docutils/RELEASE-NOTES.rst 2024-11-11 17:39:17 UTC (rev 9979)
+++ trunk/docutils/RELEASE-NOTES.rst 2024-11-12 10:34:13 UTC (rev 9980)
@@ -64,8 +64,14 @@
The default unit will change to "pt" in Docutils 2.0.
+* The `\<doctest_block>`_ element will be deprecated in Docutils 1.0.
+ The rST parser will handle a `doctest block`_ similar to a "code" directive
+ with language "pycon" (Python console) and generate a <literal_block>.
+
.. _"refname" attribute: docs/ref/doctree.html#refname
.. _"colwidth" attribute: docs/ref/doctree.html#colwidth
+.. _<doctest_block>: docs/ref/doctree.html#doctest-block
+.. _doctest block: docs/ref/rst/restructuredtext.html#doctest-blocks
Writers
-------
Modified: trunk/docutils/docs/ref/doctree.rst
===================================================================
--- trunk/docutils/docs/ref/doctree.rst 2024-11-11 17:39:17 UTC (rev 9979)
+++ trunk/docutils/docs/ref/doctree.rst 2024-11-12 10:34:13 UTC (rev 9980)
@@ -1392,14 +1392,6 @@
:Children: text data plus `inline elements`_ (`%text.model`_)
:Attributes: the `common attributes`_ and `xml:space`_.
-<doctest_block> elements are used for interactive Python interpreter
-sessions, which are distinguished by their input prompt: ``>>>``.
-They are meant to illustrate usage by example, and provide an elegant
-and powerful testing environment via the `doctest module`_ in the
-Python standard library.
-
-.. _doctest module: https://docs.python.org/3/library/doctest.html
-
Examples
--------
@@ -1418,7 +1410,10 @@
>>> print('this is a Doctest block')
this is a Doctest block
+The <doctest_block> will be deprecated in Docutils 1.0, the
+reStructuredText parser will use a `\<literal_block>`_ instead.
+
<document>
==========
Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py 2024-11-11 17:39:17 UTC (rev 9979)
+++ trunk/docutils/docutils/parsers/rst/states.py 2024-11-12 10:34:13 UTC (rev 9980)
@@ -1589,9 +1589,8 @@
def doctest(self, match, context, next_state):
line = self.document.current_line
data = '\n'.join(self.state_machine.get_text_block())
- # TODO: prepend class value ['pycon'] (Python Console)
- # parse with `directives.body.CodeBlock` (returns literal-block
- # with class "code" and syntax highlight markup).
+ # TODO: Parse with `directives.body.CodeBlock` with
+ # argument 'pycon' (Python Console) in Docutils 1.0.
n = nodes.doctest_block(data, data)
n.line = line
self.parent += n
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-11-14 16:01:36
|
Revision: 9981
http://sourceforge.net/p/docutils/code/9981
Author: milde
Date: 2024-11-14 16:01:33 +0000 (Thu, 14 Nov 2024)
Log Message:
-----------
XML parser: register substitution definitions.
Call `nodes.note_substitution_def()` for every `<substitution_definition>`
to update the list of substitution definitions.
(The `references.Substitution` transform relies on this list.)
Modified Paths:
--------------
trunk/docutils/docutils/parsers/docutils_xml.py
trunk/docutils/test/test_parsers/test_docutils_xml/test_misc.py
Modified: trunk/docutils/docutils/parsers/docutils_xml.py
===================================================================
--- trunk/docutils/docutils/parsers/docutils_xml.py 2024-11-12 10:34:13 UTC (rev 9980)
+++ trunk/docutils/docutils/parsers/docutils_xml.py 2024-11-14 16:01:33 UTC (rev 9981)
@@ -14,9 +14,10 @@
"""A Docutils-XML parser.
- Provisional: The API is not fixed yet.
- Defined objects may be renamed or changed in any Docutils release
- without prior notice.
+ Provisional:
+ The API is not fixed yet.
+ Defined objects may be renamed or changed
+ in any Docutils release without prior notice.
"""
import re
@@ -133,9 +134,7 @@
node = nodeclass()
node.line = int(element.get('source line'))
- if isinstance(node, nodes.decoration):
- document.decoration = node
- elif isinstance(node, Unknown):
+ if isinstance(node, Unknown):
node.tagname = element.tag
document.reporter.warning(
f'Unknown element type <{element.tag}>.',
@@ -151,8 +150,15 @@
if key in node.list_attributes:
value = value.split()
node.attributes[key] = value # node becomes invalid!
+
+ # Bookkeeping (register some elements/attributes in document-wide lists)
+ if isinstance(node, nodes.decoration):
+ document.decoration = node
+ elif isinstance(node, nodes.substitution_definition):
+ document.note_substitution_def(node, ' '.join(node['names']), document)
if node['ids']: # register, check for duplicates
document.set_id(node)
+ # TODO: anything missing?
# Append content:
# update "unindent" flag: change line indentation?
Modified: trunk/docutils/test/test_parsers/test_docutils_xml/test_misc.py
===================================================================
--- trunk/docutils/test/test_parsers/test_docutils_xml/test_misc.py 2024-11-12 10:34:13 UTC (rev 9980)
+++ trunk/docutils/test/test_parsers/test_docutils_xml/test_misc.py 2024-11-14 16:01:33 UTC (rev 9981)
@@ -105,6 +105,27 @@
"""],
])
+totest['substitutions'] = ({}, # resolve substitutions
+[
+["""\
+<document source="test data">
+ <substitution_definition ltrim="0" names="holla">Mara</substitution_definition>
+ <paragraph>Das ist
+ <substitution_reference refname="Holla">Holla</substitution_reference>
+ die Waldfee</paragraph>
+</document>
+""",
+"""\
+<document source="test data">
+ <substitution_definition ltrim="0" names="holla">
+ Mara
+ <paragraph>
+ Das ist
+ Mara
+ \n\
+ die Waldfee
+"""],
+])
if __name__ == '__main__':
unittest.main()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <gr...@us...> - 2024-11-18 16:50:52
|
Revision: 9986
http://sourceforge.net/p/docutils/code/9986
Author: grubert
Date: 2024-11-18 16:50:28 +0000 (Mon, 18 Nov 2024)
Log Message:
-----------
if macro references is active output refuri always.
Modified Paths:
--------------
trunk/docutils/HISTORY.rst
trunk/docutils/docutils/writers/manpage.py
Modified: trunk/docutils/HISTORY.rst
===================================================================
--- trunk/docutils/HISTORY.rst 2024-11-18 16:26:33 UTC (rev 9985)
+++ trunk/docutils/HISTORY.rst 2024-11-18 16:50:28 UTC (rev 9986)
@@ -195,6 +195,7 @@
to enable/disable usage of *man* macros .UR/.UE.
- Do not output .UR/.UE macros without refuri in node.
- Use .MT/.ME macros for mailto.uris.
+ - If macro references is active output refuri always.
* docutils/writers/null.py
Modified: trunk/docutils/docutils/writers/manpage.py
===================================================================
--- trunk/docutils/docutils/writers/manpage.py 2024-11-18 16:26:33 UTC (rev 9985)
+++ trunk/docutils/docutils/writers/manpage.py 2024-11-18 16:50:28 UTC (rev 9986)
@@ -1102,8 +1102,7 @@
else:
self.body.append(".UR ")
self.context.append('.UE\n')
- if not node['refuri'].endswith(node.astext()):
- self.body.append("%s\n" % node['refuri'])
+ self.body.append("%s\n" % node['refuri'])
else:
self.context.append('')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-11-25 13:49:01
|
Revision: 9990
http://sourceforge.net/p/docutils/code/9990
Author: milde
Date: 2024-11-25 13:48:58 +0000 (Mon, 25 Nov 2024)
Log Message:
-----------
Small documentation fixes.
Fix typo and add explanation in HISTORY.
Formatting in RELEASE NOTES.
Mark "parser" option of the "include" directive as provisional.
`frontend.OptionParser`: Add replacement hint to deprectaion warning.
Modified Paths:
--------------
trunk/docutils/HISTORY.rst
trunk/docutils/RELEASE-NOTES.rst
trunk/docutils/docs/ref/rst/directives.rst
trunk/docutils/docutils/frontend.py
Modified: trunk/docutils/HISTORY.rst
===================================================================
--- trunk/docutils/HISTORY.rst 2024-11-24 17:15:41 UTC (rev 9989)
+++ trunk/docutils/HISTORY.rst 2024-11-25 13:48:58 UTC (rev 9990)
@@ -99,7 +99,7 @@
* docutils/parsers/rst/roles.py
- - Renamed `normalized_role_options()` to `normalized_role_options()`
+ - Renamed `normalized_role_options()` to `normalize_options()`
(it is now also used for directive options).
* docutils/parsers/rst/states.py
@@ -770,7 +770,8 @@
* docutils/frontend.py
- Mark as provisional (will switch from using `optparse` to `argparse`).
- Remove hack for the now obsolete "mod_python" Apache module.
- - New function `get_default_settings()`.
+ - New function `get_default_settings()` as a replacement for the
+ deprecated `OptionParser`\ s `get_default_values()` method.
* docutils/nodes.py
Modified: trunk/docutils/RELEASE-NOTES.rst
===================================================================
--- trunk/docutils/RELEASE-NOTES.rst 2024-11-24 17:15:41 UTC (rev 9989)
+++ trunk/docutils/RELEASE-NOTES.rst 2024-11-25 13:48:58 UTC (rev 9990)
@@ -60,13 +60,12 @@
* The "rst" parser will warn if a "figure" directive is missing both
caption and legend in Docutils 1.0.
-* Values of the `"colwidth" attribute`_ will be stored in Python
- element instances as `str` (with unit "*" for proportional values)
- in Docutils 1.0. (The method `nodes.colspec.propwidth()` provides
- a stable means to extract a proportionional value as number.)
+* To match the definition in the "Exchange Table Model", the
+ `"colwidth" attribute`_ will be stored as a `str` (instead of
+ numerical) value in Python element instances in Docutils 1.0.
+ Proportional values will be stored with unit "*" in Docutils 2.0.
+ The default unit will change to "pt" in Docutils 3.0.
- The default unit will change to "pt" in Docutils 2.0.
-
* The `\<doctest_block>`_ element will be deprecated in Docutils 1.0.
The rST parser will handle a `doctest block`_ similar to a "code" directive
with language "pycon" (Python console) and generate a <literal_block>.
@@ -490,8 +489,6 @@
Release 0.19 (2022-07-05)
=========================
-(Release 0.19b1 (2022-06-21))
-
* Drop support for Python 2.7, 3.5, and 3.6.
* Output changes:
Modified: trunk/docutils/docs/ref/rst/directives.rst
===================================================================
--- trunk/docutils/docs/ref/rst/directives.rst 2024-11-24 17:15:41 UTC (rev 9989)
+++ trunk/docutils/docs/ref/rst/directives.rst 2024-11-25 13:48:58 UTC (rev 9990)
@@ -1607,7 +1607,7 @@
There is is no check whether the inserted elements are valid at the
point of insertion. It is recommended to validate_ the document.
- (New in Docutils 0.17)
+ (New in Docutils 0.17. Provisional.)
``start-after`` : text_
Only the content after the first occurrence of the specified *text*
Modified: trunk/docutils/docutils/frontend.py
===================================================================
--- trunk/docutils/docutils/frontend.py 2024-11-24 17:15:41 UTC (rev 9989)
+++ trunk/docutils/docutils/frontend.py 2024-11-25 13:48:58 UTC (rev 9990)
@@ -901,10 +901,11 @@
self.relative_path_settings = ('warning_stream',) # will be modified
- warnings.warn('The frontend.OptionParser class will be replaced '
- 'by a subclass of argparse.ArgumentParser '
- 'in Docutils 0.21 or later.',
- DeprecationWarning, stacklevel=2)
+ warnings.warn(
+ 'The frontend.OptionParser class will be replaced by a subclass '
+ 'of argparse.ArgumentParser in Docutils 0.21 or later.\n '
+ 'To get default settings, use frontend.get_default_settings().',
+ DeprecationWarning, stacklevel=2)
super().__init__(option_class=Option, add_help_option=False,
formatter=optparse.TitledHelpFormatter(width=78),
*args, **kwargs)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-11-25 20:45:30
|
Revision: 9991
http://sourceforge.net/p/docutils/code/9991
Author: milde
Date: 2024-11-25 20:45:27 +0000 (Mon, 25 Nov 2024)
Log Message:
-----------
Change default of "root_prefix" setting to empty string.
Part of a patch by Adam Turner
(cf. https://sourceforge.net/p/docutils/bugs/493/#55f0 ff.).
Modified Paths:
--------------
trunk/docutils/HISTORY.rst
trunk/docutils/docs/user/config.rst
trunk/docutils/docutils/frontend.py
trunk/docutils/docutils/parsers/rst/directives/misc.py
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/odf_odt/__init__.py
trunk/docutils/test/data/help/docutils.rst
trunk/docutils/test/data/help/rst2html.rst
trunk/docutils/test/data/help/rst2latex.rst
Modified: trunk/docutils/HISTORY.rst
===================================================================
--- trunk/docutils/HISTORY.rst 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/HISTORY.rst 2024-11-25 20:45:27 UTC (rev 9991)
@@ -37,9 +37,9 @@
* docutils/core.py
- Removed `Publisher.setup_option_parser()` (internal, obsolete).
- - Allow a string value (component name or alias) in the
- "reader", "parser", and "writer" arguments of `Publisher.__init__()`
- and the `publish_*()` convenience functions.
+ - Allow a string value (component name or alias) in the "reader",
+ "parser", and "writer" arguments of `Publisher.__init__()` and
+ the `publish_*()` convenience functions.
* docutils/frontend.py
@@ -46,6 +46,8 @@
- Drop short options ``-i`` and ``-o`` for ``--input-encoding``
and ``--output-encoding``.
- Change the default input encoding from ``None`` (auto-detect) to "utf-8".
+ - Change the default value of the _root_prefix setting to the empty string
+ (no change to the behaviour).
* docutils/io.py
@@ -194,8 +196,8 @@
- Add command line option ``--macro-references``/``--text-references``
to enable/disable usage of *man* macros .UR/.UE.
- Do not output .UR/.UE macros without refuri in node.
- - Use .MT/.ME macros for mailto.uris.
- - If macro references is active output refuri always.
+ - Use .MT/.ME macros for mailto.uris.
+ - If macro references is active output refuri always.
* docutils/writers/null.py
@@ -768,6 +770,7 @@
=========================
* docutils/frontend.py
+
- Mark as provisional (will switch from using `optparse` to `argparse`).
- Remove hack for the now obsolete "mod_python" Apache module.
- New function `get_default_settings()` as a replacement for the
Modified: trunk/docutils/docs/user/config.rst
===================================================================
--- trunk/docutils/docs/user/config.rst 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/docs/user/config.rst 2024-11-25 20:45:27 UTC (rev 9991)
@@ -589,8 +589,8 @@
Also applied when a writer converts an image URI__ to a local filesystem
path in order to determine the image size or embed the image in the output.
-:Default: "/" (keep paths unchanged).
-:Option: ``--root-prefix``
+:Default: "".
+:Option: ``--root-prefix``.
New in Docutils 0.21.
Modified: trunk/docutils/docutils/frontend.py
===================================================================
--- trunk/docutils/docutils/frontend.py 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/docutils/frontend.py 2024-11-25 20:45:27 UTC (rev 9991)
@@ -706,9 +706,9 @@
['--no-datestamp'], {'action': 'store_const', 'const': None,
'dest': 'datestamp'}),
('Base directory for absolute paths when reading '
- 'from the local filesystem. Default "/".',
+ 'from the local filesystem. Default "".',
['--root-prefix'],
- {'default': '/', 'metavar': '<path>'}),
+ {'default': '', 'metavar': '<path>'}),
('Include a "View document source" link.',
['--source-link', '-s'], {'action': 'store_true',
'validator': validate_boolean}),
Modified: trunk/docutils/docutils/parsers/rst/directives/misc.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/misc.py 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/docutils/parsers/rst/directives/misc.py 2024-11-25 20:45:27 UTC (rev 9991)
@@ -25,12 +25,12 @@
from docutils.nodes import Node, StrPath
-def adapt_path(path: str, source='', root_prefix='/') -> str:
+def adapt_path(path: str, source='', root_prefix='') -> str:
# Adapt path to files to include or embed.
# `root_prefix` is prepended to absolute paths (cf. root_prefix setting),
# `source` is the `current_source` of the including directive (which may
# be a file included by the main document).
- if path.startswith('/'):
+ if root_prefix and path.startswith('/'):
base = Path(root_prefix)
path = path[1:]
else:
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/docutils/writers/_html_base.py 2024-11-25 20:45:27 UTC (rev 9991)
@@ -650,9 +650,9 @@
if uri_parts.scheme not in ('', 'file'):
raise ValueError('Can only read local images.')
imagepath = urllib.parse.unquote(uri_parts.path)
- if imagepath.startswith('/'): # cf. config.html#root-prefix
+ if self.settings.root_prefix and imagepath.startswith('/'):
root_prefix = Path(self.settings.root_prefix)
- imagepath = (root_prefix/imagepath[1:]).as_posix()
+ imagepath = (root_prefix/imagepath.removeprefix('/')).as_posix()
elif not os.path.isabs(imagepath): # path may be absolute Windows path
destdir = os.path.abspath(os.path.dirname(destination))
imagepath = utils.relative_path(None,
Modified: trunk/docutils/docutils/writers/odf_odt/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-11-25 20:45:27 UTC (rev 9991)
@@ -2131,7 +2131,7 @@
uri_parts = urllib.parse.urlparse(source)
if uri_parts.scheme in ('', 'file'):
source = urllib.parse.unquote(uri_parts.path)
- if source.startswith('/'):
+ if self.settings.root_prefix and source.startswith('/'):
root_prefix = Path(self.settings.root_prefix)
source = (root_prefix/source[1:]).as_posix()
else:
Modified: trunk/docutils/test/data/help/docutils.rst
===================================================================
--- trunk/docutils/test/data/help/docutils.rst 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/test/data/help/docutils.rst 2024-11-25 20:45:27 UTC (rev 9991)
@@ -20,7 +20,7 @@
--time, -t Include the time & date (UTC).
--no-datestamp Do not include a datestamp of any kind.
--root-prefix=<path> Base directory for absolute paths when reading from
- the local filesystem. Default "/".
+ the local filesystem. Default "".
--source-link, -s Include a "View document source" link.
--source-url=<URL> Use <URL> for a source link; implies --source-link.
--no-source-link Do not include a "View document source" link.
Modified: trunk/docutils/test/data/help/rst2html.rst
===================================================================
--- trunk/docutils/test/data/help/rst2html.rst 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/test/data/help/rst2html.rst 2024-11-25 20:45:27 UTC (rev 9991)
@@ -21,7 +21,7 @@
--time, -t Include the time & date (UTC).
--no-datestamp Do not include a datestamp of any kind.
--root-prefix=<path> Base directory for absolute paths when reading from
- the local filesystem. Default "/".
+ the local filesystem. Default "".
--source-link, -s Include a "View document source" link.
--source-url=<URL> Use <URL> for a source link; implies --source-link.
--no-source-link Do not include a "View document source" link.
Modified: trunk/docutils/test/data/help/rst2latex.rst
===================================================================
--- trunk/docutils/test/data/help/rst2latex.rst 2024-11-25 13:48:58 UTC (rev 9990)
+++ trunk/docutils/test/data/help/rst2latex.rst 2024-11-25 20:45:27 UTC (rev 9991)
@@ -21,7 +21,7 @@
--time, -t Include the time & date (UTC).
--no-datestamp Do not include a datestamp of any kind.
--root-prefix=<path> Base directory for absolute paths when reading from
- the local filesystem. Default "/".
+ the local filesystem. Default "".
--source-link, -s Include a "View document source" link.
--source-url=<URL> Use <URL> for a source link; implies --source-link.
--no-source-link Do not include a "View document source" link.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-04 13:32:27
|
Revision: 9993
http://sourceforge.net/p/docutils/code/9993
Author: milde
Date: 2024-12-04 13:32:20 +0000 (Wed, 04 Dec 2024)
Log Message:
-----------
Revise output file path configuration setting.
The command-line usage pattern will change in Docutils 1.0 (cf. RELASE-NOTES).
In preparation, the "output" setting was introduced in Docutils 0.20.
As command line option, "--output" is a suitable name, however,
in a wider context, "output" is ambiguous and rather associated with the
actual output than the path to the output file.
Provide `settings.output_path` as "canonical" setting and
`--output` and `--output-path` as command line options.
Let `core.Publisher.set_destination()` synchronize `settings.output_path` with
the legacy settings `settings.output`, and `settings._destination`.
If the `destination_path` argument is specified, it overrides all three
settings and conflicting settings no longer raise an Error.
Use "settings.output_path" instead of the legacy settings in utils, transforms,
and writers.
Fix type hint for "destination" function argument in `Publisher.set_destination()`
(cf. the docstring of `publish_programatically()`).
Modified Paths:
--------------
trunk/docutils/RELEASE-NOTES.rst
trunk/docutils/docs/user/config.rst
trunk/docutils/docs/user/latex.rst
trunk/docutils/docs/user/slide-shows.rst
trunk/docutils/docs/user/tools.rst
trunk/docutils/docutils/core.py
trunk/docutils/docutils/frontend.py
trunk/docutils/docutils/transforms/universal.py
trunk/docutils/docutils/utils/__init__.py
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/docutils/writers/s5_html/__init__.py
trunk/docutils/test/data/help/docutils.rst
trunk/docutils/test/data/help/rst2html.rst
trunk/docutils/test/data/help/rst2latex.rst
trunk/docutils/test/test_publisher.py
Modified: trunk/docutils/RELEASE-NOTES.rst
===================================================================
--- trunk/docutils/RELEASE-NOTES.rst 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/RELEASE-NOTES.rst 2024-12-04 13:32:20 UTC (rev 9993)
@@ -31,7 +31,7 @@
+ COMMAND [OPTIONS] [SOURCE [SOURCE2 [...]]]
* Stop accepting the DESTINATION positional argument in Docutils 1.0.
- Use ``--output=DESTINATION`` (cf. the "output_" configuration setting)
+ Use ``--output=DESTINATION`` (cf. the "output_path_" configuration setting)
or output redirection.
* Accept the short option ``-o`` for ``--output`` in Docutils 1.0
@@ -226,6 +226,8 @@
Use the long equivalents ``--input-encoding`` and ``--output-encoding``.
(See `command line interface`_ for the rationale.)
+ - Rename configuration setting "output" to "output_path_".
+
Output changes
LaTeX:
Don't wrap references with custom reference-label_ in a ``\hyperref``
@@ -303,6 +305,7 @@
.. _Docutils Document Model:
.. _Docutils XML: docs/ref/doctree.html
+.. _output_path: docs/user/config.html#output
Release 0.21.2 (2024-04-23)
Modified: trunk/docutils/docs/user/config.rst
===================================================================
--- trunk/docutils/docs/user/config.rst 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docs/user/config.rst 2024-12-04 13:32:20 UTC (rev 9993)
@@ -232,7 +232,6 @@
.. _ConfigParser.py:
https://docs.python.org/3/library/configparser.html
.. _Python: https://www.python.org/
-.. _RFC 822: https://www.rfc-editor.org/rfc/rfc822.txt
__ ../api/runtime-settings.html#active-sections
@@ -471,23 +470,23 @@
*Default*: "en" (English). *Options*: ``--language``, ``-l``.
-output
-------
+output_path
+-----------
-The path of the output destination. Use "-" for `stdout`.
+Output file path or "-" for `stdout`.
.. Caution:: **An existing file will be overwritten** without warning!
-Obsoletes the `_destination`_ positional argument
-(cf. `Future changes`_ in the RELEASE-NOTES).
+Obsoletes the second `positional argument`_ and the internal
+`_destination`_ setting (cf. `Future changes`_ in the RELEASE-NOTES).
-*Default*: None (stdout). *Option*: ``--output``.
+:Default: None (write to stdout).
+:Options: ``--output-path``, ``--output``.
-New in Docutils 0.20.
+New in Docutils 0.20.
+Renamed from "_`output`" to "output_path" in Docutils 0.22.
-.. _Future changes: ../../RELEASE-NOTES.html#future-changes
-
output_encoding
---------------
@@ -1325,7 +1324,7 @@
List of paths to CSS stylesheets (comma-separated_). Relative paths are
expanded if a matching file is found in the stylesheet_dirs__.
If embed_stylesheet__ is False, paths are rewritten relative to
-the output_ file (if specified) or the current work directory.
+the output_path_ (if specified) or the current work directory.
See also `stylesheet_path [latex writers]`_.
@@ -1885,8 +1884,7 @@
List of style files (comma-separated_). Relative paths are expanded if a
matching file is found in the stylesheet_dirs__.
If embed_stylesheet__ is False, paths are rewritten relative to
-the output file (if output_ or `_destination`_ are specified)
-or the current work directory.
+the output_path_ (if specified) or the current work directory.
Overrides also stylesheet__. [#override]_
See also `stylesheet_path [html writers]`_.
@@ -2194,7 +2192,7 @@
parsed after the standard configuration files. Path settings [#pwd]_ in
these files are resolved relative to the respective directory.
-The output_ setting is ignored.
+The output_path_ setting is ignored.
dry_run
~~~~~~~
@@ -2394,10 +2392,9 @@
_destination
~~~~~~~~~~~~
-Path to output destination, set from `positional arguments`_
-or the output_ setting.
+Path to the output file, set from `positional arguments`_.
-Deprecated, obsoleted by the output_ setting. Will be removed
+Deprecated, obsoleted by the output_path_ setting. Will be removed
in Docutils 2.0 (cf. `Future changes`_ in the RELEASE-NOTES).
*Default*: None (stdout). *Option*: ``--output``.
@@ -2569,8 +2566,11 @@
.. _front-end tool:
.. _front-end tools: tools.html
.. _buildhtml.py: tools.html#buildhtml-py
+.. _positional argument:
.. _positional arguments: tools.html#usage-pattern
+.. _Future changes: ../../RELEASE-NOTES.html#future-changes
+
.. _BCP 47: https://www.rfc-editor.org/rfc/bcp/bcp47.txt
.. _Error Handlers:
https://docs.python.org/3/library/codecs.html#error-handlers
Modified: trunk/docutils/docs/user/latex.rst
===================================================================
--- trunk/docutils/docs/user/latex.rst 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docs/user/latex.rst 2024-12-04 13:32:20 UTC (rev 9993)
@@ -1789,7 +1789,7 @@
The encoding of the LaTeX source file is Docutils' *output* encoding
but LaTeX' *input* encoding.
-Option: output-encoding_
+Option: output_encoding_
``--output-encoding=OUTPUT-ENCODING``
Default:
@@ -1824,7 +1824,7 @@
(where *n* is the Unicode page-number) to the style sheet might help.
.. _LaTeX Unicode: http://www.unruh.de/DniQ/latex/unicode/
-.. _output-encoding: config.html#output-encoding
+.. _output_encoding: config.html#output-encoding
.. _inputenc: https://ctan.org/pkg/inputenc
.. _ucs: https://ctan.org/pkg/unicode
@@ -2085,7 +2085,7 @@
With "traditional" TeX engines (e.g. pdflatex_):
-- Generate LaTeX code with `output-encoding`_ "utf-8".
+- Generate LaTeX code with the default `output_encoding`_ "utf-8".
- Add the pmboxdraw_ package to the `style sheets`_.
(For shaded boxes also add the `color` package.)
Modified: trunk/docutils/docs/user/slide-shows.rst
===================================================================
--- trunk/docutils/docs/user/slide-shows.rst 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docs/user/slide-shows.rst 2024-12-04 13:32:20 UTC (rev 9993)
@@ -120,7 +120,7 @@
.. class:: handout
The console script to generate S5 slide shows.
-
+
.. _rst2s5: tools.html#rst2s5
.. topic:: Keyboard Controls
@@ -374,11 +374,11 @@
to an existing theme using the ``--theme-url`` option.
.. [#copy-theme] Theme files can only be copied by Docutils, if the
- output_ destination path is specified.
-
- .. _output: config.html#output
+ `output path`_ is specified.
+ .. _output path: config.html#output-path
+
Generating a Slide Show (2)
===========================
@@ -487,10 +487,10 @@
* http://mozilla.wikicities.com/wiki/Firefox_S5:Designs
* http://lachy.id.au/dev/mozilla/firefox/s5/
* http://www.openlight.com/Python-S5-Theme.tar.gz
-
- Do a web search for "S5
- theme" and you're bound to find plenty of choices.
+ Do a web search for "S5 theme" and you're bound to find plenty
+ of choices.
+
* "``--theme``" option.
.. container:: handout
Modified: trunk/docutils/docs/user/tools.rst
===================================================================
--- trunk/docutils/docs/user/tools.rst 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docs/user/tools.rst 2024-12-04 13:32:20 UTC (rev 9993)
@@ -331,10 +331,11 @@
<slide-shows.html>`_.
.. [#copy-theme] Theme files can only be copied by Docutils, if the
- output_ destination path is specified.
+ `output path`_ is specified.
-.. _output: config.html#output
+.. _output path: config.html#output-path
+
buildhtml.py
------------
Modified: trunk/docutils/docutils/core.py
===================================================================
--- trunk/docutils/docutils/core.py 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docutils/core.py 2024-12-04 13:32:20 UTC (rev 9993)
@@ -30,6 +30,7 @@
from docutils.readers import doctree
if TYPE_CHECKING:
+ from typing import TextIO
from docutils.nodes import StrPath
@@ -213,25 +214,33 @@
error_handler=self.settings.input_encoding_error_handler)
def set_destination(self,
- destination: str | None = None,
+ destination: TextIO | None = None,
destination_path: StrPath | None = None,
) -> None:
- if destination_path is None:
- if (self.settings.output and self.settings._destination
- and self.settings.output != self.settings._destination):
- raise SystemExit('The positional argument <destination> is '
- 'obsoleted by the --output option. '
+ # Provisional: the "_destination" and "output" settings
+ # are deprecated and will be ignored in Docutils 2.0.
+ if destination_path is not None:
+ self.settings.output_path = os.fspath(destination_path)
+ else:
+ # check 'output_path' and legacy settings
+ if getattr(self.settings, 'output', None
+ ) and not self.settings.output_path:
+ self.settings.output_path = self.settings.output
+ if (self.settings.output_path and self.settings._destination
+ and self.settings.output_path != self.settings._destination):
+ raise SystemExit('The --output-path option obsoletes the '
+ 'second positional argument (DESTINATION). '
'You cannot use them together.')
- if self.settings.output == '-': # means stdout
- self.settings.output = None
- destination_path = (self.settings.output
- or self.settings._destination)
- else:
- destination_path = os.fspath(destination_path)
- self.settings._destination = destination_path
+ if self.settings.output_path is None:
+ self.settings.output_path = self.settings._destination
+ if self.settings.output_path == '-': # use stdout
+ self.settings.output_path = None
+ self.settings._destination = self.settings.output \
+ = self.settings.output_path
+
self.destination = self.destination_class(
destination=destination,
- destination_path=destination_path,
+ destination_path=self.settings.output_path,
encoding=self.settings.output_encoding,
error_handler=self.settings.output_encoding_error_handler)
Modified: trunk/docutils/docutils/frontend.py
===================================================================
--- trunk/docutils/docutils/frontend.py 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docutils/frontend.py 2024-12-04 13:32:20 UTC (rev 9993)
@@ -687,7 +687,7 @@
None,
(('Output destination name. Obsoletes the <destination> '
'positional argument. Default: None (stdout).',
- ['--output'], {'metavar': '<destination>'}),
+ ['--output-path', '--output'], {'metavar': '<destination>'}),
('Specify the document title as metadata.',
['--title'], {'metavar': '<title>'}),
('Include a "Generated by Docutils" credit and link.',
Modified: trunk/docutils/docutils/transforms/universal.py
===================================================================
--- trunk/docutils/docutils/transforms/universal.py 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docutils/transforms/universal.py 2024-12-04 13:32:20 UTC (rev 9993)
@@ -67,7 +67,7 @@
if settings.source_url:
source = settings.source_url
else:
- source = utils.relative_path(settings._destination,
+ source = utils.relative_path(settings.output_path,
settings._source)
text.extend([
nodes.reference('', 'View document source',
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docutils/utils/__init__.py 2024-12-04 13:32:20 UTC (rev 9993)
@@ -587,7 +587,7 @@
assert not settings.stylesheet, (
'stylesheet and stylesheet_path are mutually exclusive.')
if relative_to is None:
- relative_to = settings._destination
+ relative_to = settings.output_path
return relative_path(relative_to, settings.stylesheet_path)
else:
return settings.stylesheet
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docutils/writers/_html_base.py 2024-12-04 13:32:20 UTC (rev 9993)
@@ -533,7 +533,7 @@
# else link to style file:
if adjust_path:
# rewrite path relative to output (cf. config.html#stylesheet-path)
- path = utils.relative_path(self.settings._destination, path)
+ path = utils.relative_path(self.settings.output_path, path)
return self.stylesheet_link % self.encode(path)
def starttag(self, node, tagname, suffix='\n', empty=False, **attributes):
@@ -645,7 +645,7 @@
__ https://www.rfc-editor.org/rfc/rfc3986.html
"""
- destination = self.settings._destination or ''
+ destination = self.settings.output_path or ''
uri_parts = urllib.parse.urlparse(uri)
if uri_parts.scheme not in ('', 'file'):
raise ValueError('Can only read local images.')
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-04 13:32:20 UTC (rev 9993)
@@ -1440,7 +1440,7 @@
cmd = r'\input{%s}'
if self.settings.stylesheet_path:
# adapt path relative to output (cf. config.html#stylesheet-path)
- return cmd % utils.relative_path(self.settings._destination, path)
+ return cmd % utils.relative_path(self.settings.output_path, path)
return cmd % path.as_posix()
def to_latex_encoding(self, docutils_encoding):
Modified: trunk/docutils/docutils/writers/s5_html/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/s5_html/__init__.py 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/docutils/writers/s5_html/__init__.py 2024-12-04 13:32:20 UTC (rev 9993)
@@ -198,12 +198,12 @@
required_files_copied = {}
# This is a link (URL) in HTML, so we use "/", not os.sep:
self.theme_file_path = 'ui/%s' % settings.theme
- if not settings.output:
+ if not settings.output_path:
raise docutils.ApplicationError(
'Output path not specified, you may need to copy'
' the S5 theme files "by hand" or set the "--output" option.')
dest = os.path.join(
- os.path.dirname(settings.output), 'ui', settings.theme)
+ os.path.dirname(settings.output_path), 'ui', settings.theme)
if not os.path.isdir(dest):
os.makedirs(dest)
default = False
Modified: trunk/docutils/test/data/help/docutils.rst
===================================================================
--- trunk/docutils/test/data/help/docutils.rst 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/test/data/help/docutils.rst 2024-12-04 13:32:20 UTC (rev 9993)
@@ -11,7 +11,8 @@
=======
General Docutils Options
------------------------
---output=<destination> Output destination name. Obsoletes the <destination>
+--output-path=<destination>, --output=<destination>
+ Output destination name. Obsoletes the <destination>
positional argument. Default: None (stdout).
--title=<title> Specify the document title as metadata.
--generator, -g Include a "Generated by Docutils" credit and link.
Modified: trunk/docutils/test/data/help/rst2html.rst
===================================================================
--- trunk/docutils/test/data/help/rst2html.rst 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/test/data/help/rst2html.rst 2024-12-04 13:32:20 UTC (rev 9993)
@@ -12,7 +12,8 @@
=======
General Docutils Options
------------------------
---output=<destination> Output destination name. Obsoletes the <destination>
+--output-path=<destination>, --output=<destination>
+ Output destination name. Obsoletes the <destination>
positional argument. Default: None (stdout).
--title=<title> Specify the document title as metadata.
--generator, -g Include a "Generated by Docutils" credit and link.
Modified: trunk/docutils/test/data/help/rst2latex.rst
===================================================================
--- trunk/docutils/test/data/help/rst2latex.rst 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/test/data/help/rst2latex.rst 2024-12-04 13:32:20 UTC (rev 9993)
@@ -12,7 +12,8 @@
=======
General Docutils Options
------------------------
---output=<destination> Output destination name. Obsoletes the <destination>
+--output-path=<destination>, --output=<destination>
+ Output destination name. Obsoletes the <destination>
positional argument. Default: None (stdout).
--title=<title> Specify the document title as metadata.
--generator, -g Include a "Generated by Docutils" credit and link.
Modified: trunk/docutils/test/test_publisher.py
===================================================================
--- trunk/docutils/test/test_publisher.py 2024-12-03 13:12:26 UTC (rev 9992)
+++ trunk/docutils/test/test_publisher.py 2024-12-04 13:32:20 UTC (rev 9993)
@@ -139,14 +139,18 @@
def test_set_destination(self):
# Exit if `_destination` and `output` settings conflict.
publisher = core.Publisher()
- publisher.get_settings(output='out_name', _destination='out_name')
+ publisher.get_settings(output_path='out_name', _destination='other')
+ with self.assertRaises(SystemExit):
+ publisher.set_destination()
# no conflict if both have same value:
+ publisher.settings._destination = 'out_name'
publisher.set_destination()
# no conflict if both are overridden:
publisher.set_destination(destination_path='winning_dest')
- # ... also sets _destination to 'winning_dest' -> conflict
- with self.assertRaises(SystemExit):
- publisher.set_destination()
+ # "output_path" and legacy settings are set to `destination_path`:
+ self.assertEqual(publisher.settings.output_path, 'winning_dest')
+ self.assertEqual(publisher.settings.output, 'winning_dest')
+ self.assertEqual(publisher.settings._destination, 'winning_dest')
class ConvenienceFunctionTests(unittest.TestCase):
@@ -179,7 +183,7 @@
def test_destination_output_conflict(self):
# Exit if positional argument and --output option conflict.
- settings = {'output': 'out_name'}
+ settings = {'output_path': 'out_name'}
with self.assertRaises(SystemExit):
core.publish_cmdline(argv=['-', 'dest_name'],
settings_overrides=settings)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-04 13:32:45
|
Revision: 9994
http://sourceforge.net/p/docutils/code/9994
Author: milde
Date: 2024-12-04 13:32:39 +0000 (Wed, 04 Dec 2024)
Log Message:
-----------
Update "auto" input encoding warning.
Use FutureWarning instead of DeprecationWarning in front end tools if the
"input_encoding" setting uses the special values "" or None (auto-detect).
Add DeprecationWarning in `docutils.io.Input.decode()`.
Adapt tests.
Modified Paths:
--------------
trunk/docutils/docutils/frontend.py
trunk/docutils/docutils/io.py
trunk/docutils/test/test_io.py
trunk/docutils/test/test_publisher.py
Modified: trunk/docutils/docutils/frontend.py
===================================================================
--- trunk/docutils/docutils/frontend.py 2024-12-04 13:32:20 UTC (rev 9993)
+++ trunk/docutils/docutils/frontend.py 2024-12-04 13:32:39 UTC (rev 9994)
@@ -135,8 +135,9 @@
if value is None:
value = setting
if value == '':
- warnings.warn('Input encoding detection will be removed '
- 'in Docutils 1.0.', DeprecationWarning, stacklevel=2)
+ warnings.warn('Input encoding detection will be removed and the '
+ 'special encoding values None and "" become invalid '
+ 'in Docutils 1.0.', FutureWarning, stacklevel=2)
return None
try:
codecs.lookup(value)
Modified: trunk/docutils/docutils/io.py
===================================================================
--- trunk/docutils/docutils/io.py 2024-12-04 13:32:20 UTC (rev 9993)
+++ trunk/docutils/docutils/io.py 2024-12-04 13:32:39 UTC (rev 9994)
@@ -152,7 +152,9 @@
# explicitly given.
encoding_candidates = [self.encoding]
else:
- data_encoding = self.determine_encoding_from_data(data)
+ with warnings.catch_warnings():
+ warnings.filterwarnings('ignore', category=DeprecationWarning)
+ data_encoding = self.determine_encoding_from_data(data)
if data_encoding:
# `data` declares its encoding with "magic comment" or BOM,
encoding_candidates = [data_encoding]
@@ -168,6 +170,10 @@
fallback = locale.getpreferredencoding(do_setlocale=False)
if fallback and fallback.lower() != 'utf-8':
encoding_candidates.append(fallback)
+ if not self.encoding and encoding_candidates[0] != 'utf-8':
+ warnings.warn('Input encoding auto-detection will be removed and '
+ 'the encoding values None and "" become invalid '
+ 'in Docutils 1.0.', DeprecationWarning, stacklevel=2)
for enc in encoding_candidates:
try:
decoded = str(data, enc, self.error_handler)
@@ -195,13 +201,21 @@
)
"""Sequence of (start_bytes, encoding) tuples for encoding detection.
The first bytes of input data are checked against the start_bytes strings.
- A match indicates the given encoding."""
+ A match indicates the given encoding.
+ Internal. Will be removed in Docutils 1.0.
+ """
+
def determine_encoding_from_data(self, data: bytes) -> str | None:
"""
Try to determine the encoding of `data` by looking *in* `data`.
Check for a byte order mark (BOM) or an encoding declaration.
+
+ Deprecated. Will be removed in Docutils 1.0.
"""
+ warnings.warn('docutils.io.Input.determine_encoding_from_data() '
+ 'will be removed in Docutils 1.0.',
+ DeprecationWarning, stacklevel=2)
# check for a byte order mark:
for start_bytes, encoding in self.byte_order_marks:
if data.startswith(start_bytes):
Modified: trunk/docutils/test/test_io.py
===================================================================
--- trunk/docutils/test/test_io.py 2024-12-04 13:32:20 UTC (rev 9993)
+++ trunk/docutils/test/test_io.py 2024-12-04 13:32:39 UTC (rev 9994)
@@ -10,7 +10,6 @@
import codecs
import locale
-import os.path
import sys
import unittest
import warnings
@@ -34,7 +33,7 @@
EncodingWarning = UnicodeWarning # NoQA: A001 (builtin in Py > 0.9)
# DATA_ROOT is ./test/data/ from the docutils root
-DATA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data')
+DATA_ROOT = Path(__file__).parent / 'data'
# normalize the preferred encoding's name:
with warnings.catch_warnings():
@@ -118,13 +117,16 @@
expected = 'data\n\ufeff blah\n' # only leading ZWNBSP removed
input_ = du_io.StringInput(source=source.encode('utf-16-be'),
encoding=None)
- self.assertEqual(expected, input_.read())
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ self.assertEqual(expected, input_.read())
input_ = du_io.StringInput(source=source.encode('utf-16-le'),
encoding=None)
- self.assertEqual(expected, input_.read())
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ self.assertEqual(expected, input_.read())
input_ = du_io.StringInput(source=source.encode('utf-8'),
encoding=None)
- self.assertEqual(expected, input_.read())
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ self.assertEqual(expected, input_.read())
# With `str` input all ZWNBSPs are still there.
input_ = du_io.StringInput(source=source)
self.assertEqual(source, input_.read())
@@ -135,7 +137,8 @@
data
blah
""", encoding=None)
- data = input_.read() # noqa: F841
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ data = input_.read() # noqa: F841
self.assertEqual('ascii', input_.successful_encoding)
input_ = du_io.StringInput(source=b"""\
#! python
@@ -142,7 +145,8 @@
# -*- coding: ascii -*-
print("hello world")
""", encoding=None)
- data = input_.read() # noqa: F841
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ data = input_.read() # noqa: F841
self.assertEqual('ascii', input_.successful_encoding)
input_ = du_io.StringInput(source=b"""\
#! python
@@ -276,10 +280,10 @@
with warnings.catch_warnings():
if SUPPRESS_ENCODING_WARNING:
warnings.filterwarnings('ignore', category=EncodingWarning)
- source = du_io.FileInput(
- source_path=os.path.join(DATA_ROOT, 'utf-8-sig.rst'),
- encoding=None)
- self.assertTrue(source.read().startswith('Grüße'))
+ source = du_io.FileInput(source_path=DATA_ROOT/'utf-8-sig.rst',
+ encoding=None)
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ self.assertTrue(source.read().startswith('Grüße'))
def test_bom_utf_16(self):
"""Drop BOM from utf-16 encoded files, use correct encoding.
@@ -288,10 +292,10 @@
with warnings.catch_warnings():
if SUPPRESS_ENCODING_WARNING:
warnings.filterwarnings('ignore', category=EncodingWarning)
- source = du_io.FileInput(
- source_path=os.path.join(DATA_ROOT, 'utf-16-le-sig.rst'),
- encoding=None)
- self.assertTrue(source.read().startswith('Grüße'))
+ source = du_io.FileInput(source_path=DATA_ROOT/'utf-16-le-sig.rst',
+ encoding=None)
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ self.assertTrue(source.read().startswith('Grüße'))
def test_coding_slug(self):
"""Use self-declared encoding.
@@ -299,10 +303,10 @@
with warnings.catch_warnings():
if SUPPRESS_ENCODING_WARNING:
warnings.filterwarnings('ignore', category=EncodingWarning)
- source = du_io.FileInput(
- source_path=os.path.join(DATA_ROOT, 'latin2.rst'),
- encoding=None)
- self.assertTrue(source.read().endswith('škoda\n'))
+ source = du_io.FileInput(source_path=DATA_ROOT/'latin2.rst',
+ encoding=None)
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ self.assertTrue(source.read().endswith('škoda\n'))
def test_fallback_utf8(self):
"""Try 'utf-8', if encoding is not specified in the source."""
@@ -309,14 +313,12 @@
with warnings.catch_warnings():
if SUPPRESS_ENCODING_WARNING:
warnings.filterwarnings('ignore', category=EncodingWarning)
- source = du_io.FileInput(
- source_path=os.path.join(DATA_ROOT, 'utf8.rst'),
- encoding=None)
+ source = du_io.FileInput(source_path=DATA_ROOT/'utf8.rst',
+ encoding=None)
self.assertEqual('Grüße\n', source.read())
def test_readlines(self):
- source = du_io.FileInput(
- source_path=os.path.join(DATA_ROOT, 'include.rst'))
+ source = du_io.FileInput(source_path=DATA_ROOT/'include.rst')
data = source.readlines()
self.assertEqual(['Some include text.\n'], data)
Modified: trunk/docutils/test/test_publisher.py
===================================================================
--- trunk/docutils/test/test_publisher.py 2024-12-04 13:32:20 UTC (rev 9993)
+++ trunk/docutils/test/test_publisher.py 2024-12-04 13:32:39 UTC (rev 9994)
@@ -207,8 +207,9 @@
# input encoding detection will be removed in Docutils 1.0
source = '.. encoding: latin1\n\nGrüße'
settings['input_encoding'] = None
- output = core.publish_string(source.encode('latin1'),
- settings_overrides=settings)
+ with self.assertWarnsRegex(DeprecationWarning, 'auto-detection'):
+ output = core.publish_string(source.encode('latin1'),
+ settings_overrides=settings)
self.assertTrue(output.endswith('Grüße\n'))
def test_publish_string_output_encoding(self):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-04 13:32:57
|
Revision: 9995
http://sourceforge.net/p/docutils/code/9995
Author: milde
Date: 2024-12-04 13:32:53 +0000 (Wed, 04 Dec 2024)
Log Message:
-----------
Update/fix URI reference to filesystem path conversion.
Use "pathlib" instead of "os.path".
Return a `pathlib.Path` instance instead of a `str`.
Use Path.from_uri() for "file" URIs:
* Provide a backport for Python < 3.13.
* Don't apply "root_prefix" to "file:" URIs.
* "file:" URIs with relative path are invalid and now raise an Error.
Based on patch https://github.com/AA-Turner/docutils/pull/18
by Adam Turner.
Modified Paths:
--------------
trunk/docutils/docs/ref/doctree.rst
trunk/docutils/docs/user/config.rst
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/html4css1/__init__.py
trunk/docutils/test/functional/input/data/embed_images.rst
trunk/docutils/test/test_writers/test_html5_polyglot_parts.py
Modified: trunk/docutils/docs/ref/doctree.rst
===================================================================
--- trunk/docutils/docs/ref/doctree.rst 2024-12-04 13:32:39 UTC (rev 9994)
+++ trunk/docutils/docs/ref/doctree.rst 2024-12-04 13:32:53 UTC (rev 9995)
@@ -4490,6 +4490,9 @@
The ``uri`` attribute is used in the `\<image>`_ and `\<figure>`_
elements to refer to the image via a `URI Reference`_ [#]_. [rfc3986]_
+The `root_prefix`_ configuration setting is applied when a URI Reference
+starting with "/" is converted to a local filesystem path.
+
.. [#] Examples are a full URI, an *absolute-path reference* (begins with
a single slash character) or a *relative-path reference* (does not
begin with a slash character).
@@ -5198,6 +5201,7 @@
.. _id_prefix: ../user/config.html#id-prefix
.. _image_loading: ../user/config.html#image-loading
.. _report_level: ../user/config.html#report-level
+.. _root_prefix: ../user/config.html#root-prefix
.. _stylesheet: ../user/config.html#stylesheet
.. _syntax_highlight: ../user/config.html#syntax-highlight
Modified: trunk/docutils/docs/user/config.rst
===================================================================
--- trunk/docutils/docs/user/config.rst 2024-12-04 13:32:39 UTC (rev 9994)
+++ trunk/docutils/docs/user/config.rst 2024-12-04 13:32:53 UTC (rev 9995)
@@ -588,17 +588,28 @@
Base directory, prepended to a filesystem path__ starting with "/" when
including files with the `"include"`_, `"raw"`_, or `"csv-table"`_
directives.
+Also applied to the `"uri" attribute`_ of an <image> or <figure> starting
+with "/" when it is converted to a local filesystem path.
+Not applied to absolute Windows paths and ``file:`` URIs.
-Also applied when a writer converts an image URI__ to a local filesystem
-path in order to determine the image size or embed the image in the output.
+Example:
+ The HTML server for a documentation project serves files from the
+ "DocumentRoot" ``/var/www/html/``.
+ Image files are stored in a dedicated directory ``/var/www/html/pictures/``.
-:Default: "".
+ With ``root-prefix=/var/www/html``, the rST "image" directive ::
+
+ .. image:: /pictures/mylogo.png
+
+ works for LaTeX output and HTML output with embedded images as well as
+ for HTML output with images included via URI reference.
+
+:Default: "" (empty string).
:Option: ``--root-prefix``.
New in Docutils 0.21.
__ ../ref/rst/directives.html#path
-__ ../ref/rst/directives.html#uri
sectnum_xform
@@ -609,7 +620,7 @@
with the `"sectnum" directive`_.
If disabled, section numbers might be added to the output by the
-renderer (e.g. by LaTeX or via a CSS style definition).
+renderer (e.g. by CSS style rules or by LaTeX).
:Default: True.
:Options: ``--section-numbering``, ``--no-section-numbering``.
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2024-12-04 13:32:39 UTC (rev 9994)
+++ trunk/docutils/docutils/writers/_html_base.py 2024-12-04 13:32:53 UTC (rev 9995)
@@ -25,8 +25,8 @@
import os
import os.path
import re
+import sys
import urllib.parse
-import urllib.request
import warnings
import xml.etree.ElementTree as ET
from pathlib import Path
@@ -460,7 +460,7 @@
reading_problems.append('Reading external files disabled.')
if not reading_problems:
try:
- imagepath = self.uri2imagepath(uri)
+ imagepath = self.uri2path(uri)
with PIL.Image.open(imagepath) as img:
imgsize = img.size
except (ValueError, OSError, UnicodeEncodeError) as err:
@@ -626,38 +626,47 @@
return
child['classes'].append(class_)
- def uri2imagepath(self, uri):
- """Get POSIX filesystem path corresponding to an URI.
+ def uri2path(self, uri: str) -> Path:
+ """Return filesystem path corresponding to a `URI reference`__.
- The image directive expects an image URI__. Some writers require the
- corresponding image path to read the image size from the file or to
- embed the image in the output.
+ The `root_prefix`__ setting` is applied to URI references starting
+ with "/" (but not to absolute Windows paths or "file" URIs).
- URIs with absolute "path" part consider the ``root_prefix`` setting.
+ If the `output_path`__ setting is not empty, relative paths are
+ adjusted. (To work in the output document, URI references with
+ relative path relate to the output directory. For access by the
+ writer, paths must be relative to the working directory.)
- In order to work in the output document, URI references with relative
- path relate to the output directory. For access by the writer, the
- corresponding image path must be relative to the current working
- directory.
+ Use case:
+ The <image> element refers to the image via a "URI reference".
+ The corresponding filesystem path is required to read the
+ image size from the file or to embed the image in the output.
+ A filesystem path is also expected by the "LaTeX" output format
+ (with relative paths unchanged, relating to the output directory).
+
Provisional: the function's location, interface and behaviour
may change without advance warning.
- __ https://www.rfc-editor.org/rfc/rfc3986.html
+ __ https://www.rfc-editor.org/rfc/rfc3986.html#section-4.1
+ __ https://docutils.sourceforge.io/docs/user/config.html#root-prefix
+ __ https://docutils.sourceforge.io/docs/user/config.html#output-path
"""
- destination = self.settings.output_path or ''
- uri_parts = urllib.parse.urlparse(uri)
- if uri_parts.scheme not in ('', 'file'):
- raise ValueError('Can only read local images.')
- imagepath = urllib.parse.unquote(uri_parts.path)
- if self.settings.root_prefix and imagepath.startswith('/'):
- root_prefix = Path(self.settings.root_prefix)
- imagepath = (root_prefix/imagepath.removeprefix('/')).as_posix()
- elif not os.path.isabs(imagepath): # path may be absolute Windows path
- destdir = os.path.abspath(os.path.dirname(destination))
- imagepath = utils.relative_path(None,
- os.path.join(destdir, imagepath))
- return imagepath
+ if uri.startswith('file:'):
+ return Path.from_uri(uri)
+ uri_parts = urllib.parse.urlsplit(uri)
+ if uri_parts.scheme != '':
+ raise ValueError(f'Cannot get file path corresponding to {uri}.')
+ # extract and adjust path from "relative URI reference"
+ path = urllib.parse.unquote(uri_parts.path)
+ if self.settings.root_prefix and path.startswith('/'):
+ return Path(self.settings.root_prefix) / path.removeprefix('/')
+ path = Path(path)
+ if self.settings.output_path and not path.is_absolute():
+ # rewrite relative paths, but not "d:/foo" or similar
+ dest_dir = Path(self.settings.output_path).parent.resolve()
+ path = Path(utils.relative_path(None, dest_dir/path))
+ return path
def visit_Text(self, node) -> None:
text = node.astext()
@@ -1187,7 +1196,7 @@
atts['loading'] = 'lazy'
elif loading == 'embed':
try:
- imagepath = self.uri2imagepath(uri)
+ imagepath = self.uri2path(uri)
if mimetype == 'image/svg+xml':
imagedata = Path(imagepath).read_text(encoding='utf-8')
else:
@@ -1911,3 +1920,40 @@
visit_substitution_definition = ignore_node
visit_target = ignore_node
visit_pending = ignore_node
+
+
+# Backport `pathlib.Path.from_uri()` class method:
+
+if sys.version_info[:2] < (3, 13):
+ import pathlib
+
+ # subclassing from Path must consider the OS flavour
+ # https://stackoverflow.com/questions/29850801/subclass-pathlib-path-fails
+ class Path(type(pathlib.Path())): # noqa F811 (redefinition of 'Path')
+ """`pathlib.Path` with `from_uri()` classmethod backported from 3.13.
+ """
+ # copied from
+ # https://github.com/python/cpython/blob/3.13/Lib/pathlib/_local.py
+ # with minor adaptions
+ @classmethod
+ def from_uri(cls, uri):
+ """Return a new path from the given 'file' URI."""
+ if not uri.startswith('file:'):
+ raise ValueError(f"URI does not start with 'file:': {uri!r}")
+ path = uri[5:]
+ if path[:3] == '///':
+ # Remove empty authority
+ path = path[2:]
+ elif path[:12] == '//localhost/':
+ # Remove 'localhost' authority
+ path = path[11:]
+ if path[:3] == '///' or (path[:1] == '/' and path[2:3] in ':|'):
+ # Remove slash before DOS device/UNC path
+ path = path[1:]
+ if path[1:2] == '|':
+ # Replace bar with colon in DOS drive
+ path = path[:1] + ':' + path[2:]
+ path = cls(urllib.parse.unquote(path))
+ if not path.is_absolute():
+ raise ValueError(f"URI is not absolute: {uri!r}")
+ return path
Modified: trunk/docutils/docutils/writers/html4css1/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/html4css1/__init__.py 2024-12-04 13:32:39 UTC (rev 9994)
+++ trunk/docutils/docutils/writers/html4css1/__init__.py 2024-12-04 13:32:53 UTC (rev 9995)
@@ -572,7 +572,7 @@
if (PIL and ('width' not in node or 'height' not in node)
and self.settings.file_insertion_enabled):
try:
- imagepath = self.uri2imagepath(uri)
+ imagepath = self.uri2path(uri)
with PIL.Image.open(imagepath) as img:
img_size = img.size
except (ValueError, OSError, UnicodeEncodeError) as e:
@@ -579,8 +579,7 @@
self.document.reporter.warning(
f'Problem reading image file: {e}')
else:
- self.settings.record_dependencies.add(
- imagepath.replace('\\', '/'))
+ self.settings.record_dependencies.add(imagepath.as_posix())
if 'width' not in atts:
atts['width'] = '%dpx' % img_size[0]
if 'height' not in atts:
Modified: trunk/docutils/test/functional/input/data/embed_images.rst
===================================================================
--- trunk/docutils/test/functional/input/data/embed_images.rst 2024-12-04 13:32:39 UTC (rev 9994)
+++ trunk/docutils/test/functional/input/data/embed_images.rst 2024-12-04 13:32:53 UTC (rev 9995)
@@ -6,7 +6,7 @@
directly included, other images are base64_ encoded and included
as a `data URI`_.
-.. figure:: file:../../../docs/user/rst/images/biohazard.png
+.. figure:: ../../../docs/user/rst/images/biohazard.png
:alt: biohazard
:align: left
:width: 2em
@@ -15,7 +15,7 @@
Embedded PNG image in a figure.
-.. figure:: file:../../../docs/user/rst/images/biohazard-scaling.svg
+.. figure:: ../../../docs/user/rst/images/biohazard-scaling.svg
:alt: biohazard
:align: right
:width: 2em
Modified: trunk/docutils/test/test_writers/test_html5_polyglot_parts.py
===================================================================
--- trunk/docutils/test/test_writers/test_html5_polyglot_parts.py 2024-12-04 13:32:39 UTC (rev 9994)
+++ trunk/docutils/test/test_writers/test_html5_polyglot_parts.py 2024-12-04 13:32:53 UTC (rev 9995)
@@ -23,12 +23,6 @@
import docutils.core
from docutils.writers import html5_polyglot
-# TEST_ROOT is ./test/ from the docutils root
-TEST_ROOT = Path(__file__).parents[1]
-DATA_ROOT = TEST_ROOT / 'data'
-ROOT_PREFIX = (TEST_ROOT / 'functional/input').as_posix()
-
-
# Parts returned by `publish_parts()` for the HTML5 writer by default:
# * empty input string
# * default configuration settings.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-04 13:33:24
|
Revision: 9996
http://sourceforge.net/p/docutils/code/9996
Author: milde
Date: 2024-12-04 13:33:06 +0000 (Wed, 04 Dec 2024)
Log Message:
-----------
Provide a generic Translator base class for writers.
Move the `uri2path()` method there.
Use it in LaTeX and HTML writers to reduce code duplication and
unify the handling of image URI references.
Using `uri2path()` in the ODT writer would be a backwards-incompatible
change: The ODT writer expects relative image paths to be relative to
the **source** directory. Announce upcoming change for the ODT writer.
Modified Paths:
--------------
trunk/docutils/RELEASE-NOTES.rst
trunk/docutils/docutils/writers/__init__.py
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/latex2e/__init__.py
Modified: trunk/docutils/RELEASE-NOTES.rst
===================================================================
--- trunk/docutils/RELEASE-NOTES.rst 2024-12-04 13:32:53 UTC (rev 9995)
+++ trunk/docutils/RELEASE-NOTES.rst 2024-12-04 13:33:06 UTC (rev 9996)
@@ -124,6 +124,12 @@
__ docs/user/latex.html#length-units
+* "odt" writer:
+
+ - Align adjustment of relative image paths with the behaviour of HTML
+ and LaTeX writers: assume them relative to the *output* directory (as
+ required for image references in HTML), not the *source* directory.
+
Removals
--------
Modified: trunk/docutils/docutils/writers/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/__init__.py 2024-12-04 13:32:53 UTC (rev 9995)
+++ trunk/docutils/docutils/writers/__init__.py 2024-12-04 13:33:06 UTC (rev 9996)
@@ -11,18 +11,21 @@
__docformat__ = 'reStructuredText'
import importlib
+import sys
+import urllib
+from pathlib import Path
from typing import TYPE_CHECKING
import docutils
-from docutils import languages, Component
+from docutils import Component, languages, nodes, utils
from docutils.transforms import universal
if TYPE_CHECKING:
from typing import Any, Final
- from docutils import nodes
from docutils.io import Output
from docutils.languages import LanguageModule
+ from docutils.nodes import StrPath
from docutils.transforms import Transform
@@ -137,7 +140,108 @@
return Component.get_transforms(self)
-WRITER_ALIASES = {'html': 'html4css1', # may change to html5 some day
+class DoctreeTranslator(nodes.NodeVisitor):
+ """
+ Generic Docutils document tree translator base class.
+
+ Adds auxiliary methods and attributes that are used by several
+ Docutils writers to the `nodes.NodeVisitor` abstract superclass.
+ """
+
+ def __init__(self, document) -> None:
+ super().__init__(document)
+ self.settings = document.settings
+
+ def uri2path(self, uri: str, output_path: StrPath|None = None) -> Path:
+ """Return filesystem path corresponding to a `URI reference`__.
+
+ The `root_prefix`__ setting` is applied to URI references starting
+ with "/" (but not to absolute Windows paths or "file" URIs).
+
+ If `output_path` (defaults to the `output_path`__ setting) is
+ not empty, relative paths are adjusted.
+ (To work in the output document, URI references with relative path
+ relate to the output directory. For access by the writer, paths
+ must be relative to the working directory.)
+
+ Use case:
+ The <image> element refers to the image via a "URI reference".
+ The corresponding filesystem path is required to read the
+ image size from the file or to embed the image in the output.
+
+ A filesystem path is also expected by the "LaTeX" output format
+ (with relative paths unchanged, relating to the output directory,
+ set `output_path` to the empty string).
+
+ Provisional: the function's location, interface and behaviour
+ may change without advance warning.
+
+ __ https://www.rfc-editor.org/rfc/rfc3986.html#section-4.1
+ __ https://docutils.sourceforge.io/docs/user/config.html#root-prefix
+ __ https://docutils.sourceforge.io/docs/user/config.html#output-path
+ """
+ if output_path is None:
+ output_path = self.settings.output_path
+ if uri.startswith('file:'):
+ return Path.from_uri(uri)
+ uri_parts = urllib.parse.urlsplit(uri)
+ if uri_parts.scheme != '':
+ raise ValueError(f'Cannot get file path corresponding to {uri}.')
+ # extract and adjust path from "relative URI reference"
+ path = urllib.parse.unquote(uri_parts.path)
+ if self.settings.root_prefix and path.startswith('/'):
+ return Path(self.settings.root_prefix) / path.removeprefix('/')
+ path = Path(path)
+ # adjust relative paths (but not "d:/foo" or similar)
+ if output_path and not path.is_absolute():
+ dest_dir = Path(output_path).parent.resolve()
+ path = Path(utils.relative_path(None, dest_dir/path))
+ # TODO: support paths relative to the *source* directory?
+ # source_path, line = utils.get_source_line(node)
+ # if source_path:
+ # source_dir = Path(source_path).parent.resolve()
+ # path = Path(utils.relative_path(None, source_dir/path)
+ return path
+
+
+if sys.version_info[:2] < (3, 13):
+ # Backport `pathlib.Path.from_uri()` class method:
+ import pathlib
+
+ # subclassing from Path must consider the OS flavour
+ # https://stackoverflow.com/questions/29850801/subclass-pathlib-path-fails
+ class Path(type(pathlib.Path())): # noqa F811 (redefinition of 'Path')
+ """`pathlib.Path` with `from_uri()` classmethod backported from 3.13.
+ """
+
+ # `from_uri()` is copied from
+ # https://github.com/python/cpython/blob/3.13/Lib/pathlib/_local.py
+ # with minor adaptions
+ @classmethod
+ def from_uri(cls, uri):
+ """Return a new path from the given 'file' URI."""
+ if not uri.startswith('file:'):
+ raise ValueError(f"URI does not start with 'file:': {uri!r}")
+ path = uri[5:]
+ if path[:3] == '///':
+ # Remove empty authority
+ path = path[2:]
+ elif path[:12] == '//localhost/':
+ # Remove 'localhost' authority
+ path = path[11:]
+ if path[:3] == '///' or (path[:1] == '/' and path[2:3] in ':|'):
+ # Remove slash before DOS device/UNC path
+ path = path[1:]
+ if path[1:2] == '|':
+ # Replace bar with colon in DOS drive
+ path = path[:1] + ':' + path[2:]
+ path = cls(urllib.parse.unquote(path))
+ if not path.is_absolute():
+ raise ValueError(f"URI is not absolute: {uri!r}")
+ return path
+
+
+WRITER_ALIASES = {'html': 'html4css1', # will change to html5 in Docutils 2.0
'html4': 'html4css1',
'xhtml10': 'html4css1',
'html5': 'html5_polyglot',
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2024-12-04 13:32:53 UTC (rev 9995)
+++ trunk/docutils/docutils/writers/_html_base.py 2024-12-04 13:33:06 UTC (rev 9996)
@@ -25,8 +25,6 @@
import os
import os.path
import re
-import sys
-import urllib.parse
import warnings
import xml.etree.ElementTree as ET
from pathlib import Path
@@ -186,13 +184,13 @@
self.parts[part] = ''.join(getattr(self, part))
-class HTMLTranslator(nodes.NodeVisitor):
+class HTMLTranslator(writers.DoctreeTranslator):
"""
Generic Docutils to HTML translator.
See the `html4css1` and `html5_polyglot` writers for full featured
- HTML writers.
+ HTML translators.
.. IMPORTANT::
The `visit_*` and `depart_*` methods use a
@@ -292,9 +290,9 @@
"""MIME types supported by the HTML5 <video> element."""
def __init__(self, document) -> None:
- nodes.NodeVisitor.__init__(self, document)
+ super().__init__(document)
# process settings
- self.settings = settings = document.settings
+ settings = self.settings
self.language = languages.get_language(
settings.language_code, document.reporter)
self.initial_header_level = int(settings.initial_header_level)
@@ -626,48 +624,6 @@
return
child['classes'].append(class_)
- def uri2path(self, uri: str) -> Path:
- """Return filesystem path corresponding to a `URI reference`__.
-
- The `root_prefix`__ setting` is applied to URI references starting
- with "/" (but not to absolute Windows paths or "file" URIs).
-
- If the `output_path`__ setting is not empty, relative paths are
- adjusted. (To work in the output document, URI references with
- relative path relate to the output directory. For access by the
- writer, paths must be relative to the working directory.)
-
- Use case:
- The <image> element refers to the image via a "URI reference".
- The corresponding filesystem path is required to read the
- image size from the file or to embed the image in the output.
-
- A filesystem path is also expected by the "LaTeX" output format
- (with relative paths unchanged, relating to the output directory).
-
- Provisional: the function's location, interface and behaviour
- may change without advance warning.
-
- __ https://www.rfc-editor.org/rfc/rfc3986.html#section-4.1
- __ https://docutils.sourceforge.io/docs/user/config.html#root-prefix
- __ https://docutils.sourceforge.io/docs/user/config.html#output-path
- """
- if uri.startswith('file:'):
- return Path.from_uri(uri)
- uri_parts = urllib.parse.urlsplit(uri)
- if uri_parts.scheme != '':
- raise ValueError(f'Cannot get file path corresponding to {uri}.')
- # extract and adjust path from "relative URI reference"
- path = urllib.parse.unquote(uri_parts.path)
- if self.settings.root_prefix and path.startswith('/'):
- return Path(self.settings.root_prefix) / path.removeprefix('/')
- path = Path(path)
- if self.settings.output_path and not path.is_absolute():
- # rewrite relative paths, but not "d:/foo" or similar
- dest_dir = Path(self.settings.output_path).parent.resolve()
- path = Path(utils.relative_path(None, dest_dir/path))
- return path
-
def visit_Text(self, node) -> None:
text = node.astext()
encoded = self.encode(text)
@@ -1920,40 +1876,3 @@
visit_substitution_definition = ignore_node
visit_target = ignore_node
visit_pending = ignore_node
-
-
-# Backport `pathlib.Path.from_uri()` class method:
-
-if sys.version_info[:2] < (3, 13):
- import pathlib
-
- # subclassing from Path must consider the OS flavour
- # https://stackoverflow.com/questions/29850801/subclass-pathlib-path-fails
- class Path(type(pathlib.Path())): # noqa F811 (redefinition of 'Path')
- """`pathlib.Path` with `from_uri()` classmethod backported from 3.13.
- """
- # copied from
- # https://github.com/python/cpython/blob/3.13/Lib/pathlib/_local.py
- # with minor adaptions
- @classmethod
- def from_uri(cls, uri):
- """Return a new path from the given 'file' URI."""
- if not uri.startswith('file:'):
- raise ValueError(f"URI does not start with 'file:': {uri!r}")
- path = uri[5:]
- if path[:3] == '///':
- # Remove empty authority
- path = path[2:]
- elif path[:12] == '//localhost/':
- # Remove 'localhost' authority
- path = path[11:]
- if path[:3] == '///' or (path[:1] == '/' and path[2:3] in ':|'):
- # Remove slash before DOS device/UNC path
- path = path[1:]
- if path[1:2] == '|':
- # Replace bar with colon in DOS drive
- path = path[:1] + ':' + path[2:]
- path = cls(urllib.parse.unquote(path))
- if not path.is_absolute():
- raise ValueError(f"URI is not absolute: {uri!r}")
- return path
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-04 13:32:53 UTC (rev 9995)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-04 13:33:06 UTC (rev 9996)
@@ -14,7 +14,6 @@
import re
import string
-import urllib.parse
import warnings
from pathlib import Path
@@ -1130,7 +1129,7 @@
return False
-class LaTeXTranslator(nodes.NodeVisitor):
+class LaTeXTranslator(writers.DoctreeTranslator):
"""
Generate code for 8-bit LaTeX from a Docutils document tree.
@@ -1187,7 +1186,7 @@
# Settings
# ~~~~~~~~
- self.settings = settings = document.settings
+ settings = self.settings
# warn of deprecated settings and changing defaults:
if settings.use_latex_citations is None and not settings.use_bibtex:
settings.use_latex_citations = False
@@ -2437,8 +2436,8 @@
def visit_image(self, node) -> None:
self.requirements['graphicx'] = self.graphicx_package
attrs = node.attributes
- # image URI may use %-encoding
- imagepath = urllib.parse.unquote(attrs['uri'])
+ # convert image URI to filesystem path, do not adjust relative path:
+ imagepath = self.uri2path(attrs['uri'], output_path='')
# alignment defaults:
if 'align' not in attrs:
# Set default align of image in a figure to 'center'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-11 14:36:51
|
Revision: 9998
http://sourceforge.net/p/docutils/code/9998
Author: milde
Date: 2024-12-11 14:36:47 +0000 (Wed, 11 Dec 2024)
Log Message:
-----------
Test and fix `publish_parts()` with the LaTeX writer.
New test module for the LaTeX writer "parts" interface.
Make `writers.latex2e.Writer.assemble_parts()` idempotent
The `assemble_parts()` method adds newlines to "head" parts for better formatting
of the output file. However, is called in `translate()` and again by
publish_parts(), leading to spurious double trailing newlines.
Use super() when calling methods from the parent class.
Use f-strings
Modified Paths:
--------------
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/latex2e/__init__.py
Added Paths:
-----------
trunk/docutils/test/test_writers/test_latex2e_parts.py
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2024-12-11 14:36:22 UTC (rev 9997)
+++ trunk/docutils/docutils/writers/_html_base.py 2024-12-11 14:36:47 UTC (rev 9998)
@@ -179,7 +179,7 @@
return subs
def assemble_parts(self) -> None:
- writers.Writer.assemble_parts(self)
+ super().assemble_parts()
for part in self.visitor_attributes:
self.parts[part] = ''.join(getattr(self, part))
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-11 14:36:22 UTC (rev 9997)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-11 14:36:47 UTC (rev 9998)
@@ -294,8 +294,10 @@
def assemble_parts(self) -> None:
"""Assemble the `self.parts` dictionary of output fragments."""
- writers.Writer.assemble_parts(self)
+ super().assemble_parts()
for part in self.visitor_attributes:
+ if part in self.parts:
+ continue # make the function idempotent
lines = getattr(self, part)
if part in self.head_parts:
if lines:
@@ -1256,9 +1258,8 @@
# ~~~~~~~~~~~~~~~~~~~~~~~~
# Document parts
- self.head_prefix = [r'\documentclass[%s]{%s}' %
- (self.documentoptions,
- settings.documentclass)]
+ self.head_prefix = [f'\\documentclass[{self.documentoptions}]'
+ f'{{{settings.documentclass}}}']
self.requirements = {} # converted to a list in depart_document()
self.latex_preamble = [settings.latex_preamble]
self.fallbacks = {} # converted to a list in depart_document()
Added: trunk/docutils/test/test_writers/test_latex2e_parts.py
===================================================================
--- trunk/docutils/test/test_writers/test_latex2e_parts.py (rev 0)
+++ trunk/docutils/test/test_writers/test_latex2e_parts.py 2024-12-11 14:36:47 UTC (rev 9998)
@@ -0,0 +1,117 @@
+#! /usr/bin/env python3
+# $Id$
+# Author: Günter Milde
+# Maintainer: doc...@li...
+# :Copyright: 2024 Günter Milde,
+# :License: Released under the terms of the `2-Clause BSD license`_, in short:
+#
+# Copying and distribution of this file, with or without modification,
+# are permitted in any medium without royalty provided the copyright
+# notice and this notice are preserved.
+# This file is offered as-is, without any warranty.
+#
+# .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
+
+"""
+Test `core.publish_parts()`__ with the LaTeX writer.
+
+__ https://docutils.sourceforge.io/docs/api/publisher.html#publish-parts
+"""
+
+from pathlib import Path
+import sys
+import unittest
+
+
+if __name__ == '__main__':
+ # prepend the "docutils root" to the Python library path
+ # so we import the local `docutils` package.
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+import docutils
+from docutils.core import publish_parts
+from docutils.writers import latex2e
+
+
+class LaTeXWriterPublishPartsTestCase(unittest.TestCase):
+ """Test LaTeX writer `publish_parts()` interface."""
+
+ maxDiff = None
+ settings = {'_disable_config': True,
+ 'strict_visitor': True,
+ # avoid latex writer future warnings:
+ 'use_latex_citations': False,
+ 'legacy_column_widths': True,
+ }
+
+ def test_publish_parts(self):
+ for name, (settings_overrides, cases) in samples.items():
+ for casenum, (case_input, expected_parts) in enumerate(cases):
+ parts = publish_parts(
+ source=case_input,
+ writer=latex2e.Writer(),
+ settings_overrides=self.settings|settings_overrides,
+ )
+ expected = default_parts | expected_parts
+ expected['whole'] = expected['whole'].format(**expected)
+
+ for key in parts.keys():
+ with self.subTest(id=f'samples[{name!r}][{casenum}][{key}]'):
+ self.assertEqual(f'{expected[key]}', f'{parts[key]}')
+
+
+default_parts = {
+ 'abstract': '',
+ 'body': '',
+ 'body_pre_docinfo': '',
+ 'dedication': '',
+ 'docinfo': '',
+ 'encoding': 'utf-8',
+ 'errors': 'strict',
+ 'fallbacks': '',
+ 'head_prefix': '\\documentclass[a4paper]{article}\n',
+ 'latex_preamble': '% PDF Standard Fonts\n'
+ '\\usepackage{mathptmx} % Times\n'
+ '\\usepackage[scaled=.90]{helvet}\n'
+ '\\usepackage{courier}\n',
+ 'pdfsetup': '% hyperlinks:\n'
+ '\\ifdefined\\hypersetup\n'
+ '\\else\n'
+ ' \\usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref}\n'
+ ' \\usepackage{bookmark}\n'
+ ' \\urlstyle{same} % normal text font (alternatives: tt, rm, sf)\n'
+ '\\fi\n',
+ 'requirements': '\\usepackage[T1]{fontenc}\n',
+ 'stylesheet': '',
+ 'subtitle': '',
+ 'title': '',
+ 'titledata': '',
+ 'version': f'{docutils.__version__}',
+ 'whole': '{head_prefix}'
+ '% generated by Docutils <https://docutils.sourceforge.io/>\n'
+ '\\usepackage{{cmap}} % fix search and cut-and-paste in Acrobat\n'
+ '{requirements}\n'
+ '%%% Custom LaTeX preamble\n'
+ '{latex_preamble}\n'
+ '%%% User specified packages and stylesheets\n'
+ '{stylesheet}\n'
+ '%%% Fallback definitions for Docutils-specific commands\n'
+ '{fallbacks}\n'
+ '{pdfsetup}\n'
+ '%%% Body\n'
+ '\\begin{{document}}\n'
+ '{body}\n'
+ '\\end{{document}}\n'
+ }
+
+samples = {}
+
+samples['default'] = ({}, [
+['', # empty input string
+ {} # results in default parts
+ ],
+])
+
+
+if __name__ == '__main__':
+ unittest.main()
Property changes on: trunk/docutils/test/test_writers/test_latex2e_parts.py
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision
\ No newline at end of property
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-11 21:14:53
|
Revision: 9999
http://sourceforge.net/p/docutils/code/9999
Author: milde
Date: 2024-12-11 21:14:49 +0000 (Wed, 11 Dec 2024)
Log Message:
-----------
Support SVG images in LaTeX with the "svg" package.
Modified Paths:
--------------
trunk/docutils/HISTORY.rst
trunk/docutils/docs/ref/rst/directives.rst
trunk/docutils/docs/user/config.rst
trunk/docutils/docs/user/latex.rst
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/test/test_writers/test_latex2e.py
Modified: trunk/docutils/HISTORY.rst
===================================================================
--- trunk/docutils/HISTORY.rst 2024-12-11 14:36:47 UTC (rev 9998)
+++ trunk/docutils/HISTORY.rst 2024-12-11 21:14:49 UTC (rev 9999)
@@ -177,8 +177,11 @@
- Mark the main language when loading "babel".
- Provide an "unknown_references_resolver" (cf. `docutils/TransformSpec`)
for citation references resolved with BibTeX (cf. `use_bibtex`_ setting).
+ - Support SVG image inclusion with the "svg" LaTeX package (see the
+ `stylesheet`__ configuration setting).
.. _reference-label: docs/user/config.html#reference-label
+ __ docs/user/config.html#stylesheet-latex-writers
* docutils/writers/latex2e/docutils.sty
Modified: trunk/docutils/docs/ref/rst/directives.rst
===================================================================
--- trunk/docutils/docs/ref/rst/directives.rst 2024-12-11 14:36:47 UTC (rev 9998)
+++ trunk/docutils/docs/ref/rst/directives.rst 2024-12-11 21:14:49 UTC (rev 9999)
@@ -171,7 +171,7 @@
HTML5_ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓
-LaTeX_ [#]_ ✓ ✓ ✓
+LaTeX_ [#]_ ✓ [#]_ ✓ ✓ ✓
ODT_ ✓ ✓ ✓ ✓ ✓
=========== ====== ====== ===== ===== ===== ===== ===== ===== ===== =====
@@ -190,6 +190,9 @@
Some build systems, e.g. rubber_ support additional formats
via on-the-fly image conversion.
+.. [#] New in Docutils 0.22.
+ The `"svg" package`_ must be listed in the stylesheet__ setting.
+
__ https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types
.. _HTML4:
.. _html4 writer: ../../user/html.html#html4css1
@@ -198,7 +201,9 @@
.. _LaTeX: ../../user/latex.html#image-inclusion
.. _ODT: ../../user/odt.html
.. _manpage: ../../user/manpage.html
-.. _rubber: https://github.com/petrhosek/rubber
+.. _rubber: https://gitlab.com/latex-rubber/rubber
+.. _"svg" package: https://ctan.org/pkg/svg
+__ ../../user/config.html#stylesheet-latex-writers
Image
@@ -271,7 +276,7 @@
``height`` : length_
The desired height of the image.
- Used to reserve space or scale the image vertically. When the ``scale``
+ Used to reserve space or scale the image vertically. When the scale_
option is also specified, they are combined. For example, a height of
200px and a scale of 50 is equivalent to a height of 100px with no scale.
@@ -288,6 +293,8 @@
(New in Docutils 0.21.)
+ .. _scale:
+
``scale`` : integer percentage (the "%" symbol is optional)
The uniform scaling factor of the image. The default is "100 %",
i.e. no scaling.
@@ -305,7 +312,7 @@
``width`` : length_ or percentage_ of the current line width
The width of the image.
Used to reserve space or scale the image horizontally. As with ``height``
- above, when the ``scale`` option is also specified, they are combined.
+ above, when the scale_ option is also specified, they are combined.
.. [#] Currently only recognized by the `HTML5 writer`_
(overriding the `image_loading`_ configuration setting).
@@ -596,7 +603,7 @@
The parsing can be turned off with the syntax_highlight_ configuration
setting and command line option or by specifying the language as
-`class <class option_>`_ option instead of directive argument.
+`class <class option>`_ option instead of directive argument.
This also avoids warnings when Pygments_ is not installed or the language
is not in the `supported languages and markup formats`_.
@@ -2295,7 +2302,6 @@
.. _loading attribute: ../doctree.html#loading
.. _names attribute: ../doctree.html#names
.. _title attribute: ../doctree.html#title-attribute
-.. _uri attribute: ../doctree.html#uri
.. _width attribute: ../doctree.html#width
.. _<admonition>: ../doctree.html#admonition
.. _<attention>: ../doctree.html#attention
Modified: trunk/docutils/docs/user/config.rst
===================================================================
--- trunk/docutils/docs/user/config.rst 2024-12-11 14:36:47 UTC (rev 9998)
+++ trunk/docutils/docs/user/config.rst 2024-12-11 21:14:49 UTC (rev 9999)
@@ -1853,7 +1853,7 @@
stylesheet
~~~~~~~~~~
-List of style files (comma-separated_). Used verbatim
+Comma-separated_ list of style files (LaTeX packages). Used verbatim
(under Windows, path separators are normalized to forward slashes).
Overrides also stylesheet_path__. [#override]_
See also `stylesheet [html writers]`_.
@@ -1863,11 +1863,23 @@
extension) or ``\input`` (any other extension).
LaTeX will search the specified files in the `TeX input path`_.
+Some values change the behaviour of the LaTeX writer:
+
+:docutils: If the `"docutils" package`_ is listed, fallback definitions
+ for `Docutils specific LaTeX macros`_ are loaded from there
+ instead of literal inclusion in the output document.
+:svg: If the `"svg" package`_ is listed, SVG images_ are
+ included with the ``\includesvg`` command instead of
+ the default ``\includegraphics`` (new in Docutils 0.22).
+
*Default*: empty list. *Option*: ``--stylesheet``.
__ `stylesheet_path [latex writers]`_
__ `embed_stylesheet [latex writers]`_
.. _TeX input path: https://texfaq.org/FAQ-tds
+.. _"docutils" package: https://ctan.org/pkg/docutils
+.. _Docutils specific LaTeX macros: latex.html#docutils-specific-latex-macros
+.. _"svg" package: https://ctan.org/pkg/svg
.. _stylesheet_dirs [latex writers]:
@@ -2513,8 +2525,8 @@
.. References
+.. _Docutils Document Tree:
.. _Docutils Generic document type definition:
-.. _Docutils Document Tree:
.. _Document Tree: ../ref/doctree.html
.. _class attribute: ../ref/doctree.html#classes
.. _title attribute: ../ref/doctree.html#title-attribute
@@ -2536,6 +2548,7 @@
.. _"code": ../ref/rst/directives.html#code
.. _"csv-table": ../ref/rst/directives.html#csv-table
.. _"figure": ../ref/rst/directives.html#figure
+.. _images:
.. _"image": ../ref/rst/directives.html#image
.. _"include": ../ref/rst/directives.html#include
.. _"loading": ../ref/rst/directives.html#loading
Modified: trunk/docutils/docs/user/latex.rst
===================================================================
--- trunk/docutils/docs/user/latex.rst 2024-12-11 14:36:47 UTC (rev 9998)
+++ trunk/docutils/docs/user/latex.rst 2024-12-11 21:14:49 UTC (rev 9999)
@@ -60,30 +60,29 @@
------------------------------
Some Docutils objects have no LaTeX counterpart, they will be typeset
-using a Docutils specific LaTeX *macro* (command, environment, or
-length) to allow customization. By convention, special macros use the
-prefix ``\DU``\ [#]_.
+using a Docutils specific LaTeX *macro* (command, environment, or length)
+to allow customization. By convention, these macros use the prefix
+``\DU``\ [#]_.
+Fallback definitions are included after the `custom style sheets`_,
+for all macros required in the document. Alternatively, you may list
+"docutils" in the `stylesheet`_ setting to use the `"docutils" package`_
+instead.
-The `docutils.sty`_ LaTeX package providing required definitions is
-part of Docutils ≥ 0.17 and available on CTAN since 2020-09-04.
-The generated LaTeX documents should be kept processable by a standard LaTeX
-installation. Therefore fallback definitions are included after the `custom
-style sheets`_, if a macro is required in the document and
-the `stylesheet`_ setting does not include "docutils".
-
* Custom `style sheets`_ can define alternative implementations with
``\newcommand``, ``\newenvironment``, and ``\newlength`` followed by
``\setlength``.
-* Definitions with `raw LaTeX`_ are part of the document body. Use
+* Definitions with `raw LaTeX`_ are part of the document body. Use
``\def``, ``\renewcommand`` or ``\renewenvironment``, and ``\setlength``.
-See the test output standalone_rst_latex.tex_ for an example of the fallback
-definitions and their use in the document.
+See docutils.sty_ and the test output `standalone_rst_latex.tex`_ for
+an example of the fallback definitions and their use in the document.
.. [#] DU for Documentation Utilities = Docutils
-.. _docutils.sty: https://ctan.org/pkg/docutils
+.. _"docutils" package: https://ctan.org/pkg/docutils
+.. _docutils.sty:
+ https://mirrors.ctan.org/macros/latex/contrib/docutils/docutils.sty.html
.. _length unit:
@@ -1974,35 +1973,43 @@
image inclusion
```````````````
-Images__ are included in LaTeX with the help of the `graphicx` package. The
-supported file formats depend on the used driver:
+Images_ are included in LaTeX with the help of the `graphicx`_ package.
+The supported graphic formats depend on the postprocessor:
-* pdflatex_, lualatex, and xelatex_ work with PNG, JPG, or PDF,
- but **not EPS**.
-* Standard latex_ can include **only EPS** graphics, no other format.
-* latex + dvipdfmx works with EPS and JPG (add 'dvipdfmx' to the
- documentoptions_ or graphicx-option_ setting
- and 'bmpsize' to the stylesheet_ setting).
+* pdflatex_, lualatex_, and xelatex_ work with PNG, JPG, and PDF
+ but *not EPS*.
-If PDF-image inclusion in PDF files fails, specifying
-``--graphicx-option=pdftex`` might help.
+* When compiling to DVI with the ``latex`` command, support depends on
+ the viewer or post-processor:
+ - dvips supports EPS but not other format,
+ - dvipdfmx works with EPS and JPG (add 'dvipdfmx' to the documentoptions_
+ or graphicx-option_ setting and 'bmpsize' to the stylesheet_ setting).
+
+* SVG images are supported if the `"svg" package`_ is listed in the
+ stylesheet_ setting. Pass the ``--shell-escape`` option to the LaTeX
+ compiler to enable image conversion on the fly by Inkscape_.
+ (New in Docutils 0.22.)
+
+* The Rubber_ wrapper can be used for automatic image conversion.
+
For details see grfguide.pdf_.
-The Rubber_ wrapper can be used for automatic image conversion.
-
Docutils expects a URI-reference_ as pointer to the image ressource.
-LaTeX requires it to refer to a local file.
+The LaTeX writer transforms it to a filesystem path.
By default, LaTeX does not accept spaces and more than one dot in the
filename. If using "traditional" filenames is not an option, loading the
grffile_ package may help.
-__ ../ref/rst/directives.html#images
+.. _images: ../ref/rst/directives.html#images
+.. _graphicx: https://ctan.org/pkg/graphicx
+.. _graphicx-option: config.html#graphicx-option
.. _grfguide.pdf:
https://mirrors.ctan.org/macros/latex/required/graphics/grfguide.pdf
+.. _URI-reference: https://www.rfc-editor.org/rfc/rfc3986.html#section-4.1
+.. _"svg" package: https://ctan.org/pkg/svg
+.. _Inkscape: https://inkscape.org/
.. _grffile: https://ctan.org/pkg/grffile
-.. _graphicx-option: config.html#graphicx-option
-.. _URI-reference: https://www.rfc-editor.org/rfc/rfc3986.html#section-4.1
Why are my images too big?
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-11 14:36:47 UTC (rev 9998)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-11 21:14:49 UTC (rev 9999)
@@ -2483,10 +2483,14 @@
post.append('\n')
pre.reverse()
self.out.extend(pre)
+ if imagepath.suffix == '.svg' and 'svg' in self.settings.stylesheet:
+ cmd = 'includesvg'
+ else:
+ cmd = 'includegraphics'
options = ''
if include_graphics_options:
- options = '[%s]' % (','.join(include_graphics_options))
- self.out.append('\\includegraphics%s{%s}' % (options, imagepath))
+ options = f"[{','.join(include_graphics_options)}]"
+ self.out.append(f'\\{cmd}{options}{{{imagepath}}}')
self.out.extend(post)
def depart_image(self, node) -> None:
Modified: trunk/docutils/test/test_writers/test_latex2e.py
===================================================================
--- trunk/docutils/test/test_writers/test_latex2e.py 2024-12-11 14:36:47 UTC (rev 9998)
+++ trunk/docutils/test/test_writers/test_latex2e.py 2024-12-11 21:14:49 UTC (rev 9999)
@@ -163,15 +163,39 @@
"""],
])
-samples['image'] = ({}, [
-[".. image:: blue%20square.png",
+samples['images'] = ({}, [
+["""
+.. image:: blue%20square.png
+.. image:: vectors.svg
+""",
head_image + r"""
\includegraphics{blue square.png}
+\includegraphics{vectors.svg}
+
\end{document}
"""],
])
+samples['svg-image'] = ({'stylesheet': 'svg'}, [
+["""
+.. image:: pixels.png
+.. image:: vectors.svg
+""",
+head_template.substitute(dict(parts,
+requirements=r"""\usepackage[T1]{fontenc}
+\usepackage{graphicx}
+""",
+stylesheet=r"""\usepackage{svg}
+""")) + r"""
+\includegraphics{pixels.png}
+
+\includesvg{vectors.svg}
+
+\end{document}
+"""],
+])
+
samples['spanish_quote'] = ({}, [
[".. role:: language-es\n\nUnd damit :language-es:`basta`!",
head_template.substitute(dict(parts,
@@ -1145,6 +1169,7 @@
"""],
])
+
samples['stylesheet_path'] = ({'stylesheet_path': f'{spam},{ham}'}, [
["""two stylesheet links in the header""",
head_template.substitute(dict(parts,
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-12 18:10:10
|
Revision: 10000
http://sourceforge.net/p/docutils/code/10000
Author: milde
Date: 2024-12-12 18:10:04 +0000 (Thu, 12 Dec 2024)
Log Message:
-----------
"reStructuredText Specification" tweaks (mainly formatting).
Mainly formatting (line breaks, inline literals instead of double quotes
for rST input syntax examples).
Show footnote symbols as literal chars instead of HTML character entities.
Use colons around role names (like in the "standard roles" documentation).
Slightly more discernible background colour for literals in "responsive.css"
style sheet.
Modified Paths:
--------------
trunk/docutils/docs/ref/rst/restructuredtext.rst
trunk/docutils/docs/user/config.rst
trunk/docutils/docutils/writers/html5_polyglot/responsive.css
Modified: trunk/docutils/docs/ref/rst/restructuredtext.rst
===================================================================
--- trunk/docutils/docs/ref/rst/restructuredtext.rst 2024-12-11 21:14:49 UTC (rev 9999)
+++ trunk/docutils/docs/ref/rst/restructuredtext.rst 2024-12-12 18:10:04 UTC (rev 10000)
@@ -82,7 +82,7 @@
- This is a bullet list.
- - Bullets can be "*", "+", or "-".
+ - Bullets can be ``*``, ``+``, or ``-``.
2. `Enumerated lists`_::
@@ -129,7 +129,7 @@
- `Literal blocks`_::
Literal blocks are either indented or line-prefix-quoted blocks,
- and indicated with a double-colon ("::") at the end of the
+ and indicated with a double-colon (``::``) at the end of the
preceding paragraph (right here -->)::
if literal_block:
@@ -147,8 +147,8 @@
- `Doctest blocks`_::
- >>> print 'Python-specific usage examples; begun with ">>>"'
- Python-specific usage examples; begun with ">>>"
+ >>> print 'Python-specific usage examples; begun with ">>> "'
+ Python-specific usage examples; begun with ">>> "
>>> print '(cut and pasted from interactive Python sessions)'
(cut and pasted from interactive Python sessions)
@@ -387,9 +387,9 @@
or `"figure"`_ directive), whitespace is ignored by default.
.. [#literal-context]
- In literal context (`literal blocks`_ and `inline literals`_,
+ In *literal context* (`literal blocks`_, `inline literals`_,
content of the `"code"`_, `"math"`_, and `"raw"`_ directives,
- content of the `"raw" role`_ and `custom roles`_ based on it),
+ content of the `:raw:`_ role and `custom roles`_ based on it),
reStructuredText markup characters lose their semantics
so there is no reason to escape them.
@@ -546,7 +546,7 @@
Rather than imposing a fixed number and order of section title
adornment styles, the order enforced will be the order as encountered.
-The first style encountered will be an outermost title (like HTML H1),
+The first style encountered will be an outermost title (like HTML <H1>),
the second style will be a subtitle, the third will be a subsubtitle,
and so on.
@@ -678,7 +678,7 @@
:Doctree elements: `\<bullet_list>`_, `\<list_item>`_
-A text block which begins with a "*", "+", "-", "•", "‣", or "⁃",
+A text block which begins with a ``*``, ``+``, ``-``, ``•``, ``‣``, or ``⁃``,
followed by whitespace, is a bullet list item (a.k.a. "unordered" list
item). List item bodies must be left-aligned and indented relative to
the bullet; the text immediately after the bullet determines the
@@ -738,7 +738,7 @@
- uppercase Roman numerals: I, II, III, IV, ..., MMMMCMXCIX (4999).
- lowercase Roman numerals: i, ii, iii, iv, ..., mmmmcmxcix (4999).
-In addition, the auto-enumerator, "#", may be used to automatically
+In addition, the auto-enumerator, ``#``, may be used to automatically
enumerate a list. Auto-enumerated lists may begin with explicit
enumeration, which sets the sequence. Fully auto-enumerated lists use
arabic numerals and begin with 1.
@@ -745,31 +745,31 @@
The following formatting types are recognized:
-- suffixed with a period: "1.", "A.", "a.", "I.", "i.".
-- surrounded by parentheses: "(1)", "(A)", "(a)", "(I)", "(i)".
-- suffixed with a right-parenthesis: "1)", "A)", "a)", "I)", "i)".
+- suffixed with a period: ``1.``, ``A.``, ``a.``, ``I.``, ``i.``.
+- surrounded by parentheses: ``(1)``, ``(A)``, ``(a)``, ``(I)``, ``(i)``.
+- suffixed with a right-parenthesis: ``1)``, ``A)``, ``a)``, ``I)``, ``i)``.
While parsing an enumerated list, a new list will be started whenever:
- An enumerator is encountered which does not have the same format and
- sequence type as the current list (e.g. "1.", "(a)" produces two
+ sequence type as the current list (e.g. ``1.``, ``(a)`` produces two
separate lists).
-- The enumerators are not in sequence (e.g., "1.", "3." produces two
+- The enumerators are not in sequence (e.g., ``1.``, ``3.`` produces two
separate lists).
-It is recommended that the enumerator of the first list item be
-ordinal-1 ("1", "A", "a", "I", or "i"). Although other start-values
-will be recognized, they may not be supported by the output format. A
-level-1 [info] system message will be generated for any list beginning
-with a non-ordinal-1 enumerator.
+It is recommended that the enumerator of the first list item be ordinal-1
+(``1``, ``A``, ``a``, ``I``, or ``i``).
+Although other start-values will be recognized, they may not be supported
+by the output format. A level-1 [info] system message will be generated
+for any list beginning with a non-ordinal-1 enumerator.
-Lists using Roman numerals must begin with "I"/"i" or a
-multi-character value, such as "II" or "XV". Any other
-single-character Roman numeral ("V", "X", "L", "C", "D", "M") will be
-interpreted as a letter of the alphabet, not as a Roman numeral.
+Lists using Roman numerals must begin with ``I``/``i`` or a
+multi-character value, such as ``II`` or ``XV``. Any other
+single-character Roman numeral (``V``, ``X``, ``L``, ``C``, ``D``, ``M``)
+will be interpreted as a letter of the alphabet, not as a Roman numeral.
Likewise, lists using letters of the alphabet may not begin with
-"I"/"i", since these are recognized as Roman numeral 1.
+``I``/``i``, since these are recognized as Roman numeral 1.
The second line of each enumerated list item is checked for validity.
This is to prevent ordinary paragraphs from being mistakenly
@@ -787,8 +787,8 @@
.. Caution::
If a single-line paragraph begins with text identical to an enumerator
- ("A.", "1.", "(b)", "I)", etc.), the first character will have to be
- escaped in order to have the line parsed as an ordinary paragraph::
+ (``A.``, ``1.``, ``(b)``, ``I)``, etc.), the first character will have
+ to be escaped in order to have the line parsed as an ordinary paragraph::
\A. Einstein was a really smart dude.
@@ -829,9 +829,10 @@
to prevent recognition as an `option list`_ item.
* Optional `classifiers` may follow the term on the same line, each after
- an inline " : " (space, colon, space). Inline markup is parsed in the
- term line before the classifier delimiters are recognized. A delimiter
- will only be recognized if it appears outside of any inline markup.
+ an inline :literal:`\ : \ ` (space, colon, space).
+ Inline markup is parsed in the term line before the classifier
+ delimiters are recognized. A delimiter will only be recognized if it
+ appears outside of any inline markup.
* A `definition` is a block indented relative to the term, and may
contain multiple paragraphs and other body elements. There may be no
@@ -901,7 +902,7 @@
Field lists are mappings from *field names* to *field bodies*, modeled on
RFC822_ headers. A field name may consist of any characters, but
-colons (":") inside of field names must be backslash-escaped
+colons (``:``) inside of field names must be backslash-escaped
when followed by whitespace.\ [#]_
Inline markup is parsed in field names, but care must be taken when
using `interpreted text`_ with explicit roles in field names: the role
@@ -984,34 +985,38 @@
The registered bibliographic field names and their corresponding
doctree elements are as follows:
- ============= ================
- Field name doctree element
- ============= ================
- Abstract `\<topic>`_
- Address `\<address>`_
- Author `\<author>`_
- Authors `\<authors>`_
- Contact `\<contact>`_
- Copyright `\<copyright>`_
- Date `\<date>`_
- Dedication `\<topic>`_
- Organization `\<organization>`_
- Revision `\<revision>`_
- Status `\<status>`_
- Version `\<version>`_
- ============= ================
+ =================== ================
+ Field name [#i18n]_ doctree element
+ =================== ================
+ Abstract `\<topic>`_
+ Address `\<address>`_
+ Author `\<author>`_
+ Authors `\<authors>`_
+ Contact `\<contact>`_
+ Copyright `\<copyright>`_
+ Date `\<date>`_
+ Dedication `\<topic>`_
+ Organization `\<organization>`_
+ Revision `\<revision>`_
+ Status `\<status>`_
+ Version `\<version>`_
+ =================== ================
-The "Authors" field may contain either: a single paragraph consisting
-of a list of authors, separated by ";" or "," (";" is checked first,
-so "Doe, Jane; Doe, John" will work.); multiple paragraphs (one per
-author); or a bullet list whose elements each contain a single
-paragraph per author. In some languages
-(e.g. Swedish), there is no singular/plural distinction between
-"Author" and "Authors", so only an "Authors" field is provided, and a
-single name is interpreted as an "Author". If a single name contains
-a comma, end it with a semicolon to disambiguate: ":Authors: Doe,
-Jane;".
+.. compound::
+ The "Authors" field may contain
+ * a single paragraph consisting of a list of authors, separated by
+ ``;`` or ``,`` (``;`` is checked first, so ``Doe, Jane; Doe,
+ John`` will work.) [#i18n]_
+ * multiple paragraphs (one per author) or
+ * a bullet list whose elements each contain a single paragraph per author.
+
+ In some languages (e.g. Swedish), there is no singular/plural distinction
+ between "Author" and "Authors", so only an "Authors" field is provided,
+ and a single name is interpreted as an "Author". If a single name
+ contains a comma, end it with a semicolon to disambiguate:
+ ``:Författare: Doe, Jane;``.
+
The "Address" field is for a multi-line surface mailing address.
Newlines and whitespace will be preserved.
@@ -1020,15 +1025,16 @@
with "Dedication" or "Abstract" titles (or language equivalents)
immediately following the docinfo element.
-This field-name-to-element mapping can be replaced for other
-languages. See `Docutils Internationalization`_ for details.
-
Unregistered/generic fields may contain one or more paragraphs or
arbitrary body elements. To support custom styling, the field name is
also added to the `"classes" attribute`_ value after being converted
into a valid identifier form.
+.. [#i18n] Docutils supports localised bibliographic field names and
+ author separators. See the language_code_ setting and, for details,
+ `Docutils Internationalization`_
+
RCS Keywords
````````````
@@ -1124,7 +1130,7 @@
syntax should be explained in the description text.
Either a space or an equals sign may be used as a delimiter between long
options and option argument placeholders;
-short options ("-" or "+" prefix only) use a space or omit the delimiter.
+short options (``-`` or ``+`` prefix only) use a space or omit the delimiter.
Option arguments may take one of two forms:
- Begins with a letter (``[a-zA-Z]``) and subsequently consists of
@@ -1158,7 +1164,7 @@
:Doctree element: `\<literal_block>`_
-A paragraph consisting of two colons ("::") signifies that the
+A paragraph consisting of two colons (``::``) signifies that the
following text block(s) comprise a literal block. The literal block
must either be indented or quoted (see below). No markup processing
is done within a literal block. It is left as-is, and is typically
@@ -1177,15 +1183,15 @@
is outside of the literal block, and is therefore treated as an
ordinary paragraph.
-The paragraph containing only "::" will be completely removed from the
+The paragraph containing only ``::`` will be completely removed from the
output; no empty paragraph will remain.
-As a convenience, the "::" is recognized at the end of any paragraph.
+As a convenience, the ``::`` is also recognized at the end of any paragraph.
If immediately preceded by whitespace, both colons will be removed
from the output (this is the "partially minimized" form). When text
-immediately precedes the "::", *one* colon will be removed from the
-output, leaving only one colon visible (i.e., "::" will be replaced by
-":"; this is the "fully minimized" form).
+immediately precedes the ``::``, *one* colon will be removed from the
+output, leaving only one colon visible (i.e., ``::`` will be replaced by
+``:``; this is the "fully minimized" form).
In other words, these are all equivalent (please pay attention to the
colons after "Paragraph"):
@@ -1284,7 +1290,7 @@
Line blocks are useful for address blocks, verse (poetry, song
lyrics), and unadorned lists, where the structure of lines is
significant. Line blocks are groups of lines beginning with vertical
-bar ("|") prefixes. Each vertical bar prefix indicates a new line, so
+bar (``|``) prefixes. Each vertical bar prefix indicates a new line, so
line breaks are preserved. Initial indents are also significant,
resulting in a nested structure. Inline markup is supported.
Continuation lines are wrapped portions of long lines; they begin with
@@ -1404,11 +1410,11 @@
provide an elegant and powerful testing environment via the `doctest
module`_ in the Python standard library.
-Doctest blocks are text blocks which begin with ``">>> "``, the Python
-interactive interpreter main prompt, and end with a blank line.
-Doctest blocks are treated as a special case of literal blocks,
-without requiring the literal block syntax. If both are present, the
-literal block syntax takes priority over Doctest block syntax::
+Doctest blocks are text blocks which begin with the Python interactive
+interpreter main prompt (``>>>`` followed by a space) and end with
+a blank line. Doctest blocks are treated as a special case of literal
+blocks, without requiring the literal block syntax. If both are present,
+the literal block syntax takes priority over Doctest block syntax::
This is an ordinary paragraph.
@@ -1458,12 +1464,13 @@
representation.
Grid tables are described with a visual grid made up of the characters
-"-", "=", "|", and "+". The hyphen ("-") is used for horizontal lines
-(row separators). The equals sign ("=") may be used to separate
-optional header rows from the table body (not supported by the `Emacs
-table mode`_). The vertical bar ("|") is used for vertical lines
-(column separators). The plus sign ("+") is used for intersections of
-horizontal and vertical lines. Example::
+``-``, ``=``, ``|``, and ``+``.
+The hyphen (``-``) is used for horizontal lines (row separators).
+The equals sign (``=``) may be used to separate optional header rows
+from the table body (not supported by the `Emacs table mode`_).
+The vertical bar (``|``) is used for vertical lines (column separators).
+The plus sign (``+``) is used for intersections of horizontal and
+vertical lines. Example::
+------------------------+------------+----------+----------+
| Header row, column 1 | Header 2 | Header 3 | Header 4 |
@@ -1535,10 +1542,10 @@
all but the first column) and column spans, but not row spans. See
`Grid Tables`_ above for a complete table representation.
-Simple tables are described with horizontal borders made up of "=" and
-"-" characters. The equals sign ("=") is used for top and bottom
+Simple tables are described with horizontal borders made up of ``=`` and
+``-`` characters. The equals sign (``=``) is used for top and bottom
table borders, and to separate optional header rows from the table
-body. The hyphen ("-") is used to indicate column spans in a single
+body. The hyphen (``-``) is used to indicate column spans in a single
row by underlining the joined columns, and may optionally be used to
explicitly and/or visually separate rows.
@@ -1548,10 +1555,10 @@
columns. There must be at least two columns in the table (to
differentiate it from section headers). The top border may be
followed by header rows, and the last of the optional header rows is
-underlined with '=', again with spaces at column boundaries. There
+underlined with ``=``, again with spaces at column boundaries. There
may not be a blank line below the header row separator; it would be
interpreted as the bottom border of the table. The bottom boundary of
-the table consists of '=' underlines, also with spaces at column
+the table consists of ``=`` underlines, also with spaces at column
boundaries. For example, here is a truth table, a three-column table
with one header row and four body rows::
@@ -1564,7 +1571,7 @@
True True True
===== ===== =======
-Underlines of '-' may be used to indicate column spans by "filling in"
+Underlines of ``-`` may be used to indicate column spans by "filling in"
column margins to join adjacent columns. Column span underlines must
be complete (they must cover all columns) and align with established
column boundaries. Text lines containing column span underlines may
@@ -1598,13 +1605,13 @@
To start a new row in a simple table without text in the first
column in the processed output, use one of these:
- * an empty comment (".."), which may be omitted from the processed
+ * an empty comment (``..``), which may be omitted from the processed
output (see Comments_ below)
- * a backslash escape ("``\``") followed by a space (see `Escaping
- Mechanism`_ above)
+ * a backslash escape followed by a space
+ (:literal:`\\ \ `), see `Escaping Mechanism`_ above.
-Underlines of '-' may also be used to visually separate rows, even if
+Underlines of ``-`` may also be used to visually separate rows, even if
there are no column spans. This is especially useful in long tables,
where rows are many lines long.
@@ -1647,14 +1654,14 @@
An explicit markup block is a text block:
-- whose first line begins with ".." followed by whitespace (the
- "explicit markup start"),
-- whose second and subsequent lines (if any) are indented relative to
- the first, and
+- whose first line begins with ``..`` followed by whitespace
+ (the *explicit markup start*),
+- whose second and subsequent lines (if any) are indented
+ relative to the first, and
- which ends before an unindented line.
-Explicit markup blocks are analogous to field list items. The
-maximum common indentation is always removed from the second and
+Explicit markup blocks are analogous to field list items.
+The maximum common indentation is always removed from the second and
subsequent lines of the block body. Therefore, if the first construct
fits in one line and the indentation of the first and second
constructs should differ, the first construct should not begin on the
@@ -1674,19 +1681,19 @@
:Config settings: footnote_references_
:See also: `footnote references`_
-Each footnote consists of an explicit markup start (".. "), a left
-square bracket, the footnote label, a right square bracket, and
+Each footnote consists of an explicit markup start (:literal:`.. \ `),
+a left square bracket, the footnote label, a right square bracket, and
whitespace, followed by indented body elements. A footnote label can
be:
- a whole decimal number consisting of one or more digits,
-- a single "#" (denoting `auto-numbered footnotes`_),
+- a single ``#`` (denoting `auto-numbered footnotes`_),
-- a "#" followed by a `simple reference name`_ (an `autonumber label`_),
+- a ``#`` followed by a `simple reference name`_ (an `autonumber label`_),
or
-- a single "*" (denoting `auto-symbol footnotes`_).
+- a single ``*`` (denoting `auto-symbol footnotes`_).
The footnote content (body elements) must be consistently indented
and left-aligned. The first body element within a
@@ -1722,7 +1729,7 @@
Auto-Numbered Footnotes
.......................
-A number sign ("#") may be used as the first character of a footnote
+A number sign (``#``) may be used as the first character of a footnote
label to request automatic numbering of the footnote or footnote
reference.
@@ -1740,16 +1747,16 @@
_`autonumber labels`. Autonumber labels do two things:
- On the footnote itself, they generate a hyperlink target whose name
- is the autonumber label (doesn't include the "#").
+ is the autonumber label (doesn't include the ``#``).
- They allow an automatically numbered footnote to be referred to more
than once, as a footnote reference or hyperlink reference. For
example::
- If [#note]_ is the first footnote reference, it will show up as
- "[1]". We can refer to it again as [#note]_ and again see
- "[1]". We can also refer to it as note_ (an ordinary internal
- hyperlink reference).
+ If [#note]_ is the first footnote reference, it will
+ show up as "[1]". We can refer to it again as [#note]_
+ and again see "[1]". We can also refer to it as note_
+ (an ordinary internal hyperlink reference).
.. [#note] This is the footnote labeled "note".
@@ -1759,8 +1766,8 @@
the same relative order but need not alternate in lock-step. For
example::
- [#]_ is a reference to footnote 1, and [#]_ is a reference to
- footnote 2.
+ [#]_ is a reference to footnote 1,
+ and [#]_ is a reference to footnote 2.
.. [#] This is footnote 1.
.. [#] This is footnote 2.
@@ -1778,7 +1785,7 @@
Auto-Symbol Footnotes
.....................
-An asterisk ("*") may be used for footnote labels to request automatic
+An asterisk (``*``) may be used for footnote labels to request automatic
symbol generation for footnotes and footnote references. The asterisk
may be the only character in the label. For example::
@@ -1791,34 +1798,34 @@
the number of footnotes. One symbol footnote cannot have multiple
references.
-The standard Docutils system uses the following symbols for footnote
-marks [#]_:
+The standard Docutils system uses the following symbols for
+footnote marks: [#]_
-- asterisk/star ("*")
-- dagger (HTML character entity "†", Unicode U+02020)
-- double dagger ("‡"/U+02021)
-- section mark ("§"/U+000A7)
-- pilcrow or paragraph mark ("¶"/U+000B6)
-- number sign ("#")
-- spade suit ("♠"/U+02660)
-- heart suit ("♥"/U+02665)
-- diamond suit ("♦"/U+02666)
-- club suit ("♣"/U+02663)
+- asterisk/star (``*``)
+- dagger (``†``, U+02020)
+- double dagger (``‡``, U+02021)
+- section mark (``§``, U+000A7)
+- pilcrow or paragraph mark (``¶``, U+000B6)
+- number sign (``#``)
+- spade suit (``♠``, U+02660)
+- heart suit (``♥``, U+02665)
+- diamond suit (``♦``, U+02666)
+- club suit (``♣``, U+02663)
.. [#] This list was inspired by the list of symbols for "Note
Reference Marks" in The Chicago Manual of Style, 14th edition,
- section 12.51. "Parallels" ("||") were given in CMoS instead of
+ section 12.51. "Parallels" (``||``) were given in CMoS instead of
the pilcrow. The last four symbols (the card suits) were added
arbitrarily.
If more than ten symbols are required, the same sequence will be
-reused, doubled and then tripled, and so on ("**" etc.).
+reused, doubled and then tripled, and so on (``**`` etc.).
.. Note:: When using auto-symbol footnotes, the choice of output
- encoding is important. Many of the symbols used are not encodable
- in 8-bit text encodings such as Latin-1 (ISO 8859-1). The
- use of UTF-8 for the output encoding is recommended. An
- alternative for HTML and XML output is to use the
+ encoding is important. Many of the symbols used are not
+ encodable in 8-bit text encodings such as Latin-1 (ISO 8859-1).
+ The use of UTF-8 for the output encoding is recommended.
+ An alternative for HTML and XML output is to use the
"xmlcharrefreplace" `output encoding error handler`_.
@@ -1882,9 +1889,9 @@
which may be linked to by `hyperlink references`_.
Hyperlink targets may be named or anonymous. *Named hyperlink targets*
-consist of an explicit markup start (".. "), an underscore, the
-reference name (no trailing underscore), a colon, whitespace, and a
-link block::
+consist of an explicit markup start (:literal:`.. \ `), an underscore,
+the reference name (no trailing underscore), a colon, whitespace, and
+a link block::
.. _hyperlink-name: link-block
@@ -1892,8 +1899,8 @@
`Reference Names`_ for details and examples.
*Anonymous hyperlink targets* consist of an explicit markup start
-(".. "), two underscores, a colon, whitespace, and a link block; there
-is no reference name::
+(:literal:`.. \ `), two underscores, a colon, whitespace, and
+a link block; there is no reference name::
.. __: anonymous-hyperlink-target-link-block
@@ -2081,13 +2088,13 @@
See `the web site of my favorite programming language`__.
-Anonymous targets begin with ".. __:"; no reference name is required
+Anonymous targets begin with ``.. __:``, no reference name is required
or allowed::
.. __: https://www.python.org
-As a convenient alternative, anonymous targets may begin with "__"
-only::
+As a convenient alternative, anonymous targets may begin with
+two underscores only::
__ https://www.python.org
@@ -2132,9 +2139,9 @@
- Here is a bullet list.
-Directives are indicated by an explicit markup start (".. ") followed
-by the directive type, two colons, and whitespace (together called the
-"directive marker"). Directive types are case-insensitive single
+Directives are indicated by an explicit markup start (:literal:`.. \ `)
+followed by the directive type, two colons, and whitespace (together called
+the *directive marker*). Directive types are case-insensitive single
words (alphanumerics plus isolated internal hyphens, underscores,
plus signs, colons, and periods; no whitespace). Two colons are used
after the directive type for these reasons:
@@ -2149,7 +2156,7 @@
directive (i.e., the directive-handler is not installed), a level-3
(error) system message is generated, and the entire directive block
(including the directive itself) will be included as a literal
- block. Thus "::" is a natural choice.
+ block. Thus ``::`` is a natural choice.
The directive block consists of any text on the first line of the
directive after the directive marker, and any subsequent indented
@@ -2214,7 +2221,7 @@
:See also: `substitution references`_
Substitution definitions are indicated by an explicit markup start
-(".. ") followed by a vertical bar, the substitution text, another
+(:literal:`.. \ `) followed by a vertical bar, the substitution text, another
vertical bar, whitespace, and the definition block. Substitution text
may not begin or end with whitespace. A substitution definition block
contains an embedded `inline-compatible directive`_ (such as "image" or
@@ -2378,7 +2385,7 @@
definitions`_ will be processed as a comment element.
.. tip:: To ensure that none of the other explicit markup constructs
- is recognized, leave the ".." on a line by itself.
+ is recognized, leave the ``..`` on a line by itself.
Arbitrary indented text may be used on the lines following the explicit
markup start::
@@ -2476,18 +2483,18 @@
There are nine inline markup constructs. Five of the constructs use
identical start-strings and end-strings to indicate the markup:
-- emphasis_: "*"
-- `strong emphasis`_: "**"
-- `interpreted text`_: "`"
-- `inline literals`_: "``"
-- `substitution references`_: "|"
+- emphasis_: ``*``
+- `strong emphasis`_: ``**``
+- `interpreted text`_: `````
+- `inline literals`_: ``````
+- `substitution references`_: ``|``
Three constructs use different start-strings and end-strings:
-- `inline internal targets`_: "_`" and "`"
-- `footnote references`_: "[" and "]_"
-- `hyperlink references`_: "`" and "\`_" (phrases), or just a
- trailing "_" (single words)
+- `inline internal targets`_: ``_``` and `````
+- `footnote references`_: ``[`` and ``]_``
+- `hyperlink references`_: ````` and ``\`_`` (phrases), or just a
+ trailing ``_`` (single words)
`Standalone hyperlinks`_ are recognized implicitly, and use no extra
markup.
@@ -2561,8 +2568,8 @@
https://en.wikipedia.org/wiki/Quotation_mark,_non-English_usage
The inline markup recognition rules were devised to allow 90% of non-markup
-uses of "*", "`", "_", and "|" without escaping. For example, none of the
-following terms are recognized as containing inline markup strings:
+uses of ``*``, `````, ``_``, and ``|`` without escaping. For example, none
+of the following terms are recognized as containing inline markup strings:
- 2 * x a ** b (* BOM32_* ` `` _ __ | (breaks rule 1)
- || (breaks rule 3)
@@ -2608,19 +2615,19 @@
so to avoid ambiguity there must be a specific recognition order for
each character. The inline markup recognition order is as follows:
-- Asterisks: `Strong emphasis`_ ("**") is recognized before emphasis_
- ("*").
+- Asterisks: `Strong emphasis`_ (``**``) is recognized before emphasis_
+ (``*``).
-- Backquotes: `Inline literals`_ ("``"), `inline internal targets`_
- (leading "_`", trailing "`"), are mutually independent, and are
- recognized before phrase `hyperlink references`_ (leading "`",
- trailing "\`_") and `interpreted text`_ ("`").
+- Backquotes: `Inline literals`_ (``````), `inline internal targets`_
+ (leading ``_```, trailing `````), are mutually independent, and are
+ recognized before phrase `hyperlink references`_ (leading `````,
+ trailing ``\`_``) and `interpreted text`_ (`````).
-- Trailing underscores: Footnote references ("[" + label + "]_") and
- simple `hyperlink references`_ (name + trailing "_") are mutual...
[truncated message content] |
|
From: <mi...@us...> - 2024-12-16 22:33:26
|
Revision: 10001
http://sourceforge.net/p/docutils/code/10001
Author: milde
Date: 2024-12-16 22:33:24 +0000 (Mon, 16 Dec 2024)
Log Message:
-----------
Fix LaTeX section numbering
Translate section level 0 to LaTeX section level when suppressing automatic
section numbering by LaTeX. (LaTeX section levels may start at -1, 0, or 1.)
Don't modify the "PreambleCmds" class attribute.
This may lead to wrong output when several documents are converted in one
Python run. Fix the test cases where this wrong output slipped attention and
was quoted as expected output!
Augment the list of LaTeX documentclasses that provide "chapter"
sections.
Move section numbering configuration to `visit_section()`.
(It is only required if there is at least one section in the document.)
Modified Paths:
--------------
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/test/functional/expected/latex_memoir.tex
trunk/docutils/test/test_writers/test_latex2e.py
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-12 18:10:04 UTC (rev 10000)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-16 22:33:24 UTC (rev 10001)
@@ -5,6 +5,8 @@
"""LaTeX2e document tree Writer."""
+from __future__ import annotations
+
__docformat__ = 'reStructuredText'
# code contributions from several people included, thanks to all.
@@ -236,7 +238,8 @@
)
relative_path_settings = ('template',)
- settings_defaults = {'sectnum_depth': 0} # updated by SectNum transform
+ settings_defaults = {'sectnum_depth': 0,
+ 'sectnum_start': 1} # updated by SectNum transform
config_section = 'latex2e writer'
config_section_dependencies = ('writers', 'latex writers')
@@ -830,8 +833,10 @@
self._with_part = with_part
self.sections = ['section', 'subsection', 'subsubsection',
'paragraph', 'subparagraph']
- if self.document_class in ('book', 'memoir', 'report',
- 'scrbook', 'scrreprt'):
+ if (self.document_class.endswith('book')
+ or self.document_class.endswith('report')
+ or self.document_class in ('ctexrep', 'memoir', 'mwbk',
+ 'mwrep', 'scrreprt')):
self.sections.insert(0, 'chapter')
if self._with_part:
self.sections.insert(0, 'part')
@@ -847,7 +852,7 @@
# unsupported levels
return 'DUtitle'
- def latex_section_depth(self, depth):
+ def latex_section_depth(self, depth: int) -> int:
"""
Return LaTeX equivalent of Docutils section level `depth`.
@@ -854,6 +859,15 @@
Given the value of the ``:depth:`` option of the "contents" or
"sectnum" directive, return the corresponding value for the
LaTeX ``tocdepth`` or ``secnumdepth`` counters.
+
+ LaTeX section depth values:
+ :-1|0: part (optional, 0 with "article"-like document classes)
+ :0: chapter (missing in "article"-like document classes)
+ :1: section
+ :2: subsection
+ :3: subsubsection
+ :4: paragraph
+ :5: subparagraph
"""
depth = min(depth, len(self.sections)) # limit to supported levels
if 'chapter' in self.sections:
@@ -1373,40 +1387,6 @@
if settings.hyperref_options:
self.hyperref_options += ',' + settings.hyperref_options
- # LaTeX Toc
- # include all supported sections in toc and PDF bookmarks
- # (or use documentclass-default (as currently))?
-
- # Section numbering
- if settings.sectnum_xform: # section numbering by Docutils
- PreambleCmds.secnumdepth = r'\setcounter{secnumdepth}{0}'
- else: # section numbering by LaTeX:
- secnumdepth = settings.sectnum_depth
- # Possible values of settings.sectnum_depth:
- # None "sectnum" directive without depth arg -> LaTeX default
- # 0 no "sectnum" directive -> no section numbers
- # >0 value of "depth" argument -> translate to LaTeX levels:
- # -1 part (0 with "article" document class)
- # 0 chapter (missing in "article" document class)
- # 1 section
- # 2 subsection
- # 3 subsubsection
- # 4 paragraph
- # 5 subparagraph
- if secnumdepth is not None:
- PreambleCmds.secnumdepth = (
- r'\setcounter{secnumdepth}{%d}'
- % self.d_class.latex_section_depth(secnumdepth))
- # start with specified number:
- if (hasattr(settings, 'sectnum_start')
- and settings.sectnum_start != 1):
- self.requirements['sectnum_start'] = (
- r'\setcounter{%s}{%d}' % (self.d_class.sections[0],
- settings.sectnum_start-1))
- # TODO: currently ignored (configure in a stylesheet):
- ## settings.sectnum_prefix
- ## settings.sectnum_suffix
-
# Auxiliary Methods
# -----------------
@@ -1815,7 +1795,6 @@
if self.use_latex_citations:
self.push_output_collector([])
else:
- # self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
self.out.append(r'\begin{figure}[b]')
self.append_hypertargets(node)
@@ -2048,7 +2027,8 @@
self.out.append('\n\\faketableofcontents % for local ToCs\n')
# * conditional requirements (before style sheet)
self.requirements = [self.requirements[key]
- for key in sorted(self.requirements.keys())]
+ for key in sorted(self.requirements.keys())
+ if self.requirements[key]]
# * coditional fallback definitions (after style sheet)
self.fallbacks = [self.fallbacks[key]
for key in sorted(self.fallbacks.keys())]
@@ -2903,12 +2883,37 @@
self.out.append('}\n')
def visit_section(self, node) -> None:
+ # Update counter-prefix for compound enumerators
self.section_level += 1
- # Initialize counter for potential subsections:
+ # initialize counter for potential subsections
self._section_number.append(0)
- # Counter for this section's level (initialized by parent section):
+ # counter for this section's level (initialized by parent section)
self._section_number[self.section_level - 1] += 1
+ # Add LaTeX section numbering configuration code to requirements.
+ if 'sectnum' in self.requirements:
+ return # already done
+ # settings.sectnum_depth values:
+ # 0 no section numbering or section numbering by Docutils
+ # >0 value of "sectnum"'s :depth: option (1 = top level section)
+ # None "sectnum" directive without depth arg -> keep default
+ if self.settings.sectnum_xform: # section numbering by Docutils
+ sectnum_depth = 0
+ else: # section numbering by LaTeX:
+ sectnum_depth = self.settings.sectnum_depth
+ if self.settings.sectnum_start != 1:
+ self.requirements['sectnum_start'] = (
+ r'\setcounter{%s}{%d}' % (self.d_class.sections[0],
+ self.settings.sectnum_start-1))
+ # TODO: currently ignored (configure in a stylesheet):
+ # settings.sectnum_prefix
+ # settings.sectnum_suffix
+ if sectnum_depth is None:
+ self.requirements['sectnum'] = ''
+ else:
+ self.requirements['sectnum'] = r'\setcounter{secnumdepth}{%d}' % (
+ self.d_class.latex_section_depth(sectnum_depth))
+
def depart_section(self, node) -> None:
# Remove counter for potential subsections:
self._section_number.pop()
@@ -3167,8 +3172,6 @@
self.context.append('')
# Section title
else:
- if hasattr(PreambleCmds, 'secnumdepth'):
- self.requirements['secnumdepth'] = PreambleCmds.secnumdepth
level = self.section_level
section_name = self.d_class.section(level)
self.out.append('\n\n')
Modified: trunk/docutils/test/functional/expected/latex_memoir.tex
===================================================================
--- trunk/docutils/test/functional/expected/latex_memoir.tex 2024-12-12 18:10:04 UTC (rev 10000)
+++ trunk/docutils/test/functional/expected/latex_memoir.tex 2024-12-16 22:33:24 UTC (rev 10001)
@@ -14,7 +14,7 @@
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{pifont}
-\setcounter{secnumdepth}{0}
+\setcounter{secnumdepth}{-1}
\usepackage{longtable,ltcaption,array}
\setlength{\extrarowheight}{2pt}
\newlength{\DUtablewidth} % internal use in tables
Modified: trunk/docutils/test/test_writers/test_latex2e.py
===================================================================
--- trunk/docutils/test/test_writers/test_latex2e.py 2024-12-12 18:10:04 UTC (rev 10000)
+++ trunk/docutils/test/test_writers/test_latex2e.py 2024-12-16 22:33:24 UTC (rev 10001)
@@ -454,7 +454,7 @@
head_template.substitute(dict(parts,
head_prefix=r"""\documentclass[a4paper]{book}
""",
- requirements=parts['requirements'] + '\\setcounter{secnumdepth}{0}\n'
+ requirements=parts['requirements'] + '\\setcounter{secnumdepth}{-1}\n'
)) + r"""
\phantomsection\label{contents}
\pdfbookmark[1]{Contents}{contents}
@@ -493,8 +493,7 @@
"""],
])
-samples['latex_sectnum'] = ({'use_latex_toc': False,
- 'sectnum_xform': False}, [
+samples['latex_sectnum'] = ({'sectnum_xform': False}, [
["""\
.. sectnum::
@@ -504,9 +503,7 @@
-------------
""",
# expected output
-head_template.substitute(dict(parts,
- requirements=parts['requirements'] + '\\setcounter{secnumdepth}{0}\n'
-)) + r"""
+head + r"""
some text
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-16 22:33:34
|
Revision: 10002
http://sourceforge.net/p/docutils/code/10002
Author: milde
Date: 2024-12-16 22:33:32 +0000 (Mon, 16 Dec 2024)
Log Message:
-----------
Announce removal of two deprecated functions.
Modified Paths:
--------------
trunk/docutils/RELEASE-NOTES.rst
trunk/docutils/docutils/utils/__init__.py
Modified: trunk/docutils/RELEASE-NOTES.rst
===================================================================
--- trunk/docutils/RELEASE-NOTES.rst 2024-12-16 22:33:24 UTC (rev 10001)
+++ trunk/docutils/RELEASE-NOTES.rst 2024-12-16 22:33:32 UTC (rev 10002)
@@ -145,6 +145,9 @@
* Remove `parsers.rst.directives.CSVTable.HeaderDialect`
in Docutils 1.0.
+* Remove `utils.decode_path()` and `utils.get_stylesheet_reference()`
+ in Docutils 1.0.
+
* Remove support for the `recommonmark parser`_ in Docutils 1.0.
Recommonmark is unmaintained since 2021 and deprecated in favour
of the `MyST parser`_.
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-12-16 22:33:24 UTC (rev 10001)
+++ trunk/docutils/docutils/utils/__init__.py 2024-12-16 22:33:32 UTC (rev 10002)
@@ -380,9 +380,8 @@
Decode file/path string in a failsafe manner if not already done.
- Deprecated.
+ Deprecated. Will be removed in Docutils 1.0.
"""
- # TODO: is this still required with Python 3?
if isinstance(path, str):
return path
if path is None:
@@ -469,7 +468,7 @@
Return a new empty document object.
:Parameters:
- `source_path` : string
+ `source_path` : str or pathlib.Path
The path to or description of the source text of the document.
`settings` : optparse.Values object
Runtime settings. If none are provided, a default core set will
@@ -494,7 +493,6 @@
from docutils import frontend
if settings is None:
settings = frontend.get_default_settings()
- source_path = decode_path(source_path)
reporter = new_reporter(source_path, settings)
document = nodes.document(settings, reporter, source=source_path)
document.note_source(source_path, -1)
@@ -575,9 +573,9 @@
"""
Retrieve a stylesheet reference from the settings object.
- Deprecated. Use get_stylesheet_list() instead to
- enable specification of multiple stylesheets as a comma-separated
- list.
+ Deprecated. Will be removed in Docutils 1.0.
+ Use get_stylesheet_list() instead to enable specification of multiple
+ stylesheets as a comma-separated list.
"""
warnings.warn('utils.get_stylesheet_reference()'
' is obsoleted by utils.get_stylesheet_list()'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-18 22:03:21
|
Revision: 10004
http://sourceforge.net/p/docutils/code/10004
Author: milde
Date: 2024-12-18 22:03:18 +0000 (Wed, 18 Dec 2024)
Log Message:
-----------
Add "template" to the parts returned by the LaTeX writers.
`writers.latex2e.Writer.assemble_parts()` now also returns the
"template" that is used to generate the output document from the
(other) parts.
Modified Paths:
--------------
trunk/docutils/HISTORY.rst
trunk/docutils/docs/api/publisher.rst
trunk/docutils/docs/user/config.rst
trunk/docutils/docs/user/latex.rst
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/test/test_writers/test_latex2e_parts.py
Modified: trunk/docutils/HISTORY.rst
===================================================================
--- trunk/docutils/HISTORY.rst 2024-12-18 22:03:08 UTC (rev 10003)
+++ trunk/docutils/HISTORY.rst 2024-12-18 22:03:18 UTC (rev 10004)
@@ -179,6 +179,7 @@
for citation references resolved with BibTeX (cf. `use_bibtex`_ setting).
- Support SVG image inclusion with the "svg" LaTeX package (see the
`stylesheet`__ configuration setting).
+ - Add "template" to the parts returned by `Writer.assemble_parts()`.
.. _reference-label: docs/user/config.html#reference-label
__ docs/user/config.html#stylesheet-latex-writers
@@ -3438,7 +3439,7 @@
* docutils/writers/__init__.py:
- - Added assemble_parts method to the Writer class to allow for
+ - Added assemble_parts() method to the Writer class to allow for
access to a documents individual parts.
- Documented & set default for ``Writer.output`` attribute.
Modified: trunk/docutils/docs/api/publisher.rst
===================================================================
--- trunk/docutils/docs/api/publisher.rst 2024-12-18 22:03:08 UTC (rev 10003)
+++ trunk/docutils/docs/api/publisher.rst 2024-12-18 22:03:18 UTC (rev 10004)
@@ -412,10 +412,11 @@
`"footer"`_ and a description list for the `"docinfo"`_ part.
-Parts Provided by the (Xe)LaTeX Writers
-```````````````````````````````````````
+Parts Provided by the LaTeX Writers
+```````````````````````````````````
-All parts returned by the (Xe)LaTeX writers are of data type `str`.
+All parts returned by the LaTeX writers ("latex" writer and "xelatex"
+writer) are of data type `str`.
_`"abstract"`
Formatted content of the "abstract" `bibliographic field`_.
@@ -435,11 +436,11 @@
Formatted content of the "dedication" `bibliographic field`_.
"docinfo"
- Bibliographic data, i.e. the `\<docinfo>`_ element's content,
- rendered as a table.
+ `Bibliographic data`_ except `"abstract"`_ and `"dedication"`_
+ (i.e. the `\<docinfo>`_ element's content), rendered as a table.
- With ``--use-latex-docinfo`` the <author>, <organization>,
- <contact>, <address" and <date> are moved to `"titledata"`_.
+ If the use_latex_docinfo_ setting is True, <author>, <organization>,
+ <contact>, <address>, and <date> are moved to `"titledata"`_.
"fallbacks"
Fallback definitions for Docutils-specific LaTeX commands and environments.
@@ -448,7 +449,7 @@
The declaration of documentclass and document options.
"latex_preamble"
- The argument of the ``--latex-preamble`` option.
+ The argument of the latex_preamble_ setting.
"pdfsetup"
PDF properties ("hyperref" package setup).
@@ -462,6 +463,13 @@
"subtitle"
Document subtitle text and any inline markup.
+"template"
+ Content of the template__ file.
+ The output document (i.e. part `"whole"`_) is generated from the
+ template by substituting placeholders with the corresponding
+ parts using `string.Template.substitute()`_.
+ New in Docutils 0.22.
+
"title"
Document title text and any inline markup.
@@ -468,19 +476,15 @@
_`"titledata"`
The combined title data in ``\title``, ``\author``, and ``\date`` macros.
- With ``--use-latex-docinfo``, this includes the <author>,
- <organization>, <contact>, <address" and <date> docinfo items.
+ If use_latex_docinfo_ is True, "titledata" includes content from
+ the `\<docinfo>`_ elements <author>, <organization>, <contact>,
+ <address>, and <date>.
-See the template files default.tex_, titlepage.tex_, titlingpage.tex_,
-and xelatex.tex_ for examples how these parts are combined
-into a valid LaTeX document.
+__ ../user/config.html#template-latex-writers
+.. _string.Template.substitute():
+ https://docs.python.org/3/library/string.html#template-strings
-.. _default.tex: ../../docutils/writers/latex2e/default.tex
-.. _titlepage.tex: ../../docutils/writers/latex2e/titlepage.tex
-.. _titlingpage.tex: ../../docutils/writers/latex2e/titlingpage.tex
-.. _xelatex.tex: ../../docutils/writers/latex2e/xelatex.tex
-
publish_programmatically()
--------------------------
@@ -671,6 +675,7 @@
.. _nodes.document: ../ref/doctree.html#document
.. _"source" attribute: ../ref/doctree.html#source
+.. _bibliographic data:
.. _bibliographic field:
../ref/rst/restructuredtext.html#bibliographic-fields
@@ -677,12 +682,14 @@
.. _Docutils Configuration: ../user/config.html
.. _configuration files: ../user/config.html#configuration-files
.. _input_encoding: ../user/config.html#input-encoding
+.. _latex_preamble: ../user/config.html#latex-preamble
.. _output_encoding: ../user/config.html#output-encoding
.. _output_encoding_error_handler:
../user/config.html#output-encoding-error-handler
+.. _parser component name: ../user/config.html#parser
+.. _reader component name: ../user/config.html#reader
.. _template: ../user/config.html#template
-.. _reader component name: ../user/config.html#reader
-.. _parser component name: ../user/config.html#parser
+.. _use_latex_docinfo: ../user/config.html#use-latex-docinfo
.. _writer component name: ../user/config.html#writer-docutils-application
.. _command-line applications: ../user/tools.html
Modified: trunk/docutils/docs/user/config.rst
===================================================================
--- trunk/docutils/docs/user/config.rst 2024-12-18 22:03:08 UTC (rev 10003)
+++ trunk/docutils/docs/user/config.rst 2024-12-18 22:03:18 UTC (rev 10004)
@@ -629,8 +629,8 @@
source_link
-----------
-Include a "View document source" link in the document footer. URL will
-be relative to the destination.
+Include a "View document source" link in the document footer. The URL will
+be relative to the output_path_ (if specified) or the current work directory.
:Default: None (disabled).
:Options: ``--source-link``, ``-s``, ``--no-source-link``.
@@ -1940,9 +1940,27 @@
template
~~~~~~~~
-Path [#pwd]_ to template file, which must be encoded in UTF-8.
+
+Path [#pwd]_ to a template file, which must be encoded in UTF-8.
See also `template [html writers]`_.
+Relative paths are searched in the working directory and the "latex2e"
+writer directory.
+Docutils provides the template files default.tex_, titlepage.tex_,
+titlingpage.tex_, and xelatex.tex_.
+The output document is generated from the template by
+substituting placeholders with the corresponding parts__
+using `string.Template`_.substitute().
+
+__ ../api/publisher.html#parts-provided-by-the-latex-writers
+.. _string.Template:
+ https://docs.python.org/3/library/string.html#template-strings
+.. _default.tex: ../../docutils/writers/latex2e/default.tex
+.. _titlepage.tex: ../../docutils/writers/latex2e/titlepage.tex
+.. _titlingpage.tex: ../../docutils/writers/latex2e/titlingpage.tex
+.. _xelatex.tex: ../../docutils/writers/latex2e/xelatex.tex
+
+
:Default: writer dependent (see `[latex2e writer]`_, `[xetex writer]`_).
:Option: ``--template``.
@@ -2017,10 +2035,9 @@
\usepackage{courier}
:template__:
- "default.tex" in the ``docutils/writers/latex2e/`` directory
- (installed automatically).
+ default.tex_.
- __ `template [latex writers]`_
+__ `template [latex writers]`_
font_encoding
@@ -2056,13 +2073,8 @@
The optional argument ``HyphenChar=None`` to the monospace font
prevents word hyphenation in literal text.
-:template__: "xelatex.tex" in the ``docutils/writers/latex2e/`` directory
- (installed automatically).
+:template__: xelatex.tex_.
- .. TODO: show full path with ``--help`` (like in the HTML
- writers) and add the following line: for the exact
- machine-specific path, use the ``--help`` option).
-
.. _Linux Libertine: http://www.linuxlibertine.org/
__ `template [latex writers]`_
Modified: trunk/docutils/docs/user/latex.rst
===================================================================
--- trunk/docutils/docs/user/latex.rst 2024-12-18 22:03:08 UTC (rev 10003)
+++ trunk/docutils/docs/user/latex.rst 2024-12-18 22:03:18 UTC (rev 10004)
@@ -1792,7 +1792,7 @@
``--output-encoding=OUTPUT-ENCODING``
Default:
- "utf-8"
+ "utf-8" (LaTeX's default input encoding)
Example:
Encode the LaTeX source file with the ISO `latin-1` (west european)
@@ -1812,9 +1812,6 @@
characters than does "utf8". It is, however, a non-standard
extension and no longer developed.
- Currently, the "latex2e" writer inserts ``\usepackage[utf8]{inputenc}``
- into the LaTeX source if it is UTF-8 encoded.
-
.. with utf8x:
If LaTeX issues a Warning about unloaded/unknown characters adding ::
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-18 22:03:08 UTC (rev 10003)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-18 22:03:18 UTC (rev 10004)
@@ -286,14 +286,10 @@
# copy parts
for part in self.visitor_attributes:
setattr(self, part, getattr(visitor, part))
- # get template string from file
- templatepath = Path(self.document.settings.template)
- if not templatepath.exists():
- templatepath = self.default_template_path / templatepath.name
- template = templatepath.read_text(encoding='utf-8')
# fill template
self.assemble_parts() # create dictionary of parts
- self.output = string.Template(template).substitute(self.parts)
+ self.output = string.Template(self.parts['template']
+ ).substitute(self.parts)
def assemble_parts(self) -> None:
"""Assemble the `self.parts` dictionary of output fragments."""
@@ -309,6 +305,11 @@
else:
# body contains inline elements, so join without newline
self.parts[part] = ''.join(lines)
+ # get template string from file
+ templatepath = Path(self.document.settings.template)
+ if not templatepath.exists():
+ templatepath = self.default_template_path / templatepath.name
+ self.parts['template'] = templatepath.read_text(encoding='utf-8')
class Babel:
@@ -1558,13 +1559,6 @@
"""Cleanse, encode, and return attribute value text."""
return self.encode(whitespace.sub(' ', text))
- # TODO: is this used anywhere? -> update (use template) or delete
- ## def astext(self):
- ## """Assemble document parts and return as string."""
- ## head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
- ## body = ''.join(self.body_prefix + self.body + self.body_suffix)
- ## return head + '\n' + body
-
def is_inline(self, node):
"""Check whether a node represents an inline or block-level element"""
return isinstance(node.parent, nodes.TextElement)
Modified: trunk/docutils/test/test_writers/test_latex2e_parts.py
===================================================================
--- trunk/docutils/test/test_writers/test_latex2e_parts.py 2024-12-18 22:03:08 UTC (rev 10003)
+++ trunk/docutils/test/test_writers/test_latex2e_parts.py 2024-12-18 22:03:18 UTC (rev 10004)
@@ -69,6 +69,22 @@
'requirements': '\\usepackage[T1]{fontenc}\n',
'stylesheet': '',
'subtitle': '',
+ 'template': """\
+$head_prefix% generated by Docutils <https://docutils.sourceforge.io/>
+\\usepackage{cmap} % fix search and cut-and-paste in Acrobat
+$requirements
+%%% Custom LaTeX preamble
+$latex_preamble
+%%% User specified packages and stylesheets
+$stylesheet
+%%% Fallback definitions for Docutils-specific commands
+$fallbacks
+$pdfsetup
+%%% Body
+\\begin{document}
+$titledata$body_pre_docinfo$docinfo$dedication$abstract$body
+\\end{document}
+""",
'title': '',
'titledata': '',
'version': f'{docutils.__version__}',
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-12-18 22:03:30
|
Revision: 10005
http://sourceforge.net/p/docutils/code/10005
Author: milde
Date: 2024-12-18 22:03:27 +0000 (Wed, 18 Dec 2024)
Log Message:
-----------
Small fixes.
Link in "Docutils Configuration",
class name and docstring in "html4css1" writer test.
Modified Paths:
--------------
trunk/docutils/docs/user/config.rst
trunk/docutils/test/test_writers/test_html4css1_parts.py
Modified: trunk/docutils/docs/user/config.rst
===================================================================
--- trunk/docutils/docs/user/config.rst 2024-12-18 22:03:18 UTC (rev 10004)
+++ trunk/docutils/docs/user/config.rst 2024-12-18 22:03:27 UTC (rev 10005)
@@ -87,7 +87,7 @@
Configuration File Syntax
-------------------------
-Configuration files are UTF-8-encoded text files. The ConfigParser.py_
+Configuration files are UTF-8-encoded text files. The configparser_
module from Python_'s standard library is used to read them.
From its documentation__:
@@ -99,6 +99,7 @@
[…] Configuration files may include comments, prefixed by specific
characters (``#`` and ``;`` by default).
+.. _configparser: https://docs.python.org/3/library/configparser.html
__ https://docs.python.org/3/library/configparser.html
#supported-ini-file-structure
@@ -229,8 +230,6 @@
Some knowledge of Python_ is assumed for some attributes.
-.. _ConfigParser.py:
- https://docs.python.org/3/library/configparser.html
.. _Python: https://www.python.org/
__ ../api/runtime-settings.html#active-sections
Modified: trunk/docutils/test/test_writers/test_html4css1_parts.py
===================================================================
--- trunk/docutils/test/test_writers/test_html4css1_parts.py 2024-12-18 22:03:18 UTC (rev 10004)
+++ trunk/docutils/test/test_writers/test_html4css1_parts.py 2024-12-18 22:03:27 UTC (rev 10005)
@@ -2,6 +2,7 @@
# $Id$
# Author: reggie dugard <re...@us...>
+# Maintainer: doc...@li...
# Copyright: This module has been placed in the public domain.
"""
@@ -103,8 +104,8 @@
return parts
-class Html5WriterPublishPartsTestCase(unittest.TestCase):
- """Test HTML5 writer `publish_parts()` interface."""
+class Html4WriterPublishPartsTestCase(unittest.TestCase):
+ """Test "html4css1" writer `publish_parts()` interface."""
maxDiff = None
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2025-01-16 09:50:08
|
Revision: 10006
http://sourceforge.net/p/docutils/code/10006
Author: milde
Date: 2025-01-16 09:50:06 +0000 (Thu, 16 Jan 2025)
Log Message:
-----------
Clean up and update TODO list.
Code modernization: check for and fix remaining cases from PEP 290
Doctree validation is implemented in 0.22.
Bug 241 is fixed long ago.
The proposed "--include FILE" command line option is
obsoleted by the upcoming changes to the command line interface.
Modified Paths:
--------------
trunk/docutils/docs/dev/todo.rst
trunk/docutils/docutils/utils/__init__.py
trunk/docutils/docutils/writers/latex2e/__init__.py
Modified: trunk/docutils/docs/dev/todo.rst
===================================================================
--- trunk/docutils/docs/dev/todo.rst 2024-12-18 22:03:27 UTC (rev 10005)
+++ trunk/docutils/docs/dev/todo.rst 2025-01-16 09:50:06 UTC (rev 10006)
@@ -121,18 +121,6 @@
Miscellaneous
-------------
-Code cleanup and modernization:
- Use flake8_? See also the configuration in `<../../tox.ini>`__.
-
- Check and solve issue from :PEP:`290` - Code Migration and Modernization.
- (Covers issues up to Python 2.4, is there an equivalent for more recent
- modernizations?)
-
- Ensure `backwards compatibility`_!
-
- .. _flake8: https://pypi.org/project/flake8/
- .. _backwards compatibility: policies.html#backwards-compatibility-policy
-
* Improve handling on Windows:
- Get graphical installer.
@@ -239,8 +227,6 @@
translations.
-* Add validation? See http://pytrex.sourceforge.net, RELAX NG, pyRXP.
-
* In ``docutils.readers.get_reader_class`` (& ``parsers`` &
``writers`` too), should we be importing "standalone" or
"docutils.readers.standalone"? (This would avoid importing
@@ -258,18 +244,6 @@
Do we need it at all? Or rather let the writers just ignore some
nodes (like we already do for "class" values)?
- The current implementation of the framework also leads to bug
- `bug #241`__ "doctree-based publishing != publish_string".
- The "components.Filter" transform is run by publish_doctree(). When
- filtering based on the output format, it should be run by
- publish_from_doctree() instead because only then the writer is
- known.
-
- So we need to either remove or fix the framework.
-
- __ https://sourceforge.net/p/docutils/bugs/241/
-
-
* Think about _`large documents` made up of multiple subdocument
files. Issues: continuity (`persistent sequences`_ above),
cross-references (`name-to-id mapping file`_ above and `targets in
@@ -419,11 +393,6 @@
* Rationalize Writer settings (HTML/LaTeX/PEP) -- share settings.
-* Add an "--include file" command-line option (config setting too?),
- equivalent to ".. include:: file" as the first line of the doc text?
- Especially useful for character entity sets, text transform specs,
- boilerplate, etc.
-
* Support "include" as embedded inline-compatible directive in substitution
definitions, e.g. ::
@@ -603,7 +572,10 @@
``\label{<refname}`` command, ``\ref{<refname>}`` inserts the
corresponding number.
-No such mechanism exists in HTML.
+No such mechanism exists in HTML/CSS (there is "target-counter" for paged
+media but this is not supported by browsers as of 2024).
+Cf. https://stackoverflow.com/questions/16453488/ and
+https://stackoverflow.com/questions/9463523/.
* We need _`persistent sequences`, similar to chapter and footnote
numbers. See `OpenOffice.org XML`_ "fields".
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-12-18 22:03:27 UTC (rev 10005)
+++ trunk/docutils/docutils/utils/__init__.py 2025-01-16 09:50:06 UTC (rev 10006)
@@ -409,37 +409,34 @@
"""
attlist = []
while line:
- equals = line.find('=')
- if equals == -1:
+ equals_index = line.find('=')
+ if equals_index == -1:
raise NameValueError('missing "="')
- attname = line[:equals].strip()
- if equals == 0 or not attname:
- raise NameValueError(
- 'missing attribute name before "="')
- line = line[equals+1:].lstrip()
+ attname = line[:equals_index].strip()
+ if equals_index == 0 or not attname:
+ raise NameValueError('missing attribute name before "="')
+ line = line[equals_index+1:].lstrip()
if not line:
- raise NameValueError(
- 'missing value after "%s="' % attname)
+ raise NameValueError(f'missing value after "{attname}="')
if line[0] in '\'"':
- endquote = line.find(line[0], 1)
- if endquote == -1:
+ endquote_index = line.find(line[0], 1)
+ if endquote_index == -1:
raise NameValueError(
- 'attribute "%s" missing end quote (%s)'
- % (attname, line[0]))
- if len(line) > endquote + 1 and line[endquote + 1].strip():
- raise NameValueError(
- 'attribute "%s" end quote (%s) not followed by '
- 'whitespace' % (attname, line[0]))
- data = line[1:endquote]
- line = line[endquote+1:].lstrip()
+ f'attribute "{attname}" missing end quote ({line[0]})')
+ if (len(line) > endquote_index + 1
+ and line[endquote_index + 1].strip()):
+ raise NameValueError(f'attribute "{attname}" end quote '
+ f'({line[0]}) not followed by whitespace')
+ data = line[1:endquote_index]
+ line = line[endquote_index+1:].lstrip()
else:
- space = line.find(' ')
- if space == -1:
+ space_index = line.find(' ')
+ if space_index == -1:
data = line
line = ''
else:
- data = line[:space]
- line = line[space+1:].lstrip()
+ data = line[:space_index]
+ line = line[space_index+1:].lstrip()
attlist.append((attname.lower(), data))
return attlist
@@ -664,13 +661,13 @@
parts = []
start = 0
while True:
- found = text.find('\\', start)
- if found == -1:
+ bs_index = text.find('\\', start)
+ if bs_index == -1:
parts.append(text[start:])
return ''.join(parts)
- parts.extend((text[start:found],
- '\x00' + text[found + 1:found + 2]))
- start = found + 2 # skip character after escape
+ parts.extend((text[start:bs_index],
+ '\x00' + text[bs_index + 1:bs_index + 2]))
+ start = bs_index + 2 # skip character after escape
def split_escaped_whitespace(text: str) -> list[str]:
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-12-18 22:03:27 UTC (rev 10005)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2025-01-16 09:50:06 UTC (rev 10006)
@@ -1355,9 +1355,9 @@
self.requirements['_textquotedbl'] = (
r'\DeclareTextSymbolDefault{\textquotedbl}{T1}')
# page layout with typearea (if there are relevant document options)
- if (settings.documentclass.find('scr') == -1
- and (self.documentoptions.find('DIV') != -1
- or self.documentoptions.find('BCOR') != -1)):
+ if (not settings.documentclass.startswith('scr')
+ and ('DIV' in self.documentoptions
+ or 'BCOR' in self.documentoptions)):
self.requirements['typearea'] = r'\usepackage{typearea}'
# Stylesheets
@@ -2831,7 +2831,7 @@
if 'refuri' in node:
href = str(node['refuri']).translate(special_chars)
# problematic chars double caret and unbalanced braces:
- if href.find('^^') != -1 or self.has_unbalanced_braces(href):
+ if '^^' in href or self.has_unbalanced_braces(href):
self.error(
f'External link "{href}" not supported by LaTeX.\n'
' (Must not contain "^^" or unbalanced braces.)')
@@ -3027,8 +3027,7 @@
if (self.active_table._latex_type == 'longtable'
and isinstance(node.parent, nodes.section)
and node.parent.index(node) == 1
- and self.d_class.section(
- self.section_level).find('paragraph') != -1):
+ and 'paragraph' in self.d_class.section(self.section_level)):
self.out.append('\\leavevmode')
self.active_table.open()
self.active_table.set_table_style(node, self.settings)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2025-01-31 10:15:45
|
Revision: 10007
http://sourceforge.net/p/docutils/code/10007
Author: milde
Date: 2025-01-31 10:15:44 +0000 (Fri, 31 Jan 2025)
Log Message:
-----------
LaTeX writer: Fixes for section numbering by LaTeX.
Document the internal settings "sectnum_depth", "sectnum_start",
"sectnum_prefix" and "sectnum_suffix".
Silently ignore configuration file values for these settings
(documented behaviour of internal settings) instead of raising
a ValueError.
Simplify logic and gather it in `Transformer.visit_section()`:
Do not set LaTeX-specific default values for the internal settings.
Do not (ab)use an empty requirement value to mark section number configuration
as done.
Add test cases.
Modified Paths:
--------------
trunk/docutils/docs/user/config.rst
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/test/test_writers/test_latex2e_parts.py
Modified: trunk/docutils/docs/user/config.rst
===================================================================
--- trunk/docutils/docs/user/config.rst 2025-01-16 09:50:06 UTC (rev 10006)
+++ trunk/docutils/docs/user/config.rst 2025-01-31 10:15:44 UTC (rev 10007)
@@ -614,13 +614,17 @@
sectnum_xform
-------------
-Enable automatic section numbering by Docutils
-(`docutils.transforms.parts.SectNum`) associated
-with the `"sectnum" directive`_.
+Enable automatic section numbering by Docutils (`SectNum` transform_
+associated with the `"sectnum" directive`_).
-If disabled, section numbers might be added to the output by the
-renderer (e.g. by CSS style rules or by LaTeX).
+If disabled, the `SectNum` transform adds the `internal settings`_
+sectnum_depth_, sectnum_start_, sectnum_prefix_, and sectnum_suffix_
+to store the respective `"sectnum" directive options`__.
+Section numbers may be added to the output by the renderer
+(e.g. by CSS style rules or LaTeX).
+__ ../ref/rst/directives.html#sectnum-options
+
:Default: True.
:Options: ``--section-numbering``, ``--no-section-numbering``.
@@ -2399,13 +2403,13 @@
These settings are for internal use only; setting them in
configuration files has no effect, and there are no corresponding
-command-line options.
+command-line options (except for `_destination`_).
_config_files
~~~~~~~~~~~~~
List of paths of applied configuration files.
-*Default*: None. No command-line options.
+*Default*: None.
_directories
~~~~~~~~~~~~
@@ -2414,15 +2418,14 @@
List of paths to source directories, set from `positional arguments
<tools.html#buildhtml-py>`__.
+*Default*: None (current working directory).
-*Default*: None (current working directory). No command-line options.
-
_disable_config
~~~~~~~~~~~~~~~
Prevent standard configuration files from being read.
For command-line use, set the DOCUTILSCONFIG_ variable.
-:Default: None (config files enabled). No command-line options.
+:Default: None (config files enabled).
_destination
~~~~~~~~~~~~
@@ -2433,13 +2436,40 @@
*Default*: None (stdout). *Option*: ``--output``.
-
_source
~~~~~~~
Path to input source, set from `positional arguments`_.
-*Default*: None (stdin). No command-line options.
+*Default*: None (stdin).
+sectnum_depth
+~~~~~~~~~~~~~
+Stores the value of the `"sectnum" directive`_'s "depth" option
+if sectnum_xform_ is False.
+
+No default. [#SectNum]_
+
+sectnum_prefix
+~~~~~~~~~~~~~~
+Stores the value of the `"sectnum" directive`_'s "prefix" option
+if sectnum_xform_ is False.
+
+No default. [#SectNum]_
+
+sectnum_start
+~~~~~~~~~~~~~
+Stores the value of the `"sectnum" directive`_'s "start" option
+if sectnum_xform_ is False.
+
+No default. [#SectNum]_
+
+sectnum_suffix
+~~~~~~~~~~~~~~
+Stores the value of the `"sectnum" directive`_'s "suffix" option
+if sectnum_xform_ is False.
+
+No default. [#SectNum]_
+
--------------------------------------------------------------------------
.. [#override] The overridden setting will automatically be set to
@@ -2462,6 +2492,9 @@
buildhtml_ application are resolved relative to the directory of
the respective configuration file.
+.. [#SectNum] Added by the `SectNum` transform_, if and only if there
+ is a `"sectnum" directive`_ in the source document.
+
__ https://docs.python.org/3/library/codecs.html#codecs.register
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2025-01-16 09:50:06 UTC (rev 10006)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2025-01-31 10:15:44 UTC (rev 10007)
@@ -238,8 +238,7 @@
)
relative_path_settings = ('template',)
- settings_defaults = {'sectnum_depth': 0,
- 'sectnum_start': 1} # updated by SectNum transform
+ settings_defaults = {}
config_section = 'latex2e writer'
config_section_dependencies = ('writers', 'latex writers')
@@ -2021,8 +2020,7 @@
self.out.append('\n\\faketableofcontents % for local ToCs\n')
# * conditional requirements (before style sheet)
self.requirements = [self.requirements[key]
- for key in sorted(self.requirements.keys())
- if self.requirements[key]]
+ for key in sorted(self.requirements.keys())]
# * coditional fallback definitions (after style sheet)
self.fallbacks = [self.fallbacks[key]
for key in sorted(self.fallbacks.keys())]
@@ -2884,27 +2882,29 @@
# counter for this section's level (initialized by parent section)
self._section_number[self.section_level - 1] += 1
- # Add LaTeX section numbering configuration code to requirements.
+ # Section numbering configuration
if 'sectnum' in self.requirements:
return # already done
- # settings.sectnum_depth values:
+ # sectnum_depth values:
# 0 no section numbering or section numbering by Docutils
# >0 value of "sectnum"'s :depth: option (1 = top level section)
# None "sectnum" directive without depth arg -> keep default
if self.settings.sectnum_xform: # section numbering by Docutils
- sectnum_depth = 0
- else: # section numbering by LaTeX:
- sectnum_depth = self.settings.sectnum_depth
- if self.settings.sectnum_start != 1:
- self.requirements['sectnum_start'] = (
- r'\setcounter{%s}{%d}' % (self.d_class.sections[0],
- self.settings.sectnum_start-1))
+ sectnum_depth = 0 # suppress LaTeX section numbers
+ else:
+ sectnum_depth = getattr(self.settings, 'sectnum_depth', 0)
+ if isinstance(sectnum_depth, str):
+ sectnum_depth = 0 # ignore values from config files
+ sectnum_start = getattr(self.settings, 'sectnum_start', 1)
+ if isinstance(sectnum_start, str):
+ sectnum_start = 1 # ignore values from config files
+ if sectnum_start != 1:
+ self.requirements['sectnum_start'] = r'\setcounter{%s}{%d}' % (
+ self.d_class.sections[0], sectnum_start-1)
# TODO: currently ignored (configure in a stylesheet):
# settings.sectnum_prefix
# settings.sectnum_suffix
- if sectnum_depth is None:
- self.requirements['sectnum'] = ''
- else:
+ if sectnum_depth is not None:
self.requirements['sectnum'] = r'\setcounter{secnumdepth}{%d}' % (
self.d_class.latex_section_depth(sectnum_depth))
Modified: trunk/docutils/test/test_writers/test_latex2e_parts.py
===================================================================
--- trunk/docutils/test/test_writers/test_latex2e_parts.py 2025-01-16 09:50:06 UTC (rev 10006)
+++ trunk/docutils/test/test_writers/test_latex2e_parts.py 2025-01-31 10:15:44 UTC (rev 10007)
@@ -959,25 +959,72 @@
])
-samples['sectnum_xform False'] = ({'sectnum_xform': False}, [
-# no section numbers
+# section numbering by LaTeX
+samples['sectnum_xform False'] = ({'sectnum_xform': False,
+ # ignore str values of internal settings:
+ 'sectnum_start': '42',
+ 'sectnum_depth': '3'
+ }, [
["""\
-some text
+no sectnum directive -> suppress section numbers
-first section
--------------
+section
+-------
""",
{'body': r"""
-some text
+no sectnum directive -> suppress section numbers
-\section{first section%
- \label{first-section}%
+\section{section%
+ \label{section}%
}
""",
'requirements': '\\usepackage[T1]{fontenc}\n'
'\\setcounter{secnumdepth}{0}\n',
}],
+['no sectnum directive and no section -> no requirements',
+ {'body': '\nno sectnum directive and no section -> no requirements\n'
+ }],
+
+["""\
+default section numbers -> no requirements
+
+.. sectnum::
+
+section
+-------
+""",
+ {'body': r"""
+default section numbers -> no requirements
+
+
+\section{section%
+ \label{section}%
+}
+""",
+ }],
+["""\
+section numbers with custom start and depth
+
+.. sectnum::
+ :start: 7
+ :depth: 2
+
+section
+-------
+""",
+ {'body': r"""
+section numbers with custom start and depth
+
+
+\section{section%
+ \label{section}%
+}
+""",
+ 'requirements': '\\usepackage[T1]{fontenc}\n'
+ '\\setcounter{secnumdepth}{2}\n'
+ '\\setcounter{section}{6}\n',
+ }],
])
samples['stylesheet_path'] = ({'stylesheet_path': f'{spam},{ham}'}, [
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|