|
From: <mi...@us...> - 2021-04-19 11:29:37
|
Revision: 8713
http://sourceforge.net/p/docutils/code/8713
Author: milde
Date: 2021-04-19 11:29:36 +0000 (Mon, 19 Apr 2021)
Log Message:
-----------
Documentation fixes.
Modified Paths:
--------------
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docs/ref/doctree.txt
trunk/docutils/docs/ref/rst/directives.txt
trunk/docutils/docs/user/config.txt
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2021-04-17 14:58:28 UTC (rev 8712)
+++ trunk/docutils/RELEASE-NOTES.txt 2021-04-19 11:29:36 UTC (rev 8713)
@@ -88,6 +88,9 @@
stability of the generated HTML code, e.g. because you use a custom
style sheet or post-processing that may break otherwise.
+* The html_writer_ option of the ``buildhtml.py`` application is
+ obsoleted by ``--writer`` and will be removed in future.
+
.. _id_prefix: docs/user/config.html#id-prefix
.. _auto_id_prefix: docs/user/config.html#auto-id-prefix
.. _rst2html.py: docs/user/tools.html#rst2html-py
@@ -94,6 +97,7 @@
.. _reference name: docs/ref/rst/restructuredtext.html#reference-names
.. _identifier normalization:
docs/ref/rst/directives.html#identifier-normalization
+.. _html_writer: docs/user/config.html#html-writer
Release 0.17.1 (2021-04-16)
Modified: trunk/docutils/docs/ref/doctree.txt
===================================================================
--- trunk/docutils/docs/ref/doctree.txt 2021-04-17 14:58:28 UTC (rev 8712)
+++ trunk/docutils/docs/ref/doctree.txt 2021-04-19 11:29:36 UTC (rev 8713)
@@ -4537,9 +4537,8 @@
_`number`
The attribute value must be a number. Resolves to ``NMTOKEN``.
- Used in the `start`_ and `scale`_ attributes.
+ Used in the `level`_, `morecols`_, `scale`_, and `start`_ attributes.
- .. also ltrim, rtrim
_`measure`
A number which may be immediately followed by a unit or percent sign.
Modified: trunk/docutils/docs/ref/rst/directives.txt
===================================================================
--- trunk/docutils/docs/ref/rst/directives.txt 2021-04-17 14:58:28 UTC (rev 8712)
+++ trunk/docutils/docs/ref/rst/directives.txt 2021-04-19 11:29:36 UTC (rev 8713)
@@ -517,7 +517,7 @@
The following options are recognized:
-``number-lines`` : [start line number]
+``number-lines`` : [integer]
Precede every line with a line number.
The optional argument is the number of the first line (defaut 1).
@@ -784,7 +784,7 @@
The horizontal alignment of the table.
(New in Docutils 0.13)
-``widths`` : "auto", "grid" or a list of integers
+``widths`` : "auto", "grid", or a list of integers
A comma- or space-separated list of column widths.
The default is the width of the input columns (in characters).
@@ -793,7 +793,7 @@
(LaTeX, the HTML browser, ...).
See also the `table_style`_ configuration option.
-``width`` : `length`_ or `percentage`_ of the current line width
+``width`` : `length`_ or `percentage`_
Forces the width of the table to the specified length or percentage
of the line width. If omitted, the renderer determines the width
of the table based on its contents.
@@ -869,7 +869,7 @@
whether to delegate the determination of column widths to the backend
(LaTeX, the HTML browser, ...).
-``width`` : `length`_ or `percentage`_ of the current line width
+``width`` : `length`_ or `percentage`_
Forces the width of the table to the specified length or percentage
of the line width. If omitted, the renderer determines the width
of the table based on its contents.
@@ -893,7 +893,7 @@
``url`` : string (whitespace removed)
An Internet URL reference to a CSV data file.
-``encoding`` : name of text encoding
+``encoding`` : string
The text encoding of the external CSV data (file or URL).
Defaults to the document's encoding (if specified).
@@ -909,7 +909,7 @@
Unicode code point; see the unicode_ directive for syntax
details.
-``keepspace`` : flag
+``keepspace`` : flag (empty)
Treat whitespace immediately following the delimiter as
significant. The default is to ignore such whitespace.
@@ -1331,13 +1331,13 @@
The following options are recognized:
-``ltrim`` : flag
+``ltrim`` : flag (empty)
Whitespace to the left of the substitution reference is removed.
-``rtrim`` : flag
+``rtrim`` : flag (empty)
Whitespace to the right of the substitution reference is removed.
-``trim`` : flag
+``trim`` : flag (empty)
Equivalent to ``ltrim`` plus ``rtrim``; whitespace on both sides
of the substitution reference is removed.
@@ -1454,18 +1454,18 @@
The entire included text is inserted into the document as a single
literal block.
-``code`` : formal language (optional)
+``code`` : [string] (formal language)
The argument and the included content are passed to
the code_ directive (useful for program listings).
(New in Docutils 0.9)
-``number-lines`` : [start line number]
+``number-lines`` : [integer] (start line number)
Precede every code line with a line number.
The optional argument is the number of the first line (defaut 1).
Works only with ``code`` or ``literal``.
(New in Docutils 0.9)
-``encoding`` : name of text encoding
+``encoding`` : string
The text encoding of the external data file. Defaults to the
document's input_encoding_.
@@ -1559,7 +1559,7 @@
``url`` : string (whitespace removed)
An Internet URL reference to a raw data file to be included.
-``encoding`` : name of text encoding
+``encoding`` : string
The text encoding of the external raw data (file or URL).
Defaults to the document's encoding (if specified).
Modified: trunk/docutils/docs/user/config.txt
===================================================================
--- trunk/docutils/docs/user/config.txt 2021-04-17 14:58:28 UTC (rev 8712)
+++ trunk/docutils/docs/user/config.txt 2021-04-19 11:29:36 UTC (rev 8713)
@@ -146,8 +146,8 @@
-------------------------------------
Below are the Docutils runtime settings, listed by config file
-section. Any setting may be specified in any section, but only
-settings from active sections will be used. Sections correspond to
+section. **Any setting may be specified in any section, but only
+settings from active sections will be used.** Sections correspond to
Docutils components (module name or alias; section names are always in
lowercase letters). Each `Docutils application`_ uses a specific set
of components; corresponding configuration file sections are applied
@@ -167,7 +167,7 @@
4. `[writers]`_, writer family ("[... writers]"; if applicable),
writer dependencies, and the section specific to the writer used
("[... writer]"). For example, `[pep_html writer]`_ depends
- on `[html4css1 writer]`_.
+ on `[html writers]`_ and `[html4css1 writer]`_.
5. `[applications]`_, application dependencies, and the section
specific to the Application (front-end tool) in use
@@ -211,7 +211,7 @@
A trailing "%" is replaced with the tag name (new in Docutils 0.16).
Default: "id" (`will change to "%" in future`__).
-Options: ``--auto-id-prefix`` (hidden, intended mainly for programmatic use).
+Option: ``--auto-id-prefix`` (hidden, intended mainly for programmatic use).
.. _identifier normalization:
../ref/rst/directives.html#identifier-normalization
@@ -256,7 +256,7 @@
document (``document.__dict__``) to stderr.
Default: don't (None).
-Options: ``--dump-internals`` (hidden, for development use only).
+Option: ``--dump-internals`` (hidden, for development use only).
dump_pseudo_xml
---------------
@@ -265,7 +265,7 @@
the document to stderr.
Default: don't (None).
-Options: ``--dump-pseudo-xml`` (hidden, for development use only).
+Option: ``--dump-pseudo-xml`` (hidden, for development use only).
dump_settings
-------------
@@ -273,7 +273,7 @@
At the end of processing, write all Docutils settings to stderr.
Default: don't (None).
-Options: ``--dump-settings`` (hidden, for development use only).
+Option: ``--dump-settings`` (hidden, for development use only).
dump_transforms
---------------
@@ -282,7 +282,7 @@
to the document to stderr.
Default: don't (None).
-Options: ``--dump-transforms`` (hidden, for development use only).
+Option: ``--dump-transforms`` (hidden, for development use only).
error_encoding
--------------
@@ -308,7 +308,7 @@
exit. Exit status is the maximum system message level plus 10 (11
for INFO, etc.).
-Default: disabled (5). Options: ``--exit-status``.
+Default: disabled (5). Option: ``--exit-status``.
expose_internals
----------------
@@ -319,7 +319,7 @@
line, the option may be used more than once.
Default: don't (None).
-Options: ``--expose-internal-attribute`` (hidden, for development use only).
+Option: ``--expose-internal-attribute`` (hidden, for development use only).
footnote_backlinks
------------------
@@ -355,7 +355,7 @@
See also auto_id_prefix_.
Default: "" (empty).
-Options: ``--id-prefix`` (hidden, intended mainly for programmatic use).
+Option: ``--id-prefix`` (hidden, intended mainly for programmatic use).
input_encoding
--------------
@@ -596,7 +596,7 @@
Path to a file for the output of system messages (warnings). [#pwd]_
-Default: stderr (None). Options: ``--warnings``.
+Default: stderr (None). Option: ``--warnings``.
[parsers]
@@ -678,7 +678,7 @@
Recognize and link to standalone PEP references (like "PEP 258").
Default: disabled (None); enabled (True) in PEP Reader.
-Options: ``--pep-references``.
+Option: ``--pep-references``.
pep_base_url
~~~~~~~~~~~~
@@ -701,7 +701,7 @@
Recognize and link to standalone RFC references (like "RFC 822").
Default: disabled (None); enabled (True) in PEP Reader.
-Options: ``--rfc-references``.
+Option: ``--rfc-references``.
rfc_base_url
~~~~~~~~~~~~
@@ -793,7 +793,7 @@
Number of spaces for hard tab expansion.
-Default: 8. Options: ``--tab-width``.
+Default: 8. Option: ``--tab-width``.
trim_footnote_reference_space
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -845,8 +845,8 @@
Enable or disable the promotion of the title of a lone subsection
to a subtitle (docutils.transforms.frontmatter.SectSubTitle).
-Default: disabled (False). Options: ``--section-subtitles,
---no-section-subtitles``.
+Default: disabled (False).
+Options: ``--section-subtitles, --no-section-subtitles``.
[pep reader]
@@ -908,7 +908,7 @@
Generate XML with an XML declaration.
See also `xml_declaration [html writers]`_.
-Default: do (True). Options: ``--no-xml-declaration``.
+Default: do (True). Option: ``--no-xml-declaration``.
[html writers]
@@ -923,7 +923,7 @@
prefix), "parentheses"/"parens", or "none".
See also `attribution [latex writers]`_.
-Default: "dash". Options: ``--attribution``.
+Default: "dash". Option: ``--attribution``.
cloak_email_addresses
@@ -981,8 +981,8 @@
accessible during processing.
See also `embed_stylesheet [latex writers]`_.
-Default: enabled. Options: ``--embed-stylesheet,
---link-stylesheet``.
+Default: enabled.
+Options: ``--embed-stylesheet, --link-stylesheet``.
.. _footnote_references setting:
@@ -1151,7 +1151,7 @@
Default: the working directory of the process at launch and the directory
with default stylesheet files (writer and installation specific).
Use the ``--help`` option to get the exact value.
-Option: ``--stylesheet-directories``.
+Option: ``--stylesheet-dirs``.
.. _stylesheet_path:
@@ -1172,7 +1172,7 @@
Default: writer dependent (see `[html4css1 writer]`_, `[html5 writer]`_,
`[pep_html writer]`_).
-Options: ``--stylesheet-path``.
+Option: ``--stylesheet-path``.
__ `embed_stylesheet [html writers]`_
__ `stylesheet_dirs [html writers]`_
@@ -1186,14 +1186,11 @@
Class value(s) added to all tables_.
See also `table_style [latex writers]`_.
-The default CSS sylesheet defines:
+The default CSS sylesheets define:
borderless
No borders around the table.
- booktabs
- Lines above and below the table and a thin line after the head.
-
align-left, align-center, align-right
Align the tables
@@ -1202,9 +1199,14 @@
(leave out the ``<colgroup>`` column specification).
See also the "widths" option of the `table directive`_.
+The HTML5 stylesheets also define:
+
+ booktabs
+ Only lines above and below the table and a thin line after the head.
+
captionbelow
Place the table caption below the table
- (only with the `HTML5 writer`_, new in 0.17).
+ (New in 0.17).
Default: "". Option: ``--table-style``.
@@ -1219,9 +1221,9 @@
Path to template file, which must be encoded in UTF-8. [#pwd]_
See also `template [latex writers]`_.
-Default: "template.txt" in the docutils/writers/html4css1/
-directory (installed automatically; for the exact machine-specific
-path, use the ``--help`` option). Options: ``--template``.
+Default: "template.txt" in the writer's directory (installed automatically;
+for the exact machine-specific path, use the ``--help`` option).
+Option: ``--template``.
.. _xml_declaration [html writers]:
@@ -1229,17 +1231,56 @@
xml_declaration
~~~~~~~~~~~~~~~
-Generate XML with an XML declaration.
+Prepend an XML declaration.
See also `xml_declaration [docutils_xml writer]`_.
.. Caution:: The XML declaration carries text encoding information. If the
encoding is not UTF-8 or ASCII and the XML declaration is missing,
- standard tools may be unable to read the generated XHTML.
+ standard XML tools may be unable to read the generated XHTML.
-Default: do (True). Options: ``--no-xml-declaration``.
+Default: writer dependent.
+Options: ``--xml-declaration``, ``--no-xml-declaration``.
+[html5 writer]
+~~~~~~~~~~~~~~
+The `HTML5 Writer`_ generates valid XML that is compatible with `HTML5`_.
+It shares all settings defined in the `[html writers]`_
+`configuration section`_.
+
+New in Docutils 0.13.
+
+__ https://www.w3.org/TR/html53/sections.html#the-h1-h2-h3-h4-h5-and-h6-elements
+.. _HTML5 Writer: html.html#html5-polyglot
+.. _HTML5: http://www.w3.org/TR/html5/
+
+
+Writer Specific Defaults
+""""""""""""""""""""""""
+
+`initial_header_level`_
+ 2 (for "<h2>", cf. the `HTML5.3 Working Draft`__)
+
+`stylesheet_path <stylesheet_path [html writers]_>`__:
+ "minimal.css,plain.css"
+
+embed_images
+""""""""""""
+
+Embed images in the output HTML file. If the image can be read from
+the local file system and its MIME type can be determined, it is
+base64_ encoded and included as a `data URI`_.
+
+Default: disabled (False).
+Options: ``--embed-images``, ``--link-images``.
+
+New in Docutils 0.17.
+
+.. _base64: https://en.wikipedia.org/wiki/Base64
+.. _data URI: https://en.wikipedia.org/wiki/Data_URI_scheme
+
+
[html4css1 writer]
~~~~~~~~~~~~~~~~~~
@@ -1249,7 +1290,8 @@
`configuration section`_.
-Writer specific defaults:
+Writer Specific Defaults
+""""""""""""""""""""""""
`initial_header_level`_
1 (for "<h1>")
@@ -1257,6 +1299,9 @@
`stylesheet_path <stylesheet_path [html writers]_>`__:
"html4css1.css"
+`xml_declaration <xml_declaration [html writers]_>`__
+ enabled (True)
+
.. _HTML4/CSS1 Writer: html.html#html4css1
.. _XHTML 1 Transitional: http://www.w3.org/TR/xhtml1/
@@ -1282,44 +1327,6 @@
Default: 14 (i.e. 14 characters). Option: ``--option-limit``.
-[html5 writer]
-~~~~~~~~~~~~~~
-
-The `HTML5 Writer`_ generates valid XML that is compatible with `HTML5`_.
-It shares all settings defined in the `[html writers]`_
-`configuration section`_.
-
-Writer specific defaults:
-
-`initial_header_level`_
- 2 (for "<h2>", cf. the `HTML5.3 Working Draft`__)
-
-`stylesheet_path <stylesheet_path [html writers]_>`__:
- "minimal.css,plain.css"
-
-New in Docutils 0.13.
-
-__ https://www.w3.org/TR/html53/sections.html#the-h1-h2-h3-h4-h5-and-h6-elements
-.. _HTML5 Writer: html.html#html5-polyglot
-.. _HTML5: http://www.w3.org/TR/html5/
-
-
-embed_images
-""""""""""""
-
-Embed images in the output HTML file. If the image can be read from
-the local file system and its MIME type can be determined, it is
-base64_ encoded and included as a `data URI`_.
-
-Default: disabled (False).
-Options: ``--embed-images``, ``--link-images``
-
-New in Docutils 0.17.
-
-.. _base64: https://en.wikipedia.org/wiki/Base64
-.. _data URI: https://en.wikipedia.org/wiki/Data_URI_scheme
-
-
[pep_html writer]
~~~~~~~~~~~~~~~~~
@@ -1327,7 +1334,8 @@
all settings defined in the `[html writers]`_ and `[html4css1 writer]`_
`configuration sections`_.
-Writer specific defaults:
+Writer Specific Defaults
+""""""""""""""""""""""""
`initial_header_level`_
1 (for "<h1>")
@@ -1352,13 +1360,13 @@
Home URL prefix for PEPs.
-Default: current directory ("."). Options: ``--pep-home``.
+Default: current directory ("."). Option: ``--pep-home``.
python_home
"""""""""""
Python's home URL.
-Default: parent directory (".."). Options: ``--python-home``.
+Default: parent directory (".."). Option: ``--python-home``.
[s5_html writer]
@@ -1368,7 +1376,8 @@
all settings defined in the `[html writers]`_ and `[html4css1 writer]`_
`configuration sections`_.
-Writer specific defaults:
+Writer Specific Defaults
+""""""""""""""""""""""""
compact_lists_:
disable compact lists.
@@ -1387,8 +1396,8 @@
Auto-hide the presentation controls in slideshow mode, or or keep
them visible at all times.
-Default: auto-hide (True). Options: ``--hidden-controls``,
-``--visible-controls``.
+Default: auto-hide (True).
+Options: ``--hidden-controls``, ``--visible-controls``.
current_slide
"""""""""""""
@@ -1395,8 +1404,8 @@
Enable or disable the current slide indicator ("1/15").
-Default: disabled (None). Options: ``--current-slide``,
-``--no-current-slide``.
+Default: disabled (None).
+Options: ``--current-slide``, ``--no-current-slide``.
overwrite_theme_files
"""""""""""""""""""""
@@ -1405,8 +1414,8 @@
``ui/<theme>`` directory. This has no effect if "theme_url_" is
used.
-Default: keep existing theme files (None). Options:
-``--keep-theme-files``, ``--overwrite-theme-files``.
+Default: keep existing theme files (None).
+Options: ``--keep-theme-files``, ``--overwrite-theme-files``.
theme
"""""
@@ -1601,6 +1610,7 @@
number or the page number.
Default: "" (use hyperreferences). Option: ``--reference-label``.
+
section_enumerator_separator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1673,7 +1683,7 @@
Default: the working directory of the process at launch and the directory
with default stylesheet files (writer and installation specific).
Use the ``--help`` option to get the exact value.
-Option: ``--stylesheet-directories``.
+Option: ``--stylesheet-dirs``.
.. _stylesheet_path [latex writers]:
@@ -1744,7 +1754,7 @@
See also `template [html writers]`_.
Default: writer dependent (see `[latex2e writer]`_, `[xetex writer]`_).
-Options: ``--template``.
+Option: ``--template``.
use_bibtex
@@ -1999,7 +2009,7 @@
Pretty-print <#text> nodes.
-Default: False. Options: ``--detailled``.
+Default: False. Option: ``--detailled``.
[applications]
@@ -2013,18 +2023,24 @@
Do not process files, show files that would be processed.
-Default: False. Options: ``--dry-run``.
+Default: False. Option: ``--dry-run``.
-html_writer
-~~~~~~~~~~~
+.. _html_writer:
+.. _writer [buildhtml application]:
+writer
+~~~~~~
+
`HTML writer`_ version. One of "html", "html4", "html5".
Default: "html" (use Docutils' default HTML writer).
-Options: ``--html-writer``
+Option: ``--writer``
+New in 0.17. Obsoletes the ``html_writer`` option.
+
.. _HTML writer: html.html
+
ignore
~~~~~~
@@ -2033,7 +2049,7 @@
configuration files or on the command line); on the command line, the
option may also be used more than once.
-Default: None. Options: ``--ignore``.
+Default: None. Option: ``--ignore``.
prune
~~~~~
@@ -2043,7 +2059,7 @@
on the command line); on the command line, the option may also be
used more than once.
-Default: ['.hg', '.bzr', '.git', '.svn', 'CVS']. Options:
+Default: ['.hg', '.bzr', '.git', '.svn', 'CVS']. Option:
``--prune``.
recurse
@@ -2059,7 +2075,7 @@
Work silently (no progress messages). Independent of
"report_level".
-Default: show progress (None). Options: ``--silent``.
+Default: show progress (None). Option: ``--silent``.
[docfactory application]
@@ -2089,7 +2105,7 @@
interpreted relative to the config file's location (*not* relative
to the current working directory).
-Default: None. Options: ``--config``.
+Default: None. Option: ``--config``.
Internal Settings
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-04-29 09:55:59
|
Revision: 8716
http://sourceforge.net/p/docutils/code/8716
Author: milde
Date: 2021-04-29 09:55:58 +0000 (Thu, 29 Apr 2021)
Log Message:
-----------
Fix "pseudoxml" writer option "detailled".
str.splitlines() does not allow keyword arguments under Python 2.7.
Add a test case.
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/docutils/nodes.py
trunk/docutils/test/test_writers/test_pseudoxml.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2021-04-23 09:04:41 UTC (rev 8715)
+++ trunk/docutils/HISTORY.txt 2021-04-29 09:55:58 UTC (rev 8716)
@@ -16,6 +16,10 @@
Changes Since 0.17.1
====================
+* docutils/writers/pseudoxml.py:
+
+ - Fix option "detailled" under Python 2.7.
+
Release 0.17.1 (2021-04-16)
===========================
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2021-04-23 09:04:41 UTC (rev 8715)
+++ trunk/docutils/docutils/nodes.py 2021-04-29 09:55:58 UTC (rev 8716)
@@ -457,9 +457,9 @@
def pformat(self, indent=' ', level=0):
try:
if self.document.settings.detailled:
- lines = ['%s%s' % (indent * level, '<#text>')
- ] + [indent*(level+1) + repr(line)
- for line in self.splitlines(keepends=True)]
+ lines = ['%s%s' % (indent*level, '<#text>')
+ ] + [indent*(level+1) + repr(reprunicode(line))
+ for line in self.splitlines(True)]
return '\n'.join(lines) + '\n'
except AttributeError:
pass
Modified: trunk/docutils/test/test_writers/test_pseudoxml.py
===================================================================
--- trunk/docutils/test/test_writers/test_pseudoxml.py 2021-04-23 09:04:41 UTC (rev 8715)
+++ trunk/docutils/test/test_writers/test_pseudoxml.py 2021-04-29 09:55:58 UTC (rev 8716)
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-# $Id$
+# $Id: test_pseudoxml.py 8481 2020-01-31 08:17:24Z milde $
# Author: Lea Wiemann <LeW...@gm...>
# Copyright: This module has been placed in the public domain.
@@ -15,20 +15,27 @@
def suite():
- s = DocutilsTestSupport.PublishTestSuite('pseudoxml')
+ # Settings dictionary must not be empty for later changes to work.
+ settings = {'expose_internals': []} # default
+ s = DocutilsTestSupport.PublishTestSuite('pseudoxml',
+ suite_settings=settings)
s.generateTests(totest)
+ settings['detailled'] = True
+ s.generateTests(totest_detailled)
return s
totest = {}
+totest_detailled = {}
totest['basic'] = [
# input
-["""\
+[r"""
This is a paragraph.
----------
-This is another paragraph.
+This is a paragraph
+with \escaped \characters.
A Section
---------
@@ -42,7 +49,8 @@
This is a paragraph.
<transition>
<paragraph>
- This is another paragraph.
+ This is a paragraph
+ with escaped characters.
<section ids="a-section" names="a\\ section">
<title>
A Section
@@ -51,6 +59,30 @@
"""]
]
+totest_detailled['basic'] = [
+# input
+[totest['basic'][0][0],
+# output
+"""\
+<document source="<string>">
+ <paragraph>
+ <#text>
+ 'This is a paragraph.'
+ <transition>
+ <paragraph>
+ <#text>
+ 'This is a paragraph\\n'
+ 'with \\x00escaped \\x00characters.'
+ <section ids="a-section" names="a\\ section">
+ <title>
+ <#text>
+ 'A Section'
+ <paragraph>
+ <#text>
+ 'Foo.'
+"""]
+]
+
if __name__ == '__main__':
import unittest
unittest.main(defaultTest='suite')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-02 21:23:39
|
Revision: 8717
http://sourceforge.net/p/docutils/code/8717
Author: milde
Date: 2021-05-02 21:23:37 +0000 (Sun, 02 May 2021)
Log Message:
-----------
HTML math output fixes.
Fix bug #244 Wrong subscript/superscript order
with ``math-output=HTML``.
Don't use <tt> element (deprecated in HTML5).
Support commands ``\Bbbk`` and ``operatorname``.
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/docutils/utils/math/math2html.py
trunk/docutils/docutils/writers/html5_polyglot/math.css
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2021-04-29 09:55:58 UTC (rev 8716)
+++ trunk/docutils/HISTORY.txt 2021-05-02 21:23:37 UTC (rev 8717)
@@ -19,7 +19,14 @@
* docutils/writers/pseudoxml.py:
- Fix option "detailled" under Python 2.7.
+
+* docutils/tools/math/math2html, docutils/writers/html5_polyglot/math.css
+ - Fix bug #244 Wrong subscript/superscript order with
+ ``--math-output=HTML``.
+ - Don't use <tt> element (deprecated in HTML5).
+ - Support commands ``\Bbbk`` and ``operatorname``.
+
Release 0.17.1 (2021-04-16)
===========================
Modified: trunk/docutils/docutils/utils/math/math2html.py
===================================================================
--- trunk/docutils/docutils/utils/math/math2html.py 2021-04-29 09:55:58 UTC (rev 8716)
+++ trunk/docutils/docutils/utils/math/math2html.py 2021-05-02 21:23:37 UTC (rev 8717)
@@ -385,8 +385,8 @@
u'\\&': u'&', u'\\,': u' ', u'\\:': u' ', u'\\;': u' ', u'\\AC': u'∿',
u'\\APLcomment': u'⍝', u'\\APLdownarrowbox': u'⍗', u'\\APLinput': u'⍞',
u'\\APLinv': u'⌹', u'\\APLleftarrowbox': u'⍇', u'\\APLlog': u'⍟',
- u'\\APLrightarrowbox': u'⍈', u'\\APLuparrowbox': u'⍐', u'\\Box': u'□',
- u'\\Bumpeq': u'≎', u'\\CIRCLE': u'●', u'\\Cap': u'⋒',
+ u'\\APLrightarrowbox': u'⍈', u'\\APLuparrowbox': u'⍐', u'\\Bbbk': u'𝕜',
+ u'\\Box': u'□', u'\\Bumpeq': u'≎', u'\\CIRCLE': u'●', u'\\Cap': u'⋒',
u'\\CapitalDifferentialD': u'ⅅ', u'\\CheckedBox': u'☑', u'\\Circle': u'○',
u'\\Coloneqq': u'⩴', u'\\ComplexI': u'ⅈ', u'\\ComplexJ': u'ⅉ',
u'\\Corresponds': u'≙', u'\\Cup': u'⋓', u'\\Delta': u'Δ', u'\\Diamond': u'◇',
@@ -587,6 +587,7 @@
u'align': [u'r', u'l',], u'eqnarray': [u'r', u'c', u'l',],
u'gathered': [u'l', u'l',],
}
+
fontfunctions = {
u'\\boldsymbol': u'b', u'\\mathbb': u'span class="blackboard"',
@@ -606,11 +607,13 @@
u'\\mathit': u'i', u'\\mathring{A}': u'Å', u'\\mathring{U}': u'Ů',
u'\\mathring{a}': u'å', u'\\mathring{u}': u'ů', u'\\mathring{w}': u'ẘ',
u'\\mathring{y}': u'ẙ', u'\\mathrm': u'span class="mathrm"',
- u'\\mathscr': u'span class="scriptfont"', u'\\mathscr{B}': u'ℬ',
- u'\\mathscr{E}': u'ℰ', u'\\mathscr{F}': u'ℱ', u'\\mathscr{H}': u'ℋ',
- u'\\mathscr{I}': u'ℐ', u'\\mathscr{L}': u'ℒ', u'\\mathscr{M}': u'ℳ',
- u'\\mathscr{R}': u'ℛ', u'\\mathsf': u'span class="mathsf"',
- u'\\mathtt': u'tt',
+ u'\\mathscr': u'span class="scriptfont"',
+ u'\\mathscr{B}': u'ℬ', u'\\mathscr{E}': u'ℰ', u'\\mathscr{F}':
+ u'ℱ', u'\\mathscr{H}': u'ℋ', u'\\mathscr{I}': u'ℐ',
+ u'\\mathscr{L}': u'ℒ', u'\\mathscr{M}': u'ℳ', u'\\mathscr{R}': u'ℛ',
+ u'\\mathsf': u'span class="mathsf"',
+ u'\\mathtt': u'span class="mathtt"',
+ u'\\operatorname': u'span class="mathrm"',
}
hybridfunctions = {
Modified: trunk/docutils/docutils/writers/html5_polyglot/math.css
===================================================================
--- trunk/docutils/docutils/writers/html5_polyglot/math.css 2021-04-29 09:55:58 UTC (rev 8716)
+++ trunk/docutils/docutils/writers/html5_polyglot/math.css 2021-05-02 21:23:37 UTC (rev 8717)
@@ -82,12 +82,13 @@
padding: 0ex;
border-top: thin solid;
}
+sub, sup {
+ font-size: 70%;
+}
sup.numerator, sup.unit {
- font-size: 70%;
vertical-align: 80%;
}
sub.denominator, sub.unit {
- font-size: 70%;
vertical-align: -20%;
}
span.sqrt {
@@ -96,7 +97,6 @@
padding: 0.1ex;
}
sup.root {
- font-size: 70%;
position: relative;
left: 1.4ex;
}
@@ -126,15 +126,18 @@
span.hugesymbol {
font-size: 200%;
}
+/* vertically stacked sub and superscript */
span.scripts {
- display: inline-table;
+ display: inline-flex;
vertical-align: middle;
+ flex-direction: column;
}
-.script {
- display: table-row;
- text-align: left;
- line-height: 150%;
+sup.script {
+ order: 1;
}
+sub.script {
+ order: 2;
+}
span.limits {
display: inline-table;
vertical-align: middle;
@@ -241,6 +244,10 @@
font-style: normal;
font-family: serif;
}
+span.mathtt, span.texttt {
+ font-style: normal;
+ font-family: monospace;
+}
span.text, span.textnormal {
font-style: normal;
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-17 20:28:28
|
Revision: 8721
http://sourceforge.net/p/docutils/code/8721
Author: milde
Date: 2021-05-17 20:28:27 +0000 (Mon, 17 May 2021)
Log Message:
-----------
version 0.18b.dev, open repository for development.
Modified Paths:
--------------
trunk/docutils/README.txt
trunk/docutils/docutils/__init__.py
trunk/docutils/setup.py
trunk/docutils/test/functional/expected/compact_lists.html
trunk/docutils/test/functional/expected/dangerous.html
trunk/docutils/test/functional/expected/embed_images_html5.html
trunk/docutils/test/functional/expected/field_name_limit.html
trunk/docutils/test/functional/expected/footnotes_html5.html
trunk/docutils/test/functional/expected/math_output_html.html
trunk/docutils/test/functional/expected/math_output_latex.html
trunk/docutils/test/functional/expected/math_output_mathjax.html
trunk/docutils/test/functional/expected/math_output_mathml.xhtml
trunk/docutils/test/functional/expected/misc_rst_html4css1.html
trunk/docutils/test/functional/expected/pep_html.html
trunk/docutils/test/functional/expected/standalone_rst_docutils_xml.xml
trunk/docutils/test/functional/expected/standalone_rst_html4css1.html
trunk/docutils/test/functional/expected/standalone_rst_html5.html
trunk/docutils/test/functional/expected/standalone_rst_s5_html_1.html
trunk/docutils/test/functional/expected/standalone_rst_s5_html_2.html
trunk/docutils/test/functional/expected/video.html
Modified: trunk/docutils/README.txt
===================================================================
--- trunk/docutils/README.txt 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/README.txt 2021-05-17 20:28:27 UTC (rev 8721)
@@ -1,5 +1,5 @@
===============================
- README: Docutils 0.17.2b.dev
+ README: Docutils 0.18b.dev
===============================
:Author: David Goodger
Modified: trunk/docutils/docutils/__init__.py
===================================================================
--- trunk/docutils/docutils/__init__.py 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/docutils/__init__.py 2021-05-17 20:28:27 UTC (rev 8721)
@@ -56,7 +56,7 @@
__docformat__ = 'reStructuredText'
-__version__ = '0.17.2b.dev'
+__version__ = '0.18b.dev'
"""Docutils version identifier (complies with PEP 440)::
major.minor[.micro][releaselevel[serial]][.dev]
@@ -111,8 +111,8 @@
__version_info__ = VersionInfo(
major=0,
- minor=17,
- micro=2,
+ minor=18,
+ micro=0,
releaselevel='beta', # one of 'alpha', 'beta', 'candidate', 'final'
# pre-release serial number (0 for final releases and active development):
serial=0,
Modified: trunk/docutils/setup.py
===================================================================
--- trunk/docutils/setup.py 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/setup.py 2021-05-17 20:28:27 UTC (rev 8721)
@@ -31,7 +31,7 @@
input Docutils supports reStructuredText, an easy-to-read,
what-you-see-is-what-you-get plaintext markup syntax.""", # wrap at col 60
'url': 'http://docutils.sourceforge.net/',
- 'version': '0.17.2b.dev',
+ 'version': '0.18b.dev',
'author': 'David Goodger',
'author_email': 'go...@py...',
'maintainer': 'docutils-develop list',
Modified: trunk/docutils/test/functional/expected/compact_lists.html
===================================================================
--- trunk/docutils/test/functional/expected/compact_lists.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/compact_lists.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>compact_lists.txt</title>
<link rel="stylesheet" href="../input/data/html4css1.css" type="text/css" />
</head>
Modified: trunk/docutils/test/functional/expected/dangerous.html
===================================================================
--- trunk/docutils/test/functional/expected/dangerous.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/dangerous.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>dangerous.txt</title>
<link rel="stylesheet" href="../input/data/html4css1.css" type="text/css" />
</head>
Modified: trunk/docutils/test/functional/expected/embed_images_html5.html
===================================================================
--- trunk/docutils/test/functional/expected/embed_images_html5.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/embed_images_html5.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>Embedded Images</title>
<link rel="stylesheet" href="../input/data/minimal.css" type="text/css" />
<link rel="stylesheet" href="../input/data/plain.css" type="text/css" />
Modified: trunk/docutils/test/functional/expected/field_name_limit.html
===================================================================
--- trunk/docutils/test/functional/expected/field_name_limit.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/field_name_limit.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>field_list.txt</title>
<link rel="stylesheet" href="../input/data/html4css1.css" type="text/css" />
</head>
Modified: trunk/docutils/test/functional/expected/footnotes_html5.html
===================================================================
--- trunk/docutils/test/functional/expected/footnotes_html5.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/footnotes_html5.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>Test footnote and citation rendering</title>
<link rel="stylesheet" href="../input/data/minimal.css" type="text/css" />
<link rel="stylesheet" href="../input/data/plain.css" type="text/css" />
Modified: trunk/docutils/test/functional/expected/math_output_html.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_html.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/math_output_html.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>Mathematics</title>
<link rel="stylesheet" href="../input/data/html4css1.css" type="text/css" />
<link rel="stylesheet" href="../input/data/math.css" type="text/css" />
Modified: trunk/docutils/test/functional/expected/math_output_latex.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_latex.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/math_output_latex.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>Mathematics</title>
<link rel="stylesheet" href="../input/data/html4css1.css" type="text/css" />
</head>
Modified: trunk/docutils/test/functional/expected/math_output_mathjax.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathjax.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/math_output_mathjax.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>Mathematics</title>
<script type="text/javascript" src="/usr/share/javascript/mathjax/MathJax.js?config=TeX-AMS_CHTML"></script>
<link rel="stylesheet" href="../input/data/html4css1.css" type="text/css" />
Modified: trunk/docutils/test/functional/expected/math_output_mathml.xhtml
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.xhtml 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/math_output_mathml.xhtml 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>Mathematics</title>
<link rel="stylesheet" href="../input/data/minimal.css" type="text/css" />
<link rel="stylesheet" href="../input/data/plain.css" type="text/css" />
Modified: trunk/docutils/test/functional/expected/misc_rst_html4css1.html
===================================================================
--- trunk/docutils/test/functional/expected/misc_rst_html4css1.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/misc_rst_html4css1.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>link_in_substitution.txt</title>
<link rel="stylesheet" href="foo&bar.css" type="text/css" />
</head>
Modified: trunk/docutils/test/functional/expected/pep_html.html
===================================================================
--- trunk/docutils/test/functional/expected/pep_html.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/pep_html.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -8,7 +8,7 @@
-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+ <meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>PEP 100 -- Test PEP</title>
<link rel="stylesheet" href="../input/data/html4css1.css" type="text/css" />
</head>
Modified: trunk/docutils/test/functional/expected/standalone_rst_docutils_xml.xml
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_docutils_xml.xml 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/standalone_rst_docutils_xml.xml 2021-05-17 20:28:27 UTC (rev 8721)
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE document PUBLIC "+//IDN docutils.sourceforge.net//DTD Docutils Generic//EN//XML" "http://docutils.sourceforge.net/docs/ref/docutils.dtd">
-<!-- Generated by Docutils 0.17.2b.dev -->
+<!-- Generated by Docutils 0.18b.dev -->
<document ids="restructuredtext-test-document doctitle" names="restructuredtext\ test\ document doctitle" source="functional/input/standalone_rst_docutils_xml.txt" title="reStructuredText Test Document">
<title>reStructuredText Test Document</title>
<subtitle ids="examples-of-syntax-constructs subtitle" names="examples\ of\ syntax\ constructs subtitle">Examples of Syntax Constructs</subtitle>
Modified: trunk/docutils/test/functional/expected/standalone_rst_html4css1.html
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_html4css1.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/standalone_rst_html4css1.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>reStructuredText Test Document</title>
<meta name="author" content="David Goodger" />
<meta name="authors" content="Me Myself I" />
Modified: trunk/docutils/test/functional/expected/standalone_rst_html5.html
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_html5.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/standalone_rst_html5.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>reStructuredText Test Document</title>
<meta name="author" content="David Goodger" />
<meta name="author" content="Me" />
Modified: trunk/docutils/test/functional/expected/standalone_rst_s5_html_1.html
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_s5_html_1.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/standalone_rst_s5_html_1.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<meta name="version" content="S5 1.1" />
<title>Slide Shows</title>
<meta name="author" content="David Goodger" />
Modified: trunk/docutils/test/functional/expected/standalone_rst_s5_html_2.html
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_s5_html_2.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/standalone_rst_s5_html_2.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<meta name="version" content="S5 1.1" />
<title>Slide Shows</title>
<meta name="author" content="David Goodger" />
Modified: trunk/docutils/test/functional/expected/video.html
===================================================================
--- trunk/docutils/test/functional/expected/video.html 2021-05-08 09:57:31 UTC (rev 8720)
+++ trunk/docutils/test/functional/expected/video.html 2021-05-17 20:28:27 UTC (rev 8721)
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
-<meta name="generator" content="Docutils 0.17.2b.dev: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
<title>Moving images (video)</title>
<link rel="stylesheet" href="../input/data/minimal.css" type="text/css" />
<link rel="stylesheet" href="../input/data/plain.css" type="text/css" />
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-17 20:28:59
|
Revision: 8722
http://sourceforge.net/p/docutils/code/8722
Author: milde
Date: 2021-05-17 20:28:42 +0000 (Mon, 17 May 2021)
Log Message:
-----------
Review settings_spec.
Common options for HTML writers.
Minor changes for xetex writer and docutils-cli.py.
Modified Paths:
--------------
trunk/docutils/docutils/readers/standalone.py
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/html4css1/__init__.py
trunk/docutils/docutils/writers/html5_polyglot/__init__.py
trunk/docutils/docutils/writers/pep_html/__init__.py
trunk/docutils/docutils/writers/xetex/__init__.py
trunk/docutils/tools/docutils-cli.py
Modified: trunk/docutils/docutils/readers/standalone.py
===================================================================
--- trunk/docutils/docutils/readers/standalone.py 2021-05-17 20:28:27 UTC (rev 8721)
+++ trunk/docutils/docutils/readers/standalone.py 2021-05-17 20:28:42 UTC (rev 8722)
@@ -23,7 +23,7 @@
"""A single document tree."""
settings_spec = (
- 'Standalone Reader',
+ 'Standalone Reader Options',
None,
(('Disable the promotion of a lone top-level section title to '
'document title (and subsequent section title to document '
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2021-05-17 20:28:27 UTC (rev 8721)
+++ trunk/docutils/docutils/writers/_html_base.py 2021-05-17 20:28:42 UTC (rev 8722)
@@ -34,7 +34,7 @@
PIL = None
import docutils
-from docutils import nodes, utils, writers, languages, io
+from docutils import frontend, languages, nodes, utils, writers
from docutils.utils.error_reporting import SafeString
from docutils.transforms import writer_aux
from docutils.utils.math import (unichar2tex, pick_math_environment,
@@ -54,16 +54,99 @@
supported = ('html', 'xhtml') # update in subclass
"""Formats this writer supports."""
- # default_stylesheets = [] # set in subclass!
- # default_stylesheet_dirs = ['.'] # set in subclass!
- default_template = 'template.txt'
- # default_template_path = ... # set in subclass!
- # settings_spec = ... # set in subclass!
+ settings_spec = ('HTML Writer Options', None, (
+ ('Specify the template file (UTF-8 encoded). '
+ '(default: writer dependent)',
+ ['--template'],
+ {'metavar': '<file>'}),
+ ('Comma separated list of stylesheet URLs. '
+ 'Overrides previous --stylesheet and --stylesheet-path settings.',
+ ['--stylesheet'],
+ {'metavar': '<URL[,URL,...]>', 'overrides': 'stylesheet_path',
+ 'validator': frontend.validate_comma_separated_list}),
+ ('Comma separated list of stylesheet paths. '
+ 'Relative paths are expanded if a matching file is found in '
+ 'the --stylesheet-dirs. With --link-stylesheet, '
+ 'the path is rewritten relative to the output HTML file. '
+ '(default: writer dependent)',
+ ['--stylesheet-path'],
+ {'metavar': '<file[,file,...]>', 'overrides': 'stylesheet',
+ 'validator': frontend.validate_comma_separated_list}),
+ ('Comma-separated list of directories where stylesheets are found. '
+ 'Used by --stylesheet-path when expanding relative path arguments. '
+ '(default: writer dependent)',
+ ['--stylesheet-dirs'],
+ {'metavar': '<dir[,dir,...]>',
+ 'validator': frontend.validate_comma_separated_list}),
+ ('Embed the stylesheet(s) in the output HTML file. The stylesheet '
+ 'files must be accessible during processing. (default)',
+ ['--embed-stylesheet'],
+ {'default': 1, 'action': 'store_true',
+ 'validator': frontend.validate_boolean}),
+ ('Link to the stylesheet(s) in the output HTML file. ',
+ ['--link-stylesheet'],
+ {'dest': 'embed_stylesheet', 'action': 'store_false'}),
+ ('Specify the initial header level. '
+ 'Does not affect document title & subtitle (see --no-doc-title).'
+ '(default: writer dependent).',
+ ['--initial-header-level'],
+ {'choices': '1 2 3 4 5 6'.split(), 'default': '2',
+ 'metavar': '<level>'}),
+ ('Format for footnote references: one of "superscript" or '
+ '"brackets". (default: "brackets")',
+ ['--footnote-references'],
+ {'choices': ['superscript', 'brackets'], 'default': 'brackets',
+ 'metavar': '<format>',
+ 'overrides': 'trim_footnote_reference_space'}),
+ ('Format for block quote attributions: '
+ 'one of "dash" (em-dash prefix), "parentheses"/"parens", or "none". '
+ '(default: "dash")',
+ ['--attribution'],
+ {'choices': ['dash', 'parentheses', 'parens', 'none'],
+ 'default': 'dash', 'metavar': '<format>'}),
+ ('Remove extra vertical whitespace between items of "simple" bullet '
+ 'lists and enumerated lists. (default)',
+ ['--compact-lists'],
+ {'default': True, 'action': 'store_true',
+ 'validator': frontend.validate_boolean}),
+ ('Disable compact simple bullet and enumerated lists.',
+ ['--no-compact-lists'],
+ {'dest': 'compact_lists', 'action': 'store_false'}),
+ ('Remove extra vertical whitespace between items of simple field '
+ 'lists. (default)',
+ ['--compact-field-lists'],
+ {'default': True, 'action': 'store_true',
+ 'validator': frontend.validate_boolean}),
+ ('Disable compact simple field lists.',
+ ['--no-compact-field-lists'],
+ {'dest': 'compact_field_lists', 'action': 'store_false'}),
+ ('Added to standard table classes. '
+ 'Defined styles: borderless, booktabs, '
+ 'align-left, align-center, align-right, colwidths-auto. ',
+ ['--table-style'],
+ {'default': ''}),
+ ('Math output format (one of "MathML", "HTML", "MathJax", '
+ 'or "LaTeX") and option(s). '
+ '(default: "HTML math.css")',
+ ['--math-output'],
+ {'default': 'HTML math.css'}),
+ ('Prepend an XML declaration. ',
+ ['--xml-declaration'],
+ {'default': False, 'action': 'store_true',
+ 'validator': frontend.validate_boolean}),
+ ('Omit the XML declaration.',
+ ['--no-xml-declaration'],
+ {'dest': 'xml_declaration', 'action': 'store_false'}),
+ ('Obfuscate email addresses to confuse harvesters while still '
+ 'keeping email links usable with standards-compliant browsers.',
+ ['--cloak-email-addresses'],
+ {'action': 'store_true', 'validator': frontend.validate_boolean}),
+ ))
settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'}
- # config_section = ... # set in subclass!
- config_section_dependencies = ('writers', 'html writers')
+ config_section = 'html writers'
+ config_section_dependencies = ('writers', )
visitor_attributes = (
'head_prefix', 'head', 'stylesheet', 'body_prefix',
@@ -308,8 +391,8 @@
"""Return code to reference or embed stylesheet file `path`"""
if self.settings.embed_stylesheet:
try:
- content = io.FileInput(source_path=path,
- encoding='utf-8').read()
+ content = docutils.io.FileInput(source_path=path,
+ encoding='utf-8').read()
self.settings.record_dependencies.add(path)
except IOError as err:
msg = u"Cannot embed stylesheet '%r': %s." % (
Modified: trunk/docutils/docutils/writers/html4css1/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/html4css1/__init__.py 2021-05-17 20:28:27 UTC (rev 8721)
+++ trunk/docutils/docutils/writers/html4css1/__init__.py 2021-05-17 20:28:42 UTC (rev 8722)
@@ -30,59 +30,55 @@
default_stylesheets = ['html4css1.css']
default_stylesheet_dirs = ['.',
- os.path.abspath(os.path.dirname(__file__)),
- # for math.css
- os.path.abspath(os.path.join(
- os.path.dirname(os.path.dirname(__file__)), 'html5_polyglot'))
- ]
+ os.path.abspath(os.path.dirname(__file__)),
+ os.path.abspath(os.path.join(
+ os.path.dirname(os.path.dirname(__file__)),
+ 'html5_polyglot')) # for math.css
+ ]
+ default_template = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), 'template.txt')
- default_template = 'template.txt'
- default_template_path = os.path.join(
- os.path.dirname(os.path.abspath(__file__)), default_template)
-
- settings_spec = (
- 'HTML-Specific Options',
- None,
- (('Specify the template file (UTF-8 encoded). Default is "%s".'
- % default_template_path,
+ settings_spec = frontend.filter_settings_spec(
+ writers._html_base.Writer.settings_spec,
+ # update specs with changed defaults or help string
+ template =
+ ('Template file. (UTF-8 encoded, default: "%s")' % default_template,
['--template'],
- {'default': default_template_path, 'metavar': '<file>'}),
- ('Comma separated list of stylesheet URLs. '
- 'Overrides previous --stylesheet and --stylesheet-path settings.',
- ['--stylesheet'],
- {'metavar': '<URL[,URL,...]>', 'overrides': 'stylesheet_path',
- 'validator': frontend.validate_comma_separated_list}),
+ {'default': default_template, 'metavar': '<file>'}),
+ stylesheet_path =
('Comma separated list of stylesheet paths. '
'Relative paths are expanded if a matching file is found in '
'the --stylesheet-dirs. With --link-stylesheet, '
'the path is rewritten relative to the output HTML file. '
- 'Default: "%s"' % ','.join(default_stylesheets),
+ '(default: "%s")' % ','.join(default_stylesheets),
['--stylesheet-path'],
{'metavar': '<file[,file,...]>', 'overrides': 'stylesheet',
'validator': frontend.validate_comma_separated_list,
'default': default_stylesheets}),
- ('Embed the stylesheet(s) in the output HTML file. The stylesheet '
- 'files must be accessible during processing. This is the default.',
- ['--embed-stylesheet'],
- {'default': 1, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Link to the stylesheet(s) in the output HTML file. '
- 'Default: embed stylesheets.',
- ['--link-stylesheet'],
- {'dest': 'embed_stylesheet', 'action': 'store_false'}),
+ stylesheet_dirs =
('Comma-separated list of directories where stylesheets are found. '
'Used by --stylesheet-path when expanding relative path arguments. '
- 'Default: "%s"' % default_stylesheet_dirs,
+ '(default: "%s")' % ','.join(default_stylesheet_dirs),
['--stylesheet-dirs'],
{'metavar': '<dir[,dir,...]>',
'validator': frontend.validate_comma_separated_list,
'default': default_stylesheet_dirs}),
- ('Specify the initial header level. Default is 1 for "<h1>". '
- 'Does not affect document title & subtitle (see --no-doc-title).',
+ initial_header_level =
+ ('Specify the initial header level. Does not affect document '
+ 'title & subtitle (see --no-doc-title). (default: 1 for "<h1>")',
['--initial-header-level'],
{'choices': '1 2 3 4 5 6'.split(), 'default': '1',
'metavar': '<level>'}),
- ('Specify the maximum width (in characters) for one-column field '
+ xml_declaration =
+ ('Prepend an XML declaration (default). ',
+ ['--xml-declaration'],
+ {'default': True, 'action': 'store_true',
+ 'validator': frontend.validate_boolean}),
+ )
+ settings_spec = settings_spec + (
+ 'HTML4 Writer Options',
+ '',
+ (('Specify the maximum width (in characters) for one-column field '
'names. Longer field names will span an entire row of the table '
'used to render the field list. Default is 14 characters. '
'Use 0 for "no limit".',
@@ -96,60 +92,10 @@
['--option-limit'],
{'default': 14, 'metavar': '<level>',
'validator': frontend.validate_nonnegative_int}),
- ('Format for footnote references: one of "superscript" or '
- '"brackets". Default is "brackets".',
- ['--footnote-references'],
- {'choices': ['superscript', 'brackets'], 'default': 'brackets',
- 'metavar': '<format>',
- 'overrides': 'trim_footnote_reference_space'}),
- ('Format for block quote attributions: one of "dash" (em-dash '
- 'prefix), "parentheses"/"parens", or "none". Default is "dash".',
- ['--attribution'],
- {'choices': ['dash', 'parentheses', 'parens', 'none'],
- 'default': 'dash', 'metavar': '<format>'}),
- ('Remove extra vertical whitespace between items of "simple" bullet '
- 'lists and enumerated lists. Default: enabled.',
- ['--compact-lists'],
- {'default': 1, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Disable compact simple bullet and enumerated lists.',
- ['--no-compact-lists'],
- {'dest': 'compact_lists', 'action': 'store_false'}),
- ('Remove extra vertical whitespace between items of simple field '
- 'lists. Default: enabled.',
- ['--compact-field-lists'],
- {'default': 1, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Disable compact simple field lists.',
- ['--no-compact-field-lists'],
- {'dest': 'compact_field_lists', 'action': 'store_false'}),
- ('Embed images in the output HTML file, if the image '
- 'files are accessible during processing.',
- ['--embed-images'],
- {'default': 0, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Link to images in the output HTML file. '
- 'This is the default.',
- ['--link-images'],
- {'dest': 'embed_images', 'action': 'store_false'}),
- ('Added to standard table classes. '
- 'Defined styles: "borderless". Default: ""',
- ['--table-style'],
- {'default': ''}),
- ('Math output format, one of "MathML", "HTML", "MathJax" '
- 'or "LaTeX". Default: "HTML math.css"',
- ['--math-output'],
- {'default': 'HTML math.css'}),
- ('Omit the XML declaration. Use with caution.',
- ['--no-xml-declaration'],
- {'dest': 'xml_declaration', 'default': 1, 'action': 'store_false',
- 'validator': frontend.validate_boolean}),
- ('Obfuscate email addresses to confuse harvesters while still '
- 'keeping email links usable with standards-compliant browsers.',
- ['--cloak-email-addresses'],
- {'action': 'store_true', 'validator': frontend.validate_boolean}),))
+ ))
config_section = 'html4css1 writer'
+ config_section_dependencies = ('writers', 'html writers')
def __init__(self):
self.parts = {}
Modified: trunk/docutils/docutils/writers/html5_polyglot/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/html5_polyglot/__init__.py 2021-05-17 20:28:27 UTC (rev 8721)
+++ trunk/docutils/docutils/writers/html5_polyglot/__init__.py 2021-05-17 20:28:42 UTC (rev 8722)
@@ -38,86 +38,54 @@
class Writer(writers._html_base.Writer):
- supported = ('html', 'html5', 'html4', 'xhtml', 'xhtml10')
+ supported = ('html', 'html5', 'xhtml')
"""Formats this writer supports."""
default_stylesheets = ['minimal.css', 'plain.css']
default_stylesheet_dirs = ['.', os.path.abspath(os.path.dirname(__file__))]
+ default_template = os.path.join(
+ os.path.dirname(os.path.abspath(__file__)), 'template.txt')
- default_template = 'template.txt'
- default_template_path = os.path.join(
- os.path.dirname(os.path.abspath(__file__)), default_template)
-
- settings_spec = (
- 'HTML-Specific Options',
- None,
- (('Specify the template file (UTF-8 encoded). Default is "%s".'
- % default_template_path,
+ settings_spec = frontend.filter_settings_spec(
+ writers._html_base.Writer.settings_spec,
+ # update specs with changed defaults or help string
+ template =
+ ('Template file. (UTF-8 encoded, default: "%s")' % default_template,
['--template'],
- {'default': default_template_path, 'metavar': '<file>'}),
- ('Comma separated list of stylesheet URLs. '
- 'Overrides previous --stylesheet and --stylesheet-path settings.',
- ['--stylesheet'],
- {'metavar': '<URL[,URL,...]>', 'overrides': 'stylesheet_path',
- 'validator': frontend.validate_comma_separated_list}),
+ {'default': default_template, 'metavar': '<file>'}),
+ stylesheet_path =
('Comma separated list of stylesheet paths. '
'Relative paths are expanded if a matching file is found in '
'the --stylesheet-dirs. With --link-stylesheet, '
'the path is rewritten relative to the output HTML file. '
- 'Default: "%s"' % ','.join(default_stylesheets),
+ '(default: "%s")' % ','.join(default_stylesheets),
['--stylesheet-path'],
{'metavar': '<file[,file,...]>', 'overrides': 'stylesheet',
'validator': frontend.validate_comma_separated_list,
'default': default_stylesheets}),
- ('Embed the stylesheet(s) in the output HTML file. The stylesheet '
- 'files must be accessible during processing. This is the default.',
- ['--embed-stylesheet'],
- {'default': 1, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Link to the stylesheet(s) in the output HTML file. '
- 'Default: embed stylesheets.',
- ['--link-stylesheet'],
- {'dest': 'embed_stylesheet', 'action': 'store_false'}),
+ stylesheet_dirs =
('Comma-separated list of directories where stylesheets are found. '
'Used by --stylesheet-path when expanding relative path arguments. '
- 'Default: "%s"' % default_stylesheet_dirs,
+ '(default: "%s")' % ','.join(default_stylesheet_dirs),
['--stylesheet-dirs'],
{'metavar': '<dir[,dir,...]>',
'validator': frontend.validate_comma_separated_list,
'default': default_stylesheet_dirs}),
- ('Specify the initial header level. Default is 2 for "<h2>". '
- 'Does not affect document title & subtitle (see --no-doc-title).',
+ initial_header_level =
+ ('Specify the initial header level. Does not affect document '
+ 'title & subtitle (see --no-doc-title). (default: 2 for "<h2>")',
['--initial-header-level'],
{'choices': '1 2 3 4 5 6'.split(), 'default': '2',
'metavar': '<level>'}),
- ('Format for footnote references: one of "superscript" or '
- '"brackets". Default is "brackets".',
- ['--footnote-references'],
- {'choices': ['superscript', 'brackets'], 'default': 'brackets',
- 'metavar': '<format>',
- 'overrides': 'trim_footnote_reference_space'}),
- ('Format for block quote attributions: one of "dash" (em-dash '
- 'prefix), "parentheses"/"parens", or "none". Default is "dash".',
- ['--attribution'],
- {'choices': ['dash', 'parentheses', 'parens', 'none'],
- 'default': 'dash', 'metavar': '<format>'}),
- ('Remove extra vertical whitespace between items of "simple" bullet '
- 'lists and enumerated lists. Default: enabled.',
- ['--compact-lists'],
- {'default': True, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Disable compact simple bullet and enumerated lists.',
- ['--no-compact-lists'],
- {'dest': 'compact_lists', 'action': 'store_false'}),
- ('Remove extra vertical whitespace between items of simple field '
- 'lists. Default: enabled.',
- ['--compact-field-lists'],
- {'default': True, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Disable compact simple field lists.',
- ['--no-compact-field-lists'],
- {'dest': 'compact_field_lists', 'action': 'store_false'}),
- ('Embed images in the output HTML file, if the image '
+ no_xml_declaration =
+ ('Omit the XML declaration.',
+ ['--no-xml-declaration'],
+ {'dest': 'xml_declaration', 'action': 'store_false'}),
+ )
+ settings_spec = settings_spec + (
+ 'HTML5 Writer Options',
+ '',
+ (('Embed images in the output HTML file, if the image '
'files are accessible during processing.',
['--embed-images'],
{'default': 0, 'action': 'store_true',
@@ -126,29 +94,7 @@
'This is the default.',
['--link-images'],
{'dest': 'embed_images', 'action': 'store_false'}),
- ('Added to standard table classes. '
- 'Defined styles: borderless, booktabs, '
- 'align-left, align-center, align-right, colwidths-auto. '
- 'Default: ""',
- ['--table-style'],
- {'default': ''}),
- ('Math output format (one of "MathML", "HTML", "MathJax", '
- 'or "LaTeX") and option(s). '
- 'Default: "HTML math.css"',
- ['--math-output'],
- {'default': 'HTML math.css'}),
- ('Prepend an XML declaration. (Thwarts HTML5 conformance.) '
- 'Default: False',
- ['--xml-declaration'],
- {'default': False, 'action': 'store_true',
- 'validator': frontend.validate_boolean}),
- ('Omit the XML declaration.',
- ['--no-xml-declaration'],
- {'dest': 'xml_declaration', 'action': 'store_false'}),
- ('Obfuscate email addresses to confuse harvesters while still '
- 'keeping email links usable with standards-compliant browsers.',
- ['--cloak-email-addresses'],
- {'action': 'store_true', 'validator': frontend.validate_boolean}),))
+ ))
config_section = 'html5 writer'
@@ -310,7 +256,7 @@
self.body_prefix.extend(header)
self.header.extend(header)
del self.body[start:]
-
+
# MIME types supported by the HTML5 <video> element
videotypes = ('video/mp4', 'video/webm', 'video/ogg')
@@ -330,7 +276,7 @@
if 'controls' in node.get('classes', []):
atts['controls'] = 'controls'
atts['title'] = node.get('alt', uri)
-
+
# No newline in inline context or if surrounded by <a>...</a>.
if (isinstance(node.parent, nodes.TextElement) or
(isinstance(node.parent, nodes.reference) and
Modified: trunk/docutils/docutils/writers/pep_html/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/pep_html/__init__.py 2021-05-17 20:28:27 UTC (rev 8721)
+++ trunk/docutils/docutils/writers/pep_html/__init__.py 2021-05-17 20:28:42 UTC (rev 8722)
@@ -33,10 +33,10 @@
os.path.join(os.path.dirname(__file__), default_template))
settings_spec = html4css1.Writer.settings_spec + (
- 'PEP/HTML-Specific Options',
+ 'PEP/HTML Writer Options',
'For the PEP/HTML writer, the default value for the --stylesheet-path '
'option is "%s", and the default value for --template is "%s". '
- 'See HTML-Specific Options above.'
+ 'See HTML Writer Options above.'
% (default_stylesheet_path, default_template_path),
(('Python\'s home URL. Default is "http://www.python.org".',
['--python-home'],
Modified: trunk/docutils/docutils/writers/xetex/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/xetex/__init__.py 2021-05-17 20:28:27 UTC (rev 8721)
+++ trunk/docutils/docutils/writers/xetex/__init__.py 2021-05-17 20:28:42 UTC (rev 8722)
@@ -6,12 +6,12 @@
# :Date: $Date$
# :Copyright: © 2010 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
"""
@@ -40,25 +40,27 @@
default_template = 'xelatex.tex'
default_preamble = '\n'.join([
- r'% Linux Libertine (free, wide coverage, not only for Linux)',
- r'\setmainfont{Linux Libertine O}',
- r'\setsansfont{Linux Biolinum O}',
- r'\setmonofont[HyphenChar=None,Scale=MatchLowercase]{DejaVu Sans Mono}',
+ r'% Linux Libertine (free, wide coverage, not only for Linux)',
+ r'\setmainfont{Linux Libertine O}',
+ r'\setsansfont{Linux Biolinum O}',
+ r'\setmonofont[HyphenChar=None,Scale=MatchLowercase]{DejaVu Sans Mono}',
])
config_section = 'xetex writer'
config_section_dependencies = ('writers', 'latex writers',
- 'latex2e writer') # TODO: remove dependency on `latex2e writer`.
+ 'latex2e writer') # TODO: remove dependency on `latex2e writer`.
settings_spec = frontend.filter_settings_spec(
latex2e.Writer.settings_spec,
- 'font_encoding',
+ 'font_encoding', # removed settings
+ # changed settings:
template=('Template file. Default: "%s".' % default_template,
- ['--template'], {'default': default_template, 'metavar': '<file>'}),
+ ['--template'],
+ {'default': default_template, 'metavar': '<file>'}),
latex_preamble=('Customization by LaTeX code in the preamble. '
- 'Default: select "Linux Libertine" fonts.',
- ['--latex-preamble'],
- {'default': default_preamble}),
+ 'Default: select "Linux Libertine" fonts.',
+ ['--latex-preamble'],
+ {'default': default_preamble}),
)
def __init__(self):
Modified: trunk/docutils/tools/docutils-cli.py
===================================================================
--- trunk/docutils/tools/docutils-cli.py 2021-05-17 20:28:27 UTC (rev 8721)
+++ trunk/docutils/tools/docutils-cli.py 2021-05-17 20:28:42 UTC (rev 8722)
@@ -42,16 +42,16 @@
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--reader', choices=('standalone', 'pep'),
- help=u'Reader name.',
+ help=u'reader name',
default='standalone')
parser.add_argument('--parser', choices=('markdown', 'rst'),
- help=u'Parser name.',
+ help=u'parser name',
default='rst')
parser.add_argument('--writer',
# choices=('html', 'html4', 'html5', 'latex', 'xelatex',
# 'odt', 'xml', 'pseudoxml', 'manpage',
# 'pep_html', 's5_html'),
- help=u'Writer name.',
+ help=u'writer name',
default='html5')
(args, remainder) = parser.parse_known_args()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-17 20:29:19
|
Revision: 8724
http://sourceforge.net/p/docutils/code/8724
Author: milde
Date: 2021-05-17 20:29:17 +0000 (Mon, 17 May 2021)
Log Message:
-----------
Small documentation update.
Modified Paths:
--------------
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docs/ref/rst/directives.txt
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2021-05-17 20:29:07 UTC (rev 8723)
+++ trunk/docutils/RELEASE-NOTES.txt 2021-05-17 20:29:17 UTC (rev 8724)
@@ -61,7 +61,7 @@
* Remove ``utils.unique_combinations``
(obsoleted by ``itertools.combinations``).
-* Eventually remove the "rawsource" attribute and argument from nodes.Text:
+* Remove the "rawsource" attribute and argument from nodes.Text:
we store the null-escaped text in Text nodes since 0.16 so there is no
additional information in the rawsource.
@@ -103,8 +103,6 @@
Release 0.17.1 (2021-04-16)
===========================
-(Release 0.17.1b.dev)
-
* Bug fixes (for details see the Docutils `HISTORY`_).
Release 0.17 (2021-04-03)
Modified: trunk/docutils/docs/ref/rst/directives.txt
===================================================================
--- trunk/docutils/docs/ref/rst/directives.txt 2021-05-17 20:29:07 UTC (rev 8723)
+++ trunk/docutils/docs/ref/rst/directives.txt 2021-05-17 20:29:17 UTC (rev 8724)
@@ -566,7 +566,8 @@
For inline formulas, use the `"math" role`_.
-.. _Short Math Guide: http://tug.ctan.org/info/short-math-guide/short-math-guide.pdf
+.. _Short Math Guide:
+ http://mirrors.ctan.org/info/short-math-guide/short-math-guide.pdf
.. _"math" role: roles.html#math
.. _math_output: ../../user/config.html#math-output
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-18 21:33:06
|
Revision: 8727
http://sourceforge.net/p/docutils/code/8727
Author: milde
Date: 2021-05-18 21:33:04 +0000 (Tue, 18 May 2021)
Log Message:
-----------
Small documentation update.
restructuredtext.txt:
Clarify which elements may come before the docinfo.
Add missing classes in "transforms.universal" docstring.
Modified Paths:
--------------
trunk/docutils/docs/ref/rst/restructuredtext.txt
trunk/docutils/docutils/transforms/universal.py
Modified: trunk/docutils/docs/ref/rst/restructuredtext.txt
===================================================================
--- trunk/docutils/docs/ref/rst/restructuredtext.txt 2021-05-17 20:29:35 UTC (rev 8726)
+++ trunk/docutils/docs/ref/rst/restructuredtext.txt 2021-05-18 21:33:04 UTC (rev 8727)
@@ -905,12 +905,17 @@
copyright_, date_, organization_, revision_, status_, topic_,
version_.
-When a field list is the first non-comment element in a document
-(after the document title, if there is one), it may have its fields
+When a field list is the first element in a document
+(after the document title, if there is one) [#]_, it may have its fields
transformed to document bibliographic data. This bibliographic data
corresponds to the front matter of a book, such as the title page and
copyright page.
+.. [#] In additon to the document title and subtitle, also comments_,
+ `substitution definitions`_, `hyperlink targets`_, and "header",
+ "footer", "meta", and "raw" directives_ may be placed before the
+ bibliographic fields.
+
Certain registered field names (listed below) are recognized and
transformed to the corresponding doctree elements, most becoming child
elements of the docinfo_ element. No ordering is required of these
@@ -975,9 +980,9 @@
`Bibliographic fields`_ recognized by the parser are normally checked
for RCS [#]_ keywords and cleaned up [#]_. RCS keywords may be
-entered into source files as "$keyword$", and once stored under RCS or
-CVS [#]_, they are expanded to "$keyword: expansion text $". For
-example, a "Status" field will be transformed to a "status" element::
+entered into source files as "$keyword$", and once stored under RCS,
+CVS [#]_, or SVN [#]_, they are expanded to "$keyword: expansion text $".
+For example, a "Status" field will be transformed to a "status" element::
:Status: $keyword: expansion text $
@@ -984,6 +989,7 @@
.. [#] Revision Control System.
.. [#] RCS keyword processing can be turned off (unimplemented).
.. [#] Concurrent Versions System. CVS uses the same keywords as RCS.
+.. [#] Subversion Versions System. Uses the same keywords as RCS.
Processed, the "status" element's text will become simply "expansion
text". The dollar sign delimiters and leading RCS keyword name are
Modified: trunk/docutils/docutils/transforms/universal.py
===================================================================
--- trunk/docutils/docutils/transforms/universal.py 2021-05-17 20:29:35 UTC (rev 8726)
+++ trunk/docutils/docutils/transforms/universal.py 2021-05-18 21:33:04 UTC (rev 8727)
@@ -8,10 +8,15 @@
Transforms needed by most or all documents:
- `Decorations`: Generate a document's header & footer.
-- `Messages`: Placement of system messages stored in
- `nodes.document.transform_messages`.
+- `ExposeInternals`: Expose internal attributes.
+- `Messages`: Placement of system messages generated after parsing.
+- `FilterMessages`: Remove system messages below verbosity threshold.
- `TestMessages`: Like `Messages`, used on test runs.
-- `FinalReferences`: Resolve remaining references.
+- `StripComments`: Remove comment elements from the document tree.
+- `StripClassesAndElements`: Remove elements with classes
+ in `self.document.settings.strip_elements_with_classes`
+ and class values in `self.document.settings.strip_classes`.
+- `SmartQuotes`: Replace ASCII quotation marks with typographic form.
"""
__docformat__ = 'reStructuredText'
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-18 21:33:35
|
Revision: 8728
http://sourceforge.net/p/docutils/code/8728
Author: milde
Date: 2021-05-18 21:33:28 +0000 (Tue, 18 May 2021)
Log Message:
-----------
Default of "legacy_class_functions" setting changed to "False".
- The setting `legacy_class_functions`_ now defaults to "False".
- latex2e/docutils.sty: Fix excessive padding above sidebar titles.
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docs/user/config.txt
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/docutils/writers/latex2e/docutils.sty
trunk/docutils/test/functional/expected/latex_leavevmode.tex
trunk/docutils/test/functional/expected/standalone_rst_latex.tex
trunk/docutils/test/functional/tests/latex_literal_block.py
trunk/docutils/test/functional/tests/latex_literal_block_fancyvrb.py
trunk/docutils/test/functional/tests/latex_literal_block_listings.py
trunk/docutils/test/functional/tests/latex_literal_block_verbatim.py
trunk/docutils/test/functional/tests/latex_literal_block_verbatimtab.py
trunk/docutils/test/functional/tests/latex_memoir.py
trunk/docutils/test/functional/tests/standalone_rst_xetex.py
trunk/docutils/test/test_writers/test_latex2e.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/HISTORY.txt 2021-05-18 21:33:28 UTC (rev 8728)
@@ -16,10 +16,6 @@
Changes Since 0.17.1
====================
-* docutils/writers/pseudoxml.py:
-
- - Fix option "detailled" under Python 2.7.
-
* docutils/tools/math/math2html, docutils/writers/html5_polyglot/math.css
- Fix bug #244 Wrong subscript/superscript order with
@@ -27,6 +23,19 @@
- Don't use <tt> element (deprecated in HTML5).
- Support commands ``\Bbbk`` and ``operatorname``.
+* docutils/writers/latex2e/__init__.py
+
+ - The setting `legacy_class_functions`_ now defaults to "False".
+ Adapt stylesheets modifying ``\DUadmonition`` and/or ``\DUtitle``.
+
+* docutils/writers/latex2e/docutils.sty
+
+ - Fix excessive padding above sidebar titles.
+
+* docutils/writers/pseudoxml.py:
+
+ - Fix option "detailled" under Python 2.7.
+
Release 0.17.1 (2021-04-16)
===========================
@@ -144,7 +153,7 @@
- Add a `viewport meta tag`__ to fix rendering in mobile browsers.
__ https://developer.mozilla.org/en-US/docs/Web/HTML/Viewport_meta_tag
-
+
- Use <video> for images with video MIME types supported by HTML5.
* docutils/writers/html5_polyglot/minimal.css
@@ -151,9 +160,9 @@
- Move non-essential styling to ``plain.css``.
Small fixes and tweaks.
-
+
- Support "captionbelow" class value for tables.
-
+
- Display code line numbers as pseudo-elements which are skipped
when copying text from code blocks. Solves feature request #32.
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/RELEASE-NOTES.txt 2021-05-18 21:33:28 UTC (rev 8728)
@@ -20,10 +20,6 @@
Future changes
==============
-* `latex` writer: The default for the configuration setting
- `legacy_class_functions`_ will change to "False". Adapt stylesheets
- modifying ``\DUadmonition`` and/or ``\DUtitle`` or set to "True".
-
* `html5` writer:
- Use semantic tags <aside> for footnote text, citations, for topics
@@ -100,6 +96,12 @@
.. _html_writer: docs/user/config.html#html-writer
+Release 0.18.dev
+================
+
+* Config setting `legacy_class_functions`_: default changed to "False".
+
+
Release 0.17.1 (2021-04-16)
===========================
Modified: trunk/docutils/docs/user/config.txt
===================================================================
--- trunk/docutils/docs/user/config.txt 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/docs/user/config.txt 2021-05-18 21:33:28 UTC (rev 8728)
@@ -1581,7 +1581,7 @@
values are handled with wrappers and admonitions use the ``DUadmonition``
environment. See `Generating LaTeX with Docutils`__ for details.
-Default: True (this will change to False in version 0.18).
+Default: False.
Options: ``--legacy-class-functions``, ``--new-class-functions``.
New in Docutils 0.17.
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -216,7 +216,7 @@
('Use legacy functions with class value list for '
'\\DUtitle and \\DUadmonition (current default). ',
['--legacy-class-functions'],
- {'default': True,
+ {'default': False,
'action': 'store_true',
'validator': frontend.validate_boolean}),
('Use \\DUrole and "DUclass" wrappers for class values. '
Modified: trunk/docutils/docutils/writers/latex2e/docutils.sty
===================================================================
--- trunk/docutils/docutils/writers/latex2e/docutils.sty 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/docutils/writers/latex2e/docutils.sty 2021-05-18 21:33:28 UTC (rev 8728)
@@ -17,7 +17,7 @@
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{docutils}
- [2020/08/28 macros for Docutils LaTeX output]
+ [2021/05/18 macros for Docutils LaTeX output]
% Helpers
% -------
@@ -196,7 +196,8 @@
% title::
% title for topics, admonitions, unsupported section levels, and sidebar
-\providecommand*{\DUtitle}[1]{\subsubsection*{#1}}
+\providecommand*{\DUtitle}[1]{%
+ \smallskip\noindent\textbf{#1}\smallskip}
% subtitle::
Modified: trunk/docutils/test/functional/expected/latex_leavevmode.tex
===================================================================
--- trunk/docutils/test/functional/expected/latex_leavevmode.tex 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/expected/latex_leavevmode.tex 2021-05-18 21:33:28 UTC (rev 8728)
@@ -41,21 +41,25 @@
\ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
}
-% abstract title
-\providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}
-
-% admonition (specially marked topic)
-\providecommand{\DUadmonition}[2][class-arg]{%
- % try \DUadmonition#1{#2}:
- \ifcsname DUadmonition#1\endcsname%
- \csname DUadmonition#1\endcsname{#2}%
- \else
- \begin{center}
- \fbox{\parbox{0.9\linewidth}{#2}}
- \end{center}
- \fi
+\providecommand*{\DUCLASSabstract}{
+ \renewcommand{\DUtitle}[1]{\centerline{\textbf{##1}}}
}
+% admonition environment (specially marked topic)
+\ifx\DUadmonition\undefined % poor man's "provideenvironment"
+ \newbox{\DUadmonitionbox}
+ \newenvironment{DUadmonition}%
+ {\begin{center}
+ \begin{lrbox}{\DUadmonitionbox}
+ \begin{minipage}{0.9\linewidth}
+ }%
+ { \end{minipage}
+ \end{lrbox}
+ \fbox{\usebox{\DUadmonitionbox}}
+ \end{center}
+ }
+\fi
+
% width of docinfo table
\DUprovidelength{\DUdocinfowidth}{0.9\linewidth}
@@ -123,14 +127,8 @@
\providecommand*{\DUrubric}[1]{\subsubsection*{\emph{#1}}}
% title for topics, admonitions, unsupported section levels, and sidebar
-\providecommand*{\DUtitle}[2][class-arg]{%
- % call \DUtitle#1{#2} if it exists:
- \ifcsname DUtitle#1\endcsname%
- \csname DUtitle#1\endcsname{#2}%
- \else
- \smallskip\noindent\textbf{#2}\smallskip%
- \fi
-}
+\providecommand*{\DUtitle}[1]{%
+ \smallskip\noindent\textbf{#1}\smallskip}
% titlereference standard role
\providecommand*{\DUroletitlereference}[1]{\textsl{#1}}
@@ -177,7 +175,7 @@
\begin{DUclass}{abstract}
\begin{quote}
-\DUtitle[abstract]{Abstract}
+\DUtitle{Abstract}
Test that \texttt{\textbackslash{}leavevmode} is inserted after the term or field-name
when required for correct placement of the item.
@@ -305,8 +303,9 @@
\DUrubric{A Rubric}
\item[{Admonition}] \leavevmode
-\DUadmonition[note]{
-\DUtitle[note]{Note}
+\begin{DUclass}{note}
+\begin{DUadmonition}
+\DUtitle{Note}
Admonitions need to be preceded by \texttt{\textbackslash{}leavevmode}.
Otherwise, the term ends up centered above the admonition box.
@@ -313,7 +312,8 @@
So do \emph{System Messages}, as they use the “DUadmonition”
LaTeX environment.
-}
+\end{DUadmonition}
+\end{DUclass}
\end{description}
Modified: trunk/docutils/test/functional/expected/standalone_rst_latex.tex
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_latex.tex 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/expected/standalone_rst_latex.tex 2021-05-18 21:33:28 UTC (rev 8728)
@@ -52,21 +52,25 @@
\ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
}
-% abstract title
-\providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}
-
-% admonition (specially marked topic)
-\providecommand{\DUadmonition}[2][class-arg]{%
- % try \DUadmonition#1{#2}:
- \ifcsname DUadmonition#1\endcsname%
- \csname DUadmonition#1\endcsname{#2}%
- \else
- \begin{center}
- \fbox{\parbox{0.9\linewidth}{#2}}
- \end{center}
- \fi
+\providecommand*{\DUCLASSabstract}{
+ \renewcommand{\DUtitle}[1]{\centerline{\textbf{##1}}}
}
+% admonition environment (specially marked topic)
+\ifx\DUadmonition\undefined % poor man's "provideenvironment"
+ \newbox{\DUadmonitionbox}
+ \newenvironment{DUadmonition}%
+ {\begin{center}
+ \begin{lrbox}{\DUadmonitionbox}
+ \begin{minipage}{0.9\linewidth}
+ }%
+ { \end{minipage}
+ \end{lrbox}
+ \fbox{\usebox{\DUadmonitionbox}}
+ \end{center}
+ }
+\fi
+
% special topic for dedications
\providecommand*{\DUCLASSdedication}{%
\renewenvironment{quote}{\begin{center}}{\end{center}}%
@@ -79,8 +83,7 @@
\providecommand*{\DUdocumentsubtitle}[1]{{\large #1}}
\newcounter{enumv}
-% error admonition title
-\providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}
+\providecommand*{\DUCLASSerror}{\color{red}}
% field list environment (for separate configuration of `field lists`)
\ifthenelse{\isundefined{\DUfieldlist}}{
@@ -161,14 +164,8 @@
\providecommand*{\DUsubtitle}[1]{\par\emph{#1}\smallskip}
% title for topics, admonitions, unsupported section levels, and sidebar
-\providecommand*{\DUtitle}[2][class-arg]{%
- % call \DUtitle#1{#2} if it exists:
- \ifcsname DUtitle#1\endcsname%
- \csname DUtitle#1\endcsname{#2}%
- \else
- \smallskip\noindent\textbf{#2}\smallskip%
- \fi
-}
+\providecommand*{\DUtitle}[1]{%
+ \smallskip\noindent\textbf{#1}\smallskip}
% titlereference standard role
\providecommand*{\DUroletitlereference}[1]{\textsl{#1}}
@@ -254,7 +251,7 @@
\begin{DUclass}{dedication}
\begin{quote}
-\DUtitle[dedication]{Dedication}
+\DUtitle{Dedication}
For Docutils users \& co-developers.
\end{quote}
@@ -262,7 +259,7 @@
\begin{DUclass}{abstract}
\begin{quote}
-\DUtitle[abstract]{Abstract}
+\DUtitle{Abstract}
This is a test document, containing at least one example of each
reStructuredText construct.
@@ -1119,38 +1116,49 @@
\label{admonitions}%
}
-\DUadmonition[attention]{
-\DUtitle[attention]{Attention!}
+\begin{DUclass}{attention}
+\begin{DUadmonition}
+\DUtitle{Attention!}
Directives at large.
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[caution]{
-\DUtitle[caution]{Caution!}
+\begin{DUclass}{caution}
+\begin{DUadmonition}
+\DUtitle{Caution!}
Don’t take any wooden nickels.
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[danger]{
-\DUtitle[danger]{!DANGER!}
+\begin{DUclass}{danger}
+\begin{DUadmonition}
+\DUtitle{!DANGER!}
Mad scientist at work!
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[error]{
-\DUtitle[error]{Error}
+\begin{DUclass}{error}
+\begin{DUadmonition}
+\DUtitle{Error}
Does not compute.
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[hint]{
-\DUtitle[hint]{Hint}
+\begin{DUclass}{hint}
+\begin{DUadmonition}
+\DUtitle{Hint}
It’s bigger than a bread box.
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[important]{
-\DUtitle[important]{Important}
+\begin{DUclass}{important}
+\begin{DUadmonition}
+\DUtitle{Important}
\begin{itemize}
\item Wash behind your ears.
@@ -1161,32 +1169,41 @@
\item Back up your data.
\end{itemize}
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[note]{
-\DUtitle[note]{Note}
+\begin{DUclass}{note}
+\begin{DUadmonition}
+\DUtitle{Note}
This is a note.
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[tip]{
-\DUtitle[tip]{Tip}
+\begin{DUclass}{tip}
+\begin{DUadmonition}
+\DUtitle{Tip}
15\% if the service is good.
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[warning]{
-\DUtitle[warning]{Warning}
+\begin{DUclass}{warning}
+\begin{DUadmonition}
+\DUtitle{Warning}
Strong prose may provoke extreme mental exertion.
Reader discretion is strongly advised.
-}
+\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[admonition-and-by-the-way]{
-\DUtitle[admonition-and-by-the-way]{And, by the way…}
+\begin{DUclass}{admonition-and-by-the-way}
+\begin{DUadmonition}
+\DUtitle{And, by the way…}
You can make up your own admonition too.
-}
+\end{DUadmonition}
+\end{DUclass}
\subsubsection{2.14.5 Topics, Sidebars, and Rubrics%
@@ -1196,7 +1213,7 @@
\emph{Sidebars} are like miniature, parallel documents.
\DUsidebar{
-\DUtitle[sidebar]{Optional Sidebar Title}
+\DUtitle{Optional Sidebar Title}
\DUsubtitle{Optional Subtitle}
@@ -1214,7 +1231,7 @@
\begin{DUclass}{topic}
\begin{quote}
-\DUtitle[topic]{Topic Title}
+\DUtitle{Topic Title}
This is a topic.
\end{quote}
@@ -1396,12 +1413,13 @@
a paragraph followed by a comment,
% this is a comment
a paragraph, a
+\begin{DUclass}{note}
+\begin{DUadmonition}
+\DUtitle{Note}
-\DUadmonition[note]{
-\DUtitle[note]{Note}
-
with content
-}
+\end{DUadmonition}
+\end{DUclass}
and the final paragraph of the compound 7.
\end{DUclass}
@@ -2769,8 +2787,9 @@
\item[] \href{A:DOS\\path\\}{file with DOS path}\DUfootnotemark{footnote-reference-20}{footnote-12}{11} \url{A:DOS\\path\\}\DUfootnotemark{footnote-reference-21}{footnote-12}{11}
\end{DUlineblock}
-\DUadmonition[note]{
-\DUtitle[note]{Note}
+\begin{DUclass}{note}
+\begin{DUadmonition}
+\DUtitle{Note}
These URLs are typeset inside a LaTeX command without error.
@@ -2779,7 +2798,8 @@
\item[] \url{http://example.org/Schema\%dev}
\item[] \url{A:DOS\\path\\}\DUfootnotemark{footnote-reference-22}{footnote-12}{11}
\end{DUlineblock}
-}
+\end{DUadmonition}
+\end{DUclass}
\end{itemize}
\begin{itemize}
@@ -2851,9 +2871,11 @@
(depending on the document class)
-\DUtitle[sectionVI]{3.11.1.1.1.1 level 6%
+\begin{DUclass}{sectionVI}
+\DUtitle{3.11.1.1.1.1 level 6%
\label{level-6}%
}
+\end{DUclass}
an unsupported level.
@@ -2878,8 +2900,9 @@
\section[Docutils System Messages]{\color{red}Docutils System Messages%
}
-\DUadmonition[system-message]{
-\DUtitle[system-message]{system-message
+\begin{DUclass}{system-message}
+\begin{DUadmonition}
+\DUtitle{system-message
\raisebox{1em}{\hypertarget{system-message-1}{}}}
{\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~99
@@ -2886,10 +2909,12 @@
\hyperlink{problematic-1}{
Undefined substitution referenced: \textquotedbl{}problematic\textquotedbl{}.
-}}
+}\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[system-message]{
-\DUtitle[system-message]{system-message
+\begin{DUclass}{system-message}
+\begin{DUadmonition}
+\DUtitle{system-message
\raisebox{1em}{\hypertarget{system-message-2}{}}}
{\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~387
@@ -2896,10 +2921,12 @@
\hyperlink{footnote-reference-8}{
Unknown target name: \textquotedbl{}5\textquotedbl{}.
-}}
+}\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[system-message]{
-\DUtitle[system-message]{system-message
+\begin{DUclass}{system-message}
+\begin{DUadmonition}
+\DUtitle{system-message
\raisebox{1em}{\hypertarget{system-message-3}{}}}
{\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~396
@@ -2906,10 +2933,12 @@
\hyperlink{citation-reference-3}{
Unknown target name: \textquotedbl{}nonexistent\textquotedbl{}.
-}}
+}\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[system-message]{
-\DUtitle[system-message]{system-message
+\begin{DUclass}{system-message}
+\begin{DUadmonition}
+\DUtitle{system-message
\raisebox{1em}{\hypertarget{system-message-4}{}}}
{\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~423
@@ -2916,10 +2945,12 @@
\hyperlink{problematic-2}{
Unknown target name: \textquotedbl{}hyperlink reference without a target\textquotedbl{}.
-}}
+}\end{DUadmonition}
+\end{DUclass}
-\DUadmonition[system-message]{
-\DUtitle[system-message]{system-message
+\begin{DUclass}{system-message}
+\begin{DUadmonition}
+\DUtitle{system-message
\raisebox{1em}{\hypertarget{system-message-5}{}}}
{\color{red}ERROR/3} in \texttt{functional/input/data/standard.txt}, line~436
@@ -2926,6 +2957,7 @@
\hyperlink{problematic-3}{
Duplicate target name, cannot be used as a unique reference: \textquotedbl{}duplicate target names\textquotedbl{}.
-}}
+}\end{DUadmonition}
+\end{DUclass}
\end{document}
Modified: trunk/docutils/test/functional/tests/latex_literal_block.py
===================================================================
--- trunk/docutils/test/functional/tests/latex_literal_block.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/tests/latex_literal_block.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -9,5 +9,4 @@
# Extra setting we need
settings_overrides['syntax_highlight'] = 'none'
-settings_overrides['legacy_class_functions'] = False
settings_overrides['stylesheet'] = 'docutils'
Modified: trunk/docutils/test/functional/tests/latex_literal_block_fancyvrb.py
===================================================================
--- trunk/docutils/test/functional/tests/latex_literal_block_fancyvrb.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/tests/latex_literal_block_fancyvrb.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -9,7 +9,6 @@
# Extra setting we need
settings_overrides['syntax_highlight'] = 'none'
-settings_overrides['legacy_class_functions'] = False
settings_overrides['stylesheet'] = 'docutils'
settings_overrides['literal_block_env'] = 'Verbatim'
Modified: trunk/docutils/test/functional/tests/latex_literal_block_listings.py
===================================================================
--- trunk/docutils/test/functional/tests/latex_literal_block_listings.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/tests/latex_literal_block_listings.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -8,7 +8,6 @@
writer_name = "latex"
# Extra setting we need
-settings_overrides['legacy_class_functions'] = False
settings_overrides['stylesheet'] = 'docutils'
settings_overrides['syntax_highlight'] = 'none'
Modified: trunk/docutils/test/functional/tests/latex_literal_block_verbatim.py
===================================================================
--- trunk/docutils/test/functional/tests/latex_literal_block_verbatim.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/tests/latex_literal_block_verbatim.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -9,7 +9,6 @@
# Extra setting we need
settings_overrides['syntax_highlight'] = 'none'
-settings_overrides['legacy_class_functions'] = False
settings_overrides['stylesheet'] = 'docutils'
settings_overrides['literal_block_env'] = 'verbatim'
Modified: trunk/docutils/test/functional/tests/latex_literal_block_verbatimtab.py
===================================================================
--- trunk/docutils/test/functional/tests/latex_literal_block_verbatimtab.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/tests/latex_literal_block_verbatimtab.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -9,7 +9,6 @@
# Extra setting we need
settings_overrides['syntax_highlight'] = 'none'
-settings_overrides['legacy_class_functions'] = False
settings_overrides['stylesheet'] = 'docutils'
settings_overrides['literal_block_env'] = 'verbatimtab'
Modified: trunk/docutils/test/functional/tests/latex_memoir.py
===================================================================
--- trunk/docutils/test/functional/tests/latex_memoir.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/tests/latex_memoir.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -12,3 +12,6 @@
settings_overrides['use_latex_docinfo'] = 1
settings_overrides['documentclass'] = "memoir"
settings_overrides['template'] = "titlingpage.tex"
+
+# test the legacy class functions (since 0.18 default is False )
+settings_overrides['legacy_class_functions'] = True
Modified: trunk/docutils/test/functional/tests/standalone_rst_xetex.py
===================================================================
--- trunk/docutils/test/functional/tests/standalone_rst_xetex.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/functional/tests/standalone_rst_xetex.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -12,5 +12,4 @@
# use "smartquotes" transition:
settings_overrides['smart_quotes'] = True
# use docutils.sty and up-to-date class functions:
-settings_overrides['legacy_class_functions'] = False
settings_overrides['stylesheet'] = 'docutils'
Modified: trunk/docutils/test/test_writers/test_latex2e.py
===================================================================
--- trunk/docutils/test/test_writers/test_latex2e.py 2021-05-18 21:33:04 UTC (rev 8727)
+++ trunk/docutils/test/test_writers/test_latex2e.py 2021-05-18 21:33:28 UTC (rev 8728)
@@ -189,18 +189,12 @@
requirements=parts['requirements'] + '\\setcounter{secnumdepth}{0}\n',
fallbacks=r"""
% title for topics, admonitions, unsupported section levels, and sidebar
-\providecommand*{\DUtitle}[2][class-arg]{%
- % call \DUtitle#1{#2} if it exists:
- \ifcsname DUtitle#1\endcsname%
- \csname DUtitle#1\endcsname{#2}%
- \else
- \smallskip\noindent\textbf{#2}\smallskip%
- \fi
-}
+\providecommand*{\DUtitle}[1]{%
+ \smallskip\noindent\textbf{#1}\smallskip}
""")) + r"""
\phantomsection\label{table-of-contents}
\pdfbookmark[1]{Table of Contents}{table-of-contents}
-\DUtitle[contents]{Table of Contents}
+\DUtitle{Table of Contents}
\begin{list}{}{}
\item \hyperref[title-1]{Title 1}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-18 21:33:59
|
Revision: 8729
http://sourceforge.net/p/docutils/code/8729
Author: milde
Date: 2021-05-18 21:33:58 +0000 (Tue, 18 May 2021)
Log Message:
-----------
Remove IE 6 compatibility workaround for S5.
Remove files ``iepngfix.htc`` and blank.gif, adapt code and docs.
Fixes bug #169.
Modified Paths:
--------------
trunk/docutils/COPYING.txt
trunk/docutils/HISTORY.txt
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docs/user/slide-shows.txt
trunk/docutils/docutils/writers/s5_html/__init__.py
trunk/docutils/docutils/writers/s5_html/themes/README.txt
Removed Paths:
-------------
trunk/docutils/docutils/writers/s5_html/themes/default/blank.gif
trunk/docutils/docutils/writers/s5_html/themes/default/iepngfix.htc
trunk/docutils/test/functional/expected/ui/default/blank.gif
trunk/docutils/test/functional/expected/ui/default/iepngfix.htc
trunk/docutils/test/functional/expected/ui/small-black/blank.gif
trunk/docutils/test/functional/expected/ui/small-black/iepngfix.htc
Modified: trunk/docutils/COPYING.txt
===================================================================
--- trunk/docutils/COPYING.txt 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/COPYING.txt 2021-05-18 21:33:58 UTC (rev 8729)
@@ -70,12 +70,6 @@
The exceptions to the `Public Domain Dedication`_ above are:
-* docutils/writers/s5_html/themes/default/iepngfix.htc:
-
- IE5.5+ PNG Alpha Fix v1.0 by Angus Turnbull
- <http://www.twinhelix.com>. Free usage permitted as long as
- this notice remains intact.
-
* docutils/utils/math/__init__.py,
docutils/utils/math/latex2mathml.py,
docutils/writers/xetex/__init__.py,
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/HISTORY.txt 2021-05-18 21:33:58 UTC (rev 8729)
@@ -36,6 +36,11 @@
- Fix option "detailled" under Python 2.7.
+* docutils/writers/s5_html/themes/default
+
+ - Remove IE 6 compatibility workarounds ``iepngfix.htc`` and
+ ``blank.gif`` (fixes bug #169).
+
Release 0.17.1 (2021-04-16)
===========================
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/RELEASE-NOTES.txt 2021-05-18 21:33:58 UTC (rev 8729)
@@ -38,9 +38,6 @@
* `htm4css1` writer: Support the embed_images_ option.
-* `s5_html` writer: Remove the IE PNG Fix by Angus Turnbull. IE has
- native PNG support since version 7.
-
* Make <meta> a standard Docutils doctree node.
The `meta directive`__ will insert <meta> instead of pending nodes.
@@ -101,6 +98,8 @@
* Config setting `legacy_class_functions`_: default changed to "False".
+* `s5_html` writer: Removed ``iepngfix.htc`` (workaround for IE 6).
+
Release 0.17.1 (2021-04-16)
===========================
Modified: trunk/docutils/docs/user/slide-shows.txt
===================================================================
--- trunk/docutils/docs/user/slide-shows.txt 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/docs/user/slide-shows.txt 2021-05-18 21:33:58 UTC (rev 8729)
@@ -645,13 +645,7 @@
code also manages the fallback to Opera Show if you're using
the Opera web browser.
- Two files are included to support PNG transparency (alpha
- channels) in Internet Explorer:
- - iepngfix.htc
- - blank.gif
-
-
Making a Custom Theme
=====================
Modified: trunk/docutils/docutils/writers/s5_html/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/s5_html/__init__.py 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/docutils/writers/s5_html/__init__.py 2021-05-18 21:33:58 UTC (rev 8729)
@@ -143,7 +143,7 @@
"""Names of theme files directly linked to in the output HTML"""
indirect_theme_files = (
- 's5-core.css', 'framing.css', 'pretty.css', 'blank.gif', 'iepngfix.htc')
+ 's5-core.css', 'framing.css', 'pretty.css')
"""Names of files used indirectly; imported or used by files in
`direct_theme_files`."""
Modified: trunk/docutils/docutils/writers/s5_html/themes/README.txt
===================================================================
--- trunk/docutils/docutils/writers/s5_html/themes/README.txt 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/docutils/writers/s5_html/themes/README.txt 2021-05-18 21:33:58 UTC (rev 8729)
@@ -1,4 +1,4 @@
-Except where otherwise noted (default/iepngfix.htc), all files in this
+Except where otherwise noted, all files in this
directory have been released into the Public Domain.
These files are based on files from S5 1.1, released into the Public
Deleted: trunk/docutils/docutils/writers/s5_html/themes/default/blank.gif
===================================================================
(Binary files differ)
Deleted: trunk/docutils/docutils/writers/s5_html/themes/default/iepngfix.htc
===================================================================
--- trunk/docutils/docutils/writers/s5_html/themes/default/iepngfix.htc 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/docutils/writers/s5_html/themes/default/iepngfix.htc 2021-05-18 21:33:58 UTC (rev 8729)
@@ -1,42 +0,0 @@
-<public:component>
-<public:attach event="onpropertychange" onevent="doFix()" />
-
-<script>
-
-// IE5.5+ PNG Alpha Fix v1.0 by Angus Turnbull http://www.twinhelix.com
-// Free usage permitted as long as this notice remains intact.
-
-// This must be a path to a blank image. That's all the configuration you need here.
-var blankImg = 'ui/default/blank.gif';
-
-var f = 'DXImageTransform.Microsoft.AlphaImageLoader';
-
-function filt(s, m) {
- if (filters[f]) {
- filters[f].enabled = s ? true : false;
- if (s) with (filters[f]) { src = s; sizingMethod = m }
- } else if (s) style.filter = 'progid:'+f+'(src="'+s+'",sizingMethod="'+m+'")';
-}
-
-function doFix() {
- if ((parseFloat(navigator.userAgent.match(/MSIE (\S+)/)[1]) < 5.5) ||
- (event && !/(background|src)/.test(event.propertyName))) return;
-
- if (tagName == 'IMG') {
- if ((/\.png$/i).test(src)) {
- filt(src, 'image'); // was 'scale'
- src = blankImg;
- } else if (src.indexOf(blankImg) < 0) filt();
- } else if (style.backgroundImage) {
- if (style.backgroundImage.match(/^url[("']+(.*\.png)[)"']+$/i)) {
- var s = RegExp.$1;
- style.backgroundImage = '';
- filt(s, 'crop');
- } else filt();
- }
-}
-
-doFix();
-
-</script>
-</public:component>
\ No newline at end of file
Deleted: trunk/docutils/test/functional/expected/ui/default/blank.gif
===================================================================
(Binary files differ)
Deleted: trunk/docutils/test/functional/expected/ui/default/iepngfix.htc
===================================================================
--- trunk/docutils/test/functional/expected/ui/default/iepngfix.htc 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/test/functional/expected/ui/default/iepngfix.htc 2021-05-18 21:33:58 UTC (rev 8729)
@@ -1,42 +0,0 @@
-<public:component>
-<public:attach event="onpropertychange" onevent="doFix()" />
-
-<script>
-
-// IE5.5+ PNG Alpha Fix v1.0 by Angus Turnbull http://www.twinhelix.com
-// Free usage permitted as long as this notice remains intact.
-
-// This must be a path to a blank image. That's all the configuration you need here.
-var blankImg = 'ui/default/blank.gif';
-
-var f = 'DXImageTransform.Microsoft.AlphaImageLoader';
-
-function filt(s, m) {
- if (filters[f]) {
- filters[f].enabled = s ? true : false;
- if (s) with (filters[f]) { src = s; sizingMethod = m }
- } else if (s) style.filter = 'progid:'+f+'(src="'+s+'",sizingMethod="'+m+'")';
-}
-
-function doFix() {
- if ((parseFloat(navigator.userAgent.match(/MSIE (\S+)/)[1]) < 5.5) ||
- (event && !/(background|src)/.test(event.propertyName))) return;
-
- if (tagName == 'IMG') {
- if ((/\.png$/i).test(src)) {
- filt(src, 'image'); // was 'scale'
- src = blankImg;
- } else if (src.indexOf(blankImg) < 0) filt();
- } else if (style.backgroundImage) {
- if (style.backgroundImage.match(/^url[("']+(.*\.png)[)"']+$/i)) {
- var s = RegExp.$1;
- style.backgroundImage = '';
- filt(s, 'crop');
- } else filt();
- }
-}
-
-doFix();
-
-</script>
-</public:component>
\ No newline at end of file
Deleted: trunk/docutils/test/functional/expected/ui/small-black/blank.gif
===================================================================
(Binary files differ)
Deleted: trunk/docutils/test/functional/expected/ui/small-black/iepngfix.htc
===================================================================
--- trunk/docutils/test/functional/expected/ui/small-black/iepngfix.htc 2021-05-18 21:33:28 UTC (rev 8728)
+++ trunk/docutils/test/functional/expected/ui/small-black/iepngfix.htc 2021-05-18 21:33:58 UTC (rev 8729)
@@ -1,42 +0,0 @@
-<public:component>
-<public:attach event="onpropertychange" onevent="doFix()" />
-
-<script>
-
-// IE5.5+ PNG Alpha Fix v1.0 by Angus Turnbull http://www.twinhelix.com
-// Free usage permitted as long as this notice remains intact.
-
-// This must be a path to a blank image. That's all the configuration you need here.
-var blankImg = 'ui/small-black/blank.gif';
-
-var f = 'DXImageTransform.Microsoft.AlphaImageLoader';
-
-function filt(s, m) {
- if (filters[f]) {
- filters[f].enabled = s ? true : false;
- if (s) with (filters[f]) { src = s; sizingMethod = m }
- } else if (s) style.filter = 'progid:'+f+'(src="'+s+'",sizingMethod="'+m+'")';
-}
-
-function doFix() {
- if ((parseFloat(navigator.userAgent.match(/MSIE (\S+)/)[1]) < 5.5) ||
- (event && !/(background|src)/.test(event.propertyName))) return;
-
- if (tagName == 'IMG') {
- if ((/\.png$/i).test(src)) {
- filt(src, 'image'); // was 'scale'
- src = blankImg;
- } else if (src.indexOf(blankImg) < 0) filt();
- } else if (style.backgroundImage) {
- if (style.backgroundImage.match(/^url[("']+(.*\.png)[)"']+$/i)) {
- var s = RegExp.$1;
- style.backgroundImage = '';
- filt(s, 'crop');
- } else filt();
- }
-}
-
-doFix();
-
-</script>
-</public:component>
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-18 21:34:13
|
Revision: 8730
http://sourceforge.net/p/docutils/code/8730
Author: milde
Date: 2021-05-18 21:34:11 +0000 (Tue, 18 May 2021)
Log Message:
-----------
``nodes.Node.traverse()`` now returns an iterator instead of a list.
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docutils/nodes.py
trunk/docutils/docutils/parsers/recommonmark_wrapper.py
trunk/docutils/docutils/transforms/frontmatter.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2021-05-18 21:33:58 UTC (rev 8729)
+++ trunk/docutils/HISTORY.txt 2021-05-18 21:34:11 UTC (rev 8730)
@@ -16,6 +16,10 @@
Changes Since 0.17.1
====================
+* docutils/nodes.py
+
+ - ``Node.traverse()`` returns an iterator instead of a list.
+
* docutils/tools/math/math2html, docutils/writers/html5_polyglot/math.css
- Fix bug #244 Wrong subscript/superscript order with
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2021-05-18 21:33:58 UTC (rev 8729)
+++ trunk/docutils/RELEASE-NOTES.txt 2021-05-18 21:34:11 UTC (rev 8730)
@@ -49,8 +49,6 @@
__ docs/ref/rst/directives.html#meta
-* ``Node.traverse()`` will return an iterator instead of a list.
-
* Remove ``utils.unique_combinations``
(obsoleted by ``itertools.combinations``).
@@ -98,9 +96,13 @@
* Config setting `legacy_class_functions`_: default changed to "False".
-* `s5_html` writer: Removed ``iepngfix.htc`` (workaround for IE 6).
+* Removed files:
+ - ``iepngfix.htc`` and ``blank.gif`` (IE 6 workaround for `s5_html`).
+* ``nodes.Node.traverse()`` returns an iterator instead of a list.
+
+
Release 0.17.1 (2021-04-16)
===========================
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2021-05-18 21:33:58 UTC (rev 8729)
+++ trunk/docutils/docutils/nodes.py 2021-05-18 21:34:11 UTC (rev 8730)
@@ -34,34 +34,7 @@
unicode = str # noqa
basestring = str # noqa
-class _traversal_list(list):
- # auxiliary class to report a FutureWarning
- done = False
- def _warning_decorator(fun):
- msg = ("\n The iterable returned by Node.traverse()"
- "\n will become an iterator instead of a list in "
- "Docutils > 0.16.")
- def wrapper(self, *args, **kwargs):
- if not self.done:
- warnings.warn(msg, FutureWarning, stacklevel=2)
- self.done = True
- return fun(self, *args, **kwargs)
- return wrapper
- __add__ = _warning_decorator(list.__add__)
- __contains__ = _warning_decorator(list.__contains__)
- __getitem__ = _warning_decorator(list.__getitem__)
- __reversed__ = _warning_decorator(list.__reversed__)
- __setitem__ = _warning_decorator(list.__setitem__)
- append = _warning_decorator(list.append)
- count = _warning_decorator(list.count)
- extend = _warning_decorator(list.extend)
- index = _warning_decorator(list.index)
- insert = _warning_decorator(list.insert)
- pop = _warning_decorator(list.pop)
- reverse = _warning_decorator(list.reverse)
-
-
# ==============================
# Functional Node Base Classes
# ==============================
@@ -258,7 +231,7 @@
def traverse(self, condition=None, include_self=True, descend=True,
siblings=False, ascend=False):
"""
- Return an iterable containing
+ Return an iterator yielding
* self (if include_self is true)
* all descendants in tree traversal order (if descend is true)
@@ -267,7 +240,7 @@
* the siblings of the parent (if ascend is true) and their
descendants (if also descend is true), and so on
- If `condition` is not None, the iterable contains only nodes
+ If `condition` is not None, the iterator yields only nodes
for which ``condition(node)`` is true. If `condition` is a
node class ``cls``, it is equivalent to a function consisting
of ``return isinstance(node, cls)``.
@@ -292,16 +265,7 @@
[<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>]
"""
- # Although the documented API only promises an "iterable" as return
- # value, the implementation returned a list up to v. 0.15. Some 3rd
- # party code still relies on this (e.g. Sphinx as of 2019-09-07).
- # Therefore, let's return a list until this is sorted out:
- return _traversal_list(self._traverse(condition, include_self,
- descend, siblings, ascend))
- def _traverse(self, condition=None, include_self=True, descend=True,
- siblings=False, ascend=False):
- """Return iterator over nodes following `self`. See `traverse()`."""
if ascend:
siblings=True
# Check for special argument combinations that allow using an
@@ -327,7 +291,7 @@
yield self
if descend and len(self.children):
for child in self:
- for subnode in child._traverse(condition=condition,
+ for subnode in child.traverse(condition=condition,
include_self=True, descend=True,
siblings=False, ascend=False):
yield subnode
@@ -336,7 +300,7 @@
while node.parent:
index = node.parent.index(node)
for sibling in node.parent[index+1:]:
- for subnode in sibling._traverse(condition=condition,
+ for subnode in sibling.traverse(condition=condition,
include_self=True, descend=descend,
siblings=False, ascend=False):
yield subnode
@@ -348,13 +312,13 @@
def next_node(self, condition=None, include_self=False, descend=True,
siblings=False, ascend=False):
"""
- Return the first node in the iterable returned by traverse(),
+ Return the first node in the iterator returned by traverse(),
or None if the iterable is empty.
Parameter list is the same as of traverse. Note that
include_self defaults to False, though.
"""
- node_iterator = self._traverse(condition, include_self,
+ node_iterator = self.traverse(condition, include_self,
descend, siblings, ascend)
try:
return next(node_iterator)
Modified: trunk/docutils/docutils/parsers/recommonmark_wrapper.py
===================================================================
--- trunk/docutils/docutils/parsers/recommonmark_wrapper.py 2021-05-18 21:33:58 UTC (rev 8729)
+++ trunk/docutils/docutils/parsers/recommonmark_wrapper.py 2021-05-18 21:34:11 UTC (rev 8730)
@@ -94,7 +94,7 @@
del node['language']
# remove empty target nodes
- for node in document.traverse(nodes.target):
+ for node in list(document.traverse(nodes.target)):
# remove empty name
node['names'] = [v for v in node['names'] if v]
if node.children or [v for v in node.attributes.values() if v]:
Modified: trunk/docutils/docutils/transforms/frontmatter.py
===================================================================
--- trunk/docutils/docutils/transforms/frontmatter.py 2021-05-18 21:33:58 UTC (rev 8729)
+++ trunk/docutils/docutils/transforms/frontmatter.py 2021-05-18 21:34:11 UTC (rev 8730)
@@ -281,10 +281,10 @@
def apply(self):
if not self.document.settings.setdefault('sectsubtitle_xform', True):
return
- for section in self.document._traverse(nodes.section):
+ for section in self.document.traverse(nodes.section):
# On our way through the node tree, we are modifying it
# but only the not-yet-visited part, so that the iterator
- # returned by _traverse() is not corrupted.
+ # returned by traverse() is not corrupted.
self.promote_subtitle(section)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-18 21:34:28
|
Revision: 8731
http://sourceforge.net/p/docutils/code/8731
Author: milde
Date: 2021-05-18 21:34:27 +0000 (Tue, 18 May 2021)
Log Message:
-----------
Remove utils.unique_combinations().
Obsoleted by ``itertools.combinations().
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docutils/utils/__init__.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2021-05-18 21:34:11 UTC (rev 8730)
+++ trunk/docutils/HISTORY.txt 2021-05-18 21:34:27 UTC (rev 8731)
@@ -27,6 +27,10 @@
- Don't use <tt> element (deprecated in HTML5).
- Support commands ``\Bbbk`` and ``operatorname``.
+* docutils/utils/__init__.py
+
+ - Removed ``unique_combinations`` (obsoleted by ``itertools.combinations``).
+
* docutils/writers/latex2e/__init__.py
- The setting `legacy_class_functions`_ now defaults to "False".
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2021-05-18 21:34:11 UTC (rev 8730)
+++ trunk/docutils/RELEASE-NOTES.txt 2021-05-18 21:34:27 UTC (rev 8731)
@@ -49,9 +49,6 @@
__ docs/ref/rst/directives.html#meta
-* Remove ``utils.unique_combinations``
- (obsoleted by ``itertools.combinations``).
-
* Remove the "rawsource" attribute and argument from nodes.Text:
we store the null-escaped text in Text nodes since 0.16 so there is no
additional information in the rawsource.
@@ -101,6 +98,9 @@
- ``iepngfix.htc`` and ``blank.gif`` (IE 6 workaround for `s5_html`).
* ``nodes.Node.traverse()`` returns an iterator instead of a list.
+
+* Removed ``utils.unique_combinations``
+ (obsoleted by ``itertools.combinations``).
Release 0.17.1 (2021-04-16)
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2021-05-18 21:34:11 UTC (rev 8730)
+++ trunk/docutils/docutils/utils/__init__.py 2021-05-18 21:34:27 UTC (rev 8731)
@@ -655,13 +655,6 @@
r.append(item)
return r
-def unique_combinations(items, n):
- """Return `itertools.combinations`."""
- warnings.warn('docutils.utils.unique_combinations is deprecated; '
- 'use itertools.combinations directly.',
- DeprecationWarning, stacklevel=2)
- return itertools.combinations(items, n)
-
def normalize_language_tag(tag):
"""Return a list of normalized combinations for a `BCP 47` language tag.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 10:07:56
|
Revision: 8734
http://sourceforge.net/p/docutils/code/8734
Author: milde
Date: 2021-05-20 10:07:55 +0000 (Thu, 20 May 2021)
Log Message:
-----------
Write footnote brackets and field term colons to HTML.
Makes them available also without CSS and when copying text.
Hide brackets with CSS for "footnote-references=superscript".
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/html5_polyglot/minimal.css
trunk/docutils/docutils/writers/html5_polyglot/responsive.css
trunk/docutils/test/functional/expected/footnotes_html5.html
trunk/docutils/test/functional/expected/standalone_rst_html5.html
trunk/docutils/test/test_writers/test_html5_polyglot_parts.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2021-05-20 10:07:40 UTC (rev 8733)
+++ trunk/docutils/HISTORY.txt 2021-05-20 10:07:55 UTC (rev 8734)
@@ -1,5 +1,3 @@
-.. -*- coding: utf-8 -*-
-
==================
Docutils History
==================
@@ -31,13 +29,19 @@
- Removed ``unique_combinations`` (obsoleted by ``itertools.combinations``).
+* docutils/writers/_html_base.py
+
+ - Write footnote brackets and field term colons to HTML, so that
+ they are present also without CSS and when copying text.
+ Adapt ``minimal.css``.
+
* docutils/writers/latex2e/__init__.py
- - The setting `legacy_class_functions`_ now defaults to "False".
+ - The setting `legacy_class_functions`_ now defaults to "False".
Adapt stylesheets modifying ``\DUadmonition`` and/or ``\DUtitle``.
* docutils/writers/latex2e/docutils.sty
-
+
- Fix excessive padding above sidebar titles.
* docutils/writers/pseudoxml.py:
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2021-05-20 10:07:40 UTC (rev 8733)
+++ trunk/docutils/RELEASE-NOTES.txt 2021-05-20 10:07:55 UTC (rev 8734)
@@ -29,12 +29,12 @@
- Use <summary> and <details> tags for term and definition of a
definition list with class value "details".
- - Write footnote brackets and field term colons to HTML, so that
- they are present also without CSS and when copying text.
- Hide with CSS if required.
+ - Move attribution behind the blockquote to comply with the
+ __`"living standard"`?
+ HTML5__ allows <cite> elements inside a blockquote (cf. Example 16).
- - Move attribution behind the blockquote to comply with
- https://html.spec.whatwg.org/#the-blockquote-element.
+ __ https://html.spec.whatwg.org/#the-blockquote-element
+ __ https://www.w3.org/TR/html52/grouping-content.html#the-blockquote-element
* `htm4css1` writer: Support the embed_images_ option.
@@ -91,16 +91,22 @@
Release 0.18.dev
================
-* Config setting `legacy_class_functions`_: default changed to "False".
-
* Removed files:
- ``iepngfix.htc`` and ``blank.gif`` (IE 6 workaround for `s5_html`).
+* Removed function: ``utils.unique_combinations``
+ (obsoleted by ``itertools.combinations``).
+
+* HTML5 writer: changes to HTML output
+
+ - Write footnote brackets and field term colons to HTML, so that
+ they are present also without CSS and when copying text.
+
+* LaTeX writer: `legacy_class_functions`_ setting default changed to "False".
+
* ``nodes.Node.traverse()`` returns an iterator instead of a list.
-* Removed ``utils.unique_combinations``
- (obsoleted by ``itertools.combinations``).
Release 0.17.1 (2021-04-16)
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2021-05-20 10:07:40 UTC (rev 8733)
+++ trunk/docutils/docutils/writers/_html_base.py 2021-05-20 10:07:55 UTC (rev 8734)
@@ -432,9 +432,7 @@
atts['class'] = ' '.join(classes)
assert 'id' not in atts
ids.extend(node.get('ids', []))
- if 'ids' in atts:
- ids.extend(atts['ids'])
- del atts['ids']
+ ids.extend(atts.pop('ids', []))
if ids:
atts['id'] = ids[0]
for id in ids[1:]:
@@ -788,8 +786,9 @@
meta_tag = '<meta name="%s" content="%s" />\n' \
% (name, self.attval(node.astext()))
self.add_meta(meta_tag)
- self.body.append('<dt class="%s">%s</dt>\n'
- % (name, self.language.labels[name]))
+ self.body.append(
+ '<dt class="%s">%s<span class="colon">:</span></dt>\n'
+ % (name, self.language.labels[name]))
self.body.append(self.starttag(node, 'dd', '', CLASS=name))
def depart_docinfo_item(self):
@@ -903,7 +902,7 @@
CLASS=''.join(node.parent['classes'])))
def depart_field_name(self, node):
- self.body.append('</dt>\n')
+ self.body.append('<span class="colon">:</span></dt>\n')
def visit_field_body(self, node):
self.body.append(self.starttag(node, 'dd', '',
@@ -940,9 +939,6 @@
self.body_suffix[:0] = footer
del self.body[start:]
- # TODO: use the new HTML5 element <aside> for footnote text
- # (allows better styling with CSS, the current <dl> list styling
- # with "float" interferes with sidebars).
def visit_footnote(self, node):
if not self.in_footnote_list:
listnode = node.copy()
@@ -962,10 +958,12 @@
def visit_footnote_reference(self, node):
href = '#' + node['refid']
classes = 'footnote-reference ' + self.settings.footnote_references
- self.body.append(self.starttag(node, 'a', '', #suffix,
+ self.body.append(self.starttag(node, 'a', suffix='',
CLASS=classes, href=href))
+ self.body.append('<span class="fn-bracket">[</span>')
def depart_footnote_reference(self, node):
+ self.body.append('<span class="fn-bracket">]</span>')
self.body.append('</a>')
# Docutils-generated text: put section numbers in a span for CSS styling:
@@ -1090,31 +1088,31 @@
# footnote and citation labels:
def visit_label(self, node):
- if (isinstance(node.parent, nodes.footnote)):
- classes = self.settings.footnote_references
- else:
- classes = 'brackets'
# pass parent node to get id into starttag:
self.body.append(self.starttag(node.parent, 'dt', '', CLASS='label'))
- self.body.append(self.starttag(node, 'span', '', CLASS=classes))
- # footnote/citation backrefs:
+ # backlinks to the footnote/citation reference(s):
if self.settings.footnote_backlinks:
backrefs = node.parent['backrefs']
if len(backrefs) == 1:
self.body.append('<a class="fn-backref" href="#%s">'
% backrefs[0])
+ # bracket (hidden by CSS for superscript footnotes)
+ self.body.append('<span class="fn-bracket">[</span>')
def depart_label(self, node):
+ self.body.append('<span class="fn-bracket">]</span>')
+ # backlinks to the footnote/citation reference(s):
if self.settings.footnote_backlinks:
backrefs = node.parent['backrefs']
- if len(backrefs) == 1:
- self.body.append('</a>')
- self.body.append('</span>')
- if self.settings.footnote_backlinks and len(backrefs) > 1:
+ else:
+ backrefs = []
+ if len(backrefs) == 1:
+ self.body.append('</a>')
+ if len(backrefs) > 1:
backlinks = ['<a href="#%s">%s</a>' % (ref, i)
- for (i, ref) in enumerate(backrefs, 1)]
+ for (i, ref) in enumerate(backrefs, 1)]
self.body.append('<span class="fn-backref">(%s)</span>'
- % ','.join(backlinks))
+ % ','.join(backlinks))
self.body.append('</dt>\n<dd>')
def visit_legend(self, node):
@@ -1599,10 +1597,8 @@
self.body.append(self.starttag(node, 'dt', ''))
def depart_term(self, node):
- """
- Leave the end tag to `self.visit_definition()`, in case there's a
- classifier.
- """
+ # Leave the end tag to `self.visit_definition()`,
+ # in case there's a classifier.
pass
def visit_tgroup(self, node):
Modified: trunk/docutils/docutils/writers/html5_polyglot/minimal.css
===================================================================
--- trunk/docutils/docutils/writers/html5_polyglot/minimal.css 2021-05-20 10:07:40 UTC (rev 8733)
+++ trunk/docutils/docutils/writers/html5_polyglot/minimal.css 2021-05-20 10:07:55 UTC (rev 8734)
@@ -140,11 +140,6 @@
width: 100%;
margin: 0;
}
-/* field names followed by a colon */
-dl.field-list > dt:after,
-dl.docinfo > dt:after {
- content: ":";
-}
/* Bibliographic Fields (docinfo) */
dl.docinfo pre.address {
@@ -161,15 +156,15 @@
dl.footnote.superscript > dd { margin-left: 0.7em; }
dl.footnote.brackets > dd { margin-left: 1.6em; }
dl.footnote > dt { font-weight: normal; }
-a.footnote-reference.brackets:before,
-dt.label > span.brackets:before { content: "["; }
-a.footnote-reference.brackets:after,
-dt.label > span.brackets:after { content: "]"; }
a.footnote-reference.superscript,
dl.footnote.superscript > dt.label {
vertical-align: super;
font-size: small;
}
+a.footnote-reference.superscript > span.fn-bracket,
+dl.footnote.superscript > dt.label span.fn-bracket {
+ display: none;
+}
dt.label > span.fn-backref {
margin-left: 0.2em;
font-weight: normal;
Modified: trunk/docutils/docutils/writers/html5_polyglot/responsive.css
===================================================================
--- trunk/docutils/docutils/writers/html5_polyglot/responsive.css 2021-05-20 10:07:40 UTC (rev 8733)
+++ trunk/docutils/docutils/writers/html5_polyglot/responsive.css 2021-05-20 10:07:55 UTC (rev 8734)
@@ -172,7 +172,6 @@
}
/* Footnotes and Citations */
-/* TODO: use <aside> */
dl.footnote {
font-size: small;
padding-left: 0.5em;
@@ -179,9 +178,11 @@
border-left: solid;
border-left-width: thin;
}
-dt.label > span.fn-backref {
+dl.citation > dt.label span.fn-bracket {
+ display: none;
}
+
/* Images, Figures, and Tables */
img {
display: block;
@@ -296,7 +297,6 @@
/* Let content flow to the side of aligned images and figures */
/* no floats around this elements */
-dl.footnote, dl.citation, /* errors with internal floats */
footer, header, hr,
h1, h2, h3 {
clear: both;
Modified: trunk/docutils/test/functional/expected/footnotes_html5.html
===================================================================
--- trunk/docutils/test/functional/expected/footnotes_html5.html 2021-05-20 10:07:40 UTC (rev 8733)
+++ trunk/docutils/test/functional/expected/footnotes_html5.html 2021-05-20 10:07:55 UTC (rev 8734)
@@ -12,52 +12,52 @@
<main id="test-footnote-and-citation-rendering">
<h1 class="title">Test footnote and citation rendering</h1>
-<p>Paragraphs may contain footnote references (manually numbered<a class="footnote-reference superscript" href="#footnote-1" id="footnote-reference-1">1</a>, anonymous auto-numbered<a class="footnote-reference superscript" href="#footnote-2" id="footnote-reference-2">3</a>, labeled auto-numbered<a class="footnote-reference superscript" href="#label" id="footnote-reference-3">2</a>, or
-symbolic<a class="footnote-reference superscript" href="#footnote-3" id="footnote-reference-4">*</a>) or citation references (<a class="citation-reference" href="#cit2002" id="citation-reference-1">[CIT2002]</a>, <a class="citation-reference" href="#du2015" id="citation-reference-2">[DU2015]</a>).</p>
+<p>Paragraphs may contain footnote references (manually numbered<a class="footnote-reference superscript" href="#footnote-1" id="footnote-reference-1"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>, anonymous auto-numbered<a class="footnote-reference superscript" href="#footnote-2" id="footnote-reference-2"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a>, labeled auto-numbered<a class="footnote-reference superscript" href="#label" id="footnote-reference-3"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a>, or
+symbolic<a class="footnote-reference superscript" href="#footnote-3" id="footnote-reference-4"><span class="fn-bracket">[</span>*<span class="fn-bracket">]</span></a>) or citation references (<a class="citation-reference" href="#cit2002" id="citation-reference-1">[CIT2002]</a>, <a class="citation-reference" href="#du2015" id="citation-reference-2">[DU2015]</a>).</p>
<dl class="footnote superscript">
-<dt class="label" id="footnote-1"><span class="superscript">1</span><span class="fn-backref">(<a href="#footnote-reference-1">1</a>,<a href="#footnote-reference-5">2</a>)</span></dt>
+<dt class="label" id="footnote-1"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span><span class="fn-backref">(<a href="#footnote-reference-1">1</a>,<a href="#footnote-reference-5">2</a>)</span></dt>
<dd><p>A footnote contains body elements, consistently indented by at
least 3 spaces.</p>
<p>This is the footnote's second paragraph.</p>
</dd>
-<dt class="label" id="label"><span class="superscript">2</span><span class="fn-backref">(<a href="#footnote-reference-3">1</a>,<a href="#footnote-reference-6">2</a>)</span></dt>
-<dd><p>Footnotes may be numbered, either manually (as in<a class="footnote-reference superscript" href="#footnote-1" id="footnote-reference-5">1</a>) or
+<dt class="label" id="label"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span><span class="fn-backref">(<a href="#footnote-reference-3">1</a>,<a href="#footnote-reference-6">2</a>)</span></dt>
+<dd><p>Footnotes may be numbered, either manually (as in<a class="footnote-reference superscript" href="#footnote-1" id="footnote-reference-5"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>) or
automatically using a "#"-prefixed label. This footnote has a
label so it can be referred to from multiple places, both as a
-footnote reference (<a class="footnote-reference superscript" href="#label" id="footnote-reference-6">2</a>) and as a <a class="reference internal" href="#label">hyperlink reference</a>.</p>
+footnote reference (<a class="footnote-reference superscript" href="#label" id="footnote-reference-6"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a>) and as a <a class="reference internal" href="#label">hyperlink reference</a>.</p>
</dd>
-<dt class="label" id="footnote-2"><span class="superscript"><a class="fn-backref" href="#footnote-reference-2">3</a></span></dt>
+<dt class="label" id="footnote-2"><a class="fn-backref" href="#footnote-reference-2"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a></dt>
<dd><p>This footnote is numbered automatically and anonymously using a
label of "#" only.</p>
<p>This is the second paragraph.</p>
<p>And this is the third paragraph.</p>
</dd>
-<dt class="label" id="footnote-3"><span class="superscript"><a class="fn-backref" href="#footnote-reference-4">*</a></span></dt>
+<dt class="label" id="footnote-3"><a class="fn-backref" href="#footnote-reference-4"><span class="fn-bracket">[</span>*<span class="fn-bracket">]</span></a></dt>
<dd><p>Footnotes may also use symbols, specified with a "*" label.
-Here's a reference to the next footnote:<a class="footnote-reference superscript" href="#footnote-4" id="footnote-reference-7">†</a>.</p>
+Here's a reference to the next footnote:<a class="footnote-reference superscript" href="#footnote-4" id="footnote-reference-7"><span class="fn-bracket">[</span>†<span class="fn-bracket">]</span></a>.</p>
</dd>
-<dt class="label" id="footnote-4"><span class="superscript"><a class="fn-backref" href="#footnote-reference-7">†</a></span></dt>
+<dt class="label" id="footnote-4"><a class="fn-backref" href="#footnote-reference-7"><span class="fn-bracket">[</span>†<span class="fn-bracket">]</span></a></dt>
<dd><p>This footnote shows the next symbol in the sequence.</p>
</dd>
-<dt class="label" id="footnote-5"><span class="superscript">4</span></dt>
+<dt class="label" id="footnote-5"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></dt>
<dd><p>Here's an unreferenced footnote, with a reference to a
-nonexistent footnote:<a class="footnote-reference superscript" href="#footnote-6" id="footnote-reference-8">5</a>.</p>
+nonexistent footnote:<a class="footnote-reference superscript" href="#footnote-6" id="footnote-reference-8"><span class="fn-bracket">[</span>5<span class="fn-bracket">]</span></a>.</p>
</dd>
</dl>
<section id="citations">
<h2>Citations</h2>
<dl class="citation">
-<dt class="label" id="cit2002"><span class="brackets">CIT2002</span><span class="fn-backref">(<a href="#citation-reference-1">1</a>,<a href="#citation-reference-3">2</a>)</span></dt>
+<dt class="label" id="cit2002"><span class="fn-bracket">[</span>CIT2002<span class="fn-bracket">]</span><span class="fn-backref">(<a href="#citation-reference-1">1</a>,<a href="#citation-reference-3">2</a>)</span></dt>
<dd><p>Citations are text-labeled footnotes. They may be
rendered separately and differently from footnotes.</p>
</dd>
-<dt class="label" id="du2015"><span class="brackets"><a class="fn-backref" href="#citation-reference-2">DU2015</a></span></dt>
+<dt class="label" id="du2015"><a class="fn-backref" href="#citation-reference-2"><span class="fn-bracket">[</span>DU2015<span class="fn-bracket">]</span></a></dt>
<dd><p><cite>Example document</cite>, Hometown: 2015.</p>
</dd>
</dl>
<p>Here's a reference to the above, <a class="citation-reference" href="#cit2002" id="citation-reference-3">[CIT2002]</a>.</p>
<dl class="footnote superscript">
-<dt class="label" id="footnote-6"><span class="superscript"><a class="fn-backref" href="#footnote-reference-8">5</a></span></dt>
+<dt class="label" id="footnote-6"><a class="fn-backref" href="#footnote-reference-8"><span class="fn-bracket">[</span>5<span class="fn-bracket">]</span></a></dt>
<dd><p>this footnote is missing in the standard example document.</p>
</dd>
</dl>
Modified: trunk/docutils/test/functional/expected/standalone_rst_html5.html
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_html5.html 2021-05-20 10:07:40 UTC (rev 8733)
+++ trunk/docutils/test/functional/expected/standalone_rst_html5.html 2021-05-20 10:07:55 UTC (rev 8734)
@@ -27,32 +27,32 @@
<h1 class="title">reStructuredText Test Document</h1>
<p class="subtitle" id="examples-of-syntax-constructs"><span id="subtitle"></span>Examples of Syntax Constructs</p>
<dl class="docinfo">
-<dt class="author">Author</dt>
+<dt class="author">Author<span class="colon">:</span></dt>
<dd class="author"><p>David Goodger</p></dd>
-<dt class="address">Address</dt>
+<dt class="address">Address<span class="colon">:</span></dt>
<dd class="address"><pre class="address">123 Example Street
Example, EX Canada
A1B 2C3
</pre>
</dd>
-<dt class="contact">Contact</dt>
+<dt class="contact">Contact<span class="colon">:</span></dt>
<dd class="contact"><a class="reference external" href="mailto:goodger@python.org">goodger@python.org</a></dd>
-<dt class="authors">Authors</dt>
+<dt class="authors">Authors<span class="colon">:</span></dt>
<dd class="authors"><p>Me</p>
<p>Myself</p>
<p>I</p>
</dd>
-<dt class="organization">Organization</dt>
+<dt class="organization">Organization<span class="colon">:</span></dt>
<dd class="organization">humankind</dd>
-<dt class="date">Date</dt>
+<dt class="date">Date<span class="colon">:</span></dt>
<dd class="date">Now, or yesterday. Or maybe even <em>before</em> yesterday.</dd>
-<dt class="status">Status</dt>
+<dt class="status">Status<span class="colon">:</span></dt>
<dd class="status">This is a "work in progress"</dd>
-<dt class="revision">Revision</dt>
+<dt class="revision">Revision<span class="colon">:</span></dt>
<dd class="revision">is managed by a version control system.</dd>
-<dt class="version">Version</dt>
+<dt class="version">Version<span class="colon">:</span></dt>
<dd class="version">1</dd>
-<dt class="copyright">Copyright</dt>
+<dt class="copyright">Copyright<span class="colon">:</span></dt>
<dd class="copyright">This document has been placed in the public domain. You
may do with it as you wish. You may copy, modify,
redistribute, reattribute, sell, buy, rent, lease,
@@ -60,10 +60,10 @@
incorporate, collate, fold, staple, or mutilate it, or do
anything else to it that your or anyone else's heart
desires.</dd>
-<dt class="field-name">field name</dt>
+<dt class="field-name">field name<span class="colon">:</span></dt>
<dd class="field-name"><p>This is a "generic bibliographic field".</p>
</dd>
-<dt class="field-name-2">field name "2"</dt>
+<dt class="field-name-2">field name "2"<span class="colon">:</span></dt>
<dd class="field-name-2"><p>Generic bibliographic fields may contain multiple body elements.</p>
<p>Like this.</p>
</dd>
@@ -189,12 +189,12 @@
<h4><a class="toc-backref" href="#toc-entry-7"><span class="sectnum">2.1.1</span> Inline Markup</a></h4>
<p>Paragraphs contain text and may contain inline markup: <em>emphasis</em>,
<strong>strong emphasis</strong>, <span class="docutils literal">inline literals</span>, standalone hyperlinks
-(<a class="reference external" href="http://www.python.org">http://www.python.org</a>), external hyperlinks (<a class="reference external" href="http://www.python.org/">Python</a> <a class="footnote-reference brackets" href="#footnote-7" id="footnote-reference-18">7</a>), internal
+(<a class="reference external" href="http://www.python.org">http://www.python.org</a>), external hyperlinks (<a class="reference external" href="http://www.python.org/">Python</a> <a class="footnote-reference brackets" href="#footnote-7" id="footnote-reference-18"><span class="fn-bracket">[</span>7<span class="fn-bracket">]</span></a>), internal
cross-references (<a class="reference internal" href="#example">example</a>), external hyperlinks with embedded URIs
(<a class="reference external" href="http://www.python.org">Python web site</a>), <a class="reference external" href="http://www.python.org/">anonymous hyperlink
-references</a> <a class="footnote-reference brackets" href="#footnote-7" id="footnote-reference-25">7</a> (<a class="reference external" href="https://docutils.sourceforge.io/">a second reference</a> <a class="footnote-reference brackets" href="#footnote-12" id="footnote-reference-26">12</a>), footnote references (manually
-numbered <a class="footnote-reference brackets" href="#footnote-1" id="footnote-reference-1">1</a>, anonymous auto-numbered <a class="footnote-reference brackets" href="#footnote-2" id="footnote-reference-2">3</a>, labeled auto-numbered
-<a class="footnote-reference brackets" href="#label" id="footnote-reference-3">2</a>, or symbolic <a class="footnote-reference brackets" href="#footnote-3" id="footnote-reference-4">*</a>), citation references (see <a class="citation-reference" href="#cit2002" id="citation-reference-1">[CIT2002]</a>),
+references</a> <a class="footnote-reference brackets" href="#footnote-7" id="footnote-reference-25"><span class="fn-bracket">[</span>7<span class="fn-bracket">]</span></a> (<a class="reference external" href="https://docutils.sourceforge.io/">a second reference</a> <a class="footnote-reference brackets" href="#footnote-12" id="footnote-reference-26"><span class="fn-bracket">[</span>12<span class="fn-bracket">]</span></a>), footnote references (manually
+numbered <a class="footnote-reference brackets" href="#footnote-1" id="footnote-reference-1"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>, anonymous auto-numbered <a class="footnote-reference brackets" href="#footnote-2" id="footnote-reference-2"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a>, labeled auto-numbered
+<a class="footnote-reference brackets" href="#label" id="footnote-reference-3"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a>, or symbolic <a class="footnote-reference brackets" href="#footnote-3" id="footnote-reference-4"><span class="fn-bracket">[</span>*<span class="fn-bracket">]</span></a>), citation references (see <a class="citation-reference" href="#cit2002" id="citation-reference-1">[CIT2002]</a>),
substitution references (<img alt="EXAMPLE" src="../../../docs/user/rst/images/biohazard.png" /> &
a <em>trimmed heart</em> <span class="docutils literal">(U+2665):</span>♥), and <span class="target" id="inline-hyperlink-targets">inline hyperlink targets</span>
(see <a class="reference internal" href="#targets">Targets</a> below for a reference back to here). Character-level
@@ -298,17 +298,17 @@
<section id="field-lists">
<h3><a class="toc-backref" href="#toc-entry-11"><span class="sectnum">2.5</span> Field Lists</a></h3>
<dl class="field-list">
-<dt>what</dt>
+<dt>what<span class="colon">:</span></dt>
<dd><p>Field lists map field names to field bodies, like database
records. They are often part of an extension syntax. They are
an unambiguous variant of RFC 2822 fields.</p>
</dd>
-<dt>how arg1 arg2</dt>
+<dt>how arg1 arg2<span class="colon">:</span></dt>
<dd><p>The field marker is a colon, the field name, and a colon.</p>
<p>The field body may contain one or more body elements, indented
relative to the field marker.</p>
</dd>
-<dt>credits</dt>
+<dt>credits<span class="colon">:</span></dt>
<dd><p class="credits">This paragraph has the <cite>credits</cite> class set. (This is actually not
about credits but just for ensuring that the class attribute
doesn't get stripped away.)</p>
@@ -471,31 +471,31 @@
<section id="footnotes">
<h3><a class="toc-backref" href="#toc-entry-17"><span class="sectnum">2.11</span> Footnotes</a></h3>
<dl class="footnote brackets">
-<dt class="label" id="footnote-1"><span class="brackets">1</span><span class="fn-backref">(<a href="#footnote-reference-1">1</a>,<a href="#footnote-reference-5">2</a>,<a href="#footnote-reference-9">3</a>)</span></dt>
+<dt class="label" id="footnote-1"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span><span class="fn-backref">(<a href="#footnote-reference-1">1</a>,<a href="#footnote-reference-5">2</a>,<a href="#footnote-reference-9">3</a>)</span></dt>
<dd><p>A footnote contains body elements, consistently indented by at
least 3 spaces.</p>
<p>This is the footnote's second paragraph.</p>
</dd>
-<dt class="label" id="label"><span class="brackets">2</span><span class="fn-backref">(<a href="#footnote-reference-3">1</a>,<a href="#footnote-reference-6">2</a>)</span></dt>
-<dd><p>Footnotes may be numbered, either manually (as in <a class="footnote-reference brackets" href="#footnote-1" id="footnote-reference-5">1</a>) or
+<dt class="label" id="label"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span><span class="fn-backref">(<a href="#footnote-reference-3">1</a>,<a href="#footnote-reference-6">2</a>)</span></dt>
+<dd><p>Footnotes may be numbered, either manually (as in <a class="footnote-reference brackets" href="#footnote-1" id="footnote-reference-5"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>) or
automatically using a "#"-prefixed label. This footnote has a
label so it can be referred to from multiple places, both as a
-footnote reference (<a class="footnote-reference brackets" href="#label" id="footnote-reference-6">2</a>) and as a <a class="reference internal" href="#label">hyperlink reference</a>.</p>
+footnote reference (<a class="footnote-reference brackets" href="#label" id="footnote-reference-6"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a>) and as a <a class="reference internal" href="#label">hyperlink reference</a>.</p>
</dd>
-<dt class="label" id="footnote-2"><span class="brackets"><a class="fn-backref" href="#footnote-reference-2">3</a></span></dt>
+<dt class="label" id="footnote-2"><a class="fn-backref" href="#footnote-reference-2"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a></dt>
<dd><p>This footnote is numbered automatically and anonymously using a
label of "#" only.</p>
<p>This is the second paragraph.</p>
<p>And this is the third paragraph.</p>
</dd>
-<dt class="label" id="footnote-3"><span class="brackets"><a class="fn-backref" href="#footnote-reference-4">*</a></span></dt>
+<dt class="label" id="footnote-3"><a class="fn-backref" href="#footnote-reference-4"><span class="fn-bracket">[</span>*<span class="fn-bracket">]</span></a></dt>
<dd><p>Footnotes may also use symbols, specified with a "*" label.
-Here's a reference to the next footnote: <a class="footnote-reference brackets" href="#footnote-4" id="footnote-reference-7">†</a>.</p>
+Here's a reference to the next footnote: <a class="footnote-reference brackets" href="#footnote-4" id="footnote-reference-7"><span class="fn-bracket">[</span>†<span class="fn-bracket">]</span></a>.</p>
</dd>
-<dt class="label" id="footnote-4"><span class="brackets"><a class="fn-backref" href="#footnote-reference-7">†</a></span></dt>
+<dt class="label" id="footnote-4"><a class="fn-backref" href="#footnote-reference-7"><span class="fn-bracket">[</span>†<span class="fn-bracket">]</span></a></dt>
<dd><p>This footnote shows the next symbol in the sequence.</p>
</dd>
-<dt class="label" id="footnote-5"><span class="brackets">4</span></dt>
+<dt class="label" id="footnote-5"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></dt>
<dd><p>Here's an unreferenced footnote, with a reference to a
nonexistent footnote: <a href="#system-message-2"><span class="problematic" id="footnote-reference-8">[5]_</span></a>.</p>
</dd>
@@ -504,7 +504,7 @@
<section id="citations">
<h3><a class="toc-backref" href="#toc-entry-18"><span class=...
[truncated message content] |
|
From: <mi...@us...> - 2021-05-20 10:08:13
|
Revision: 8735
http://sourceforge.net/p/docutils/code/8735
Author: milde
Date: 2021-05-20 10:08:11 +0000 (Thu, 20 May 2021)
Log Message:
-----------
html5 writer: support field lists with custom indent.
Review handling of "classes" attribute.
Modified Paths:
--------------
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/html5_polyglot/plain.css
trunk/docutils/test/functional/expected/standalone_rst_html5.html
trunk/docutils/test/functional/input/data/html5-features.txt
trunk/docutils/test/test_writers/test_html5_polyglot_parts.py
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2021-05-20 10:07:55 UTC (rev 8734)
+++ trunk/docutils/docutils/writers/_html_base.py 2021-05-20 10:08:11 UTC (rev 8735)
@@ -35,6 +35,7 @@
import docutils
from docutils import frontend, languages, nodes, utils, writers
+from docutils.parsers.rst.directives import length_or_percentage_or_unitless
from docutils.utils.error_reporting import SafeString
from docutils.transforms import writer_aux
from docutils.utils.math import (unichar2tex, pick_math_environment,
@@ -742,9 +743,8 @@
self.body.append('</dd>\n')
def visit_definition_list(self, node):
- classes = node.setdefault('classes', [])
if self.is_compactable(node):
- classes.append('simple')
+ node.setdefault('classes', []).append('simple')
self.body.append(self.starttag(node, 'dl'))
def depart_definition_list(self, node):
@@ -879,12 +879,22 @@
self.body.append('</ol>\n')
def visit_field_list(self, node):
- # Keep simple paragraphs in the field_body to enable CSS
- # rule to start body on new line if the label is too long
- classes = 'field-list'
+ atts = {}
+ classes = node.setdefault('classes', [])
+ for i, cls in enumerate(classes):
+ if cls.startswith('field-indent-'):
+ try:
+ indent_length = length_or_percentage_or_unitless(
+ cls[13:], 'px')
+ except ValueError:
+ break
+ atts['style'] = '--field-indent: %s;' % indent_length
+ classes.pop(i)
+ break
+ classes.append('field-list')
if (self.is_compactable(node)):
- classes += ' simple'
- self.body.append(self.starttag(node, 'dl', CLASS=classes))
+ classes.append('simple')
+ self.body.append(self.starttag(node, 'dl', **atts))
def depart_field_list(self, node):
self.body.append('</dl>\n')
@@ -945,7 +955,6 @@
listnode['ids'] = []
classes = 'footnote ' + self.settings.footnote_references
self.body.append(self.starttag(listnode, 'dl', CLASS=classes))
- # self.body.append('<dl class="%s">\n'%classes)
self.in_footnote_list = True
def depart_footnote(self, node):
@@ -1147,13 +1156,12 @@
classes = node.get('classes', [])
if 'code' in classes:
# filter 'code' from class arguments
- node['classes'] = [cls for cls in classes if cls != 'code']
+ classes.pop(classes.index('code'))
self.body.append(self.starttag(node, 'code', ''))
return
self.body.append(
self.starttag(node, 'span', '', CLASS='docutils literal'))
text = node.astext()
- # remove hard line breaks (except if in a parsed-literal block)
if not isinstance(node.parent, nodes.literal_block):
text = text.replace('\n', ' ')
# Protect text like ``--an-option`` and the regular expression
@@ -1165,8 +1173,7 @@
else:
self.body.append(self.encode(token))
self.body.append('</span>')
- # Content already processed:
- raise nodes.SkipNode
+ raise nodes.SkipNode # content already processed
def depart_literal(self, node):
# skipped unless literal element is from "code" role:
@@ -1563,13 +1570,14 @@
def visit_table(self, node):
atts = {}
- classes = [cls.strip(u' \t\n')
- for cls in self.settings.table_style.split(',')]
+ classes = node.setdefault('classes', [])
+ classes += [cls.strip(u' \t\n')
+ for cls in self.settings.table_style.split(',')]
if 'align' in node:
classes.append('align-%s' % node['align'])
if 'width' in node:
- atts['style'] = 'width: %s' % node['width']
- tag = self.starttag(node, 'table', CLASS=' '.join(classes), **atts)
+ atts['style'] = 'width: %s;' % node['width']
+ tag = self.starttag(node, 'table', **atts)
self.body.append(tag)
def depart_table(self, node):
Modified: trunk/docutils/docutils/writers/html5_polyglot/plain.css
===================================================================
--- trunk/docutils/docutils/writers/html5_polyglot/plain.css 2021-05-20 10:07:55 UTC (rev 8734)
+++ trunk/docutils/docutils/writers/html5_polyglot/plain.css 2021-05-20 10:08:11 UTC (rev 8735)
@@ -24,6 +24,7 @@
body {
margin: 0;
background-color: #dbdbdb;
+ --field-indent: 9em; /* default indent of fields in field lists */
}
main, footer, header {
line-height:1.3;
@@ -98,9 +99,14 @@
/* Field Lists */
+dl.field-list > dd,
+dl.docinfo > dd {
+ margin-left: var(--field-indent); /* adapted in media queries or HTML */
+}
+
/* example for custom field-name width */
dl.field-list.narrow > dd {
- margin-left: 5em;
+ --field-indent: 5em;
}
/* run-in: start field-body on same line after long field names */
dl.field-list.run-in > dd p {
Modified: trunk/docutils/test/functional/expected/standalone_rst_html5.html
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_html5.html 2021-05-20 10:07:55 UTC (rev 8734)
+++ trunk/docutils/test/functional/expected/standalone_rst_html5.html 2021-05-20 10:08:11 UTC (rev 8735)
@@ -1179,7 +1179,7 @@
<section id="list-tables">
<h3><a class="toc-backref" href="#toc-entry-41"><span class="sectnum">2.22</span> List Tables</a></h3>
<p>Here's a list table exercising all features:</p>
-<table class="colwidths-given test" style="width: 95%">
+<table class="colwidths-given test" style="width: 95%;">
<caption>list table with integral header</caption>
<colgroup>
<col style="width: 26%" />
@@ -1350,7 +1350,7 @@
<section id="field-list-variants">
<h4><a class="toc-backref" href="#toc-entry-47"><span class="sectnum">3.2.2</span> Field List Variants</a></h4>
<p>For field lists, the "compact/open", "narrow" and "run-in" styles are defined
-in the style sheet <span class="docutils literal">plain.css</span>.</p>
+in the style sheets <span class="docutils literal">plain.css</span> and <span class="docutils literal">responsive.css</span>.</p>
<dl class="simple">
<dt><em>compact</em></dt>
<dd><dl class="compact field-list simple">
@@ -1394,7 +1394,21 @@
</dd>
</dl>
</dd>
+<dt>custom <em>field-indent</em></dt>
+<dd><dl class="field-list simple" style="--field-indent: 3em;">
+<dt>Feature<span class="colon">:</span></dt>
+<dd><p>Field body indented by custom amount.</p>
+</dd>
+<dt>Use<span class="colon">:</span></dt>
+<dd><p>class value starting with <span class="docutils literal"><span class="pre">field-indent-</span></span> followed by
+a valid lenght, e.g. <span class="docutils literal"><span class="pre">field-indent-3em</span></span>.</p>
+</dd>
+<dt>The writer<span class="colon">:</span></dt>
+<dd><p>will convert this class value to a <span class="docutils literal">style</span> attribute setting.</p>
+</dd>
</dl>
+</dd>
+</dl>
<dl class="simple" id="run-in">
<dt><em>run-in</em></dt>
<dd><dl class="run-in field-list simple">
Modified: trunk/docutils/test/functional/input/data/html5-features.txt
===================================================================
--- trunk/docutils/test/functional/input/data/html5-features.txt 2021-05-20 10:07:55 UTC (rev 8734)
+++ trunk/docutils/test/functional/input/data/html5-features.txt 2021-05-20 10:08:11 UTC (rev 8735)
@@ -101,7 +101,7 @@
```````````````````
For field lists, the "compact/open", "narrow" and "run-in" styles are defined
-in the style sheet ``plain.css``.
+in the style sheets ``plain.css`` and ``responsive.css``.
*compact*
.. class:: compact
@@ -133,6 +133,15 @@
sticks into the field body and the field body starts on a
new line (if not combined with `run-in`_).
+custom *field-indent*
+ .. class:: field-indent-3em
+
+ :Feature: Field body indented by custom amount.
+ :Use: class value starting with ``field-indent-`` followed by
+ a valid lenght, e.g. ``field-indent-3em``.
+ :The writer:
+ will convert this class value to a ``style`` attribute setting.
+
.. _`run-in`:
*run-in*
Modified: trunk/docutils/test/test_writers/test_html5_polyglot_parts.py
===================================================================
--- trunk/docutils/test/test_writers/test_html5_polyglot_parts.py 2021-05-20 10:07:55 UTC (rev 8734)
+++ trunk/docutils/test/test_writers/test_html5_polyglot_parts.py 2021-05-20 10:08:11 UTC (rev 8735)
@@ -451,6 +451,71 @@
'html_head': '''...<title><string></title>\\n'''}
"""],
["""\
+Not a docinfo.
+
+.. class:: field-indent-200
+
+:This: is a
+:simple: field list with custom indent.
+""",
+"""\
+{'fragment': '''<p>Not a docinfo.</p>
+<dl class="field-list simple" style="--field-indent: 200px;">
+<dt>This<span class="colon">:</span></dt>
+<dd><p>is a</p>
+</dd>
+<dt>simple<span class="colon">:</span></dt>
+<dd><p>field list with custom indent.</p>
+</dd>
+</dl>\\n''',
+ 'html_body': '''<main>
+<p>Not a docinfo.</p>
+<dl class="field-list simple" style="--field-indent: 200px;">
+<dt>This<span class="colon">:</span></dt>
+<dd><p>is a</p>
+</dd>
+<dt>simple<span class="colon">:</span></dt>
+<dd><p>field list with custom indent.</p>
+</dd>
+</dl>
+</main>\\n''',
+ 'html_head': '''...<title><string></title>\\n'''}
+"""],
+["""\
+Not a docinfo.
+
+.. class:: field-indent-200uf
+
+:This: is a
+:simple: field list without custom indent,
+ because the unit "uf" is invalid.
+""",
+"""\
+{'fragment': '''<p>Not a docinfo.</p>
+<dl class="field-indent-200uf field-list simple">
+<dt>This<span class="colon">:</span></dt>
+<dd><p>is a</p>
+</dd>
+<dt>simple<span class="colon">:</span></dt>
+<dd><p>field list without custom indent,
+because the unit "uf" is invalid.</p>
+</dd>
+</dl>\\n''',
+ 'html_body': '''<main>
+<p>Not a docinfo.</p>
+<dl class="field-indent-200uf field-list simple">
+<dt>This<span class="colon">:</span></dt>
+<dd><p>is a</p>
+</dd>
+<dt>simple<span class="colon">:</span></dt>
+<dd><p>field list without custom indent,
+because the unit "uf" is invalid.</p>
+</dd>
+</dl>
+</main>\\n''',
+ 'html_head': '''...<title><string></title>\\n'''}
+"""],
+["""\
.. figure:: dummy.png
The figure's caption.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:18:58
|
Revision: 8736
http://sourceforge.net/p/docutils/code/8736
Author: milde
Date: 2021-05-20 12:18:55 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: First part of fix to #407.
Partially fix #407 "Inline MathML role and block MathML
directive appear with reversed styles."
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/tests/math_output_mathml.py
Added Paths:
-----------
trunk/docutils/test/functional/expected/math_output_mathml.html
Removed Paths:
-------------
trunk/docutils/test/functional/expected/math_output_mathml.xhtml
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 10:08:11 UTC (rev 8735)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:18:55 UTC (rev 8736)
@@ -233,9 +233,9 @@
return ['<%s>' % self.__class__.__name__]
xmlns = 'http://www.w3.org/1998/Math/MathML'
if self.inline:
- return ['<math xmlns="%s">' % xmlns]
+ return ['<math xmlns="%s" displaystyle="false">' % xmlns]
else:
- return ['<math xmlns="%s" mode="display">' % xmlns]
+ return ['<math xmlns="%s" display="block">' % xmlns]
def xml_end(self):
return ['</%s>' % self.__class__.__name__]
Copied: trunk/docutils/test/functional/expected/math_output_mathml.html (from rev 8735, trunk/docutils/test/functional/expected/math_output_mathml.xhtml)
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html (rev 0)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:18:55 UTC (rev 8736)
@@ -0,0 +1,221 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+<meta charset="utf-8"/>
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
+<title>Mathematics</title>
+<link rel="stylesheet" href="../input/data/minimal.css" type="text/css" />
+<link rel="stylesheet" href="../input/data/plain.css" type="text/css" />
+</head>
+<body>
+<main id="mathematics">
+<h1 class="title">Mathematics</h1>
+
+<p>Docutils supports inline math with the prefix or postfix <span class="docutils literal">:math:</span>
+role specificator, <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo>(</mo><msubsup><mi>x</mi><mi>n</mi><mn>2</mn></msubsup><mo>)</mo></mrow></math> and <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><msub><mi>A</mi><mtext>c</mtext></msub><mo>=</mo><mfrac>
+<mrow><mi>π</mi></mrow>
+<mrow><mn>4</mn></mrow></mfrac><msup><mi>d</mi><mn>2</mn></msup></mrow></math>, as well as displayed math via the
+<cite>math</cite> directive:</p>
+<div>
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><mi>f</mi><mo>(</mo><mi>ϵ</mi><mo>)</mo><mo>=</mo><mfrac>
+<mrow><mn>1</mn></mrow>
+<mrow><mn>1</mn><mo>+</mo><mo>exp</mo><mfenced open="(" close=")">
+<mrow><mfrac>
+<mrow><mi>ε</mi></mrow>
+<mrow><msub><mi>k</mi><mtext>B</mtext></msub><mi>T</mi></mrow></mfrac></mrow></mfenced></mrow></mfrac></mtd></mtr></mtable></math>
+</div>
+<p>Content may start on the first line of the directive, e.g.</p>
+<div>
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><mi>N</mi><mo>=</mo><mfrac>
+<mrow><mtext>number of apples</mtext></mrow>
+<mrow><mn>7</mn></mrow></mfrac></mtd></mtr></mtable></math>
+</div>
+<p>Equations can be labeled with a reference name using the <span class="docutils literal">:name:</span> option.
+See <a class="reference internal" href="#eq-m">eq:M</a> and <a class="reference internal" href="#eq-schrodinger">eq:schrödinger</a> below.</p>
+<p>The determinant of the matrix</p>
+<div id="eq-m">
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><mstyle mathvariant="bold">
+<mrow><mi>M</mi></mrow></mstyle><mo>=</mo><mfenced open="(" close=")">
+<mrow>
+<mtable>
+<mtr>
+<mtd><mi>a</mi></mtd>
+<mtd><mi>b</mi></mtd></mtr>
+<mtr>
+<mtd><mi>c</mi></mtd>
+<mtd><mi>d</mi></mtd></mtr></mtable></mrow></mfenced></mtd></mtr></mtable></math>
+</div>
+<p>is <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mo>|</mo><mstyle mathvariant="bold">
+<mrow><mi>M</mi></mrow></mstyle><mo>|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi></mrow></math>.</p>
+<p>More than one display math block can be put in one math directive.
+For example, the following sum and integral with limits:</p>
+<div>
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><munderover><mo>∫</mo><mn>0</mn><mn>1</mn></munderover><msup><mi>x</mi><mi>n</mi></msup><mi>d</mi><mi>x</mi><mo>=</mo><mfrac>
+<mrow><mn>1</mn></mrow>
+<mrow><mi>n</mi><mo>+</mo><mn>1</mn></mrow></mfrac></mtd></mtr></mtable></math>
+</div>
+<div>
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><munderover><mo>∑</mo>
+<mrow><mi>n</mi><mo>=</mo><mn>1</mn></mrow><mi>m</mi></munderover><mi>n</mi><mo>=</mo><mfrac>
+<mrow><mi>m</mi><mo>(</mo><mi>m</mi><mo>+</mo><mn>1</mn><mo>)</mo></mrow>
+<mrow><mn>2</mn></mrow></mfrac></mtd></mtr></mtable></math>
+</div>
+<p>LaTeX-supported Unicode math symbols can be used in math roles and
+directives:</p>
+<p>The Schrödinger equation</p>
+<div id="eq-schrodinger">
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><mi>i</mi><mi>ℏ</mi><mfrac>
+<mrow><mo>∂</mo></mrow>
+<mrow><mo>∂</mo><mi>t</mi></mrow></mfrac><mo>Ψ</mo><mo>=</mo><mover>
+<mrow><mi>H</mi></mrow><mo>^</mo></mover><mo>Ψ</mo><mo>,</mo></mtd></mtr></mtable></math>
+</div>
+<p>with the <em>wave function</em> <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mo>Ψ</mo></mrow></math>, describes how the quantum state of a
+physical system changes in time.</p>
+<dl>
+<dt>Math-Accents:</dt>
+<dd><table class="colwidths-given borderless">
+<colgroup>
+<col style="width: 33%" />
+<col style="width: 33%" />
+<col style="width: 33%" />
+</colgroup>
+<tbody>
+<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>a</mi></mrow><mo>´</mo></mover></mrow></math> <span class="docutils literal">\acute{a}</span></p></td>
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>t</mi></mrow><mo>˙</mo></mover></mrow></math> <span class="docutils literal">\dot{t}</span></p></td>
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>γ</mi></mrow><mo>^</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\hat{\gamma}</span></span></p></td>
+</tr>
+<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>a</mi></mrow><mo>`</mo></mover></mrow></math> <span class="docutils literal">\grave{a}</span></p></td>
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>t</mi></mrow><mo>¨</mo></mover></mrow></math> <span class="docutils literal">\ddot{t}</span></p></td>
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>α</mi></mrow><mo>˜</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\tilde{\alpha}</span></span></p></td>
+</tr>
+<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>x</mi></mrow><mo>˘</mo></mover></mrow></math> <span class="docutils literal">\breve{x}</span></p></td>
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>t</mi></mrow><mo>⃛</mo></mover></mrow></math> <span class="docutils literal">\dddot{t}</span></p></td>
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>ı</mi></mrow><mo>⃗</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\vec{\imath}</span></span></p></td>
+</tr>
+<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>a</mi></mrow><mo>ˇ</mo></mover></mrow></math> <span class="docutils literal">\check{a}</span></p></td>
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>a</mi></mrow><mo>¯</mo></mover></mrow></math> <span class="docutils literal">\bar{a}</span></p></td>
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<mrow><mover>
+<mrow><mi>R</mi></mrow><mo>⃗</mo></mover></mrow></math> <span class="docutils literal">\vec{R}</span></p></td>
+</tr>
+</tbody>
+</table>
+</dd>
+</dl>
+<!-- \widetilde{xxx}
+\widehat{xxx} -->
+<p>Modulation Transfer Function:</p>
+<div>
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><mtext>MTF</mtext><mo>=</mo><mfenced open="|" close="|">
+<mrow><mfrac>
+<mrow><mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo></mrow>
+<mrow><mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo><msub><mo>|</mo>
+<mrow><msub><mi>ω</mi>
+<mrow><mi>x</mi></mrow></msub><mo>=</mo><mn>0</mn></mrow></msub></mrow></mfrac></mrow></mfenced><mo>=</mo><mtext>abs</mtext><mfenced open="(" close=")">
+<mrow><mfrac>
+<mrow><munderover><mo>∫</mo>
+<mrow><mo>-</mo><mo>∞</mo></mrow>
+<mrow><mo>∞</mo></mrow></munderover><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><msup><mtext>e</mtext>
+<mrow><mtext>i</mtext><msub><mi>ω</mi>
+<mrow><mi>x</mi></mrow></msub><mi>x</mi></mrow></msup><mtext>d</mtext>
+<mrow><mi>x</mi></mrow></mrow>
+<mrow><munderover><mo>∫</mo>
+<mrow><mo>-</mo><mo>∞</mo></mrow>
+<mrow><mo>∞</mo></mrow></munderover><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mtext>d</mtext>
+<mrow><mi>x</mi></mrow></mrow></mfrac></mrow></mfenced><mo>.</mo></mtd></mtr></mtable></math>
+</div>
+<p>Math split over two lines: If a double backslash is detected outside a
+<span class="docutils literal"><span class="pre">\begin{...}</span> <span class="pre">\end{...}</span></span> pair, the math code is wrapped in an <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a>
+<span class="docutils literal">align</span> environment:</p>
+<div>
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><msub><mi>s</mi>
+<mrow><mtext>out</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>)</mo></mtd>
+<mtd><mo>=</mo><msub><mi>s</mi>
+<mrow><mtext>in</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo><mo>*</mo><msub><mi>s</mi><mi>δ</mi></msub><mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo></mtd></mtr>
+<mtr>
+<mtd></mtd>
+<mtd><mo>=</mo><mo>∫</mo><msub><mi>s</mi>
+<mrow><mtext>in</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo><msub><mi>s</mi><mi>δ</mi></msub><mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo><mtext>d</mtext><mi>x</mi><mo>'</mo></mtd></mtr></mtable></math>
+</div>
+<p>Cases ("manually", with <span class="docutils literal">matrix</span> environment):</p>
+<div>
+<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<mtable>
+<mtr>
+<mtd><mtext>sgn</mtext><mo>(</mo><mi>x</mi><mo>)</mo><mo>=</mo><mfenced open="{" close="">
+<mrow>
+<mtable>
+<mtr>
+<mtd><mo>-</mo><mn>1</mn></mtd>
+<mtd><mi>x</mi><mo><</mo><mn>0</mn></mtd></mtr>
+<mtr>
+<mtd><mn>1</mn></mtd>
+<mtd><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr></mtable></mrow></mfenced></mtd></mtr></mtable></math>
+</div>
+<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <span class="docutils literal">cases</span> environment (not (yet) supported by
+HTML writers with <span class="docutils literal"><span class="pre">--math-output=MathML</span></span>):</p>
+<div class="system-message">
+<p class="system-message-title">System Message: ERROR/3 (<span class="docutils literal">functional/input/data/math.txt</span>, line 108)</p>
+<p>
+Environment not supported! Supported environment: "matrix".</p>
+<pre class="literal-block">
+\mathrm{sgn}(x) = \begin{cases}
+ -1 & x<0\\
+ 1 & x>0
+ \end{cases}
+</pre>
+</div>
+</main>
+</body>
+</html>
Property changes on: trunk/docutils/test/functional/expected/math_output_mathml.html
___________________________________________________________________
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
Deleted: trunk/docutils/test/functional/expected/math_output_mathml.xhtml
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.xhtml 2021-05-20 10:08:11 UTC (rev 8735)
+++ trunk/docutils/test/functional/expected/math_output_mathml.xhtml 2021-05-20 12:18:55 UTC (rev 8736)
@@ -1,221 +0,0 @@
-<!DOCTYPE html>
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
-<meta charset="utf-8"/>
-<meta name="viewport" content="width=device-width, initial-scale=1" />
-<meta name="generator" content="Docutils 0.18b.dev: http://docutils.sourceforge.net/" />
-<title>Mathematics</title>
-<link rel="stylesheet" href="../input/data/minimal.css" type="text/css" />
-<link rel="stylesheet" href="../input/data/plain.css" type="text/css" />
-</head>
-<body>
-<main id="mathematics">
-<h1 class="title">Mathematics</h1>
-
-<p>Docutils supports inline math with the prefix or postfix <span class="docutils literal">:math:</span>
-role specificator, <math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo>(</mo><msubsup><mi>x</mi><mi>n</mi><mn>2</mn></msubsup><mo>)</mo></mrow></math> and <math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><msub><mi>A</mi><mtext>c</mtext></msub><mo>=</mo><mfrac>
-<mrow><mi>π</mi></mrow>
-<mrow><mn>4</mn></mrow></mfrac><msup><mi>d</mi><mn>2</mn></msup></mrow></math>, as well as displayed math via the
-<cite>math</cite> directive:</p>
-<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><mi>f</mi><mo>(</mo><mi>ϵ</mi><mo>)</mo><mo>=</mo><mfrac>
-<mrow><mn>1</mn></mrow>
-<mrow><mn>1</mn><mo>+</mo><mo>exp</mo><mfenced open="(" close=")">
-<mrow><mfrac>
-<mrow><mi>ε</mi></mrow>
-<mrow><msub><mi>k</mi><mtext>B</mtext></msub><mi>T</mi></mrow></mfrac></mrow></mfenced></mrow></mfrac></mtd></mtr></mtable></math>
-</div>
-<p>Content may start on the first line of the directive, e.g.</p>
-<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><mi>N</mi><mo>=</mo><mfrac>
-<mrow><mtext>number of apples</mtext></mrow>
-<mrow><mn>7</mn></mrow></mfrac></mtd></mtr></mtable></math>
-</div>
-<p>Equations can be labeled with a reference name using the <span class="docutils literal">:name:</span> option.
-See <a class="reference internal" href="#eq-m">eq:M</a> and <a class="reference internal" href="#eq-schrodinger">eq:schrödinger</a> below.</p>
-<p>The determinant of the matrix</p>
-<div id="eq-m">
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><mstyle mathvariant="bold">
-<mrow><mi>M</mi></mrow></mstyle><mo>=</mo><mfenced open="(" close=")">
-<mrow>
-<mtable>
-<mtr>
-<mtd><mi>a</mi></mtd>
-<mtd><mi>b</mi></mtd></mtr>
-<mtr>
-<mtd><mi>c</mi></mtd>
-<mtd><mi>d</mi></mtd></mtr></mtable></mrow></mfenced></mtd></mtr></mtable></math>
-</div>
-<p>is <math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mo>|</mo><mstyle mathvariant="bold">
-<mrow><mi>M</mi></mrow></mstyle><mo>|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi></mrow></math>.</p>
-<p>More than one display math block can be put in one math directive.
-For example, the following sum and integral with limits:</p>
-<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><munderover><mo>∫</mo><mn>0</mn><mn>1</mn></munderover><msup><mi>x</mi><mi>n</mi></msup><mi>d</mi><mi>x</mi><mo>=</mo><mfrac>
-<mrow><mn>1</mn></mrow>
-<mrow><mi>n</mi><mo>+</mo><mn>1</mn></mrow></mfrac></mtd></mtr></mtable></math>
-</div>
-<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><munderover><mo>∑</mo>
-<mrow><mi>n</mi><mo>=</mo><mn>1</mn></mrow><mi>m</mi></munderover><mi>n</mi><mo>=</mo><mfrac>
-<mrow><mi>m</mi><mo>(</mo><mi>m</mi><mo>+</mo><mn>1</mn><mo>)</mo></mrow>
-<mrow><mn>2</mn></mrow></mfrac></mtd></mtr></mtable></math>
-</div>
-<p>LaTeX-supported Unicode math symbols can be used in math roles and
-directives:</p>
-<p>The Schrödinger equation</p>
-<div id="eq-schrodinger">
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><mi>i</mi><mi>ℏ</mi><mfrac>
-<mrow><mo>∂</mo></mrow>
-<mrow><mo>∂</mo><mi>t</mi></mrow></mfrac><mo>Ψ</mo><mo>=</mo><mover>
-<mrow><mi>H</mi></mrow><mo>^</mo></mover><mo>Ψ</mo><mo>,</mo></mtd></mtr></mtable></math>
-</div>
-<p>with the <em>wave function</em> <math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mo>Ψ</mo></mrow></math>, describes how the quantum state of a
-physical system changes in time.</p>
-<dl>
-<dt>Math-Accents:</dt>
-<dd><table class="colwidths-given borderless">
-<colgroup>
-<col style="width: 33%" />
-<col style="width: 33%" />
-<col style="width: 33%" />
-</colgroup>
-<tbody>
-<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>a</mi></mrow><mo>´</mo></mover></mrow></math> <span class="docutils literal">\acute{a}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>t</mi></mrow><mo>˙</mo></mover></mrow></math> <span class="docutils literal">\dot{t}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>γ</mi></mrow><mo>^</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\hat{\gamma}</span></span></p></td>
-</tr>
-<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>a</mi></mrow><mo>`</mo></mover></mrow></math> <span class="docutils literal">\grave{a}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>t</mi></mrow><mo>¨</mo></mover></mrow></math> <span class="docutils literal">\ddot{t}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>α</mi></mrow><mo>˜</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\tilde{\alpha}</span></span></p></td>
-</tr>
-<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>x</mi></mrow><mo>˘</mo></mover></mrow></math> <span class="docutils literal">\breve{x}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>t</mi></mrow><mo>⃛</mo></mover></mrow></math> <span class="docutils literal">\dddot{t}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>ı</mi></mrow><mo>⃗</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\vec{\imath}</span></span></p></td>
-</tr>
-<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>a</mi></mrow><mo>ˇ</mo></mover></mrow></math> <span class="docutils literal">\check{a}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>a</mi></mrow><mo>¯</mo></mover></mrow></math> <span class="docutils literal">\bar{a}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>R</mi></mrow><mo>⃗</mo></mover></mrow></math> <span class="docutils literal">\vec{R}</span></p></td>
-</tr>
-</tbody>
-</table>
-</dd>
-</dl>
-<!-- \widetilde{xxx}
-\widehat{xxx} -->
-<p>Modulation Transfer Function:</p>
-<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><mtext>MTF</mtext><mo>=</mo><mfenced open="|" close="|">
-<mrow><mfrac>
-<mrow><mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo></mrow>
-<mrow><mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo><msub><mo>|</mo>
-<mrow><msub><mi>ω</mi>
-<mrow><mi>x</mi></mrow></msub><mo>=</mo><mn>0</mn></mrow></msub></mrow></mfrac></mrow></mfenced><mo>=</mo><mtext>abs</mtext><mfenced open="(" close=")">
-<mrow><mfrac>
-<mrow><munderover><mo>∫</mo>
-<mrow><mo>-</mo><mo>∞</mo></mrow>
-<mrow><mo>∞</mo></mrow></munderover><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><msup><mtext>e</mtext>
-<mrow><mtext>i</mtext><msub><mi>ω</mi>
-<mrow><mi>x</mi></mrow></msub><mi>x</mi></mrow></msup><mtext>d</mtext>
-<mrow><mi>x</mi></mrow></mrow>
-<mrow><munderover><mo>∫</mo>
-<mrow><mo>-</mo><mo>∞</mo></mrow>
-<mrow><mo>∞</mo></mrow></munderover><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mtext>d</mtext>
-<mrow><mi>x</mi></mrow></mrow></mfrac></mrow></mfenced><mo>.</mo></mtd></mtr></mtable></math>
-</div>
-<p>Math split over two lines: If a double backslash is detected outside a
-<span class="docutils literal"><span class="pre">\begin{...}</span> <span class="pre">\end{...}</span></span> pair, the math code is wrapped in an <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a>
-<span class="docutils literal">align</span> environment:</p>
-<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><msub><mi>s</mi>
-<mrow><mtext>out</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>)</mo></mtd>
-<mtd><mo>=</mo><msub><mi>s</mi>
-<mrow><mtext>in</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo><mo>*</mo><msub><mi>s</mi><mi>δ</mi></msub><mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo></mtd></mtr>
-<mtr>
-<mtd></mtd>
-<mtd><mo>=</mo><mo>∫</mo><msub><mi>s</mi>
-<mrow><mtext>in</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo><msub><mi>s</mi><mi>δ</mi></msub><mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo><mtext>d</mtext><mi>x</mi><mo>'</mo></mtd></mtr></mtable></math>
-</div>
-<p>Cases ("manually", with <span class="docutils literal">matrix</span> environment):</p>
-<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" mode="display">
-<mtable>
-<mtr>
-<mtd><mtext>sgn</mtext><mo>(</mo><mi>x</mi><mo>)</mo><mo>=</mo><mfenced open="{" close="">
-<mrow>
-<mtable>
-<mtr>
-<mtd><mo>-</mo><mn>1</mn></mtd>
-<mtd><mi>x</mi><mo><</mo><mn>0</mn></mtd></mtr>
-<mtr>
-<mtd><mn>1</mn></mtd>
-<mtd><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr></mtable></mrow></mfenced></mtd></mtr></mtable></math>
-</div>
-<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <span class="docutils literal">cases</span> environment (not (yet) supported by
-HTML writers with <span class="docutils literal"><span class="pre">--math-output=MathML</span></span>):</p>
-<div class="system-message">
-<p class="system-message-title">System Message: ERROR/3 (<span class="docutils literal">functional/input/data/math.txt</span>, line 108)</p>
-<p>
-Environment not supported! Supported environment: "matrix".</p>
-<pre class="literal-block">
-\mathrm{sgn}(x) = \begin{cases}
- -1 & x<0\\
- 1 & x>0
- \end{cases}
-</pre>
-</div>
-</main>
-</body>
-</html>
Modified: trunk/docutils/test/functional/tests/math_output_mathml.py
===================================================================
--- trunk/docutils/test/functional/tests/math_output_mathml.py 2021-05-20 10:08:11 UTC (rev 8735)
+++ trunk/docutils/test/functional/tests/math_output_mathml.py 2021-05-20 12:18:55 UTC (rev 8736)
@@ -1,6 +1,6 @@
# Source and destination file names.
test_source = "data/math.txt"
-test_destination = "math_output_mathml.xhtml"
+test_destination = "math_output_mathml.html"
# Keyword parameters passed to publish_file.
reader_name = "standalone"
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:19:13
|
Revision: 8737
http://sourceforge.net/p/docutils/code/8737
Author: milde
Date: 2021-05-20 12:19:09 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: Replace deprecated <mfenced> element.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/math_output_mathml.html
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:18:55 UTC (rev 8736)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:19:09 UTC (rev 8737)
@@ -2,9 +2,9 @@
# -*- coding: utf-8 -*-
# :Id: $Id$
-# :Copyright: © 2010 Günter Milde.
-# Based on rst2mathml.py from the latex_math sandbox project
-# © 2005 Jens Jørgen Mortensen
+# :Copyright: © 2005 Jens Jørgen Mortensen [1]_
+# © 2010, 2021 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,
@@ -15,9 +15,14 @@
# .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
-"""Convert LaTex math code into presentational MathML"""
+"""Convert LaTex maths code into presentational MathML.
+"""
-# Based on the `latex_math` sandbox project by Jens Jørgen Mortensen
+# .. [1] the original `rst2mathml.py` in `sandbox/jensj/latex_math`
+#
+# Usage:
+#
+# >>> import latex2mathml
import docutils.utils.math.tex2unichar as tex2unichar
@@ -56,6 +61,9 @@
sumintprod = ''.join([special[symbol] for symbol in
['sum', 'int', 'oint', 'prod']])
+# >>> print(latex2mathml.sumintprod)
+# ∑∫∮∏
+
functions = ['arccos', 'arcsin', 'arctan', 'arg', 'cos', 'cosh',
'cot', 'coth', 'csc', 'deg', 'det', 'dim',
'exp', 'gcd', 'hom', 'inf', 'ker', 'lg',
@@ -150,10 +158,43 @@
'z': u'\U0001D4CF',
}
+# >>> print(''.join(latex2mathml.mathscr.values()))
+# 𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵𝒶𝒷𝒸𝒹ℯ𝒻ℊ𝒽𝒾𝒿𝓀𝓁𝓂𝓃ℴ𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏
+
negatables = {'=': u'\u2260',
r'\in': u'\u2209',
r'\equiv': u'\u2262'}
+# cmds/characters allowed in left/right cmds
+fence_args = {'(': '(',
+ ')': ')',
+ '[': '[',
+ ']': ']',
+ '/': '/',
+ r'\backslash': '\\',
+ '|': '|',
+ '.': '', # emty fence
+ r'\uparrow': u'\u2191', # ↑ UPWARDS ARROW
+ r'\downarrow': u'\u2193', # ↓ DOWNWARDS ARROW
+ r'\updownarrow': u'\u2195', # ↕ UP DOWN ARROW
+ r'\Uparrow': u'\u21d1', # ⇑ UPWARDS DOUBLE ARROW
+ r'\Downarrow': u'\u21d3', # ⇓ DOWNWARDS DOUBLE ARROW
+ r'\Updownarrow': u'\u21d5', # ⇕ UP DOWN DOUBLE ARROW
+
+ }
+for (key, value) in tex2unichar.mathfence.items():
+ fence_args['\\'+key] = value
+for (key, value) in tex2unichar.mathopen.items():
+ fence_args['\\'+key] = value
+for (key, value) in tex2unichar.mathclose.items():
+ fence_args['\\'+key] = value
+# shorter with {**something} syntax, new in 3.5
+# if sys.version_info >= (3, 5):
+# for (key, value) in {**tex2unichar.mathclose,
+# **tex2unichar.mathopen,
+# **tex2unichar.mathfence}.items():
+# fence_args['\\'+key] = value
+
# LaTeX to MathML translation stuff:
class math(object):
"""Base class for MathML elements."""
@@ -233,9 +274,10 @@
return ['<%s>' % self.__class__.__name__]
xmlns = 'http://www.w3.org/1998/Math/MathML'
if self.inline:
- return ['<math xmlns="%s" displaystyle="false">' % xmlns]
+ args = 'displaystyle="false"'
else:
- return ['<math xmlns="%s" display="block">' % xmlns]
+ args = 'display="block"'
+ return ['<math xmlns="%s" %s>' % (xmlns, args)]
def xml_end(self):
return ['</%s>' % self.__class__.__name__]
@@ -268,10 +310,13 @@
return [self.data]
class mo(mx):
- translation = {'<': '<', '>': '>'}
+ translation = {ord('<'): u'<', ord('>'): u'>'}
def xml_body(self):
- return [self.translation.get(self.data, self.data)]
+ return [self.data.translate(self.translation)]
+# >>> latex2mathml.mo(u'<').xml()
+# ['<mo>', '<', '</mo>']
+
class mi(mx): pass
class mn(mx): pass
@@ -303,19 +348,6 @@
self.reversed = False
return math.xml(self)
-class mfenced(math):
- translation = {'\\{': '{', '\\langle': u'\u2329',
- '\\}': '}', '\\rangle': u'\u232A',
- '.': ''}
- def __init__(self, par):
- self.openpar = par
- math.__init__(self)
-
- def xml_start(self):
- open = self.translation.get(self.openpar, self.openpar)
- close = self.translation.get(self.closepar, self.closepar)
- return ['<mfenced open="%s" close="%s">' % (open, close)]
-
class mspace(math):
nchildren = 0
@@ -494,26 +526,24 @@
node.append(frac)
node = frac
elif name == 'left':
- for par in ['(', '[', '|', '\\{', '\\langle', '.']:
+ for par in fence_args.keys():
if string.startswith(par):
break
else:
raise SyntaxError(u'Missing left-brace!')
- fenced = mfenced(par)
- node.append(fenced)
row = mrow()
- fenced.append(row)
+ node.append(row)
node = row
+ node.append(mo(fence_args[par]))
skip += len(par)
elif name == 'right':
- for par in [')', ']', '|', '\\}', '\\rangle', '.']:
+ for par in fence_args.keys():
if string.startswith(par):
break
else:
raise SyntaxError(u'Missing right-brace!')
+ node.append(mo(fence_args[par]))
node = node.close()
- node.closepar = par
- node = node.close()
skip += len(par)
elif name == 'not':
for operator in negatables:
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:18:55 UTC (rev 8736)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:19:09 UTC (rev 8737)
@@ -25,10 +25,10 @@
<mtr>
<mtd><mi>f</mi><mo>(</mo><mi>ϵ</mi><mo>)</mo><mo>=</mo><mfrac>
<mrow><mn>1</mn></mrow>
-<mrow><mn>1</mn><mo>+</mo><mo>exp</mo><mfenced open="(" close=")">
-<mrow><mfrac>
+<mrow><mn>1</mn><mo>+</mo><mo>exp</mo>
+<mrow><mo>(</mo><mfrac>
<mrow><mi>ε</mi></mrow>
-<mrow><msub><mi>k</mi><mtext>B</mtext></msub><mi>T</mi></mrow></mfrac></mrow></mfenced></mrow></mfrac></mtd></mtr></mtable></math>
+<mrow><msub><mi>k</mi><mtext>B</mtext></msub><mi>T</mi></mrow></mfrac><mo>)</mo></mrow></mrow></mfrac></mtd></mtr></mtable></math>
</div>
<p>Content may start on the first line of the directive, e.g.</p>
<div>
@@ -47,8 +47,8 @@
<mtable>
<mtr>
<mtd><mstyle mathvariant="bold">
-<mrow><mi>M</mi></mrow></mstyle><mo>=</mo><mfenced open="(" close=")">
-<mrow>
+<mrow><mi>M</mi></mrow></mstyle><mo>=</mo>
+<mrow><mo>(</mo>
<mtable>
<mtr>
<mtd><mi>a</mi></mtd>
@@ -55,7 +55,7 @@
<mtd><mi>b</mi></mtd></mtr>
<mtr>
<mtd><mi>c</mi></mtd>
-<mtd><mi>d</mi></mtd></mtr></mtable></mrow></mfenced></mtd></mtr></mtable></math>
+<mtd><mi>d</mi></mtd></mtr></mtable><mo>)</mo></mrow></mtd></mtr></mtable></math>
</div>
<p>is <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
<mrow><mo>|</mo><mstyle mathvariant="bold">
@@ -154,13 +154,13 @@
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
<mtable>
<mtr>
-<mtd><mtext>MTF</mtext><mo>=</mo><mfenced open="|" close="|">
-<mrow><mfrac>
+<mtd><mtext>MTF</mtext><mo>=</mo>
+<mrow><mo>|</mo><mfrac>
<mrow><mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo></mrow>
<mrow><mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo><msub><mo>|</mo>
<mrow><msub><mi>ω</mi>
-<mrow><mi>x</mi></mrow></msub><mo>=</mo><mn>0</mn></mrow></msub></mrow></mfrac></mrow></mfenced><mo>=</mo><mtext>abs</mtext><mfenced open="(" close=")">
-<mrow><mfrac>
+<mrow><mi>x</mi></mrow></msub><mo>=</mo><mn>0</mn></mrow></msub></mrow></mfrac><mo>|</mo></mrow><mo>=</mo><mtext>abs</mtext>
+<mrow><mo>(</mo><mfrac>
<mrow><munderover><mo>∫</mo>
<mrow><mo>-</mo><mo>∞</mo></mrow>
<mrow><mo>∞</mo></mrow></munderover><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><msup><mtext>e</mtext>
@@ -170,7 +170,7 @@
<mrow><munderover><mo>∫</mo>
<mrow><mo>-</mo><mo>∞</mo></mrow>
<mrow><mo>∞</mo></mrow></munderover><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mtext>d</mtext>
-<mrow><mi>x</mi></mrow></mrow></mfrac></mrow></mfenced><mo>.</mo></mtd></mtr></mtable></math>
+<mrow><mi>x</mi></mrow></mrow></mfrac><mo>)</mo></mrow><mo>.</mo></mtd></mtr></mtable></math>
</div>
<p>Math split over two lines: If a double backslash is detected outside a
<span class="docutils literal"><span class="pre">\begin{...}</span> <span class="pre">\end{...}</span></span> pair, the math code is wrapped in an <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a>
@@ -193,8 +193,8 @@
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
<mtable>
<mtr>
-<mtd><mtext>sgn</mtext><mo>(</mo><mi>x</mi><mo>)</mo><mo>=</mo><mfenced open="{" close="">
-<mrow>
+<mtd><mtext>sgn</mtext><mo>(</mo><mi>x</mi><mo>)</mo><mo>=</mo>
+<mrow><mo>{</mo>
<mtable>
<mtr>
<mtd><mo>-</mo><mn>1</mn></mtd>
@@ -201,7 +201,7 @@
<mtd><mi>x</mi><mo><</mo><mn>0</mn></mtd></mtr>
<mtr>
<mtd><mn>1</mn></mtd>
-<mtd><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr></mtable></mrow></mfenced></mtd></mtr></mtable></math>
+<mtd><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr></mtable><mo></mo></mrow></mtd></mtr></mtable></math>
</div>
<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <span class="docutils literal">cases</span> environment (not (yet) supported by
HTML writers with <span class="docutils literal"><span class="pre">--math-output=MathML</span></span>):</p>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:19:24
|
Revision: 8738
http://sourceforge.net/p/docutils/code/8738
Author: milde
Date: 2021-05-20 12:19:23 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: Use large operators and fix alignment in "math" blocks.
Set displaystyle="true" and class="align" for the outer ``<mtable>``1
in math blocks.
1 The "mtable"-wrapper is used to support multi-line formulas
similar to the "align" environment in the "amsmath" LaTeX package.
Add CSS to left-align the table cells in "align"-emulating mtables.
Fixes part of bug #407.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/__init__.py
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/docutils/writers/html5_polyglot/plain.css
trunk/docutils/docutils/writers/html5_polyglot/responsive.css
trunk/docutils/test/functional/expected/math_output_mathml.html
Modified: trunk/docutils/docutils/utils/math/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/math/__init__.py 2021-05-20 12:19:09 UTC (rev 8737)
+++ trunk/docutils/docutils/utils/math/__init__.py 2021-05-20 12:19:23 UTC (rev 8738)
@@ -19,7 +19,7 @@
:latex2mathml: LaTeX math -> presentational MathML
:unichar2tex: Unicode character to LaTeX math translation table
:tex2unichar: LaTeX math to Unicode character translation dictionaries
-:tex2mathml_extern: Wrapper for TeX -> MathML command line converters
+:tex2mathml_extern: Wrapper for 3rd party TeX -> MathML converters
"""
# helpers for Docutils math support
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:19:09 UTC (rev 8737)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:19:23 UTC (rev 8738)
@@ -22,11 +22,20 @@
#
# Usage:
#
-# >>> import latex2mathml
+# >>> import latex2mathml as l2m
-import docutils.utils.math.tex2unichar as tex2unichar
+import collections
+import sys
+if sys.version_info >= (3, 0):
+ unicode = str # noqa
-# TeX spacing combining
+from docutils.utils.math import tex2unichar
+
+
+# Metadata
+# --------
+
+# TeX spacing combining
over = {'acute': u'\u00B4', # u'\u0301',
'bar': u'\u00AF', # u'\u0304',
'breve': u'\u02D8', # u'\u0306',
@@ -61,7 +70,7 @@
sumintprod = ''.join([special[symbol] for symbol in
['sum', 'int', 'oint', 'prod']])
-# >>> print(latex2mathml.sumintprod)
+# >>> print(l2m.sumintprod)
# ∑∫∮∏
functions = ['arccos', 'arcsin', 'arctan', 'arg', 'cos', 'cosh',
@@ -158,7 +167,7 @@
'z': u'\U0001D4CF',
}
-# >>> print(''.join(latex2mathml.mathscr.values()))
+# >>> print(''.join(l2m.mathscr.values()))
# 𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵𝒶𝒷𝒸𝒹ℯ𝒻ℊ𝒽𝒾𝒿𝓀𝓁𝓂𝓃ℴ𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏
negatables = {'=': u'\u2260',
@@ -195,7 +204,10 @@
# **tex2unichar.mathfence}.items():
# fence_args['\\'+key] = value
-# LaTeX to MathML translation stuff:
+
+# MathML element classes
+# ----------------------
+
class math(object):
"""Base class for MathML elements."""
@@ -202,7 +214,7 @@
nchildren = 1000000
"""Required number of children"""
- def __init__(self, children=None, inline=None):
+ def __init__(self, children=None, inline=None, **kwargs):
"""math([children]) -> MathML element
children can be one child or a list of children."""
@@ -216,15 +228,24 @@
# Only one child:
self.append(children)
+ self.attributes = collections.OrderedDict()
if inline is not None:
- self.inline = inline
+ self.attributes['xmlns'] = 'http://www.w3.org/1998/Math/MathML'
+ if inline is False:
+ self.attributes['display'] = 'block'
+ # self.attributes['displaystyle'] = 'true'
+ # sort kwargs for predictable functional tests
+ # as self.attributes.update(kwargs) does not keep order in Python < 3.6
+ for key in sorted(kwargs.keys()):
+ self.attributes.setdefault(key, kwargs[key])
def __repr__(self):
- if hasattr(self, 'children'):
- return self.__class__.__name__ + '(%s)' % \
- ','.join([repr(child) for child in self.children])
- else:
- return self.__class__.__name__
+ content = [repr(item) for item in getattr(self, 'children', [])]
+ if hasattr(self, 'data'):
+ content.append(str(self.data))
+ if hasattr(self, 'attributes'):
+ content += ["%s='%s'"%(k, v) for k, v in self.attributes.items()]
+ return self.__class__.__name__ + '(%s)' % ', '.join(content)
def full(self):
"""Room for more children?"""
@@ -270,14 +291,10 @@
return self.xml_start() + self.xml_body() + self.xml_end()
def xml_start(self):
- if not hasattr(self, 'inline'):
- return ['<%s>' % self.__class__.__name__]
- xmlns = 'http://www.w3.org/1998/Math/MathML'
- if self.inline:
- args = 'displaystyle="false"'
- else:
- args = 'display="block"'
- return ['<math xmlns="%s" %s>' % (xmlns, args)]
+ # MathML uses only lowercase attributes, allow CLASS for class (Python keyword)
+ attrs = ['%s="%s"'%(k.lower(), v) for k, v
+ in getattr(self, 'attributes', {}).items()]
+ return ['<%s>' % ' '.join([self.__class__.__name__] + attrs)]
def xml_end(self):
return ['</%s>' % self.__class__.__name__]
@@ -288,38 +305,71 @@
xml.extend(child.xml())
return xml
+# >>> l2m.math(l2m.mn(2))
+# math(mn(2))
+# >>> l2m.math(l2m.mn(2)).xml()
+# ['<math>', '<mn>', 2, '</mn>', '</math>']
+#
+# >>> l2m.math(id='eq3')
+# math(id='eq3')
+# >>> l2m.math(id='eq3').xml()
+# ['<math id="eq3">', '</math>']
+#
+# use CLASS to get "class" in XML
+# >>> l2m.math(CLASS='test')
+# math(CLASS='test')
+# >>> l2m.math(CLASS='test').xml()
+# ['<math class="test">', '</math>']
+
+# >>> l2m.math(inline=True)
+# math(xmlns='http://www.w3.org/1998/Math/MathML')
+# >>> l2m.math(inline=True).xml()
+# ['<math xmlns="http://www.w3.org/1998/Math/MathML">', '</math>']
+# >>> l2m.math(inline=False)
+# math(xmlns='http://www.w3.org/1998/Math/MathML', display='block')
+# >>> l2m.math(inline=False).xml()
+# ['<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">', '</math>']
+
class mrow(math):
def xml_start(self):
- return ['\n<%s>' % self.__class__.__name__]
+ return ['\n'] + super(mrow, self).xml_start()
+# >>> l2m.mrow(displaystyle='false')
+# mrow(displaystyle='false')
+
class mtable(math):
def xml_start(self):
- return ['\n<%s>' % self.__class__.__name__]
+ return ['\n'] + super(mtable, self).xml_start()
+# >>> l2m.mtable(displaystyle='true')
+# mtable(displaystyle='true')
+# >>> l2m.math(l2m.mtable(displaystyle='true')).xml()
+# ['<math>', '\n', '<mtable displaystyle="true">', '</mtable>', '</math>']
+
class mtr(mrow): pass
class mtd(mrow): pass
class mx(math):
- """Base class for mo, mi, and mn"""
+ """Token Element: Base class for mo, mi, and mn.
+ """
+ nchildren = 0
+ entity_table = {ord('<'): u'<', ord('>'): u'>'}
- nchildren = 0
def __init__(self, data):
self.data = data
def xml_body(self):
- return [self.data]
+ return [unicode(self.data).translate(self.entity_table)]
-class mo(mx):
- translation = {ord('<'): u'<', ord('>'): u'>'}
- def xml_body(self):
- return [self.data.translate(self.translation)]
+class mi(mx): pass
+class mn(mx): pass
+class mo(mx): pass
-# >>> latex2mathml.mo(u'<').xml()
+# >>> l2m.mo(u'<')
+# mo(<)
+# >>> l2m.mo(u'<').xml()
# ['<mo>', '<', '</mo>']
-class mi(mx): pass
-class mn(mx): pass
-
class msub(math):
nchildren = 2
@@ -390,6 +440,10 @@
def xml_body(self):
return [self.text]
+
+# LaTeX to MathML translation
+# ---------------------------
+
def parse_latex_math(string, inline=True):
"""parse_latex_math(string [,inline]) -> MathML-tree
@@ -406,7 +460,8 @@
tree = math(node, inline=True)
else:
node = mtd()
- tree = math(mtable(mtr(node)), inline=False)
+ content = mtable(mtr(node), displaystyle='true', CLASS='align')
+ tree = math(content, inline=False)
while len(string) > 0:
n = len(string)
Modified: trunk/docutils/docutils/writers/html5_polyglot/plain.css
===================================================================
--- trunk/docutils/docutils/writers/html5_polyglot/plain.css 2021-05-20 12:19:09 UTC (rev 8737)
+++ trunk/docutils/docutils/writers/html5_polyglot/plain.css 2021-05-20 12:19:23 UTC (rev 8738)
@@ -59,6 +59,7 @@
p, ol, ul, dl, li,
div.line-block,
div.topic,
+div > math,
table {
margin-top: 0.5em;
margin-bottom: 0.5em;
@@ -260,7 +261,10 @@
pre.code .inserted, code .inserted { background-color: #A3D289}
/* Math */
-/* styled separately (see math.css for math-output=HTML) */
+/* for math-output=MathML (for math-output=HTML, see math.css) */
+mtable.align > mtr > mtd { /* emulate AMS "align" environment. */
+ text-align: left;
+}
/* Epigraph */
/* Highlights */
Modified: trunk/docutils/docutils/writers/html5_polyglot/responsive.css
===================================================================
--- trunk/docutils/docutils/writers/html5_polyglot/responsive.css 2021-05-20 12:19:09 UTC (rev 8737)
+++ trunk/docutils/docutils/writers/html5_polyglot/responsive.css 2021-05-20 12:19:23 UTC (rev 8738)
@@ -45,6 +45,7 @@
p, ol, ul, dl, li,
div.line-block,
div.topic,
+div > math,
table {
margin-top: 0.5em;
margin-bottom: 0.5em;
@@ -339,6 +340,12 @@
width: 40%;
}
+/* Math */
+/* for math-output=MathML (for math-output=HTML, see math.css) */
+mtable.align > mtr > mtd { /* emulate AMS "align" environment. */
+ text-align: left;
+}
+
/* Adaptive page layout */
/* ==================== */
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:19:09 UTC (rev 8737)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:19:23 UTC (rev 8738)
@@ -13,8 +13,8 @@
<h1 class="title">Mathematics</h1>
<p>Docutils supports inline math with the prefix or postfix <span class="docutils literal">:math:</span>
-role specificator, <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
-<mrow><mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo>(</mo><msubsup><mi>x</mi><mi>n</mi><mn>2</mn></msubsup><mo>)</mo></mrow></math> and <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+role specificator, <math xmlns="http://www.w3.org/1998/Math/MathML">
+<mrow><mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo>(</mo><msubsup><mi>x</mi><mi>n</mi><mn>2</mn></msubsup><mo>)</mo></mrow></math> and <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><msub><mi>A</mi><mtext>c</mtext></msub><mo>=</mo><mfrac>
<mrow><mi>π</mi></mrow>
<mrow><mn>4</mn></mrow></mfrac><msup><mi>d</mi><mn>2</mn></msup></mrow></math>, as well as displayed math via the
@@ -21,7 +21,7 @@
<cite>math</cite> directive:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><mi>f</mi><mo>(</mo><mi>ϵ</mi><mo>)</mo><mo>=</mo><mfrac>
<mrow><mn>1</mn></mrow>
@@ -33,7 +33,7 @@
<p>Content may start on the first line of the directive, e.g.</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><mi>N</mi><mo>=</mo><mfrac>
<mrow><mtext>number of apples</mtext></mrow>
@@ -44,7 +44,7 @@
<p>The determinant of the matrix</p>
<div id="eq-m">
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><mstyle mathvariant="bold">
<mrow><mi>M</mi></mrow></mstyle><mo>=</mo>
@@ -57,7 +57,7 @@
<mtd><mi>c</mi></mtd>
<mtd><mi>d</mi></mtd></mtr></mtable><mo>)</mo></mrow></mtd></mtr></mtable></math>
</div>
-<p>is <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<p>is <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mo>|</mo><mstyle mathvariant="bold">
<mrow><mi>M</mi></mrow></mstyle><mo>|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi></mrow></math>.</p>
<p>More than one display math block can be put in one math directive.
@@ -64,7 +64,7 @@
For example, the following sum and integral with limits:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><munderover><mo>∫</mo><mn>0</mn><mn>1</mn></munderover><msup><mi>x</mi><mi>n</mi></msup><mi>d</mi><mi>x</mi><mo>=</mo><mfrac>
<mrow><mn>1</mn></mrow>
@@ -72,7 +72,7 @@
</div>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><munderover><mo>∑</mo>
<mrow><mi>n</mi><mo>=</mo><mn>1</mn></mrow><mi>m</mi></munderover><mi>n</mi><mo>=</mo><mfrac>
@@ -84,7 +84,7 @@
<p>The Schrödinger equation</p>
<div id="eq-schrodinger">
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><mi>i</mi><mi>ℏ</mi><mfrac>
<mrow><mo>∂</mo></mrow>
@@ -91,7 +91,7 @@
<mrow><mo>∂</mo><mi>t</mi></mrow></mfrac><mo>Ψ</mo><mo>=</mo><mover>
<mrow><mi>H</mi></mrow><mo>^</mo></mover><mo>Ψ</mo><mo>,</mo></mtd></mtr></mtable></math>
</div>
-<p>with the <em>wave function</em> <math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<p>with the <em>wave function</em> <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mo>Ψ</mo></mrow></math>, describes how the quantum state of a
physical system changes in time.</p>
<dl>
@@ -103,43 +103,43 @@
<col style="width: 33%" />
</colgroup>
<tbody>
-<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>a</mi></mrow><mo>´</mo></mover></mrow></math> <span class="docutils literal">\acute{a}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>t</mi></mrow><mo>˙</mo></mover></mrow></math> <span class="docutils literal">\dot{t}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>γ</mi></mrow><mo>^</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\hat{\gamma}</span></span></p></td>
</tr>
-<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>a</mi></mrow><mo>`</mo></mover></mrow></math> <span class="docutils literal">\grave{a}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>t</mi></mrow><mo>¨</mo></mover></mrow></math> <span class="docutils literal">\ddot{t}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>α</mi></mrow><mo>˜</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\tilde{\alpha}</span></span></p></td>
</tr>
-<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>x</mi></mrow><mo>˘</mo></mover></mrow></math> <span class="docutils literal">\breve{x}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>t</mi></mrow><mo>⃛</mo></mover></mrow></math> <span class="docutils literal">\dddot{t}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>ı</mi></mrow><mo>⃗</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\vec{\imath}</span></span></p></td>
</tr>
-<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>a</mi></mrow><mo>ˇ</mo></mover></mrow></math> <span class="docutils literal">\check{a}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>a</mi></mrow><mo>¯</mo></mover></mrow></math> <span class="docutils literal">\bar{a}</span></p></td>
-<td><p><math xmlns="http://www.w3.org/1998/Math/MathML" displaystyle="false">
+<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow><mover>
<mrow><mi>R</mi></mrow><mo>⃗</mo></mover></mrow></math> <span class="docutils literal">\vec{R}</span></p></td>
</tr>
@@ -152,7 +152,7 @@
<p>Modulation Transfer Function:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><mtext>MTF</mtext><mo>=</mo>
<mrow><mo>|</mo><mfrac>
@@ -177,7 +177,7 @@
<span class="docutils literal">align</span> environment:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><msub><mi>s</mi>
<mrow><mtext>out</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>)</mo></mtd>
@@ -191,7 +191,7 @@
<p>Cases ("manually", with <span class="docutils literal">matrix</span> environment):</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable>
+<mtable class="align" displaystyle="true">
<mtr>
<mtd><mtext>sgn</mtext><mo>(</mo><mi>x</mi><mo>)</mo><mo>=</mo>
<mrow><mo>{</mo>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:19:42
|
Revision: 8739
http://sourceforge.net/p/docutils/code/8739
Author: milde
Date: 2021-05-20 12:19:35 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: pretty print XML.
Add newlines and indentation around non-token MathML tags.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/math_output_mathml.html
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:19:23 UTC (rev 8738)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:19:35 UTC (rev 8739)
@@ -213,6 +213,7 @@
nchildren = 1000000
"""Required number of children"""
+ _level = 0 # indentation level (static class variable)
def __init__(self, children=None, inline=None, **kwargs):
"""math([children]) -> MathML element
@@ -291,61 +292,68 @@
return self.xml_start() + self.xml_body() + self.xml_end()
def xml_start(self):
- # MathML uses only lowercase attributes, allow CLASS for class (Python keyword)
+ # Use k.lower() to allow argument `CLASS` for attribute `class`
+ # (Python keyword). MathML uses only lowercase attributes.
attrs = ['%s="%s"'%(k.lower(), v) for k, v
in getattr(self, 'attributes', {}).items()]
+ if not isinstance(self, mx): # token elements
+ math._level += 1
return ['<%s>' % ' '.join([self.__class__.__name__] + attrs)]
def xml_end(self):
- return ['</%s>' % self.__class__.__name__]
+ xml = []
+ if not isinstance(self, mx): # except token elements
+ math._level -= 1
+ xml.append('\n' + ' ' * math._level)
+ xml.append('</%s>' % self.__class__.__name__)
+ return xml
def xml_body(self):
xml = []
+ last_child = None
for child in self.children:
+ if not (isinstance(last_child, mx) and isinstance(child, mx)):
+ xml.append('\n' + ' ' * math._level)
xml.extend(child.xml())
+ last_child = child
return xml
# >>> l2m.math(l2m.mn(2))
# math(mn(2))
# >>> l2m.math(l2m.mn(2)).xml()
-# ['<math>', '<mn>', 2, '</mn>', '</math>']
+# ['<math>', '\n ', '<mn>', '2', '</mn>', '\n', '</math>']
#
# >>> l2m.math(id='eq3')
# math(id='eq3')
# >>> l2m.math(id='eq3').xml()
-# ['<math id="eq3">', '</math>']
+# ['<math id="eq3">', '\n', '</math>']
#
# use CLASS to get "class" in XML
# >>> l2m.math(CLASS='test')
# math(CLASS='test')
# >>> l2m.math(CLASS='test').xml()
-# ['<math class="test">', '</math>']
+# ['<math class="test">', '\n', '</math>']
# >>> l2m.math(inline=True)
# math(xmlns='http://www.w3.org/1998/Math/MathML')
# >>> l2m.math(inline=True).xml()
-# ['<math xmlns="http://www.w3.org/1998/Math/MathML">', '</math>']
+# ['<math xmlns="http://www.w3.org/1998/Math/MathML">', '\n', '</math>']
# >>> l2m.math(inline=False)
# math(xmlns='http://www.w3.org/1998/Math/MathML', display='block')
# >>> l2m.math(inline=False).xml()
-# ['<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">', '</math>']
+# ['<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">', '\n', '</math>']
-class mrow(math):
- def xml_start(self):
- return ['\n'] + super(mrow, self).xml_start()
+class mrow(math): pass
# >>> l2m.mrow(displaystyle='false')
# mrow(displaystyle='false')
-class mtable(math):
- def xml_start(self):
- return ['\n'] + super(mtable, self).xml_start()
+class mtable(math): pass
# >>> l2m.mtable(displaystyle='true')
# mtable(displaystyle='true')
# >>> l2m.math(l2m.mtable(displaystyle='true')).xml()
-# ['<math>', '\n', '<mtable displaystyle="true">', '</mtable>', '</math>']
-
+# ['<math>', '\n ', '<mtable displaystyle="true">', '\n ', '</mtable>', '\n', '</math>']
class mtr(mrow): pass
class mtd(mrow): pass
@@ -364,6 +372,7 @@
class mi(mx): pass
class mn(mx): pass
class mo(mx): pass
+class mtext(mx): pass
# >>> l2m.mo(u'<')
# mo(<)
@@ -393,10 +402,10 @@
def xml(self):
if self.reversed:
-## self.children[1:3] = self.children[2:0:-1]
+ ## self.children[1:3] = self.children[2:0:-1]
self.children[1:3] = [self.children[2], self.children[1]]
self.reversed = False
- return math.xml(self)
+ return super(msubsup, self).xml()
class mspace(math):
nchildren = 0
@@ -406,12 +415,8 @@
if nchildren is not None:
self.nchildren = nchildren
math.__init__(self, children)
- self.attrs = kwargs
+ self.attributes = kwargs
- def xml_start(self):
- return ['<mstyle '] + ['%s="%s"' % item
- for item in self.attrs.items()] + ['>']
-
class mover(math):
nchildren = 2
def __init__(self, children=None, reversed=False):
@@ -432,15 +437,6 @@
def __init__(self, children=None):
math.__init__(self, children)
-class mtext(math):
- nchildren = 0
- def __init__(self, text):
- self.text = text
-
- def xml_body(self):
- return [self.text]
-
-
# LaTeX to MathML translation
# ---------------------------
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:19:23 UTC (rev 8738)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:19:35 UTC (rev 8739)
@@ -14,30 +14,86 @@
<p>Docutils supports inline math with the prefix or postfix <span class="docutils literal">:math:</span>
role specificator, <math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo>(</mo><msubsup><mi>x</mi><mi>n</mi><mn>2</mn></msubsup><mo>)</mo></mrow></math> and <math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><msub><mi>A</mi><mtext>c</mtext></msub><mo>=</mo><mfrac>
-<mrow><mi>π</mi></mrow>
-<mrow><mn>4</mn></mrow></mfrac><msup><mi>d</mi><mn>2</mn></msup></mrow></math>, as well as displayed math via the
+ <mrow>
+ <mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo>(</mo>
+ <msubsup>
+ <mi>x</mi><mi>n</mi><mn>2</mn>
+ </msubsup>
+ <mo>)</mo>
+ </mrow>
+</math> and <math xmlns="http://www.w3.org/1998/Math/MathML">
+ <mrow>
+ <msub>
+ <mi>A</mi><mtext>c</mtext>
+ </msub>
+ <mo>=</mo>
+ <mfrac>
+ <mrow>
+ <mi>π</mi>
+ </mrow>
+ <mrow>
+ <mn>4</mn>
+ </mrow>
+ </mfrac>
+ <msup>
+ <mi>d</mi><mn>2</mn>
+ </msup>
+ </mrow>
+</math>, as well as displayed math via the
<cite>math</cite> directive:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><mi>f</mi><mo>(</mo><mi>ϵ</mi><mo>)</mo><mo>=</mo><mfrac>
-<mrow><mn>1</mn></mrow>
-<mrow><mn>1</mn><mo>+</mo><mo>exp</mo>
-<mrow><mo>(</mo><mfrac>
-<mrow><mi>ε</mi></mrow>
-<mrow><msub><mi>k</mi><mtext>B</mtext></msub><mi>T</mi></mrow></mfrac><mo>)</mo></mrow></mrow></mfrac></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <mi>f</mi><mo>(</mo><mi>ϵ</mi><mo>)</mo><mo>=</mo>
+ <mfrac>
+ <mrow>
+ <mn>1</mn>
+ </mrow>
+ <mrow>
+ <mn>1</mn><mo>+</mo><mo>exp</mo>
+ <mrow>
+ <mo>(</mo>
+ <mfrac>
+ <mrow>
+ <mi>ε</mi>
+ </mrow>
+ <mrow>
+ <msub>
+ <mi>k</mi><mtext>B</mtext>
+ </msub>
+ <mi>T</mi>
+ </mrow>
+ </mfrac>
+ <mo>)</mo>
+ </mrow>
+ </mrow>
+ </mfrac>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<p>Content may start on the first line of the directive, e.g.</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><mi>N</mi><mo>=</mo><mfrac>
-<mrow><mtext>number of apples</mtext></mrow>
-<mrow><mn>7</mn></mrow></mfrac></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <mi>N</mi><mo>=</mo>
+ <mfrac>
+ <mrow>
+ <mtext>number of apples</mtext>
+ </mrow>
+ <mrow>
+ <mn>7</mn>
+ </mrow>
+ </mfrac>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<p>Equations can be labeled with a reference name using the <span class="docutils literal">:name:</span> option.
See <a class="reference internal" href="#eq-m">eq:M</a> and <a class="reference internal" href="#eq-schrodinger">eq:schrödinger</a> below.</p>
@@ -44,40 +100,105 @@
<p>The determinant of the matrix</p>
<div id="eq-m">
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><mstyle mathvariant="bold">
-<mrow><mi>M</mi></mrow></mstyle><mo>=</mo>
-<mrow><mo>(</mo>
-<mtable>
-<mtr>
-<mtd><mi>a</mi></mtd>
-<mtd><mi>b</mi></mtd></mtr>
-<mtr>
-<mtd><mi>c</mi></mtd>
-<mtd><mi>d</mi></mtd></mtr></mtable><mo>)</mo></mrow></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <mstyle mathvariant="bold">
+ <mrow>
+ <mi>M</mi>
+ </mrow>
+ </mstyle>
+ <mo>=</mo>
+ <mrow>
+ <mo>(</mo>
+ <mtable>
+ <mtr>
+ <mtd>
+ <mi>a</mi>
+ </mtd>
+ <mtd>
+ <mi>b</mi>
+ </mtd>
+ </mtr>
+ <mtr>
+ <mtd>
+ <mi>c</mi>
+ </mtd>
+ <mtd>
+ <mi>d</mi>
+ </mtd>
+ </mtr>
+ </mtable>
+ <mo>)</mo>
+ </mrow>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<p>is <math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mo>|</mo><mstyle mathvariant="bold">
-<mrow><mi>M</mi></mrow></mstyle><mo>|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi></mrow></math>.</p>
+ <mrow>
+ <mo>|</mo>
+ <mstyle mathvariant="bold">
+ <mrow>
+ <mi>M</mi>
+ </mrow>
+ </mstyle>
+ <mo>|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi>
+ </mrow>
+</math>.</p>
<p>More than one display math block can be put in one math directive.
For example, the following sum and integral with limits:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><munderover><mo>∫</mo><mn>0</mn><mn>1</mn></munderover><msup><mi>x</mi><mi>n</mi></msup><mi>d</mi><mi>x</mi><mo>=</mo><mfrac>
-<mrow><mn>1</mn></mrow>
-<mrow><mi>n</mi><mo>+</mo><mn>1</mn></mrow></mfrac></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <munderover>
+ <mo>∫</mo><mn>0</mn><mn>1</mn>
+ </munderover>
+ <msup>
+ <mi>x</mi><mi>n</mi>
+ </msup>
+ <mi>d</mi><mi>x</mi><mo>=</mo>
+ <mfrac>
+ <mrow>
+ <mn>1</mn>
+ </mrow>
+ <mrow>
+ <mi>n</mi><mo>+</mo><mn>1</mn>
+ </mrow>
+ </mfrac>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><munderover><mo>∑</mo>
-<mrow><mi>n</mi><mo>=</mo><mn>1</mn></mrow><mi>m</mi></munderover><mi>n</mi><mo>=</mo><mfrac>
-<mrow><mi>m</mi><mo>(</mo><mi>m</mi><mo>+</mo><mn>1</mn><mo>)</mo></mrow>
-<mrow><mn>2</mn></mrow></mfrac></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <munderover>
+ <mo>∑</mo>
+ <mrow>
+ <mi>n</mi><mo>=</mo><mn>1</mn>
+ </mrow>
+ <mi>m</mi>
+ </munderover>
+ <mi>n</mi><mo>=</mo>
+ <mfrac>
+ <mrow>
+ <mi>m</mi><mo>(</mo><mi>m</mi><mo>+</mo><mn>1</mn><mo>)</mo>
+ </mrow>
+ <mrow>
+ <mn>2</mn>
+ </mrow>
+ </mfrac>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<p>LaTeX-supported Unicode math symbols can be used in math roles and
directives:</p>
@@ -84,15 +205,36 @@
<p>The Schrödinger equation</p>
<div id="eq-schrodinger">
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><mi>i</mi><mi>ℏ</mi><mfrac>
-<mrow><mo>∂</mo></mrow>
-<mrow><mo>∂</mo><mi>t</mi></mrow></mfrac><mo>Ψ</mo><mo>=</mo><mover>
-<mrow><mi>H</mi></mrow><mo>^</mo></mover><mo>Ψ</mo><mo>,</mo></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <mi>i</mi><mi>ℏ</mi>
+ <mfrac>
+ <mrow>
+ <mo>∂</mo>
+ </mrow>
+ <mrow>
+ <mo>∂</mo><mi>t</mi>
+ </mrow>
+ </mfrac>
+ <mo>Ψ</mo><mo>=</mo>
+ <mover>
+ <mrow>
+ <mi>H</mi>
+ </mrow>
+ <mo>^</mo>
+ </mover>
+ <mo>Ψ</mo><mo>,</mo>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<p>with the <em>wave function</em> <math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mo>Ψ</mo></mrow></math>, describes how the quantum state of a
+ <mrow>
+ <mo>Ψ</mo>
+ </mrow>
+</math>, describes how the quantum state of a
physical system changes in time.</p>
<dl>
<dt>Math-Accents:</dt>
@@ -104,44 +246,128 @@
</colgroup>
<tbody>
<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>a</mi></mrow><mo>´</mo></mover></mrow></math> <span class="docutils literal">\acute{a}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>a</mi>
+ </mrow>
+ <mo>´</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\acute{a}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>t</mi></mrow><mo>˙</mo></mover></mrow></math> <span class="docutils literal">\dot{t}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>t</mi>
+ </mrow>
+ <mo>˙</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\dot{t}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>γ</mi></mrow><mo>^</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\hat{\gamma}</span></span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>γ</mi>
+ </mrow>
+ <mo>^</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal"><span class="pre">\hat{\gamma}</span></span></p></td>
</tr>
<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>a</mi></mrow><mo>`</mo></mover></mrow></math> <span class="docutils literal">\grave{a}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>a</mi>
+ </mrow>
+ <mo>`</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\grave{a}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>t</mi></mrow><mo>¨</mo></mover></mrow></math> <span class="docutils literal">\ddot{t}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>t</mi>
+ </mrow>
+ <mo>¨</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\ddot{t}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>α</mi></mrow><mo>˜</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\tilde{\alpha}</span></span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>α</mi>
+ </mrow>
+ <mo>˜</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal"><span class="pre">\tilde{\alpha}</span></span></p></td>
</tr>
<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>x</mi></mrow><mo>˘</mo></mover></mrow></math> <span class="docutils literal">\breve{x}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>x</mi>
+ </mrow>
+ <mo>˘</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\breve{x}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>t</mi></mrow><mo>⃛</mo></mover></mrow></math> <span class="docutils literal">\dddot{t}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>t</mi>
+ </mrow>
+ <mo>⃛</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\dddot{t}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>ı</mi></mrow><mo>⃗</mo></mover></mrow></math> <span class="docutils literal"><span class="pre">\vec{\imath}</span></span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>ı</mi>
+ </mrow>
+ <mo>⃗</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal"><span class="pre">\vec{\imath}</span></span></p></td>
</tr>
<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>a</mi></mrow><mo>ˇ</mo></mover></mrow></math> <span class="docutils literal">\check{a}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>a</mi>
+ </mrow>
+ <mo>ˇ</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\check{a}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>a</mi></mrow><mo>¯</mo></mover></mrow></math> <span class="docutils literal">\bar{a}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>a</mi>
+ </mrow>
+ <mo>¯</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\bar{a}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
-<mrow><mover>
-<mrow><mi>R</mi></mrow><mo>⃗</mo></mover></mrow></math> <span class="docutils literal">\vec{R}</span></p></td>
+ <mrow>
+ <mover>
+ <mrow>
+ <mi>R</mi>
+ </mrow>
+ <mo>⃗</mo>
+ </mover>
+ </mrow>
+</math> <span class="docutils literal">\vec{R}</span></p></td>
</tr>
</tbody>
</table>
@@ -152,25 +378,90 @@
<p>Modulation Transfer Function:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><mtext>MTF</mtext><mo>=</mo>
-<mrow><mo>|</mo><mfrac>
-<mrow><mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo></mrow>
-<mrow><mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo><msub><mo>|</mo>
-<mrow><msub><mi>ω</mi>
-<mrow><mi>x</mi></mrow></msub><mo>=</mo><mn>0</mn></mrow></msub></mrow></mfrac><mo>|</mo></mrow><mo>=</mo><mtext>abs</mtext>
-<mrow><mo>(</mo><mfrac>
-<mrow><munderover><mo>∫</mo>
-<mrow><mo>-</mo><mo>∞</mo></mrow>
-<mrow><mo>∞</mo></mrow></munderover><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><msup><mtext>e</mtext>
-<mrow><mtext>i</mtext><msub><mi>ω</mi>
-<mrow><mi>x</mi></mrow></msub><mi>x</mi></mrow></msup><mtext>d</mtext>
-<mrow><mi>x</mi></mrow></mrow>
-<mrow><munderover><mo>∫</mo>
-<mrow><mo>-</mo><mo>∞</mo></mrow>
-<mrow><mo>∞</mo></mrow></munderover><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mtext>d</mtext>
-<mrow><mi>x</mi></mrow></mrow></mfrac><mo>)</mo></mrow><mo>.</mo></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <mtext>MTF</mtext><mo>=</mo>
+ <mrow>
+ <mo>|</mo>
+ <mfrac>
+ <mrow>
+ <mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo>
+ </mrow>
+ <mrow>
+ <mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo>
+ <msub>
+ <mo>|</mo>
+ <mrow>
+ <msub>
+ <mi>ω</mi>
+ <mrow>
+ <mi>x</mi>
+ </mrow>
+ </msub>
+ <mo>=</mo><mn>0</mn>
+ </mrow>
+ </msub>
+ </mrow>
+ </mfrac>
+ <mo>|</mo>
+ </mrow>
+ <mo>=</mo><mtext>abs</mtext>
+ <mrow>
+ <mo>(</mo>
+ <mfrac>
+ <mrow>
+ <munderover>
+ <mo>∫</mo>
+ <mrow>
+ <mo>-</mo><mo>∞</mo>
+ </mrow>
+ <mrow>
+ <mo>∞</mo>
+ </mrow>
+ </munderover>
+ <mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo>
+ <msup>
+ <mtext>e</mtext>
+ <mrow>
+ <mtext>i</mtext>
+ <msub>
+ <mi>ω</mi>
+ <mrow>
+ <mi>x</mi>
+ </mrow>
+ </msub>
+ <mi>x</mi>
+ </mrow>
+ </msup>
+ <mtext>d</mtext>
+ <mrow>
+ <mi>x</mi>
+ </mrow>
+ </mrow>
+ <mrow>
+ <munderover>
+ <mo>∫</mo>
+ <mrow>
+ <mo>-</mo><mo>∞</mo>
+ </mrow>
+ <mrow>
+ <mo>∞</mo>
+ </mrow>
+ </munderover>
+ <mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mtext>d</mtext>
+ <mrow>
+ <mi>x</mi>
+ </mrow>
+ </mrow>
+ </mfrac>
+ <mo>)</mo>
+ </mrow>
+ <mo>.</mo>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<p>Math split over two lines: If a double backslash is detected outside a
<span class="docutils literal"><span class="pre">\begin{...}</span> <span class="pre">\end{...}</span></span> pair, the math code is wrapped in an <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a>
@@ -177,31 +468,86 @@
<span class="docutils literal">align</span> environment:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><msub><mi>s</mi>
-<mrow><mtext>out</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>)</mo></mtd>
-<mtd><mo>=</mo><msub><mi>s</mi>
-<mrow><mtext>in</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo><mo>*</mo><msub><mi>s</mi><mi>δ</mi></msub><mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo></mtd></mtr>
-<mtr>
-<mtd></mtd>
-<mtd><mo>=</mo><mo>∫</mo><msub><mi>s</mi>
-<mrow><mtext>in</mtext></mrow></msub><mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo><msub><mi>s</mi><mi>δ</mi></msub><mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo><mtext>d</mtext><mi>x</mi><mo>'</mo></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <msub>
+ <mi>s</mi>
+ <mrow>
+ <mtext>out</mtext>
+ </mrow>
+ </msub>
+ <mo>(</mo><mi>x</mi><mo>)</mo>
+ </mtd>
+ <mtd>
+ <mo>=</mo>
+ <msub>
+ <mi>s</mi>
+ <mrow>
+ <mtext>in</mtext>
+ </mrow>
+ </msub>
+ <mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo><mo>*</mo>
+ <msub>
+ <mi>s</mi><mi>δ</mi>
+ </msub>
+ <mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo>
+ </mtd>
+ </mtr>
+ <mtr>
+ <mtd>
+ </mtd>
+ <mtd>
+ <mo>=</mo><mo>∫</mo>
+ <msub>
+ <mi>s</mi>
+ <mrow>
+ <mtext>in</mtext>
+ </mrow>
+ </msub>
+ <mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo>
+ <msub>
+ <mi>s</mi><mi>δ</mi>
+ </msub>
+ <mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo><mtext>d</mtext><mi>x</mi><mo>'</mo>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<p>Cases ("manually", with <span class="docutils literal">matrix</span> environment):</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
-<mtable class="align" displaystyle="true">
-<mtr>
-<mtd><mtext>sgn</mtext><mo>(</mo><mi>x</mi><mo>)</mo><mo>=</mo>
-<mrow><mo>{</mo>
-<mtable>
-<mtr>
-<mtd><mo>-</mo><mn>1</mn></mtd>
-<mtd><mi>x</mi><mo><</mo><mn>0</mn></mtd></mtr>
-<mtr>
-<mtd><mn>1</mn></mtd>
-<mtd><mi>x</mi><mo>></mo><mn>0</mn></mtd></mtr></mtable><mo></mo></mrow></mtd></mtr></mtable></math>
+ <mtable class="align" displaystyle="true">
+ <mtr>
+ <mtd>
+ <mtext>sgn</mtext><mo>(</mo><mi>x</mi><mo>)</mo><mo>=</mo>
+ <mrow>
+ <mo>{</mo>
+ <mtable>
+ <mtr>
+ <mtd>
+ <mo>-</mo><mn>1</mn>
+ </mtd>
+ <mtd>
+ <mi>x</mi><mo><</mo><mn>0</mn>
+ </mtd>
+ </mtr>
+ <mtr>
+ <mtd>
+ <mn>1</mn>
+ </mtd>
+ <mtd>
+ <mi>x</mi><mo>></mo><mn>0</mn>
+ </mtd>
+ </mtr>
+ </mtable>
+ <mo></mo>
+ </mrow>
+ </mtd>
+ </mtr>
+ </mtable>
+</math>
</div>
<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <span class="docutils literal">cases</span> environment (not (yet) supported by
HTML writers with <span class="docutils literal"><span class="pre">--math-output=MathML</span></span>):</p>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:19:54
|
Revision: 8740
http://sourceforge.net/p/docutils/code/8740
Author: milde
Date: 2021-05-20 12:19:54 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: Implement "cases" environment in latex2mathml.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/latex_memoir.tex
trunk/docutils/test/functional/expected/math_output_html.html
trunk/docutils/test/functional/expected/math_output_latex.html
trunk/docutils/test/functional/expected/math_output_mathjax.html
trunk/docutils/test/functional/expected/math_output_mathml.html
trunk/docutils/test/functional/expected/standalone_rst_latex.tex
trunk/docutils/test/functional/expected/standalone_rst_xetex.tex
trunk/docutils/test/functional/input/data/math.txt
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:19:54 UTC (rev 8740)
@@ -222,12 +222,10 @@
self.children = []
if children is not None:
- if isinstance(children, list):
- for child in children:
- self.append(child)
- else:
- # Only one child:
- self.append(children)
+ if not isinstance(children, list):
+ children = [children]
+ for child in children:
+ self.append(child)
self.attributes = collections.OrderedDict()
if inline is not None:
@@ -547,19 +545,31 @@
string = string[1:]
skip = 1
if name == 'begin':
- if not string.startswith('{matrix}'):
+ if string.startswith('{matrix}'):
+ skip += 8
+ entry = mtd()
+ table = mtable(mtr(entry))
+ node.append(table)
+ node = entry
+ elif string.startswith('{cases}'):
+ skip += 7
+ entry = mtd()
+ cases = mrow([mo('{'), mtable(mtr(entry))])
+ node.append(cases)
+ node = entry
+ else:
raise SyntaxError(u'Environment not supported! '
- u'Supported environment: "matrix".')
- skip += 8
- entry = mtd()
- table = mtable(mtr(entry))
- node.append(table)
- node = entry
+ u'Supported environments: "matrix", "cases".')
elif name == 'end':
- if not string.startswith('{matrix}'):
- raise SyntaxError(u'Expected "\\end{matrix}"!')
- skip += 8
- node = node.close().close().close()
+ if string.startswith('{matrix}'):
+ skip += 8
+ node = node.close().close().close()
+ elif string.startswith('{cases}'):
+ skip += 7
+ node = node.close().close().close().close()
+ else:
+ raise SyntaxError(u'Environment not supported! '
+ u'Supported environments: "matrix", "cases".')
elif name in ('text', 'mathrm'):
if string[0] != '{':
raise SyntaxError(u'Expected "\\text{...}"!')
@@ -585,7 +595,8 @@
row = mrow()
node.append(row)
node = row
- node.append(mo(fence_args[par]))
+ if par != '.':
+ node.append(mo(fence_args[par]))
skip += len(par)
elif name == 'right':
for par in fence_args.keys():
@@ -593,7 +604,8 @@
break
else:
raise SyntaxError(u'Missing right-brace!')
- node.append(mo(fence_args[par]))
+ if par != '.':
+ node.append(mo(fence_args[par]))
node = node.close()
skip += len(par)
elif name == 'not':
Modified: trunk/docutils/test/functional/expected/latex_memoir.tex
===================================================================
--- trunk/docutils/test/functional/expected/latex_memoir.tex 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/test/functional/expected/latex_memoir.tex 2021-05-20 12:19:54 UTC (rev 8740)
@@ -1908,18 +1908,9 @@
s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_\delta (x-x') \\
& = \int s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x'
\end{align*}
-Cases (\textquotedbl{}manually\textquotedbl{}, with \texttt{matrix} environment):
+Cases with the \href{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf}{AMSmath}\DUfootnotemark{footnote-reference-15}{footnote-8}{7} \texttt{cases} environment:
%
\begin{equation*}
-\mathrm{sgn}(x) = \left\{\begin{matrix}
- -1 & x<0\\
- 1 & x>0
- \end{matrix}\right.
-\end{equation*}
-Cases with the \href{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf}{AMSmath}\DUfootnotemark{footnote-reference-15}{footnote-8}{7} \texttt{cases} environment (not (yet) supported by
-HTML writers with \texttt{-{}-math-output=MathML}):
-%
-\begin{equation*}
\mathrm{sgn}(x) = \begin{cases}
-1 & x<0\\
1 & x>0
Modified: trunk/docutils/test/functional/expected/math_output_html.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_html.html 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/test/functional/expected/math_output_html.html 2021-05-20 12:19:54 UTC (rev 8740)
@@ -140,40 +140,8 @@
</span>
</span>
</div>
-<p>Cases ("manually", with <tt class="docutils literal">matrix</tt> environment):</p>
+<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <tt class="docutils literal">cases</tt> environment:</p>
<div class="formula">
-<span class="mathrm">sgn</span>(<i>x</i>) = <span class="array"><span class="arrayrow"><span class="bracket align-left">⎧</span></span><span class="arrayrow"><span class="bracket align-left">⎨</span></span><span class="arrayrow"><span class="bracket align-left">⎩</span></span></span><span class="array"><span class="arrayrow">
-<span class="arraycell align-c">
- − 1
-</span>
-<span class="arraycell align-c">
-<i>x</i> < 0
-</span>
-
-</span>
-<span class="arrayrow">
-<span class="arraycell align-c">
-
-</span>
-<span class="arraycell align-c">
-
-</span>
-
-</span>
-<span class="arrayrow">
-<span class="arraycell align-c">
-1
-</span>
-<span class="arraycell align-c">
-<i>x</i> > 0
-</span>
-
-</span>
-</span><span class="emptydot"></span>
-</div>
-<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <tt class="docutils literal">cases</tt> environment (not (yet) supported by
-HTML writers with <tt class="docutils literal"><span class="pre">--math-output=MathML</span></tt>):</p>
-<div class="formula">
<span class="mathrm">sgn</span>(<i>x</i>) = <span class="array"><span class="arrayrow"><span class="bracket align-l">⎧</span></span><span class="arrayrow"><span class="bracket align-l">⎨</span></span><span class="arrayrow"><span class="bracket align-l">⎩</span></span></span><span class="bracketcases">
<span class="arrayrow">
<span class="case align-l">
Modified: trunk/docutils/test/functional/expected/math_output_latex.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_latex.html 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/test/functional/expected/math_output_latex.html 2021-05-20 12:19:54 UTC (rev 8740)
@@ -92,16 +92,8 @@
s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_\delta (x-x') \\
& = \int s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x'
</pre>
-<p>Cases ("manually", with <tt class="docutils literal">matrix</tt> environment):</p>
+<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <tt class="docutils literal">cases</tt> environment:</p>
<pre class="math">
-\mathrm{sgn}(x) = \left\{\begin{matrix}
- -1 & x<0\\
- 1 & x>0
- \end{matrix}\right.
-</pre>
-<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <tt class="docutils literal">cases</tt> environment (not (yet) supported by
-HTML writers with <tt class="docutils literal"><span class="pre">--math-output=MathML</span></tt>):</p>
-<pre class="math">
\mathrm{sgn}(x) = \begin{cases}
-1 & x<0\\
1 & x>0
Modified: trunk/docutils/test/functional/expected/math_output_mathjax.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathjax.html 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/test/functional/expected/math_output_mathjax.html 2021-05-20 12:19:54 UTC (rev 8740)
@@ -109,19 +109,9 @@
& = \int s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x'
\end{align*}
</div>
-<p>Cases ("manually", with <tt class="docutils literal">matrix</tt> environment):</p>
+<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <tt class="docutils literal">cases</tt> environment:</p>
<div class="math">
\begin{equation*}
-\mathrm{sgn}(x) = \left\{\begin{matrix}
- -1 & x<0\\
- 1 & x>0
- \end{matrix}\right.
-\end{equation*}
-</div>
-<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <tt class="docutils literal">cases</tt> environment (not (yet) supported by
-HTML writers with <tt class="docutils literal"><span class="pre">--math-output=MathML</span></tt>):</p>
-<div class="math">
-\begin{equation*}
\mathrm{sgn}(x) = \begin{cases}
-1 & x<0\\
1 & x>0
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:19:54 UTC (rev 8740)
@@ -515,7 +515,7 @@
</mtable>
</math>
</div>
-<p>Cases ("manually", with <span class="docutils literal">matrix</span> environment):</p>
+<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <span class="docutils literal">cases</span> environment:</p>
<div>
<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
<mtable class="align" displaystyle="true">
@@ -542,7 +542,6 @@
</mtd>
</mtr>
</mtable>
- <mo></mo>
</mrow>
</mtd>
</mtr>
@@ -549,19 +548,6 @@
</mtable>
</math>
</div>
-<p>Cases with the <a class="reference external" href="ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf">AMSmath</a> <span class="docutils literal">cases</span> environment (not (yet) supported by
-HTML writers with <span class="docutils literal"><span class="pre">--math-output=MathML</span></span>):</p>
-<div class="system-message">
-<p class="system-message-title">System Message: ERROR/3 (<span class="docutils literal">functional/input/data/math.txt</span>, line 108)</p>
-<p>
-Environment not supported! Supported environment: "matrix".</p>
-<pre class="literal-block">
-\mathrm{sgn}(x) = \begin{cases}
- -1 & x<0\\
- 1 & x>0
- \end{cases}
-</pre>
-</div>
</main>
</body>
</html>
Modified: trunk/docutils/test/functional/expected/standalone_rst_latex.tex
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_latex.tex 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/test/functional/expected/standalone_rst_latex.tex 2021-05-20 12:19:54 UTC (rev 8740)
@@ -1930,18 +1930,9 @@
s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_\delta (x-x') \\
& = \int s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x'
\end{align*}
-Cases (“manually”, with \texttt{matrix} environment):
+Cases with the \href{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf}{AMSmath}\DUfootnotemark{footnote-reference-15}{footnote-8}{7} \texttt{cases} environment:
%
\begin{equation*}
-\mathrm{sgn}(x) = \left\{\begin{matrix}
- -1 & x<0\\
- 1 & x>0
- \end{matrix}\right.
-\end{equation*}
-Cases with the \href{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf}{AMSmath}\DUfootnotemark{footnote-reference-15}{footnote-8}{7} \texttt{cases} environment (not (yet) supported by
-HTML writers with \texttt{-{}-math-output=MathML}):
-%
-\begin{equation*}
\mathrm{sgn}(x) = \begin{cases}
-1 & x<0\\
1 & x>0
Modified: trunk/docutils/test/functional/expected/standalone_rst_xetex.tex
===================================================================
--- trunk/docutils/test/functional/expected/standalone_rst_xetex.tex 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/test/functional/expected/standalone_rst_xetex.tex 2021-05-20 12:19:54 UTC (rev 8740)
@@ -1796,18 +1796,9 @@
s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_\delta (x-x') \\
& = \int s_{\mathrm{in}}(x')s_\delta (x-x')\mathrm{d}x'
\end{align*}
-Cases (“manually”, with \texttt{matrix} environment):
+Cases with the \href{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf}{AMSmath}\DUfootnotemark{footnote-reference-15}{footnote-8}{7} \texttt{cases} environment:
%
\begin{equation*}
-\mathrm{sgn}(x) = \left\{\begin{matrix}
- -1 & x<0\\
- 1 & x>0
- \end{matrix}\right.
-\end{equation*}
-Cases with the \href{ftp://ftp.ams.org/ams/doc/amsmath/short-math-guide.pdf}{AMSmath}\DUfootnotemark{footnote-reference-15}{footnote-8}{7} \texttt{cases} environment (not (yet) supported by
-HTML writers with \texttt{--math-output=MathML}):
-%
-\begin{equation*}
\mathrm{sgn}(x) = \begin{cases}
-1 & x<0\\
1 & x>0
Modified: trunk/docutils/test/functional/input/data/math.txt
===================================================================
--- trunk/docutils/test/functional/input/data/math.txt 2021-05-20 12:19:35 UTC (rev 8739)
+++ trunk/docutils/test/functional/input/data/math.txt 2021-05-20 12:19:54 UTC (rev 8740)
@@ -91,20 +91,10 @@
s_{\mathrm{out}}(x) & = s_{\mathrm{in}}(x') * s_δ(x-x') \\
& = ∫ s_{\mathrm{in}}(x')s_δ(x-x')\mathrm{d}x'
-Cases ("manually", with ``matrix`` environment):
+Cases with the AMSmath_ ``cases`` environment:
.. math::
- \mathrm{sgn}(x) = \left\{\begin{matrix}
- -1 & x<0\\
- 1 & x>0
- \end{matrix}\right.
-
-Cases with the AMSmath_ ``cases`` environment (not (yet) supported by
-HTML writers with ``--math-output=MathML``):
-
-.. math::
-
\mathrm{sgn}(x) = \begin{cases}
-1 & x<0\\
1 & x>0
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:20:22
|
Revision: 8741
http://sourceforge.net/p/docutils/code/8741
Author: milde
Date: 2021-05-20 12:20:20 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: make delimiters "non-strechy" by default. Fixes bug #407.
LaTeX lets delimiters grow to the size of the enclosed content
only, when they are arguments to ``\left`` or `\right``.
MathML streches delimiters inside ``mrow`` by default.
Add ``stretchy="false"`` to keep LaTeX and MathML appearance in sync.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/math_output_mathml.html
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:19:54 UTC (rev 8740)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:20:20 UTC (rev 8741)
@@ -175,35 +175,37 @@
r'\equiv': u'\u2262'}
# cmds/characters allowed in left/right cmds
-fence_args = {'(': '(',
- ')': ')',
- '[': '[',
- ']': ']',
- '/': '/',
- r'\backslash': '\\',
- '|': '|',
- '.': '', # emty fence
- r'\uparrow': u'\u2191', # ↑ UPWARDS ARROW
- r'\downarrow': u'\u2193', # ↓ DOWNWARDS ARROW
- r'\updownarrow': u'\u2195', # ↕ UP DOWN ARROW
- r'\Uparrow': u'\u21d1', # ⇑ UPWARDS DOUBLE ARROW
- r'\Downarrow': u'\u21d3', # ⇓ DOWNWARDS DOUBLE ARROW
- r'\Updownarrow': u'\u21d5', # ⇕ UP DOWN DOUBLE ARROW
+stretchables = {'(': '(',
+ ')': ')',
+ '[': '[',
+ ']': ']',
+ '/': '/',
+ r'\backslash': '\\',
+ '|': '|',
+ '.': '', # emty fence
+ r'\uparrow': u'\u2191', # ↑ UPWARDS ARROW
+ r'\downarrow': u'\u2193', # ↓ DOWNWARDS ARROW
+ r'\updownarrow': u'\u2195', # ↕ UP DOWN ARROW
+ r'\Uparrow': u'\u21d1', # ⇑ UPWARDS DOUBLE ARROW
+ r'\Downarrow': u'\u21d3', # ⇓ DOWNWARDS DOUBLE ARROW
+ r'\Updownarrow': u'\u21d5', # ⇕ UP DOWN DOUBLE ARROW
}
for (key, value) in tex2unichar.mathfence.items():
- fence_args['\\'+key] = value
+ stretchables['\\'+key] = value
for (key, value) in tex2unichar.mathopen.items():
- fence_args['\\'+key] = value
+ stretchables['\\'+key] = value
for (key, value) in tex2unichar.mathclose.items():
- fence_args['\\'+key] = value
+ stretchables['\\'+key] = value
# shorter with {**something} syntax, new in 3.5
# if sys.version_info >= (3, 5):
# for (key, value) in {**tex2unichar.mathclose,
# **tex2unichar.mathopen,
# **tex2unichar.mathfence}.items():
-# fence_args['\\'+key] = value
+# stretchables['\\'+key] = value
+# >>> print(' '.join(sorted(set(l2m.stretchables.values()))))
+# ( ) / [ \ ] { | } ‖ ↑ ↓ ↕ ⇑ ⇓ ⇕ ⌈ ⌉ ⌊ ⌋ ⌜ ⌝ ⌞ ⌟ ⟅ ⟆ ⟦ ⟧ ⟨ ⟩ ⟮ ⟯ ⦇ ⦈
# MathML element classes
# ----------------------
@@ -361,8 +363,9 @@
nchildren = 0
entity_table = {ord('<'): u'<', ord('>'): u'>'}
- def __init__(self, data):
+ def __init__(self, data, **kwargs):
self.data = data
+ super(mx, self).__init__(**kwargs)
def xml_body(self):
return [unicode(self.data).translate(self.entity_table)]
@@ -498,7 +501,9 @@
node = node.append(mi(c))
elif c.isdigit():
node = node.append(mn(c))
- elif c in "+-*/=()[]|<>,.!?':;@":
+ elif c in "/()[]|":
+ node = node.append(mo(c, stretchy='false'))
+ elif c in "+-*=<>,.!?':;@":
node = node.append(mo(c))
elif c == '_':
child = node.delete_child()
@@ -587,7 +592,7 @@
node.append(frac)
node = frac
elif name == 'left':
- for par in fence_args.keys():
+ for par in stretchables.keys():
if string.startswith(par):
break
else:
@@ -596,16 +601,16 @@
node.append(row)
node = row
if par != '.':
- node.append(mo(fence_args[par]))
+ node.append(mo(stretchables[par]))
skip += len(par)
elif name == 'right':
- for par in fence_args.keys():
+ for par in stretchables.keys():
if string.startswith(par):
break
else:
raise SyntaxError(u'Missing right-brace!')
if par != '.':
- node.append(mo(fence_args[par]))
+ node.append(mo(stretchables[par]))
node = node.close()
skip += len(par)
elif name == 'not':
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:19:54 UTC (rev 8740)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:20:20 UTC (rev 8741)
@@ -15,11 +15,11 @@
<p>Docutils supports inline math with the prefix or postfix <span class="docutils literal">:math:</span>
role specificator, <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
- <mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo>(</mo>
+ <mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo stretchy="false">(</mo>
<msubsup>
<mi>x</mi><mi>n</mi><mn>2</mn>
</msubsup>
- <mo>)</mo>
+ <mo stretchy="false">)</mo>
</mrow>
</math> and <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
@@ -46,7 +46,7 @@
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
- <mi>f</mi><mo>(</mo><mi>ϵ</mi><mo>)</mo><mo>=</mo>
+ <mi>f</mi><mo stretchy="false">(</mo><mi>ϵ</mi><mo stretchy="false">)</mo><mo>=</mo>
<mfrac>
<mrow>
<mn>1</mn>
@@ -138,13 +138,13 @@
</div>
<p>is <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
- <mo>|</mo>
+ <mo stretchy="false">|</mo>
<mstyle mathvariant="bold">
<mrow>
<mi>M</mi>
</mrow>
</mstyle>
- <mo>|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi>
+ <mo stretchy="false">|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi>
</mrow>
</math>.</p>
<p>More than one display math block can be put in one math directive.
@@ -189,7 +189,7 @@
<mi>n</mi><mo>=</mo>
<mfrac>
<mrow>
- <mi>m</mi><mo>(</mo><mi>m</mi><mo>+</mo><mn>1</mn><mo>)</mo>
+ <mi>m</mi><mo stretchy="false">(</mo><mi>m</mi><mo>+</mo><mn>1</mn><mo stretchy="false">)</mo>
</mrow>
<mrow>
<mn>2</mn>
@@ -386,12 +386,12 @@
<mo>|</mo>
<mfrac>
<mrow>
- <mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo>
+ <mi>ℱ</mi><mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
</mrow>
<mrow>
- <mi>ℱ</mi><mo>{</mo><mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mo>}</mo>
+ <mi>ℱ</mi><mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
<msub>
- <mo>|</mo>
+ <mo stretchy="false">|</mo>
<mrow>
<msub>
<mi>ω</mi>
@@ -420,7 +420,7 @@
<mo>∞</mo>
</mrow>
</munderover>
- <mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo>
+ <mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo>
<msup>
<mtext>e</mtext>
<mrow>
@@ -449,7 +449,7 @@
<mo>∞</mo>
</mrow>
</munderover>
- <mi>s</mi><mo>(</mo><mi>x</mi><mo>)</mo><mtext>d</mtext>
+ <mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mtext>d</mtext>
<mrow>
<mi>x</mi>
</mrow>
@@ -477,7 +477,7 @@
<mtext>out</mtext>
</mrow>
</msub>
- <mo>(</mo><mi>x</mi><mo>)</mo>
+ <mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo>
</mtd>
<mtd>
<mo>=</mo>
@@ -487,11 +487,11 @@
<mtext>in</mtext>
</mrow>
</msub>
- <mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo><mo>*</mo>
+ <mo stretchy="false">(</mo><mi>x</mi><mo>'</mo><mo stretchy="false">)</mo><mo>*</mo>
<msub>
<mi>s</mi><mi>δ</mi>
</msub>
- <mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo>
+ <mo stretchy="false">(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo stretchy="false">)</mo>
</mtd>
</mtr>
<mtr>
@@ -505,11 +505,11 @@
<mtext>in</mtext>
</mrow>
</msub>
- <mo>(</mo><mi>x</mi><mo>'</mo><mo>)</mo>
+ <mo stretchy="false">(</mo><mi>x</mi><mo>'</mo><mo stretchy="false">)</mo>
<msub>
<mi>s</mi><mi>δ</mi>
</msub>
- <mo>(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo>)</mo><mtext>d</mtext><mi>x</mi><mo>'</mo>
+ <mo stretchy="false">(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo stretchy="false">)</mo><mtext>d</mtext><mi>x</mi><mo>'</mo>
</mtd>
</mtr>
</mtable>
@@ -521,7 +521,7 @@
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
- <mtext>sgn</mtext><mo>(</mo><mi>x</mi><mo>)</mo><mo>=</mo>
+ <mtext>sgn</mtext><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo>
<mrow>
<mo>{</mo>
<mtable>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:21:00
|
Revision: 8743
http://sourceforge.net/p/docutils/code/8743
Author: milde
Date: 2021-05-20 12:20:54 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: Use <mi> for captial Greek letters.
Use ``<mi>`` (letters are identifiers) and set upright with
'mathvariant="normal"'.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/math_output_mathml.html
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:20:35 UTC (rev 8742)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:20:54 UTC (rev 8743)
@@ -689,9 +689,9 @@
elif name == 'colon': # "normal" colon, not binary operator
node = node.append(mo(':')) # TODO: add ``lspace="0pt"``
elif name in Greek: # Greek capitals (upright in "TeX style")
- node = node.append(mo(Greek[name]))
- # TODO: "ISO style" sets them italic. Could we use a class argument
- # to enable styling via CSS?
+ node = node.append(mi(Greek[name], mathvariant='normal'))
+ # TODO: "ISO style" sets them italic. Could we use a class argument?
+ # Unfortunately CSS styling does not change the font style in Firefox 78
elif name in letters:
node = node.append(mi(letters[name]))
elif name in special:
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:20:35 UTC (rev 8742)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:20:54 UTC (rev 8743)
@@ -217,7 +217,7 @@
<mo>∂</mo><mi>t</mi>
</mrow>
</mfrac>
- <mo>Ψ</mo><mo>=</mo>
+ <mi mathvariant="normal">Ψ</mi><mo>=</mo>
<mover>
<mrow>
<mi>H</mi>
@@ -224,7 +224,7 @@
</mrow>
<mo>^</mo>
</mover>
- <mo>Ψ</mo><mo>,</mo>
+ <mi mathvariant="normal">Ψ</mi><mo>,</mo>
</mtd>
</mtr>
</mtable>
@@ -232,7 +232,7 @@
</div>
<p>with the <em>wave function</em> <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
- <mo>Ψ</mo>
+ <mi mathvariant="normal">Ψ</mi>
</mrow>
</math>, describes how the quantum state of a
physical system changes in time.</p>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:21:11
|
Revision: 8744
http://sourceforge.net/p/docutils/code/8744
Author: milde
Date: 2021-05-20 12:21:11 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: auxiliary TeX parsing functions, cleanup.
New functions that help parsing a (La)TeX string.
Skip <mrow> inside <mstyle>.
Fix repr() of token elements.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/math_output_mathml.html
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:20:54 UTC (rev 8743)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:21:11 UTC (rev 8744)
@@ -25,6 +25,7 @@
# >>> import latex2mathml as l2m
import collections
+import re
import sys
if sys.version_info >= (3, 0):
unicode = str # noqa
@@ -32,8 +33,8 @@
from docutils.utils.math import tex2unichar
-# Metadata
-# --------
+# Command lists and dictionaries
+# ------------------------------
# TeX spacing combining
over = {'acute': u'\u00B4', # u'\u0301',
@@ -51,7 +52,7 @@
'tilde': u'\u02DC', # u'\u0303',
'vec': u'\u20D7'}
-Greek = { # Capital Greek letters: (upright in TeX style)
+greek_capitals = { # Capital Greek letters: (upright in TeX style)
'Phi':u'\u03a6', 'Xi':u'\u039e', 'Sigma':u'\u03a3',
'Psi':u'\u03a8', 'Delta':u'\u0394', 'Theta':u'\u0398',
'Upsilon':u'\u03d2', 'Pi':u'\u03a0', 'Omega':u'\u03a9',
@@ -230,7 +231,6 @@
r'\Uparrow': u'\u21d1', # ⇑ UPWARDS DOUBLE ARROW
r'\Downarrow': u'\u21d3', # ⇓ DOWNWARDS DOUBLE ARROW
r'\Updownarrow': u'\u21d5', # ⇕ UP DOWN DOUBLE ARROW
-
}
for (key, value) in tex2unichar.mathfence.items():
stretchables['\\'+key] = value
@@ -248,6 +248,7 @@
# >>> print(' '.join(sorted(set(l2m.stretchables.values()))))
# ( ) / [ \ ] { | } ‖ ↑ ↓ ↕ ⇑ ⇓ ⇕ ⌈ ⌉ ⌊ ⌋ ⌜ ⌝ ⌞ ⌟ ⟅ ⟆ ⟦ ⟧ ⟨ ⟩ ⟮ ⟯ ⦇ ⦈
+
# MathML element classes
# ----------------------
@@ -255,7 +256,7 @@
"""Base class for MathML elements."""
nchildren = 1000000
- """Required number of children"""
+ """Required/Supported number of children"""
_level = 0 # indentation level (static class variable)
def __init__(self, children=None, inline=None, **kwargs):
@@ -284,7 +285,7 @@
def __repr__(self):
content = [repr(item) for item in getattr(self, 'children', [])]
if hasattr(self, 'data'):
- content.append(str(self.data))
+ content.append(repr(self.data))
if hasattr(self, 'attributes'):
content += ["%s='%s'"%(k, v) for k, v in self.attributes.items()]
return self.__class__.__name__ + '(%s)' % ', '.join(content)
@@ -417,7 +418,7 @@
class mtext(mx): pass
# >>> l2m.mo(u'<')
-# mo(<)
+# mo('<')
# >>> l2m.mo(u'<').xml()
# ['<mo>', '<', '</mo>']
@@ -479,24 +480,75 @@
def __init__(self, children=None):
math.__init__(self, children)
+
# LaTeX to MathML translation
# ---------------------------
+# auxiliary functions
+# ~~~~~~~~~~~~~~~~~~~
+
+def tex_cmdname(string):
+ """Return leading TeX command name from `string`.
+ """
+ name = re.match(r'([a-zA-Z]+|.?)', string)
+ return name.group(0)
+
+# >>> l2m.tex_cmdname('m2') # first non-letter terminates
+# 'm'
+# >>> l2m.tex_cmdname('m_2') # first non-letter terminates
+# 'm'
+# >>> l2m.tex_cmdname('m 2') # first non-letter terminates
+# 'm'
+# >>> l2m.tex_cmdname('_2') # single non-letter character
+# '_'
+# >>> l2m.tex_cmdname(' 2') # single non-letter character
+# ' '
+# >>> l2m.tex_cmdname('') # empty string
+# ''
+
+def tex_token(string):
+ """Return first simple TeX token from `string`.
+ """
+ token = re.match(r"""({([^{]|\\{)*} # {group} without nested groups
+ |\\([a-zA-Z]+|.) # or \cmdname
+ |.?) # or first character or empty
+ """, string, re.VERBOSE)
+ return token.group(0)
+
+# What is returned?
+#
+# >>> l2m.tex_token(r'\command{without argument}')
+# '\\command'
+# >>> l2m.tex_token('\\nor trailing whitespace, or')
+# '\\nor'
+# >>> l2m.tex_token('{first simple group} or')
+# '{first simple group}'
+# >>> l2m.tex_token('{opening bracket of group with {nested group}} or')
+# '{'
+# >>> l2m.tex_token('{group with \\{escaped\\} brackets} or')
+# '{group with \\{escaped\\} brackets}'
+# >>> l2m.tex_token('first character, or')
+# 'f'
+# >>> l2m.tex_token('') # empty string
+# ''
+
+
def parse_latex_math(string, inline=True):
"""parse_latex_math(string [,inline]) -> MathML-tree
Returns a MathML-tree parsed from string. inline=True is for
inline math and inline=False is for displayed math.
+ """
- tree is the whole tree and node is the current element."""
-
# Normalize white-space:
string = ' '.join(string.split())
+ # Set up: tree is the whole tree and node is the current element.
if inline:
node = mrow()
tree = math(node, inline=True)
else:
+ # block: emulate align* environment with a math table
node = mtd()
content = mtable(mtr(node), displaystyle='true', CLASS='align')
tree = math(content, inline=False)
@@ -505,13 +557,14 @@
n = len(string)
c = string[0]
skip = 1 # number of characters consumed
- if n > 1:
- c2 = string[1]
- else:
- c2 = ''
+
if c == ' ':
pass
elif c == '\\':
+ if n > 1:
+ c2 = string[1]
+ else:
+ c2 = ''
if c2 in '{}':
node = node.append(mo(c2))
skip = 2
@@ -584,12 +637,18 @@
string = string[skip:]
return tree
+# >>> l2m.parse_latex_math('\\alpha')
+# math(mrow(mi('α')), xmlns='http://www.w3.org/1998/Math/MathML')
+# >>> l2m.parse_latex_math(' \\sqrt{ \\alpha}')
+# math(mrow(msqrt(mrow(mi('α')))), xmlns='http://www.w3.org/1998/Math/MathML')
def handle_keyword(name, node, string):
skip = 0
- if len(string) > 0 and string[0] == ' ':
+ if string.startswith(' '):
+ # remove leading whitespace (already normalized to " "):
string = string[1:]
skip = 1
+
if name == 'begin':
if string.startswith('{matrix}'):
skip += 8
@@ -630,40 +689,37 @@
frac = mfrac()
node.append(frac)
node = frac
- elif name == 'left':
- for par in stretchables.keys():
- if string.startswith(par):
- break
- else:
- raise SyntaxError(u'Missing left-brace!')
- row = mrow()
- node.append(row)
- node = row
- if par != '.':
- node.append(mo(stretchables[par]))
- skip += len(par)
- elif name == 'right':
- for par in stretchables.keys():
- if string.startswith(par):
- break
- else:
- raise SyntaxError(u'Missing right-brace!')
- if par != '.':
- node.append(mo(stretchables[par]))
- node = node.close()
- skip += len(par)
+ elif name in ('left', 'right'):
+ arg = tex_token(string)
+ try:
+ delimiter = stretchables[arg]
+ except KeyError:
+ raise SyntaxError(u'Missing %s delimiter!' % name)
+ if name == 'left':
+ row = mrow()
+ node.append(row)
+ node = row
+ if delimiter:
+ node.append(mo(delimiter))
+ if name == 'right':
+ node = node.close()
+ skip += len(arg)
elif name == 'not':
- for operator in negatables:
- if string.startswith(operator):
- break
- else:
+ arg = tex_token(string)
+ try:
+ node = node.append(mo(negatables[arg.rstrip()]))
+ except KeyError:
raise SyntaxError(u'Expected something to negate: "\\not ..."!')
- node = node.append(mo(negatables[operator]))
- skip += len(operator)
+ skip += len(arg)
elif name == 'mathbf':
- style = mstyle(nchildren=1, mathvariant='bold')
+ if string.startswith('{'):
+ nchildren = None
+ else:
+ nchildren = 1
+ style = mstyle(nchildren=nchildren, mathvariant='bold')
node.append(style)
node = style
+ skip += 1
elif name == 'mathbb':
i = string.find('}')
if string[0] != '{' or i == -1:
@@ -688,8 +744,8 @@
skip += i + 1
elif name == 'colon': # "normal" colon, not binary operator
node = node.append(mo(':')) # TODO: add ``lspace="0pt"``
- elif name in Greek: # Greek capitals (upright in "TeX style")
- node = node.append(mi(Greek[name], mathvariant='normal'))
+ elif name in greek_capitals: # Greek capitals (upright in "TeX style")
+ node = node.append(mi(greek_capitals[name], mathvariant='normal'))
# TODO: "ISO style" sets them italic. Could we use a class argument?
# Unfortunately CSS styling does not change the font style in Firefox 78
elif name in letters:
@@ -707,6 +763,20 @@
return node, skip
+# >>> l2m.handle_keyword('left', l2m.math(), '[a\right]')
+# (mrow(mo('[')), 1)
+# >>> l2m.handle_keyword('left', l2m.math(), '(a)')[0].xml()
+# ['<mrow>', '\n ', '<mo>', '(', '</mo>', '\n', '</mrow>']
+# >>> l2m.handle_keyword('left', l2m.math(), '. a)') # emtpy \left
+# (mrow(), 1)
+# >>> l2m.handle_keyword('left', l2m.math(), r'\uparrow. a)') # cmd
+# (mrow(mo('↑')), 8)
+# >>> l2m.handle_keyword('not', l2m.math(), r'\equiv a)') # cmd
+# (math(mo('≢')), 6)
+# >>> l2m.handle_keyword('text', l2m.math(), r'{for} i \in S)') # cmd
+# (math(mtext('for')), 5)
+
+
def tex2mathml(tex_math, inline=True):
"""Return string with MathML code corresponding to `tex_math`.
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:20:54 UTC (rev 8743)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:21:11 UTC (rev 8744)
@@ -104,9 +104,7 @@
<mtr>
<mtd>
<mstyle mathvariant="bold">
- <mrow>
- <mi>M</mi>
- </mrow>
+ <mi>M</mi>
</mstyle>
<mo>=</mo>
<mrow>
@@ -140,9 +138,7 @@
<mrow>
<mo stretchy="false">|</mo>
<mstyle mathvariant="bold">
- <mrow>
- <mi>M</mi>
- </mrow>
+ <mi>M</mi>
</mstyle>
<mo stretchy="false">|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi>
</mrow>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:21:33
|
Revision: 8745
http://sourceforge.net/p/docutils/code/8745
Author: milde
Date: 2021-05-20 12:21:30 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: support space commands, fix math alphabets, cleanup.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/math_output_mathml.html
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:21:11 UTC (rev 8744)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:21:30 UTC (rev 8745)
@@ -79,11 +79,29 @@
'exp', 'gcd', 'hom', 'inf', 'ker', 'lg',
'lim', 'liminf', 'limsup', 'ln', 'log', 'max',
'min', 'Pr', 'sec', 'sin', 'sinh', 'sup',
- 'tan', 'tanh',
- 'injlim', 'varinjlim', 'varlimsup',
- 'projlim', 'varliminf', 'varprojlim']
+ 'tan', 'tanh', 'injlim', 'varinjlim', 'projlim',
+ 'varlimsup', 'varliminf', 'varprojlim']
+math_alphabets = {# 'cmdname': 'mathvariant value' # package
+ 'boldsymbol': 'bold',
+ 'mathbb': 'double-struck', # amssymb
+ 'mathbf': 'bold',
+ 'mathcal': 'script',
+ 'mathfrak': 'fraktur', # amssymb
+ 'mathit': 'italic',
+ 'mathrm': 'normal',
+ 'mathscr': 'script', # mathrsfs
+ 'mathsf': 'sans-serif',
+ 'mathtt': 'monospace',
+ 'mathbfit': 'bold-italic', # isomath
+ 'mathsfit': 'sans-serif-italic', # isomath
+ 'mathsfbfit': 'sans-serif-bold-italic', # isomath
+ # unsupported: bold-fraktur
+ # bold-script
+ # bold-sans-serif
+ }
+
mathbb = {
'0': u'\U0001D7D8', # 𝟘
'1': u'\U0001D7D9', # 𝟙
@@ -152,66 +170,13 @@
u'Σ': u'\u2140', # ⅀
u'γ': u'\u213D', # ℽ
u'π': u'\u213C', # ℼ
+ r'\Gamma': u'\u213E', # ℾ
+ r'\Pi': u'\u213F', # ℿ
+ r'\Sigma': u'\u2140', # ⅀
+ r'\gamma': u'\u213D', # ℽ
+ r'\pi': u'\u213C', # ℼ
}
-mathscr = {
- 'A': u'\U0001D49C',
- 'B': u'\u212C', # bernoulli function
- 'C': u'\U0001D49E',
- 'D': u'\U0001D49F',
- 'E': u'\u2130',
- 'F': u'\u2131',
- 'G': u'\U0001D4A2',
- 'H': u'\u210B', # hamiltonian
- 'I': u'\u2110',
- 'J': u'\U0001D4A5',
- 'K': u'\U0001D4A6',
- 'L': u'\u2112', # lagrangian
- 'M': u'\u2133', # physics m-matrix
- 'N': u'\U0001D4A9',
- 'O': u'\U0001D4AA',
- 'P': u'\U0001D4AB',
- 'Q': u'\U0001D4AC',
- 'R': u'\u211B',
- 'S': u'\U0001D4AE',
- 'T': u'\U0001D4AF',
- 'U': u'\U0001D4B0',
- 'V': u'\U0001D4B1',
- 'W': u'\U0001D4B2',
- 'X': u'\U0001D4B3',
- 'Y': u'\U0001D4B4',
- 'Z': u'\U0001D4B5',
- 'a': u'\U0001D4B6',
- 'b': u'\U0001D4B7',
- 'c': u'\U0001D4B8',
- 'd': u'\U0001D4B9',
- 'e': u'\u212F',
- 'f': u'\U0001D4BB',
- 'g': u'\u210A',
- 'h': u'\U0001D4BD',
- 'i': u'\U0001D4BE',
- 'j': u'\U0001D4BF',
- 'k': u'\U0001D4C0',
- 'l': u'\U0001D4C1',
- 'm': u'\U0001D4C2',
- 'n': u'\U0001D4C3',
- 'o': u'\u2134', # order of
- 'p': u'\U0001D4C5',
- 'q': u'\U0001D4C6',
- 'r': u'\U0001D4C7',
- 's': u'\U0001D4C8',
- 't': u'\U0001D4C9',
- 'u': u'\U0001D4CA',
- 'v': u'\U0001D4CB',
- 'w': u'\U0001D4CC',
- 'x': u'\U0001D4CD',
- 'y': u'\U0001D4CE',
- 'z': u'\U0001D4CF',
- }
-
-# >>> print(''.join(l2m.mathscr.values()))
-# 𝒜ℬ𝒞𝒟ℰℱ𝒢ℋℐ𝒥𝒦ℒℳ𝒩𝒪𝒫𝒬ℛ𝒮𝒯𝒰𝒱𝒲𝒳𝒴𝒵𝒶𝒷𝒸𝒹ℯ𝒻ℊ𝒽𝒾𝒿𝓀𝓁𝓂𝓃ℴ𝓅𝓆𝓇𝓈𝓉𝓊𝓋𝓌𝓍𝓎𝓏
-
negatables = {'=': u'\u2260',
r'\in': u'\u2209',
r'\equiv': u'\u2262'}
@@ -248,6 +213,21 @@
# >>> print(' '.join(sorted(set(l2m.stretchables.values()))))
# ( ) / [ \ ] { | } ‖ ↑ ↓ ↕ ⇑ ⇓ ⇕ ⌈ ⌉ ⌊ ⌋ ⌜ ⌝ ⌞ ⌟ ⟅ ⟆ ⟦ ⟧ ⟨ ⟩ ⟮ ⟯ ⦇ ⦈
+spaces = {'qquad': '2em', # two \quad
+ 'quad': '1em', # 18 mu
+ 'qquad': '2em', # two \quad
+ 'thickspace': '0.2778em', # 5mu = 5/18em
+ 'medspace': '0.2222em', # 4mu = 2/9em
+ 'thinspace': '0.1667em', # 3mu = 1/6em
+ 'negthinspace': '-0.1667em', # -3mu = -1/6em
+ 'negmedspace': '-0.2222em', # -4mu = -2/9em
+ 'negthickspace': '-0.2778em', # -5mu = -5/18em
+ ' ': '0.25em', # inter word space
+ ';': '0.2778em', # thickspace
+ ':': '0.2222em', # medspace
+ ',': '0.1667em', # thinspace
+ '!': '-0.1667em', # negthinspace
+ }
# MathML element classes
# ----------------------
@@ -509,9 +489,9 @@
def tex_token(string):
"""Return first simple TeX token from `string`.
"""
- token = re.match(r"""({([^{]|\\{)*} # {group} without nested groups
- |\\([a-zA-Z]+|.) # or \cmdname
- |.?) # or first character or empty
+ token = re.match(r"""({(\\}|[^{}]|\\{)*} # {group} without nested groups
+ |\\([a-zA-Z]+|.) # or \cmdname
+ |.?) # or first character/empty string
""", string, re.VERBOSE)
return token.group(0)
@@ -521,7 +501,7 @@
# '\\command'
# >>> l2m.tex_token('\\nor trailing whitespace, or')
# '\\nor'
-# >>> l2m.tex_token('{first simple group} or')
+# >>> l2m.tex_token('{first simple group} or')
# '{first simple group}'
# >>> l2m.tex_token('{opening bracket of group with {nested group}} or')
# '{'
@@ -531,8 +511,27 @@
# 'f'
# >>> l2m.tex_token('') # empty string
# ''
+#
+# test:
+# >>> l2m.tex_token('{group followed by closing bracket}} from outer group')
+# '{group followed by closing bracket}'
+def strip_brackets(string):
+ """Strip outer brackets from `string`."""
+ if string.startswith('{') and string.endswith('}'):
+ return string[1:-1]
+ return string
+# >>> l2m.strip_brackets('{a}')
+# 'a'
+# >>> l2m.strip_brackets('a')
+# 'a'
+# >>> l2m.strip_brackets('{a')
+# '{a'
+# >>> l2m.strip_brackets('{a}}')
+# 'a}'
+
+
def parse_latex_math(string, inline=True):
"""parse_latex_math(string [,inline]) -> MathML-tree
@@ -554,43 +553,15 @@
tree = math(content, inline=False)
while len(string) > 0:
- n = len(string)
- c = string[0]
- skip = 1 # number of characters consumed
-
+ # Take of first character:
+ c, string = string[0], string[1:]
if c == ' ':
pass
- elif c == '\\':
- if n > 1:
- c2 = string[1]
- else:
- c2 = ''
- if c2 in '{}':
- node = node.append(mo(c2))
- skip = 2
- elif c2 == ' ':
- node = node.append(mspace())
- skip = 2
- elif c2 == ',': # TODO: small space
- node = node.append(mspace())
- skip = 2
- elif c2.isalpha():
- # We have a LaTeX-name:
- i = 2
- while i < n and string[i].isalpha():
- i += 1
- name = string[1:i]
- node, skip = handle_keyword(name, node, string[i:])
- skip += i
- elif c2 == '\\':
- # End of a row:
- entry = mtd()
- row = mtr(entry)
- node.close().close().append(row)
- node = entry
- skip = 2
- else:
- raise SyntaxError(u'Syntax error: "%s%s"' % (c, c2))
+ elif c == '\\': # start of a LaTeX macro
+ name = tex_cmdname(string)
+ string = string[len(name):]
+ node, skip = handle_keyword(name, node, string)
+ string = string[skip:]
elif c.isalpha():
node = node.append(mi(c))
elif c.isdigit():
@@ -634,7 +605,6 @@
node = entry
else:
raise SyntaxError(u'Illegal character: "%s"' % c)
- string = string[skip:]
return tree
# >>> l2m.parse_latex_math('\\alpha')
@@ -644,20 +614,19 @@
def handle_keyword(name, node, string):
skip = 0
- if string.startswith(' '):
+ if string.startswith(' '):
# remove leading whitespace (already normalized to " "):
string = string[1:]
skip = 1
-
+ arg = tex_token(string) # argument: single letter, \cmd, or {group}
+
if name == 'begin':
if string.startswith('{matrix}'):
- skip += 8
entry = mtd()
table = mtable(mtr(entry))
node.append(table)
node = entry
elif string.startswith('{cases}'):
- skip += 7
entry = mtd()
cases = mrow([mo('{'), mtable(mtr(entry))])
node.append(cases)
@@ -665,22 +634,47 @@
else:
raise SyntaxError(u'Environment not supported! '
u'Supported environments: "matrix", "cases".')
+ skip += len(arg)
elif name == 'end':
if string.startswith('{matrix}'):
- skip += 8
node = node.close().close().close()
elif string.startswith('{cases}'):
- skip += 7
node = node.close().close().close().close()
else:
raise SyntaxError(u'Environment not supported! '
u'Supported environments: "matrix", "cases".')
- elif name in ('text', 'mbox', 'mathrm'):
- i = string.find('}')
- if string[0] != '{' or i == -1:
- raise SyntaxError(u'Expected "\\%s{...}"!'%name)
- node = node.append(mtext(string[1:i]))
- skip += i + 1
+ skip += len(arg)
+ elif name in ('text', 'mbox', 'textrm'):
+ text = arg.replace('{ ', ' ', 1).replace(' }', ' ', 1)
+ node = node.append(mtext(strip_brackets(text)))
+ skip += len(arg)
+ elif name == 'mathrm': # upright identifier
+ # https://www.w3.org/TR/MathML3/chapter3.html#presm.mi
+ node = node.append(mi(strip_brackets(arg), mathvariant='normal'))
+ # node = node.append(mo(strip_brackets(arg)))
+ skip += len(arg)
+ elif name == 'operatorname':
+ # use <mi> (see https://www.w3.org/TR/MathML3/chapter3.html#presm.mi)
+ node = node.append(mi(strip_brackets(arg), mathvariant='normal'))
+ node = node.append(mo('⁡'))
+ skip += len(arg)
+ elif name == 'mathbb':
+ chs = strip_brackets(arg)
+ while chs:
+ c = tex_token(chs)
+ chs = chs[len(c):]
+ try:
+ node = node.append(mi(mathbb[c]))
+ except KeyError:
+ raise SyntaxError(u'Character "%s" not supported '
+ u'in "\\mathbb{}"!' % c)
+ skip += len(arg)
+ elif name in math_alphabets.keys():
+ n_c = None if string.startswith('{') else 1
+ style = mstyle(nchildren=n_c, mathvariant=math_alphabets[name])
+ node.append(style)
+ node = style
+ skip += 1
elif name == 'sqrt':
sqrt = msqrt()
node.append(sqrt)
@@ -689,8 +683,15 @@
frac = mfrac()
node.append(frac)
node = frac
+ elif name in '{}':
+ node = node.append(mo(name))
+ elif name == '\\':
+ # End of a row:
+ entry = mtd()
+ row = mtr(entry)
+ node.close().close().append(row)
+ node = entry
elif name in ('left', 'right'):
- arg = tex_token(string)
try:
delimiter = stretchables[arg]
except KeyError:
@@ -705,55 +706,31 @@
node = node.close()
skip += len(arg)
elif name == 'not':
- arg = tex_token(string)
try:
- node = node.append(mo(negatables[arg.rstrip()]))
+ node = node.append(mo(negatables[strip_brackets(arg)]))
except KeyError:
raise SyntaxError(u'Expected something to negate: "\\not ..."!')
skip += len(arg)
- elif name == 'mathbf':
- if string.startswith('{'):
- nchildren = None
- else:
- nchildren = 1
- style = mstyle(nchildren=nchildren, mathvariant='bold')
- node.append(style)
- node = style
- skip += 1
- elif name == 'mathbb':
- i = string.find('}')
- if string[0] != '{' or i == -1:
- raise SyntaxError(u'Expected "\\mathbb{...}"!')
- try:
- bbchars = ''.join(mathbb[c] for c in string[1:i])
- except KeyError:
- raise SyntaxError(u'Character "%s" not supportd in "\\mathbb{}"!'
- %[c for c in string[1:i] if c not in mathbb][0])
- node = node.append(mi(bbchars))
- skip += i + 1
- elif name in ('mathscr', 'mathcal'):
- i = string.find('}')
- if string[0] != '{' or i == -1:
- raise SyntaxError(u'Expected "\\%s{...}"!'%name)
- try:
- scrchars = ''.join(mathscr[c] for c in string[1:i])
- except KeyError:
- raise SyntaxError(u'Character "%s" not supportd in "\\%s{}"!'
- %([c for c in string[1:i] if c not in mathscr][0], name))
- node = node.append(mi(scrchars))
- skip += i + 1
elif name == 'colon': # "normal" colon, not binary operator
- node = node.append(mo(':')) # TODO: add ``lspace="0pt"``
+ node = node.append(mo(':', lspace='0', rspace='0.28em'))
+ elif name in spaces.keys():
+ node = node.append(mspace(width='%s'%spaces[name]))
+ elif name == 'hspace':
+ node = node.append(mspace(width='%s'%strip_brackets(arg)))
+ skip += len(arg)
elif name in greek_capitals: # Greek capitals (upright in "TeX style")
- node = node.append(mi(greek_capitals[name], mathvariant='normal'))
- # TODO: "ISO style" sets them italic. Could we use a class argument?
- # Unfortunately CSS styling does not change the font style in Firefox 78
+ node = node.append(mi(greek_capitals[name], CLASS='capital-greek'))
+ # TODO: Use 'mathvariant="normal"'?
+ # MathML sets them italic (ISO style).
+ # CSS styling does not change the font style in Firefox 78.
elif name in letters:
node = node.append(mi(letters[name]))
elif name in special:
node = node.append(mo(special[name]))
elif name in functions:
- node = node.append(mo(name))
+ # use <mi> (see https://www.w3.org/TR/MathML3/chapter3.html#presm.mi)
+ node = node.append(mi(name))
+ node = node.append(mo('⁡'))
elif name in over:
ovr = mover(mo(over[name]), reversed=True)
node.append(ovr)
@@ -773,10 +750,21 @@
# (mrow(mo('↑')), 8)
# >>> l2m.handle_keyword('not', l2m.math(), r'\equiv a)') # cmd
# (math(mo('≢')), 6)
-# >>> l2m.handle_keyword('text', l2m.math(), r'{for} i \in S)') # cmd
-# (math(mtext('for')), 5)
+# >>> l2m.handle_keyword('text', l2m.math(), r'{ for } i>0)') # group
+# (math(mtext(' for ')), 7)
+# >>> l2m.handle_keyword('text', l2m.math(), r'{B}T') # group
+# (math(mtext('B')), 3)
+# >>> l2m.handle_keyword('text', l2m.math(), r'{number of apples}}') # group
+# (math(mtext('number of apples')), 18)
+# >>> l2m.handle_keyword('text', l2m.math(), r'i \sin(x)') # single char
+# (math(mtext('i')), 1)
+# >>> l2m.handle_keyword('operatorname', l2m.math(), r'{abs}(x)')
+# (math(mi('abs', mathvariant='normal'), mo('⁡')), 5)
+# >>> l2m.handle_keyword('hspace', l2m.math(), r'{1ex} (x)')
+# (math(mspace(width='1ex')), 5)
+# >>> l2m.handle_keyword('not', l2m.math(), r'{=} x')
+# (math(mo('≠')), 3)
-
def tex2mathml(tex_math, inline=True):
"""Return string with MathML code corresponding to `tex_math`.
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:21:11 UTC (rev 8744)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:21:30 UTC (rev 8745)
@@ -15,7 +15,7 @@
<p>Docutils supports inline math with the prefix or postfix <span class="docutils literal">:math:</span>
role specificator, <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
- <mi>n</mi><mo>!</mo><mo>+</mo><mo>sin</mo><mo stretchy="false">(</mo>
+ <mi>n</mi><mo>!</mo><mo>+</mo><mi>sin</mi><mo>⁡</mo><mo stretchy="false">(</mo>
<msubsup>
<mi>x</mi><mi>n</mi><mn>2</mn>
</msubsup>
@@ -52,7 +52,7 @@
<mn>1</mn>
</mrow>
<mrow>
- <mn>1</mn><mo>+</mo><mo>exp</mo>
+ <mn>1</mn><mo>+</mo><mi>exp</mi><mo>⁡</mo>
<mrow>
<mo>(</mo>
<mfrac>
@@ -213,7 +213,7 @@
<mo>∂</mo><mi>t</mi>
</mrow>
</mfrac>
- <mi mathvariant="normal">Ψ</mi><mo>=</mo>
+ <mi class="capital-greek">Ψ</mi><mo>=</mo>
<mover>
<mrow>
<mi>H</mi>
@@ -220,7 +220,7 @@
</mrow>
<mo>^</mo>
</mover>
- <mi mathvariant="normal">Ψ</mi><mo>,</mo>
+ <mi class="capital-greek">Ψ</mi><mo>,</mo>
</mtd>
</mtr>
</mtable>
@@ -228,7 +228,7 @@
</div>
<p>with the <em>wave function</em> <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
- <mi mathvariant="normal">Ψ</mi>
+ <mi class="capital-greek">Ψ</mi>
</mrow>
</math>, describes how the quantum state of a
physical system changes in time.</p>
@@ -382,10 +382,16 @@
<mo>|</mo>
<mfrac>
<mrow>
- <mi>ℱ</mi><mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
+ <mstyle mathvariant="script">
+ <mi>F</mi>
+ </mstyle>
+ <mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
</mrow>
<mrow>
- <mi>ℱ</mi><mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
+ <mstyle mathvariant="script">
+ <mi>F</mi>
+ </mstyle>
+ <mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
<msub>
<mo stretchy="false">|</mo>
<mrow>
@@ -402,7 +408,7 @@
</mfrac>
<mo>|</mo>
</mrow>
- <mo>=</mo><mtext>abs</mtext>
+ <mo>=</mo><mi mathvariant="normal">abs</mi>
<mrow>
<mo>(</mo>
<mfrac>
@@ -418,9 +424,9 @@
</munderover>
<mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo>
<msup>
- <mtext>e</mtext>
+ <mi mathvariant="normal">e</mi>
<mrow>
- <mtext>i</mtext>
+ <mi mathvariant="normal">i</mi>
<msub>
<mi>ω</mi>
<mrow>
@@ -430,7 +436,7 @@
<mi>x</mi>
</mrow>
</msup>
- <mtext>d</mtext>
+ <mi mathvariant="normal">d</mi>
<mrow>
<mi>x</mi>
</mrow>
@@ -445,7 +451,7 @@
<mo>∞</mo>
</mrow>
</munderover>
- <mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mtext>d</mtext>
+ <mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mi mathvariant="normal">d</mi>
<mrow>
<mi>x</mi>
</mrow>
@@ -470,7 +476,7 @@
<msub>
<mi>s</mi>
<mrow>
- <mtext>out</mtext>
+ <mi mathvariant="normal">out</mi>
</mrow>
</msub>
<mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo>
@@ -480,7 +486,7 @@
<msub>
<mi>s</mi>
<mrow>
- <mtext>in</mtext>
+ <mi mathvariant="normal">in</mi>
</mrow>
</msub>
<mo stretchy="false">(</mo><mi>x</mi><mo>'</mo><mo stretchy="false">)</mo><mo>*</mo>
@@ -498,7 +504,7 @@
<msub>
<mi>s</mi>
<mrow>
- <mtext>in</mtext>
+ <mi mathvariant="normal">in</mi>
</mrow>
</msub>
<mo stretchy="false">(</mo><mi>x</mi><mo>'</mo><mo stretchy="false">)</mo>
@@ -505,7 +511,7 @@
<msub>
<mi>s</mi><mi>δ</mi>
</msub>
- <mo stretchy="false">(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo stretchy="false">)</mo><mtext>d</mtext><mi>x</mi><mo>'</mo>
+ <mo stretchy="false">(</mo><mi>x</mi><mo>-</mo><mi>x</mi><mo>'</mo><mo stretchy="false">)</mo><mi mathvariant="normal">d</mi><mi>x</mi><mo>'</mo>
</mtd>
</mtr>
</mtable>
@@ -517,7 +523,7 @@
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
- <mtext>sgn</mtext><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo>
+ <mi mathvariant="normal">sgn</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>=</mo>
<mrow>
<mo>{</mo>
<mtable>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2021-05-20 12:22:07
|
Revision: 8747
http://sourceforge.net/p/docutils/code/8747
Author: milde
Date: 2021-05-20 12:22:05 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML update: math alphabets, tex_token(), add documentation.
* math alphabets: Use token elements for single symbols or names.
* tex_token: skip whitespace after command names.
* comprehensive documentation/test document.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/math_output_mathml.html
Added Paths:
-----------
trunk/docutils/test/functional/input/data/comprehensive-math-test.txt
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:21:48 UTC (rev 8746)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:22:05 UTC (rev 8747)
@@ -80,70 +80,7 @@
}
# blackboar bold (Greek characters not working with "mathvariant" (Firefox 78)
-mathbb = {
- '0': u'\U0001D7D8', # 𝟘
- '1': u'\U0001D7D9', # 𝟙
- '2': u'\U0001D7DA', # 𝟚
- '3': u'\U0001D7DB', # 𝟛
- '4': u'\U0001D7DC', # 𝟜
- '5': u'\U0001D7DD', # 𝟝
- '6': u'\U0001D7DE', # 𝟞
- '7': u'\U0001D7DF', # 𝟟
- '8': u'\U0001D7E0', # 𝟠
- '9': u'\U0001D7E1', # 𝟡
- 'A': u'\U0001D538', # 𝔸
- 'B': u'\U0001D539', # 𝔹
- 'C': u'\u2102', # ℂ
- 'D': u'\U0001D53B', # 𝔻
- 'E': u'\U0001D53C', # 𝔼
- 'F': u'\U0001D53D', # 𝔽
- 'G': u'\U0001D53E', # 𝔾
- 'H': u'\u210D', # ℍ
- 'I': u'\U0001D540', # 𝕀
- 'J': u'\U0001D541', # 𝕁
- 'K': u'\U0001D542', # 𝕂
- 'L': u'\U0001D543', # 𝕃
- 'M': u'\U0001D544', # 𝕄
- 'N': u'\u2115', # ℕ
- 'O': u'\U0001D546', # 𝕆
- 'P': u'\u2119', # ℙ
- 'Q': u'\u211A', # ℚ
- 'R': u'\u211D', # ℝ
- 'S': u'\U0001D54A', # 𝕊
- 'T': u'\U0001D54B', # 𝕋
- 'U': u'\U0001D54C', # 𝕌
- 'V': u'\U0001D54D', # 𝕍
- 'W': u'\U0001D54E', # 𝕎
- 'X': u'\U0001D54F', # 𝕏
- 'Y': u'\U0001D550', # 𝕐
- 'Z': u'\u2124', # ℤ
- 'a': u'\U0001D552', # 𝕒
- 'b': u'\U0001D553', # 𝕓
- 'c': u'\U0001D554', # 𝕔
- 'd': u'\U0001D555', # 𝕕
- 'e': u'\U0001D556', # 𝕖
- 'f': u'\U0001D557', # 𝕗
- 'g': u'\U0001D558', # 𝕘
- 'h': u'\U0001D559', # 𝕙
- 'i': u'\U0001D55A', # 𝕚
- 'j': u'\U0001D55B', # 𝕛
- 'k': u'\U0001D55C', # 𝕜
- 'l': u'\U0001D55D', # 𝕝
- 'm': u'\U0001D55E', # 𝕞
- 'n': u'\U0001D55F', # 𝕟
- 'o': u'\U0001D560', # 𝕠
- 'p': u'\U0001D561', # 𝕡
- 'q': u'\U0001D562', # 𝕢
- 'r': u'\U0001D563', # 𝕣
- 's': u'\U0001D564', # 𝕤
- 't': u'\U0001D565', # 𝕥
- 'u': u'\U0001D566', # 𝕦
- 'v': u'\U0001D567', # 𝕧
- 'w': u'\U0001D568', # 𝕨
- 'x': u'\U0001D569', # 𝕩
- 'y': u'\U0001D56A', # 𝕪
- 'z': u'\U0001D56B', # 𝕫
- u'Γ': u'\u213E', # ℾ
+mathbb = {u'Γ': u'\u213E', # ℾ
u'Π': u'\u213F', # ℿ
u'Σ': u'\u2140', # ⅀
u'γ': u'\u213D', # ℽ
@@ -250,6 +187,18 @@
'vec': u'\u20D7'}
+# all supported math-characters:
+#mathcharacters = dict(letters)
+#mathcharacters.update(operators)
+#mathcharacters.update(tex2unichar.space)
+#
+## >>> l2m.mathcharacters['alpha']
+## 'α'
+## >>> l2m.mathcharacters['{']
+## '{'
+## >>> l2m.mathcharacters['pm']
+## '±'
+
# MathML element classes
# ----------------------
@@ -491,27 +440,39 @@
def tex_cmdname(string):
"""Return leading TeX command name from `string`.
- >>> l2m.tex_cmdname('name2') # first non-letter terminates
+ >>> l2m.tex_cmdname('name2') # up to first non-letter
('name', '2')
+ >>> l2m.tex_cmdname('name 2') # strip trailing whitespace
+ ('name', '2')
>>> l2m.tex_cmdname('_2') # single non-letter character
('_', '2')
"""
- cmdname = re.match(r'([a-zA-Z]+|.?)(.*)', string)
- return cmdname.group(1), cmdname.group(2)
+ m = re.match(r'([a-zA-Z]+) *(.*)', string)
+ if m is None:
+ m = re.match(r'(.?)(.*)', string)
+ return m.group(1), m.group(2)
# Test:
#
-# >>> l2m.tex_cmdname('name 2') # first non-letter terminates
-# ('name', ' 2')
# >>> l2m.tex_cmdname('name_2') # first non-letter terminates
# ('name', '_2')
-# >>> l2m.tex_cmdname(' 2') # leading whitespace is returned
-# (' ', '2')
+# >>> l2m.tex_cmdname(' next') # leading whitespace is returned
+# (' ', 'next')
+# >>> l2m.tex_cmdname('1 2') # whitespace after non-letter is kept
+# ('1', ' 2')
# >>> l2m.tex_cmdname('') # empty string
# ('', '')
+# TODO: check for Inferred <mrow>s:
+
+# The elements <msqrt>, <mstyle>, <merror>, <mpadded>, <mphantom>, <menclose>,
+# <mtd, mscarry>, and <math> treat their contents as a single inferred mrow
+# formed from all their children
+#
+# --- https://www.w3.org/TR/MathML3/chapter3.html#id.3.1.3.2
+
def tex_token(string):
"""Take first simple TeX token from `string`.
@@ -526,21 +487,22 @@
"""
m = re.match(r"""\s* # leading whitespace
- (?P<token>
- ({(\\}|[^{}]|\\{)*} # {group} without nested groups
- |\\([a-zA-Z]+|.) # \cmdname
- |.?) # first character or empty string
- )
+ {(?P<token>(\\}|[^{}]|\\{)*)} # {group} without nested groups
+ (?P<remainder>.*$)
+ """, string, re.VERBOSE)
+ if m is None:
+ m = re.match(r"""\s* # leading whitespace
+ (?P<token>\\([a-zA-Z]+))\s* # \cmdname
(?P<remainder>.*$)
""", string, re.VERBOSE)
+ if m is None:
+ m = re.match(r"""\s* # leading whitespace
+ (?P<token>.?) # first character or empty string
+ (?P<remainder>.*$)
+ """, string, re.VERBOSE)
- # strip {brackets}
- token = m.group('token')
- if token.startswith('{') and token.endswith('}'):
- token = token[1:-1]
+ return m.group('token'), m.group('remainder')
- return token, m.group('remainder')
-
# Test:
#
# >>> l2m.tex_token('{opening bracket of group with {nested group}}')
@@ -553,8 +515,8 @@
# ('skip leading whitespace', '')
# >>> l2m.tex_token(' \\skip{leading whitespace}')
# ('\\skip', '{leading whitespace}')
-# >>> l2m.tex_token('\\leave trailing whitespace')
-# ('\\leave', ' trailing whitespace')
+# >>> l2m.tex_token('\\skip whitespace after macro name')
+# ('\\skip', 'whitespace after macro name')
# >>> l2m.tex_token('') # empty string.
# ('', '')
@@ -689,34 +651,36 @@
node = node.append(mo('⁡')) # '\u2061'
return node, string
- if name == 'mathrm':
- # typically used for multi-character identifier ``s_\mathrm{out}``
- # https://www.w3.org/TR/MathML3/chapter3.html#presm.mi
- # TODO: too much space after d in ``\int f(x) \mathrm{d}x``.
- arg, string = tex_token(string)
- node = node.append(mi(arg, mathvariant='normal'))
- # node = node.append(mo(arg))
- return node, string
+ if name in math_alphabets:
+ arg, remainder = tex_token(string)
+ if arg[0] == '\\':
+ if name == 'mathbb':
+ # mathvariant="double-struck" is ignored for Greek letters
+ # (tested in Firefox 78). Use literal Unicode characters.
+ arg = mathbb.get(arg, arg)
+ # convert single letters (so they can be set with <mi>)
+ arg = letters.get(arg[1:], arg)
- if name == 'mathbb':
- arg, string = tex_token(string)
- chs = arg
- while chs:
- c, chs = tex_token(chs)
- try:
- node = node.append(mi(mathbb[c]))
- except KeyError:
- raise SyntaxError(u'Character "%s" not supported '
- u'in "\\mathbb{}"!' % chs)
- return node, string
+ if name == 'boldsymbol':
+ kwargs = {'style': 'font-weight: bold'}
+ else:
+ kwargs = {'mathvariant': math_alphabets[name]}
- if name in math_alphabets:
- # TODO: use <mi> if it applies to just 1 character
- # Wrap in <style> (implies <mgroup>)
- n_c = None if string.startswith('{') else 1
- style = mstyle(nchildren=n_c, mathvariant=math_alphabets[name])
+ # one symbol (single letter, name, or number)
+ if arg.isalpha():
+ node = node.append(mi(arg, **kwargs))
+ return node, remainder
+ if arg.replace('.', '').replace(',', '').isdigit():
+ node = node.append(mn(arg, **kwargs))
+ return node, remainder
+ if len(arg) == 1 and arg != '{':
+ node = node.append(mo(arg, **kwargs))
+ return node, remainder
+
+ # Wrap in <style>
+ style = mstyle(**kwargs)
node.append(style)
- return style, string[1:]
+ return style, string[1:] # take of the opening '{', <mrow> is inferred
# operator, fence, or separator -> <mo>
@@ -835,9 +799,9 @@
# >>> l2m.handle_keyword('left', l2m.math(), '. a)') # emtpy \left
# (mrow(), ' a)')
# >>> l2m.handle_keyword('left', l2m.math(), '\\uparrow a)') # cmd
-# (mrow(mo('↑')), ' a)')
+# (mrow(mo('↑')), 'a)')
# >>> l2m.handle_keyword('not', l2m.math(), '\\equiv \\alpha)') # cmd
-# (math(mo('≢')), ' \\alpha)')
+# (math(mo('≢')), '\\alpha)')
# >>> l2m.handle_keyword('text', l2m.math(), '{ for } i>0') # group
# (math(mtext(' for ')), ' i>0')
# >>> l2m.handle_keyword('text', l2m.math(), '{B}T') # group
@@ -852,8 +816,11 @@
# (math(mi('sin'), mo('⁡')), ' \\alpha')
# >>> l2m.handle_keyword('operatorname', l2m.math(), '{abs}(x)')
# (math(mi('abs', mathvariant='normal'), mo('⁡')), '(x)')
+# >>> l2m.handle_keyword('mathrm', l2m.math(), '\\alpha')
+# (math(mi('α', mathvariant='normal')), '')
+# >>> l2m.handle_keyword('mathrm', l2m.math(), '{out} = 3')
+# (math(mi('out', mathvariant='normal')), ' = 3')
-
def tex2mathml(tex_math, inline=True):
"""Return string with MathML code corresponding to `tex_math`.
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:21:48 UTC (rev 8746)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:22:05 UTC (rev 8747)
@@ -103,10 +103,7 @@
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
- <mstyle mathvariant="bold">
- <mi>M</mi>
- </mstyle>
- <mo>=</mo>
+ <mi mathvariant="bold">M</mi><mo>=</mo>
<mrow>
<mo>(</mo>
<mtable>
@@ -136,11 +133,7 @@
</div>
<p>is <math xmlns="http://www.w3.org/1998/Math/MathML">
<mrow>
- <mo stretchy="false">|</mo>
- <mstyle mathvariant="bold">
- <mi>M</mi>
- </mstyle>
- <mo stretchy="false">|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi>
+ <mo stretchy="false">|</mo><mi mathvariant="bold">M</mi><mo stretchy="false">|</mo><mo>=</mo><mi>a</mi><mi>d</mi><mo>-</mo><mi>b</mi><mi>c</mi>
</mrow>
</math>.</p>
<p>More than one display math block can be put in one math directive.
@@ -382,16 +375,10 @@
<mo>|</mo>
<mfrac>
<mrow>
- <mstyle mathvariant="script">
- <mi>F</mi>
- </mstyle>
- <mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
+ <mi mathvariant="script">F</mi><mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
</mrow>
<mrow>
- <mstyle mathvariant="script">
- <mi>F</mi>
- </mstyle>
- <mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
+ <mi mathvariant="script">F</mi><mo>{</mo><mi>s</mi><mo stretchy="false">(</mo><mi>x</mi><mo stretchy="false">)</mo><mo>}</mo>
<msub>
<mo stretchy="false">|</mo>
<mrow>
Added: trunk/docutils/test/functional/input/data/comprehensive-math-test.txt
===================================================================
--- trunk/docutils/test/functional/input/data/comprehensive-math-test.txt (rev 0)
+++ trunk/docutils/test/functional/input/data/comprehensive-math-test.txt 2021-05-20 12:22:05 UTC (rev 8747)
@@ -0,0 +1,462 @@
+==================================
+Using LaTeX syntax for mathematics
+==================================
+
+.. role:: m(math)
+.. default-role:: math
+.. |latex| replace:: L\ :sup:`A`\ T\ :sub:`E`\ X
+
+.. contents::
+
+
+Introduction
+============
+
+Since version 0.8, Docutils supports mathematical content with a `"math"
+directive`__ and `role`__.
+The input format is *LaTeX math syntax*\ [#math-syntax]_ with support for
+Unicode symbols.
+
+
+.. [#math-syntax] The supported LaTeX commands include AMS extensions
+ (see, e.g., the `Short Math Guide`_).
+
+ The support is limited to a subset of *LaTeX math* by the conversion
+ required for many output formats. For HTML, the `math_output`_
+ configuration setting (or the corresponding ``--math-output`` command
+ line option) select between alternative output formats with different
+ subsets of supported elements. If a writer does not support math
+ typesetting at all, the content is inserted verbatim.
+
+__ https://docutils.sourceforge.io/docs/ref/rst/directives.html#math
+__ https://docutils.sourceforge.io/docs/ref/rst/roles.html#math
+.. _Short Math Guide:
+ http://mirrors.ctan.org/info/short-math-guide/short-math-guide.pdf
+.. _math_output:
+ https://docutils.sourceforge.io/docs/user/config.html#math-output
+
+
+Role and directive
+==================
+
+The ``math`` role can be used for inline mathematical expressions:
+``:math:`\psi(r) = \exp(-2r)``` will produce :m:`\psi(r)=\exp(-2r)`.
+Inside the backtics you can write anything you would write between dollar
+signs in a LaTeX document.
+
+For producing displayed math (like an ``equation*`` environment in a
+LaTeX document) there is a ``math`` directive. If you write::
+
+ .. math:: \psi(r) = e^{-2r}
+
+you will get:
+
+.. math:: \psi(r) = e^{-2r}
+
+A more complex example is the definition of the Fourier transform
+
+.. math::
+
+ (\mathcal{F}f)(y) =
+ \frac{1}{\sqrt{2\pi}^{\ n}}
+ \int_{\mathbb{R}^n} f(x)\,e^{-\mathrm{i} y \cdot x} \,\mathrm{d} x.
+
+
+.. tip::
+
+ If you put ``.. default-role:: math`` at the top of your
+ document, then you can write ```x^2``` instead of the longer
+ version: ``:math:`x^2```. You can also introduce an
+ abreviation like this ``.. role:: m(math)``. That will allow
+ you to write ``:m:`x^2``` or ```x^2`:m:``.
+
+
+Not *all* math syntax constructs work with every output format, but basic
+everyday-math should work.
+
+If a command or a special symbol is not desribed in this document, then
+it is probably not implemented in the internal LaTeX -> MathML converter.
+
+
+Commands
+========
+
+
+.. class:: colwidths-auto
+
+ ===================== ============================== ============================
+ command example result
+ ===================== ============================== ============================
+ ``\sqrt`` ``\sqrt{x^2-1}`` `\sqrt{x^2-1}`
+ ``\frac`` ``\frac{1}{2}`` `\frac{1}{2}`
+ ``\left``, ``\right`` ``\left(\frac{1}{2}\right)^n`` `\left(\frac{1}{2}\right)^n`
+ ===================== ============================== ============================
+
+
+Environments
+============
+
+Displayed math can use ``\\`` and ``&`` for line shifts and alignments::
+
+ .. math::
+
+ a & = (x + y)^2 \\
+ & = x^2 + 2xy + y^2
+
+LaTeX output will wrap it in an ``align*`` environment.
+The result is:
+
+.. math::
+
+ a & = (x + y)^2 \\
+ & = x^2 + 2xy + y^2
+
+The ``matrix`` and ``cases`` environments can also contain ``\\`` and
+``&``::
+
+ .. math::
+
+ \left(\begin{matrix} a & b \\ c & d \end{matrix}\right)
+
+Result:
+
+.. math::
+
+ \left(\begin{matrix} a & b \\ c & d \end{matrix}\right)
+
+
+Mathematical symbols
+====================
+
+The following tables are adapted from the first edition of
+"The LaTeX Companion" (Goossens, Mittelbach, Samarin).
+
+Accents
+-------
+.. class:: colwidths-auto
+
+ =========== ============= =========== ============= ============== ================
+ `\acute{x}` ``\acute{x}`` `\dot{x}` ``\dot{x}`` `\hat{H}` ``\hat{H}``
+ `\bar{v}` ``\bar{v}`` `\ddot{x}` ``\ddot{x}`` `\mathring{x}` ``\mathring{x}``
+ `\breve{x}` ``\breve{x}`` `\dddot{x}` ``\dddot{x}`` `\tilde{n}` ``\tilde{n}``
+ `\check{x}` ``\check{x}`` `\grave{x}` ``\grave{x}`` `\vec{R}` ``\vec{R}``
+ =========== ============= =========== ============= ============== ================
+
+When adding an accent to an i or j in math, dotless variants can be
+obtained with ``\imath`` and ``\jmath``: `\bar \imath`, `\hat{\jmath}`
+
+alphabets
+---------
+.. class:: colwidths-auto
+
+ =============== ============================ ==========================
+ command example result
+ =============== ============================ ==========================
+ ``\boldsymbol`` ``\boldsymbol{\alpha + 3}`` `\boldsymbol{\alpha + 3}`
+ ``\mathbf`` ``\mathbf{r}^2=x^2+y^2+z^2`` `\mathbf{r}^2=x^2+y^2+z^2`
+ ``\mathbb`` ``\mathbb{R \subset C}`` `\mathbb{R \subset C}`
+ ``\mathcal`` ``\mathcal{F}f(x)`` `\mathcal{F}f(x)`
+ ``\mathfrak`` ``\mathfrak{a}`` `\mathfrak{a}`
+ ``\mathit`` ``\mathit{\Gamma}`` `\mathit{\Gamma}`
+ ``\mathrm`` ``s_\mathrm{out}`` `s_\mathrm{out}`
+ ``\mathsf`` ``\mathsf x`` `\mathsf x`
+ ``\mathtt`` ``\mathtt{0.12}`` `\mathtt{0.12}`
+ =============== ============================ ==========================
+
+.. with isomath:
+ 'mathbfit': 'bold-italic', # isomath
+ 'mathsfit': 'sans-serif-italic', # isomath
+ 'mathsfbfit': 'sans-serif-bold-italic', # isomath
+ with mathrsfs, ... 'mathscr'
+
+
+Arrows
+------
+.. class:: colwidths-auto
+
+ ===================== ======================= ===================== =======================
+ `\leftarrow` ``\leftarrow`` `\Leftarrow` ``\Leftarrow``
+ `\rightarrow` ``\rightarrow`` `\Rightarrow` ``\Rightarrow``
+ `\leftrightarrow` ``\leftrightarrow`` `\Leftrightarrow` ``\Leftrightarrow``
+ `\uparrow` ``\uparrow`` `\Uparrow` ``\Uparrow``
+ `\downarrow` ``\downarrow`` `\Downarrow` ``\Downarrow``
+ `\updownarrow` ``\updownarrow`` `\Updownarrow` ``\Updownarrow``
+
+ `\longleftarrow` ``\longleftarrow`` `\Longleftarrow` ``\Longleftarrow``
+ `\longrightarrow` ``\longrightarrow`` `\Longrightarrow` ``\Longrightarrow``
+ `\longleftrightarrow` ``\longleftrightarrow`` `\Longleftrightarrow` ``\Longleftrightarrow``
+
+ `\nearrow` ``\nearrow`` `\leftharpoonup` ``\leftharpoonup``
+ `\searrow` ``\searrow`` `\rightharpoonup` ``\rightharpoonup``
+ `\swarrow` ``\swarrow`` `\leftharpoondown` ``\leftharpoondown``
+ `\nwarrow` ``\nwarrow`` `\rightharpoondown` ``\rightharpoondown``
+
+ `\mapsto` ``\mapsto`` `\hookleftarrow` ``\hookleftarrow``
+ `\longmapsto` ``\longmapsto`` `\hookrightarrow` ``\hookrightarrow``
+ ===================== ======================= ===================== =======================
+
+
+Binary operators
+----------------
+.. class:: colwidths-auto
+
+ ================== ==================== ================= =================== ================== ====================
+ `*` ``*`` `\circledast` ``\circledast`` `\odot` ``\odot``
+ `+` ``+`` `\circledcirc` ``\circledcirc`` `\ominus` ``\ominus``
+ `-` ``-`` `\circleddash` ``\circleddash`` `\oplus` ``\oplus``
+ `:` ``:`` `\cup` ``\cup`` `\oslash` ``\oslash``
+ `\Cap` ``\Cap`` `\curlyvee` ``\curlyvee`` `\otimes` ``\otimes``
+ `\Cup` ``\Cup`` `\curlywedge` ``\curlywedge`` `\pm` ``\pm``
+ `\amalg` ``\amalg`` `\dagger` ``\dagger`` `\rightthreetimes` ``\rightthreetimes``
+ `\ast` ``\ast`` `\ddagger` ``\ddagger`` `\rtimes` ``\rtimes``
+ `\bigcirc` ``\bigcirc`` `\diamond` ``\diamond`` `\setminus` ``\setminus``
+ `\bigtriangledown` ``\bigtriangledown`` `\div` ``\div`` `\smallsetminus` ``\smallsetminus``
+ `\bigtriangleup` ``\bigtriangleup`` `\divideontimes` ``\divideontimes`` `\sqcap` ``\sqcap``
+ `\boxdot` ``\boxdot`` `\dotplus` ``\dotplus`` `\sqcup` ``\sqcup``
+ `\boxminus` ``\boxminus`` `\doublebarwedge` ``\doublebarwedge`` `\star` ``\star``
+ `\boxplus` ``\boxplus`` `\gtrdot` ``\gtrdot`` `\times` ``\times``
+ `\boxtimes` ``\boxtimes`` `\intercal` ``\intercal`` `\triangleleft` ``\triangleleft``
+ `\bullet` ``\bullet`` `\leftthreetimes` ``\leftthreetimes`` `\triangleright` ``\triangleright``
+ `\cap` ``\cap`` `\lessdot` ``\lessdot`` `\uplus` ``\uplus``
+ `\cdot` ``\cdot`` `\ltimes` ``\ltimes`` `\vee` ``\vee``
+ `\centerdot` ``\centerdot`` `\mp` ``\mp`` `\veebar` ``\veebar``
+ `\circ` ``\circ`` `\wedge` ``\wedge``
+ .. `\wr` ``\wr``
+ ================== ==================== ================= =================== ================== ====================
+
+
+Braces
+------
+.. class:: colwidths-auto
+
+ ============ ============ ============ ============== ========================
+ `(` ``(`` `[` ``[`` `|` ``|`` `\{` ``\{`` `\langle` ``\langle``
+ `)` ``)`` `]` ``]`` `|` ``|`` `\}` ``\}`` `\rangle` ``\rangle``
+ ============ ============ ============ ============== ========================
+
+
+Greek letters
+-------------
+.. class:: colwidths-auto
+
+ ========== ============ ========== ============ ========== ============ ============== ===============
+ `\Gamma` ``\Gamma`` `\alpha` ``\alpha`` `\mu` ``\mu`` `\omega` ``\omega``
+ `\Delta` ``\Delta`` `\beta` ``\beta`` `\nu` ``\nu`` `\backepsilon` ``\backepsilon``
+ `\Lambda` ``\Lambda`` `\gamma` ``\gamma`` `\xi` ``\xi`` `\digamma` ``\digamma``
+ `\Omega` ``\Omega`` `\delta` ``\delta`` `\pi` ``\pi`` `\varepsilon` ``\varepsilon``
+ `\Phi` ``\Phi`` `\epsilon` ``\epsilon`` `\rho` ``\rho`` `\varkappa` ``\varkappa``
+ `\Pi` ``\Pi`` `\zeta` ``\zeta`` `\sigma` ``\sigma`` `\varphi` ``\varphi``
+ `\Psi` ``\Psi`` `\eta` ``\eta`` `\tau` ``\tau`` `\varpi` ``\varpi``
+ `\Sigma` ``\Sigma`` `\theta` ``\theta`` `\upsilon` ``\upsilon`` `\varrho` ``\varrho``
+ `\Theta` ``\Theta`` `\iota` ``\iota`` `\phi` ``\phi`` `\varsigma` ``\varsigma``
+ `\Upsilon` ``\Upsilon`` `\kappa` ``\kappa`` `\chi` ``\chi`` `\vartheta` ``\vartheta``
+ `\Xi` ``\Xi`` `\lambda` ``\lambda`` `\psi` ``\psi``
+ ========== ============ ========== ============ ========== ============ ============== ===============
+
+
+Letterlike symbols
+------------------
+.. class:: colwidths-auto
+
+======= ========== ============= =============== ========= =========== ========== ============
+`\Im` ``\Im`` `\forall` ``\forall`` `\aleph` ``\aleph`` `\eth` ``\eth``
+`\Re` ``\Re`` `\exists` ``\exists`` `\beth` ``\beth`` `\hbar` ``\hbar``
+`\mho` ``\mho`` `\complement` ``\complement`` `\gimel` ``\gimel`` `\hslash` ``\hslash``
+`\Bbbk` ``\Bbbk`` `\Finv` ``\Finv`` `\daleth` ``\daleth`` `\imath` ``\imath``
+`\ell` ``\ell`` `\Game` ``\Game`` `\nabla` ``\nabla`` `\partial` ``\partial``
+`\wp` ``\wp``
+======= ========== ============= =============== ========= =========== ========== ============
+
+
+Miscellaneous symbols
+---------------------
+.. class:: colwidths-auto
+
+======== =============== =========== ============= ============== ================ ========== ============
+`\angle` ``\angle`` `\emptyset` ``\emptyset`` `\clubsuit` ``\clubsuit`` `\flat` ``\flat``
+`\colon` ``\colon`` [#]_ `\infty` ``\infty`` `\diamondsuit` ``\diamondsuit`` `\natural` ``\natural``
+`\cdots` ``\cdots`` `\neg` ``\neg`` `\heartsuit` ``\heartsuit`` `\sharp` ``\sharp``
+`\ddots` ``\ddots`` `\bot` ``\bot`` `\spadesuit` ``\spadesuit``
+`\ddots` ``\ddots`` `\top` ``\top``
+======== =============== =========== ============= ============== ================ ========== ============
+
+.. [#] Punctuation (not ratio):
+ Compare spacing in `a\colon b\to c` and `a:b = c`.
+
+
+Named operators
+---------------
+.. class:: colwidths-auto
+
+ ========= =========== ====== ======== ====== ======== ======= =========
+ `\arccos` ``\arccos`` `\csc` ``\csc`` `\ker` ``\ker`` `\sec` ``\sec``
+ `\arcsin` ``\arcsin`` `\deg` ``\deg`` `\lg` ``\lg`` `\sin` ``\sin``
+ `\arctan` ``\arctan`` `\det` ``\det`` `\lim` ``\lim`` `\sinh` ``\sinh``
+ `\arg` ``\arg`` `\dim` ``\dim`` `\ln` ``\ln`` `\sup` ``\sup``
+ `\cos` ``\cos`` `\exp` ``\exp`` `\log` ``\log`` `\tan` ``\tan``
+ `\cosh` ``\cosh`` `\gcd` ``\gcd`` `\max` ``\max`` `\tanh` ``\tanh``
+ `\cot` ``\cot`` `\hom` ``\hom`` `\min` ``\min``
+ `\coth` ``\coth`` `\inf` ``\inf`` `\Pr` ``\Pr``
+ ========= =========== ====== ======== ====== ======== ======= =========
+
+Named operators outside the above list can be typeset with
+``\operatorname{name}``, e.g. `\operatorname{sgn}(-3) = -1`.
+
+
+Relation symbols
+----------------
+.. class:: colwidths-auto
+
+ ================================ ================================ ================================ ================================
+ `\Join` ``\Join`` `\approx` ``\approx`` `\asymp` ``\asymp`` `\bowtie` ``\bowtie``
+ `\cong` ``\cong`` `\dashv` ``\dashv`` `\doteq` ``\doteq`` `\equiv` ``\equiv``
+ `\frown` ``\frown`` `\ge` ``\ge`` `\geq` ``\geq`` `\gg` ``\gg``
+ `\in` ``\in`` `\le` ``\le`` `\leq` ``\leq`` `\ll` ``\ll``
+ `\mid` ``\mid`` `\models` ``\models`` `\neq` ``\neq`` `\ni` ``\ni``
+ `\parallel` ``\parallel`` `\perp` ``\perp`` `\prec` ``\prec`` `\precsim` ``\precsim``
+ `\propto` ``\propto`` `\sim` ``\sim`` `\simeq` ``\simeq`` `\smile` ``\smile``
+ `\sqsubset` ``\sqsubset`` `\sqsubseteq` ``\sqsubseteq`` `\sqsupset` ``\sqsupset`` `\sqsupseteq` ``\sqsupseteq``
+ `\subset` ``\subset`` `\subseteq` ``\subseteq`` `\succ` ``\succ`` `\succsim` ``\succsim``
+ `\supset` ``\supset`` `\supseteq` ``\supseteq`` `\vdash` ``\vdash``
+ ================================ ================================ ================================ ================================
+
+negated relations
+.. class:: colwidths-auto
+
+ ============================= ===================
+ `\not\in` ``\not\in`` `\not =` ``\not =``
+ `\not \equiv` ``\not \equiv``
+ ============================= ===================
+
+
+Variable-sized symbols
+----------------------
+.. class:: colwidths-auto
+
+ ================= =========================== ========================= ========================= =====================
+ `\sum` ``\sum`` `\bigodot` ``\bigodot`` `\bigcap` ``\bigcap`` `\bigwedge` ``\bigwedge`` `\prod` ``\prod``
+ `\int` ``\int`` `\bigoplus` ``\bigoplus`` `\bigcup` ``\bigcup`` `\bigvee` ``\bigvee`` `\coprod` ``\coprod``
+ `\oint` ``\oint`` `\bigotimes` ``\bigotimes`` `\biguplus` ``\biguplus``
+ ================= =========================== ========================= ========================= =====================
+
+Larger symbols are used in displayed formulas:
+
+.. math::
+
+ \sum\ \int\ \oint \bigcap \prod \ldots
+
+Extensible delimiters
+---------...
[truncated message content] |
|
From: <mi...@us...> - 2021-05-20 12:22:29
|
Revision: 8748
http://sourceforge.net/p/docutils/code/8748
Author: milde
Date: 2021-05-20 12:22:27 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: support more functions and symbols.
- Support emellished identifiers,
- support more functions and symbols from "amsmath",
- map HYPHEN-MINUS -> MINUS SIGN and COLON -> RATIO im math context,
- simplify doctests with starred import,
- dont wrap content in <mrow> when it is inferred by an element
(let these elements inherit from "mrow").
- tex2unichar: Fix/extend character mappings.
Modified Paths:
--------------
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/docutils/utils/math/tex2unichar.py
trunk/docutils/test/functional/expected/math_output_mathml.html
trunk/docutils/test/functional/input/data/comprehensive-math-test.txt
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:22:05 UTC (rev 8747)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:22:27 UTC (rev 8748)
@@ -22,7 +22,7 @@
#
# Usage:
#
-# >>> import latex2mathml as l2m
+# >>> from latex2mathml import *
import collections
import re
@@ -54,12 +54,17 @@
functions = ['arccos', 'arcsin', 'arctan', 'arg', 'cos', 'cosh',
'cot', 'coth', 'csc', 'deg', 'det', 'dim',
'exp', 'gcd', 'hom', 'inf', 'ker', 'lg',
- 'lim', 'liminf', 'limsup', 'ln', 'log', 'max',
- 'min', 'Pr', 'sec', 'sin', 'sinh', 'sup',
- 'tan', 'tanh', 'injlim', 'varinjlim', 'projlim',
- 'varlimsup', 'varliminf', 'varprojlim']
+ 'lim', 'ln', 'log', 'max', 'min', 'Pr',
+ 'sec', 'sin', 'sinh', 'sup', 'tan', 'tanh']
+functions = dict((name, name) for name in functions)
+functions.update({# functions with a space in the name
+ 'liminf': u'lim\u202finf', 'limsup': u'lim\u202fsup',
+ 'injlim': u'inj\u202flim', 'projlim': u'proj\u202flim',
+ # embellished function names (see handle_keyword() below)
+ 'varlimsup': 'lim', 'varliminf': 'lim',
+ 'varprojlim': 'lim', 'varinjlim': 'lim'})
-# font selection -> <mi mathvariant=...>
+# math font selection -> <mi mathvariant=...> or <mstyle mathvariant=...>
math_alphabets = {# 'cmdname': 'mathvariant value' # package
'boldsymbol': 'bold',
'mathbb': 'double-struck', # amssymb
@@ -79,19 +84,6 @@
# bold-sans-serif
}
-# blackboar bold (Greek characters not working with "mathvariant" (Firefox 78)
-mathbb = {u'Γ': u'\u213E', # ℾ
- u'Π': u'\u213F', # ℿ
- u'Σ': u'\u2140', # ⅀
- u'γ': u'\u213D', # ℽ
- u'π': u'\u213C', # ℼ
- r'\Gamma': u'\u213E', # ℾ
- r'\Pi': u'\u213F', # ℿ
- r'\Sigma': u'\u2140', # ⅀
- r'\gamma': u'\u213D', # ℽ
- r'\pi': u'\u213C', # ℼ
- }
-
# operator, fence, or separator -> <mo>
operators = tex2unichar.mathbin # Binary symbols
@@ -101,24 +93,58 @@
operators.update(tex2unichar.mathopen) # Braces
operators.update(tex2unichar.mathclose) # Braces
operators.update(tex2unichar.mathfence)
+operators.update({# negated symbols without pre-composed Unicode character
+ 'nleqq': u'\u2266\u0338', # ≦̸
+ 'ngeqq': u'\u2267\u0338', # ≧̸
+ 'nleqslant': u'\u2a7d\u0338', # ⩽̸
+ 'ngeqslant': u'\u2a7e\u0338', # ⩾̸
+ 'nsubseteqq': u'\u2AC5\u0338', # ⫅̸
+ 'nsupseteqq': u'\u2AC6\u0338', # ⫆̸
+ })
-# >>> '{' in l2m.operators.values()
+# >>> '{' in operators.values()
# True
# special cases
+thick_operators = {# style='font-weight: bold;'
+ 'thicksim': u'\u223C', # ∼
+ 'thickapprox':u'\u2248', # ≈
+ }
+
+small_operators = {# mathsize='75%'
+ 'shortmid': u'\u2223', # ∣
+ 'shortparallel': u'\u2225', # ∥
+ 'nshortmid': u'\u2224', # ∤
+ 'nshortparallel': u'\u2226', # ∦
+ 'smallfrown': u'\u2322', # ⌢ FROWN
+ 'smallsmile': u'\u2323', # ⌣ SMILE
+ 'smallint': u'\u222b', # ∫ INTEGRAL
+ }
+
+left_delimiters = {# rspace='0', lspace='0.22em'
+ 'lvert': '|',
+ 'lVert': u'\u2016' # ‖ DOUBLE VERTICAL LINE
+ }
+
+right_delimiters = {# lspace='0', rspace='0.22em'
+ 'rvert': '|',
+ 'rVert': u'\u2016', # ‖ DOUBLE VERTICAL LINE
+ }
+
sumintprod = ''.join([operators[symbol] for symbol in
['sum', 'int', 'oint', 'prod']])
-# >>> print(l2m.sumintprod)
+# >>> print(sumintprod)
# ∑∫∮∏
-#
+# pre-composed characters for negated symbols
+# see https://www.w3.org/TR/xml-entity-names/#combining
negatables = {'=': u'\u2260',
r'\in': u'\u2209',
r'\equiv': u'\u2262'}
-# cmds/characters allowed in left/right cmds
+# extensible delimiters allowed in left/right cmds
stretchables = {'(': '(',
')': ')',
'[': '[',
@@ -147,7 +173,7 @@
# **tex2unichar.mathfence}.items():
# stretchables['\\'+key] = value
-# >>> print(' '.join(sorted(set(l2m.stretchables.values()))))
+# >>> print(' '.join(sorted(set(stretchables.values()))))
# ( ) / [ \ ] { | } ‖ ↑ ↓ ↕ ⇑ ⇓ ⇕ ⌈ ⌉ ⌊ ⌋ ⌜ ⌝ ⌞ ⌟ ⟅ ⟆ ⟦ ⟧ ⟨ ⟩ ⟮ ⟯ ⦇ ⦈
@@ -171,34 +197,54 @@
# accents -> <mover>
# TeX spacing combining
-over = {'acute': u'\u00B4', # u'\u0301',
- 'bar': u'\u00AF', # u'\u0304',
- 'breve': u'\u02D8', # u'\u0306',
- 'check': u'\u02C7', # u'\u030C',
- 'dot': u'\u02D9', # u'\u0307',
- 'ddot': u'\u00A8', # u'\u0308',
- 'dddot': u'\u20DB',
+over = {'acute': u'´', # u'\u0301',
+ 'bar': u'-', # u'\u0304',
+ 'breve': u'˘', # u'\u0306',
+ 'check': u'ˇ', # u'\u030C',
+ 'dot': u'·', # u'\u0307',
+ 'ddot': u'··', # u'\u0308',
+ 'dddot': u'···', # u'\u20DB',
'grave': u'`', # u'\u0300',
'hat': u'^', # u'\u0302',
- 'mathring': u'\u02DA', # u'\u030A',
- 'overleftrightarrow': u'\u20e1',
- # 'overline': # u'\u0305',
- 'tilde': u'\u02DC', # u'\u0303',
- 'vec': u'\u20D7'}
+ 'mathring': u'°', # u'\u030A',
+ 'tilde': u'\u223C', # u'\u0303',
+ 'vec': u'\u20D7',
+ }
+wideover = {'overbrace': u'\u23DE', # TOP CURLY BRACKET
+ 'overleftarrow': u'\u2190',
+ 'overleftrightarrow': u'\u2194',
+ 'overline': u'¯',
+ 'overrightarrow': u'\u2192',
+ 'widehat': u'^',
+ 'widetilde': u'~'}
+wideunder = {'underbrace': u'\u23DF',
+ 'underleftarrow': u'\u2190',
+ 'underleftrightarrow': u'\u2194',
+ 'underline': u'_',
+ 'underrightarrow': u'\u2192'}
-# all supported math-characters:
-#mathcharacters = dict(letters)
-#mathcharacters.update(operators)
-#mathcharacters.update(tex2unichar.space)
-#
-## >>> l2m.mathcharacters['alpha']
-## 'α'
-## >>> l2m.mathcharacters['{']
-## '{'
-## >>> l2m.mathcharacters['pm']
-## '±'
+# Character translations
+# ----------------------
+# characters with preferred alternative in mathematical use
+anomalous_chars = {'-': u'\u2212', # HYPHEN-MINUS -> MINUS SIGN
+ ':': u'\u2236', # COLON -> RATIO
+ }
+# blackboard bold (Greek characters not working with "mathvariant" (Firefox 78)
+mathbb = {u'Γ': u'\u213E', # ℾ
+ u'Π': u'\u213F', # ℿ
+ u'Σ': u'\u2140', # ⅀
+ u'γ': u'\u213D', # ℽ
+ u'π': u'\u213C', # ℼ
+ r'\Gamma': u'\u213E', # ℾ
+ r'\Pi': u'\u213F', # ℿ
+ r'\Sigma': u'\u2140', # ⅀
+ r'\gamma': u'\u213D', # ℽ
+ r'\pi': u'\u213C', # ℼ
+ }
+
+
# MathML element classes
# ----------------------
@@ -205,8 +251,10 @@
class math(object):
"""Base class for MathML elements."""
- nchildren = 1000000
- """Required/Supported number of children"""
+ nchildren = None
+ """Expected number of children or None"""
+ parent = None
+ """Parent node in MathML DOM tree."""
_level = 0 # indentation level (static class variable)
def __init__(self, children=None, inline=None, **kwargs):
@@ -216,7 +264,7 @@
self.children = []
if children is not None:
- if not isinstance(children, list):
+ if not isinstance(children, (list, tuple)):
children = [children]
for child in children:
self.append(child)
@@ -226,7 +274,6 @@
self.attributes['xmlns'] = 'http://www.w3.org/1998/Math/MathML'
if inline is False:
self.attributes['display'] = 'block'
- # self.attributes['displaystyle'] = 'true'
# sort kwargs for predictable functional tests
# as self.attributes.update(kwargs) does not keep order in Python < 3.6
for key in sorted(kwargs.keys()):
@@ -242,9 +289,9 @@
def full(self):
"""Room for more children?"""
+ return (self.nchildren is not None
+ and len(self.children) >= self.nchildren)
- return len(self.children) >= self.nchildren
-
def append(self, child):
"""append(child) -> element
@@ -255,7 +302,7 @@
self.children.append(child)
child.parent = self
node = self
- while node.full():
+ while node is not None and node.full():
node = node.parent
return node
@@ -310,42 +357,55 @@
last_child = child
return xml
-# >>> l2m.math(l2m.mn(2))
+# >>> math(mn(2))
# math(mn(2))
-# >>> l2m.math(l2m.mn(2)).xml()
+# >>> math(mn(2)).xml()
# ['<math>', '\n ', '<mn>', '2', '</mn>', '\n', '</math>']
#
-# >>> l2m.math(id='eq3')
+# >>> math(id='eq3')
# math(id='eq3')
-# >>> l2m.math(id='eq3').xml()
+# >>> math(id='eq3').xml()
# ['<math id="eq3">', '\n', '</math>']
#
# use CLASS to get "class" in XML
-# >>> l2m.math(CLASS='test')
+# >>> math(CLASS='test')
# math(CLASS='test')
-# >>> l2m.math(CLASS='test').xml()
+# >>> math(CLASS='test').xml()
# ['<math class="test">', '\n', '</math>']
-# >>> l2m.math(inline=True)
+# >>> math(inline=True)
# math(xmlns='http://www.w3.org/1998/Math/MathML')
-# >>> l2m.math(inline=True).xml()
+# >>> math(inline=True).xml()
# ['<math xmlns="http://www.w3.org/1998/Math/MathML">', '\n', '</math>']
-# >>> l2m.math(inline=False)
+# >>> math(inline=False)
# math(xmlns='http://www.w3.org/1998/Math/MathML', display='block')
-# >>> l2m.math(inline=False).xml()
+# >>> math(inline=False).xml()
# ['<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">', '\n', '</math>']
-class mrow(math): pass
+class mrow(math):
+ """Group sub-expressions as a horizontal row.
+ """
+ def __init__(self, children=None, nchildren=None, **kwargs):
+ self.nchildren = nchildren
+ math.__init__(self, children)
+ self.attributes = kwargs
-# >>> l2m.mrow(displaystyle='false')
+# >>> mrow(displaystyle='false')
# mrow(displaystyle='false')
class mtable(math): pass
-# >>> l2m.mtable(displaystyle='true')
+# >>> mtable(displaystyle='true')
# mtable(displaystyle='true')
-# >>> l2m.math(l2m.mtable(displaystyle='true')).xml()
+# >>> math(mtable(displaystyle='true')).xml()
# ['<math>', '\n ', '<mtable displaystyle="true">', '\n ', '</mtable>', '\n', '</math>']
+
+
+# The elements <msqrt>, <mstyle>, <merror>, <mpadded>, <mphantom>, <menclose>,
+# <mtd>, <mscarry>, and <math> treat their contents as a single inferred mrow
+# formed from all their children.
+class msqrt(mrow): pass
+class mstyle(mrow): pass
class mtr(mrow): pass
class mtd(mrow): pass
@@ -367,9 +427,9 @@
class mo(mx): pass
class mtext(mx): pass
-# >>> l2m.mo(u'<')
+# >>> mo(u'<')
# mo('<')
-# >>> l2m.mo(u'<').xml()
+# >>> mo(u'<').xml()
# ['<mo>', '<', '</mo>']
class msub(math):
@@ -378,9 +438,6 @@
class msup(math):
nchildren = 2
-class msqrt(math):
- nchildren = 1
-
class mroot(math):
nchildren = 2
@@ -403,18 +460,11 @@
class mspace(math):
nchildren = 0
-class mstyle(math):
- def __init__(self, children=None, nchildren=None, **kwargs):
- if nchildren is not None:
- self.nchildren = nchildren
- math.__init__(self, children)
- self.attributes = kwargs
-
class mover(math):
nchildren = 2
- def __init__(self, children=None, reversed=False):
+ def __init__(self, children=None, reversed=False, **kwargs):
self.reversed = reversed
- math.__init__(self, children)
+ math.__init__(self, children, **kwargs)
def xml(self):
if self.reversed:
@@ -422,7 +472,10 @@
self.reversed = False
return math.xml(self)
-class munder(math):
+# >>> mover(children=[mi('lim'), mo('-')], accent='false')
+# mover(mi('lim'), mo('-'), accent='false')
+
+class munder(mover):
nchildren = 2
class munderover(math):
@@ -440,11 +493,11 @@
def tex_cmdname(string):
"""Return leading TeX command name from `string`.
- >>> l2m.tex_cmdname('name2') # up to first non-letter
+ >>> tex_cmdname('name2') # up to first non-letter
('name', '2')
- >>> l2m.tex_cmdname('name 2') # strip trailing whitespace
+ >>> tex_cmdname('name 2') # strip trailing whitespace
('name', '2')
- >>> l2m.tex_cmdname('_2') # single non-letter character
+ >>> tex_cmdname('_2') # single non-letter character
('_', '2')
"""
@@ -455,21 +508,15 @@
# Test:
#
-# >>> l2m.tex_cmdname('name_2') # first non-letter terminates
+# >>> tex_cmdname('name_2') # first non-letter terminates
# ('name', '_2')
-# >>> l2m.tex_cmdname(' next') # leading whitespace is returned
+# >>> tex_cmdname(' next') # leading whitespace is returned
# (' ', 'next')
-# >>> l2m.tex_cmdname('1 2') # whitespace after non-letter is kept
+# >>> tex_cmdname('1 2') # whitespace after non-letter is kept
# ('1', ' 2')
-# >>> l2m.tex_cmdname('') # empty string
+# >>> tex_cmdname('') # empty string
# ('', '')
-
-# TODO: check for Inferred <mrow>s:
-
-# The elements <msqrt>, <mstyle>, <merror>, <mpadded>, <mphantom>, <menclose>,
-# <mtd, mscarry>, and <math> treat their contents as a single inferred mrow
-# formed from all their children
#
# --- https://www.w3.org/TR/MathML3/chapter3.html#id.3.1.3.2
@@ -478,11 +525,11 @@
Return token and remainder.
- >>> l2m.tex_token('{first simple group} {without brackets}')
+ >>> tex_token('{first simple group} {without brackets}')
('first simple group', ' {without brackets}')
- >>> l2m.tex_token('\\command{without argument}')
+ >>> tex_token('\\command{without argument}')
('\\command', '{without argument}')
- >>> l2m.tex_token(' first non-white character')
+ >>> tex_token(' first non-white character')
('f', 'irst non-white character')
"""
@@ -505,19 +552,19 @@
# Test:
#
-# >>> l2m.tex_token('{opening bracket of group with {nested group}}')
+# >>> tex_token('{opening bracket of group with {nested group}}')
# ('{', 'opening bracket of group with {nested group}}')
-# >>> l2m.tex_token('{group with \\{escaped\\} brackets}')
+# >>> tex_token('{group with \\{escaped\\} brackets}')
# ('group with \\{escaped\\} brackets', '')
-# >>> l2m.tex_token('{group followed by closing bracket}} from outer group')
+# >>> tex_token('{group followed by closing bracket}} from outer group')
# ('group followed by closing bracket', '} from outer group')
-# >>> l2m.tex_token(' {skip leading whitespace}')
+# >>> tex_token(' {skip leading whitespace}')
# ('skip leading whitespace', '')
-# >>> l2m.tex_token(' \\skip{leading whitespace}')
+# >>> tex_token(' \\skip{leading whitespace}')
# ('\\skip', '{leading whitespace}')
-# >>> l2m.tex_token('\\skip whitespace after macro name')
+# >>> tex_token('\\skip whitespace after macro name')
# ('\\skip', 'whitespace after macro name')
-# >>> l2m.tex_token('') # empty string.
+# >>> tex_token('') # empty string.
# ('', '')
@@ -527,8 +574,8 @@
Return a MathML-tree parsed from `string`.
Set `inline` to False for displayed math.
- >>> l2m.parse_latex_math('\\alpha')
- math(mrow(mi('α')), xmlns='http://www.w3.org/1998/Math/MathML')
+ >>> parse_latex_math('\\alpha')
+ math(mi('α'), xmlns='http://www.w3.org/1998/Math/MathML')
"""
@@ -537,8 +584,8 @@
# Set up: tree is the whole tree and node is the current element.
if inline:
- node = mrow()
- tree = math(node, inline=True)
+ node = math(inline=True)
+ tree = node
else:
# block: emulate align* environment with a math table
node = mtd()
@@ -550,7 +597,7 @@
c, string = string[0], string[1:]
if c == ' ':
- continue
+ continue # whitespace is ignored in LaTeX math mode
if c == '\\': # start of a LaTeX macro
cmdname, string = tex_cmdname(string)
@@ -561,7 +608,10 @@
node = node.append(mn(c))
elif c in "/()[]|":
node = node.append(mo(c, stretchy='false'))
- elif c in "+-*=<>,.!?':;@":
+ # use dedicated mathematical operator characters
+ elif c in anomalous_chars:
+ node = node.append(mo(anomalous_chars[c]))
+ elif c in "+*=<>,.!?';@":
node = node.append(mo(c))
elif c == '_':
child = node.delete_child()
@@ -603,12 +653,15 @@
# Test:
-# >>> l2m.parse_latex_math(' \\sqrt{ \\alpha}')
-# math(mrow(msqrt(mrow(mi('α')))), xmlns='http://www.w3.org/1998/Math/MathML')
-# >>> l2m.parse_latex_math('\\alpha', inline=False)
+# >>> parse_latex_math(' \\sqrt{ \\alpha}')
+# math(msqrt(mi('α')), xmlns='http://www.w3.org/1998/Math/MathML')
+# >>> parse_latex_math('\\alpha', inline=False)
# math(mtable(mtr(mtd(mi('α'))), CLASS='align', displaystyle='true'), xmlns='http://www.w3.org/1998/Math/MathML', display='block')
+# >>> parse_latex_math('\\sqrt 2 \\ne 3')
+# math(msqrt(mn('2')), mo('≠'), mn('3'), xmlns='http://www.w3.org/1998/Math/MathML')
+# >>> parse_latex_math('\\sqrt{2 + 3} < 3')
+# math(msqrt(mn('2'), mo('+'), mn('3')), mo('<'), mn('3'), xmlns='http://www.w3.org/1998/Math/MathML')
-
def handle_keyword(name, node, string):
"""Process LaTeX macro `name` followed by `string`.
@@ -615,9 +668,9 @@
If needed, parse `string` for macro argument.
Return updated current node and remainder:
- >>> l2m.handle_keyword('hbar', l2m.math(), r' \frac')
+ >>> handle_keyword('hbar', math(), r' \frac')
(math(mi('ℏ')), ' \\frac')
- >>> l2m.handle_keyword('hspace', l2m.math(), r'{1ex} (x)')
+ >>> handle_keyword('hspace', math(), r'{1ex} (x)')
(math(mspace(width='1ex')), ' (x)')
"""
@@ -637,20 +690,31 @@
node = node.append(mi(letters[name]))
return node, string
- if name in functions:
+ if (name in functions or name == 'operatorname'):
# use <mi> followed by invisible function applicator character
# (see https://www.w3.org/TR/MathML3/chapter3.html#presm.mi)
- node = node.append(mi(name))
- node = node.append(mo('⁡'))
- return node, string
+ if name == 'operatorname':
+ # custom function name ``\operatorname{abs}(x)``
+ arg, string = tex_token(string)
+ identifier = mi(arg, mathvariant='normal')
+ else:
+ identifier = mi(functions[name])
+ # functions with embellished names
+ if name == 'varliminf': # \underline\lim
+ identifier = munder([identifier, mo(u'_')], accent='false')
+ elif name == 'varlimsup': # \overline\lim
+ identifier = mover([identifier, mo(u'¯')], accent='false')
+ elif name == 'varprojlim': # \underleftarrow\lim
+ identifier = munder([identifier, mo(u'\u2190')], accent='false')
+ elif name == 'varinjlim': # \underrightarrow\lim
+ identifier = munder([identifier, mo(u'\u2192')], accent='false')
- if name == 'operatorname':
- # custom function name ``\operatorname{abs}(x)``
- arg, string = tex_token(string)
- node = node.append(mi(arg, mathvariant='normal'))
+ node = node.append(identifier)
+ # TODO: only add ApplyFunction when appropriate (not \sin ^2(x), say)
node = node.append(mo('⁡')) # '\u2061'
return node, string
+
if name in math_alphabets:
arg, remainder = tex_token(string)
if arg[0] == '\\':
@@ -665,6 +729,8 @@
kwargs = {'style': 'font-weight: bold'}
else:
kwargs = {'mathvariant': math_alphabets[name]}
+ if name == 'mathscr':
+ kwargs['style'] = 'font-family: STIX' # alternative script letter shapes
# one symbol (single letter, name, or number)
if arg.isalpha():
@@ -685,10 +751,26 @@
# operator, fence, or separator -> <mo>
- if name == 'colon': # "normal" colon, not binary operator
+ if name in left_delimiters: # opening delimiters
+ node = node.append(mo(left_delimiters[name], rspace='0'))
+ return node, string
+
+ if name in right_delimiters: # closing delimiters
+ node = node.append(mo(right_delimiters[name], lspace='0', ))
+ return node, string
+
+ if name == 'colon': # trailing punctuation, not binary relation
node = node.append(mo(':', lspace='0', rspace='0.28em'))
return node, string
+ if name in thick_operators:
+ node = node.append(mo(thick_operators[name], style='font-weight: bold'))
+ return node, string
+
+ if name in small_operators:
+ node = node.append(mo(small_operators[name], mathsize='75%'))
+ return node, string
+
if name in operators:
node = node.append(mo(operators[name]))
return node, string
@@ -714,7 +796,7 @@
try:
node = node.append(mo(negatables[arg]))
except KeyError:
- raise SyntaxError(u'Expected something to negate: "\\not ..."!')
+ raise SyntaxError(u'"\\not: Cannot negate: %s!'%arg)
return node, string
# arbitrary text (usually comments) -> <mtext>
@@ -741,7 +823,11 @@
# ==================================
if name == 'sqrt':
- sqrt = msqrt()
+ if string.startswith('{'): # argument is a group
+ string = string[1:] # mrow implied, skip opening bracket
+ sqrt = msqrt()
+ else: # no group, enclose only one element
+ sqrt = msqrt(nchildren=1)
node.append(sqrt)
return sqrt, string
@@ -757,12 +843,21 @@
node = entry
return node, string
- if name in over:
- ovr = mover(mo(over[name]), reversed=True)
+ if name in over or name in wideover:
+ try:
+ ovr = mover(mo(over[name]), reversed=True)
+ except KeyError:
+ ovr = mover(mo(wideover[name]), reversed=True, accent='false')
node.append(ovr)
node = ovr
return node, string
+ if name in wideunder:
+ ovr = munder(mo(wideunder[name]), reversed=True, accent='false')
+ node.append(ovr)
+ node = ovr
+ return node, string
+
if name == 'begin':
env_name, string = tex_token(string)
if env_name == 'matrix':
@@ -794,33 +889,36 @@
raise SyntaxError(u'Unknown LaTeX command: ' + name)
-# >>> l2m.handle_keyword('left', l2m.math(), '[a\\right]')
+# >>> handle_keyword('left', math(), '[a\\right]')
# (mrow(mo('[')), 'a\\right]')
-# >>> l2m.handle_keyword('left', l2m.math(), '. a)') # emtpy \left
+# >>> handle_keyword('left', math(), '. a)') # emtpy \left
# (mrow(), ' a)')
-# >>> l2m.handle_keyword('left', l2m.math(), '\\uparrow a)') # cmd
+# >>> handle_keyword('left', math(), '\\uparrow a)') # cmd
# (mrow(mo('↑')), 'a)')
-# >>> l2m.handle_keyword('not', l2m.math(), '\\equiv \\alpha)') # cmd
+# >>> handle_keyword('not', math(), '\\equiv \\alpha)') # cmd
# (math(mo('≢')), '\\alpha)')
-# >>> l2m.handle_keyword('text', l2m.math(), '{ for } i>0') # group
+# >>> handle_keyword('text', math(), '{ for } i>0') # group
# (math(mtext(' for ')), ' i>0')
-# >>> l2m.handle_keyword('text', l2m.math(), '{B}T') # group
+# >>> handle_keyword('text', math(), '{B}T') # group
# (math(mtext('B')), 'T')
-# >>> l2m.handle_keyword('text', l2m.math(), '{number of apples}}') # group
+# >>> handle_keyword('text', math(), '{number of apples}}') # group
# (math(mtext('number of apples')), '}')
-# >>> l2m.handle_keyword('text', l2m.math(), 'i \\sin(x)') # single char
+# >>> handle_keyword('text', math(), 'i \\sin(x)') # single char
# (math(mtext('i')), ' \\sin(x)')
-# >>> l2m.handle_keyword('sin', l2m.math(), '(\\alpha)')
+# >>> handle_keyword('sin', math(), '(\\alpha)')
# (math(mi('sin'), mo('⁡')), '(\\alpha)')
-# >>> l2m.handle_keyword('sin', l2m.math(), ' \\alpha')
+# >>> handle_keyword('sin', math(), ' \\alpha')
# (math(mi('sin'), mo('⁡')), ' \\alpha')
-# >>> l2m.handle_keyword('operatorname', l2m.math(), '{abs}(x)')
+# >>> handle_keyword('operatorname', math(), '{abs}(x)')
# (math(mi('abs', mathvariant='normal'), mo('⁡')), '(x)')
-# >>> l2m.handle_keyword('mathrm', l2m.math(), '\\alpha')
+# >>> handle_keyword('mathrm', math(), '\\alpha')
# (math(mi('α', mathvariant='normal')), '')
-# >>> l2m.handle_keyword('mathrm', l2m.math(), '{out} = 3')
+# >>> handle_keyword('mathrm', math(), '{out} = 3')
# (math(mi('out', mathvariant='normal')), ' = 3')
+# >>> handle_keyword('overline', math(), '{981}')
+# (mover(mo('¯'), accent='false'), '{981}')
+
def tex2mathml(tex_math, inline=True):
"""Return string with MathML code corresponding to `tex_math`.
Modified: trunk/docutils/docutils/utils/math/tex2unichar.py
===================================================================
--- trunk/docutils/docutils/utils/math/tex2unichar.py 2021-05-20 12:22:05 UTC (rev 8747)
+++ trunk/docutils/docutils/utils/math/tex2unichar.py 2021-05-20 12:22:27 UTC (rev 8748)
@@ -1,4 +1,4 @@
-# -*- coding: utf-8 -*-
+# -*- coding: utf8 -*-
# LaTeX math to Unicode symbols translation dictionaries.
# Generated with ``write_tex2unichar.py`` from the data in
@@ -7,30 +7,30 @@
# Includes commands from: wasysym, stmaryrd, mathdots, mathabx, esint, bbold, amsxtra, amsmath, amssymb, standard LaTeX
mathaccent = {
- 'acute': u'\u0301', # x́ COMBINING ACUTE ACCENT
- 'bar': u'\u0304', # x̄ COMBINING MACRON
- 'breve': u'\u0306', # x̆ COMBINING BREVE
- 'check': u'\u030c', # x̌ COMBINING CARON
+ 'acute': u'\u0301', # ́ COMBINING ACUTE ACCENT
+ 'bar': u'\u0304', # ̄ COMBINING MACRON
+ 'breve': u'\u0306', # ̆ COMBINING BREVE
+ 'check': u'\u030c', # ̌ COMBINING CARON
'ddddot': u'\u20dc', # x⃜ COMBINING FOUR DOTS ABOVE
'dddot': u'\u20db', # x⃛ COMBINING THREE DOTS ABOVE
- 'ddot': u'\u0308', # ẍ COMBINING DIAERESIS
- 'dot': u'\u0307', # ẋ COMBINING DOT ABOVE
- 'grave': u'\u0300', # x̀ COMBINING GRAVE ACCENT
- 'hat': u'\u0302', # x̂ COMBINING CIRCUMFLEX ACCENT
- 'mathring': u'\u030a', # x̊ COMBINING RING ABOVE
- 'not': u'\u0338', # x̸ COMBINING LONG SOLIDUS OVERLAY
+ 'ddot': u'\u0308', # ̈ COMBINING DIAERESIS
+ 'dot': u'\u0307', # ̇ COMBINING DOT ABOVE
+ 'grave': u'\u0300', # ̀ COMBINING GRAVE ACCENT
+ 'hat': u'\u0302', # ̂ COMBINING CIRCUMFLEX ACCENT
+ 'mathring': u'\u030a', # ̊ COMBINING RING ABOVE
+ 'not': u'\u0338', # ̸ COMBINING LONG SOLIDUS OVERLAY
'overleftarrow': u'\u20d6', # x⃖ COMBINING LEFT ARROW ABOVE
'overleftrightarrow': u'\u20e1', # x⃡ COMBINING LEFT RIGHT ARROW ABOVE
- 'overline': u'\u0305', # x̅ COMBINING OVERLINE
+ 'overline': u'\u0305', # ̅ COMBINING OVERLINE
'overrightarrow': u'\u20d7', # x⃗ COMBINING RIGHT ARROW ABOVE
- 'tilde': u'\u0303', # x̃ COMBINING TILDE
- 'underbar': u'\u0331', # x̱ COMBINING MACRON BELOW
+ 'tilde': u'\u0303', # ̃ COMBINING TILDE
+ 'underbar': u'\u0331', # ̱ COMBINING MACRON BELOW
'underleftarrow': u'\u20ee', # x⃮ COMBINING LEFT ARROW BELOW
- 'underline': u'\u0332', # x̲ COMBINING LOW LINE
+ 'underline': u'\u0332', # ̲ COMBINING LOW LINE
'underrightarrow': u'\u20ef', # x⃯ COMBINING RIGHT ARROW BELOW
'vec': u'\u20d7', # x⃗ COMBINING RIGHT ARROW ABOVE
- 'widehat': u'\u0302', # x̂ COMBINING CIRCUMFLEX ACCENT
- 'widetilde': u'\u0303', # x̃ COMBINING TILDE
+ 'widehat': u'\u0302', # ̂ COMBINING CIRCUMFLEX ACCENT
+ 'widetilde': u'\u0303', # ̃ COMBINING TILDE
}
mathalpha = {
'Bbbk': u'\U0001d55c', # 𝕜 MATHEMATICAL DOUBLE-STRUCK SMALL K
@@ -54,7 +54,7 @@
'chi': u'\u03c7', # χ GREEK SMALL LETTER CHI
'daleth': u'\u2138', # ℸ DALET SYMBOL
'delta': u'\u03b4', # δ GREEK SMALL LETTER DELTA
- 'digamma': u'\u03dc', # Ϝ GREEK LETTER DIGAMMA
+ 'digamma': u'\u03dd', # ϝ GREEK SMALL LETTER DIGAMMA
'ell': u'\u2113', # ℓ SCRIPT SMALL L
'epsilon': u'\u03f5', # ϵ GREEK LUNATE EPSILON SYMBOL
'eta': u'\u03b7', # η GREEK SMALL LETTER ETA
@@ -91,7 +91,7 @@
'varUpsilon': u'\U0001d6f6', # 𝛶 MATHEMATICAL ITALIC CAPITAL UPSILON
'varXi': u'\U0001d6ef', # 𝛯 MATHEMATICAL ITALIC CAPITAL XI
'varepsilon': u'\u03b5', # ε GREEK SMALL LETTER EPSILON
- 'varkappa': u'\U0001d718', # 𝜘 MATHEMATICAL ITALIC KAPPA SYMBOL
+ 'varkappa': u'\u03f0', # ϰ GREEK KAPPA SYMBOL
'varphi': u'\u03c6', # φ GREEK SMALL LETTER PHI
'va...
[truncated message content] |
|
From: <mi...@us...> - 2021-05-20 12:23:08
|
Revision: 8750
http://sourceforge.net/p/docutils/code/8750
Author: milde
Date: 2021-05-20 12:23:06 +0000 (Thu, 20 May 2021)
Log Message:
-----------
MathML: simplify node class interface, fix accent handling.
Instantiating functions for "math" class and descendents handle all
positional arguments as children/data and named arguments as attributes.
Set "accent" argument for <mover> according to LaTeX macro.
Influences dropping of i-dot and size of top character, defaults to
"automatic" (MathML 3) or "false" (MathML Core Draft).
Modified Paths:
--------------
trunk/docutils/docs/user/mathematics.txt
trunk/docutils/docutils/utils/math/latex2mathml.py
trunk/docutils/test/functional/expected/math_output_mathml.html
Modified: trunk/docutils/docs/user/mathematics.txt
===================================================================
--- trunk/docutils/docs/user/mathematics.txt 2021-05-20 12:22:52 UTC (rev 8749)
+++ trunk/docutils/docs/user/mathematics.txt 2021-05-20 12:23:06 UTC (rev 8750)
@@ -132,8 +132,7 @@
=========== ============= =========== ============= ============== ================
When adding an accent to an i or j in math, dotless variants can be
-obtained with ``\imath`` and ``\jmath``: `\bar \imath`, `\hat{\jmath}`
-(MathML drops the dot automatically).
+obtained with ``\imath`` and ``\jmath``: `\hat \imath`, `\vec{\jmath}`.
For embellishments that span multiple symbols, use:
@@ -669,23 +668,27 @@
~~~~~~~~~~~~~~~~~~~~~~~~~~
The elements <msqrt>, <mstyle>, <merror>, <mpadded>, <mphantom>, <menclose>,
-<mtd, mscarry>, and <math> treat their contents as a single inferred mrow
+<mtd>, <mscarry>, and <math> treat their contents as a single inferred mrow
formed from all their children.
-.. math:: a = \sqrt 2, b = \sqrt{1+x^2}, c = \sqrt\frac{sin(x)}{23}
+.. math:: a = \sqrt 2 + x, b = \sqrt{1+x^2}, c = \sqrt\frac{sin(x)}{23},
-inline: :math:`a = \sqrt 2, b = \sqrt{1+x^2}, c = \sqrt\frac{sin(x)}{23}`.
+inline: :math:`a = \sqrt 2 + x, b = \sqrt{1+x^2}, c = \sqrt\frac{sin(x)}{23}`.
+
Accents vs. embellishments
--------------------------
-MathML with Firefox 78 drobs dots on "i" and "j" with accents:
+MathML with Firefox 78 drops dots on "i" and "j" with accents:
.. math:: \vec i \ne \overrightarrow i
\text{ and } \vec\lim \ne \overrightarrow\lim.
-Accents should be nearer to the base (in MathML Firefox 78, it's vice versa!):
+Accents should be nearer to the base (in MathML Firefox 78, it's vice versa!):
+`\vec a \overrightarrow a, \vec l \overrightarrow l, \vec i \overrightarrow i`
+and `\bar a \overline a, \bar l \overline l, \bar i \overline i`.
-.. math:: \vec a \vec l \ne \overrightarrow a \overrightarrow l
+In inline formulas and fractions, the limits on lim, sum and integral should
+move to index postions: `\lim_{c\to0} \oint_c f(x) \mathrm{d}x` vs.
- \bar a \bar l \ne \overline a \overline l
+.. math:: \lim_{c\to0} \oint_c f(x) \mathrm{d}x
Modified: trunk/docutils/docutils/utils/math/latex2mathml.py
===================================================================
--- trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:22:52 UTC (rev 8749)
+++ trunk/docutils/docutils/utils/math/latex2mathml.py 2021-05-20 12:23:06 UTC (rev 8750)
@@ -54,7 +54,7 @@
functions = ['arccos', 'arcsin', 'arctan', 'arg', 'cos', 'cosh',
'cot', 'coth', 'csc', 'deg', 'det', 'dim',
'exp', 'gcd', 'hom', 'inf', 'ker', 'lg',
- 'lim', 'ln', 'log', 'max', 'min', 'Pr',
+ 'ln', 'log', 'max', 'min', 'Pr',
'sec', 'sin', 'sinh', 'sup', 'tan', 'tanh']
functions = dict((name, name) for name in functions)
functions.update({# functions with a space in the name
@@ -100,11 +100,10 @@
'ngeqslant': u'\u2a7e\u0338', # ⩾̸
'nsubseteqq': u'\u2AC5\u0338', # ⫅̸
'nsupseteqq': u'\u2AC6\u0338', # ⫆̸
+ # use <mo> to allow "movablelimits" attribute
+ 'lim': u'lim',
})
-# >>> '{' in operators.values()
-# True
-
# special cases
thick_operators = {# style='font-weight: bold;'
@@ -132,12 +131,13 @@
'rVert': u'\u2016', # ‖ DOUBLE VERTICAL LINE
}
-sumintprod = ''.join([operators[symbol] for symbol in
- ['sum', 'int', 'oint', 'prod']])
+# operators with limits either over/under or in index position
+sumintprod = ['coprod', 'fatsemi', 'fint', 'iiiint', 'iiint',
+ 'iint', 'int', 'oiint', 'oint', 'ointctrclockwise',
+ 'prod', 'sqint', 'sum', 'varointclockwise']
+sumintprod += [operators[name] for name in sumintprod]
+sumintprod.append('lim')
-# >>> print(sumintprod)
-# ∑∫∮∏
-
# pre-composed characters for negated symbols
# see https://www.w3.org/TR/xml-entity-names/#combining
negatables = {'=': u'\u2260',
@@ -195,34 +195,35 @@
'!': '-0.1667em', # negthinspace
}
-# accents -> <mover>
+# accents -> <mover accent="true">
# TeX spacing combining
-over = {'acute': u'´', # u'\u0301',
- 'bar': u'-', # u'\u0304',
- 'breve': u'˘', # u'\u0306',
- 'check': u'ˇ', # u'\u030C',
- 'dot': u'·', # u'\u0307',
- 'ddot': u'··', # u'\u0308',
- 'dddot': u'···', # u'\u20DB',
- 'grave': u'`', # u'\u0300',
- 'hat': u'^', # u'\u0302',
- 'mathring': u'°', # u'\u030A',
- 'tilde': u'\u223C', # u'\u0303',
- 'vec': u'\u20D7',
+accents = {'acute': u'´', # u'\u0301',
+ 'bar': u'ˉ', # u'\u0304',
+ 'breve': u'˘', # u'\u0306',
+ 'check': u'ˇ', # u'\u030C',
+ 'dot': u'˙', # u'\u0307',
+ 'ddot': u'¨', # u'\u0308',
+ 'dddot': u'\u20DB', # '…' too wide
+ 'grave': u'`', # u'\u0300',
+ 'hat': u'ˆ', # u'\u0302',
+ 'mathring': u'˚', # u'\u030A',
+ 'tilde': u'˜', # u'\u0303',
}
-wideover = {'overbrace': u'\u23DE', # TOP CURLY BRACKET
- 'overleftarrow': u'\u2190',
- 'overleftrightarrow': u'\u2194',
- 'overline': u'¯',
- 'overrightarrow': u'\u2192',
- 'widehat': u'^',
- 'widetilde': u'~'}
-wideunder = {'underbrace': u'\u23DF',
- 'underleftarrow': u'\u2190',
- 'underleftrightarrow': u'\u2194',
- 'underline': u'_',
- 'underrightarrow': u'\u2192'}
+# limits etc. -> <mover> rsp. <munder>
+over = {'overbrace': u'\u23DE', # TOP CURLY BRACKET
+ 'overleftarrow': u'\u2190',
+ 'overleftrightarrow': u'\u2194',
+ 'overline': u'¯',
+ 'overrightarrow': u'\u2192',
+ 'vec': u'\u2192', # → (too heavy if accent="true")
+ 'widehat': u'^',
+ 'widetilde': u'~'}
+under = {'underbrace': u'\u23DF',
+ 'underleftarrow': u'\u2190',
+ 'underleftrightarrow': u'\u2194',
+ 'underline': u'_',
+ 'underrightarrow': u'\u2192'}
# Character translations
# ----------------------
@@ -257,32 +258,26 @@
"""Parent node in MathML DOM tree."""
_level = 0 # indentation level (static class variable)
- def __init__(self, children=None, inline=None, **kwargs):
- """math([children]) -> MathML element
+ def __init__(self, *children, **attributes):
+ """math(*children **attributes) -> MathML element
+ """
- children can be one child or a list of children."""
-
self.children = []
- if children is not None:
- if not isinstance(children, (list, tuple)):
- children = [children]
- for child in children:
- self.append(child)
+ for child in children:
+ self.append(child)
self.attributes = collections.OrderedDict()
- if inline is not None:
- self.attributes['xmlns'] = 'http://www.w3.org/1998/Math/MathML'
- if inline is False:
- self.attributes['display'] = 'block'
- # sort kwargs for predictable functional tests
- # as self.attributes.update(kwargs) does not keep order in Python < 3.6
- for key in sorted(kwargs.keys()):
- self.attributes.setdefault(key, kwargs[key])
+ # sort attributes for predictable functional tests
+ # as self.attributes.update(attributes) does not keep order in Python < 3.6
+ for key in sorted(attributes.keys()):
+ self.attributes.setdefault(key, attributes[key])
def __repr__(self):
content = [repr(item) for item in getattr(self, 'children', [])]
if hasattr(self, 'data'):
content.append(repr(self.data))
+ if isinstance(self, MathScriptOrLimit) and self.reversed:
+ content.append('reversed=True')
if hasattr(self, 'attributes'):
content += ["%s='%s'"%(k, v) for k, v in self.attributes.items()]
return self.__class__.__name__ + '(%s)' % ', '.join(content)
@@ -306,15 +301,6 @@
node = node.parent
return node
- def delete_child(self):
- """delete_child() -> child
-
- Delete last child and return it."""
-
- child = self.children[-1]
- del self.children[-1]
- return child
-
def close(self):
"""close() -> parent
@@ -335,13 +321,13 @@
# (Python keyword). MathML uses only lowercase attributes.
attrs = ['%s="%s"'%(k.lower(), v) for k, v
in getattr(self, 'attributes', {}).items()]
- if not isinstance(self, mx): # token elements
+ if not isinstance(self, MathToken): # token elements
math._level += 1
return ['<%s>' % ' '.join([self.__class__.__name__] + attrs)]
def xml_end(self):
xml = []
- if not isinstance(self, mx): # except token elements
+ if not isinstance(self, MathToken): # except token elements
math._level -= 1
xml.append('\n' + ' ' * math._level)
xml.append('</%s>' % self.__class__.__name__)
@@ -351,7 +337,7 @@
xml = []
last_child = None
for child in self.children:
- if not (isinstance(last_child, mx) and isinstance(child, mx)):
+ if not (isinstance(last_child, MathToken) and isinstance(child, MathToken)):
xml.append('\n' + ' ' * math._level)
xml.extend(child.xml())
last_child = child
@@ -373,22 +359,11 @@
# >>> math(CLASS='test').xml()
# ['<math class="test">', '\n', '</math>']
-# >>> math(inline=True)
-# math(xmlns='http://www.w3.org/1998/Math/MathML')
-# >>> math(inline=True).xml()
+# >>> math(xmlns='http://www.w3.org/1998/Math/MathML').xml()
# ['<math xmlns="http://www.w3.org/1998/Math/MathML">', '\n', '</math>']
-# >>> math(inline=False)
-# math(xmlns='http://www.w3.org/1998/Math/MathML', display='block')
-# >>> math(inline=False).xml()
-# ['<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">', '\n', '</math>']
class mrow(math):
- """Group sub-expressions as a horizontal row.
- """
- def __init__(self, children=None, nchildren=None, **kwargs):
- self.nchildren = nchildren
- math.__init__(self, children)
- self.attributes = kwargs
+ """Group sub-expressions as a horizontal row."""
# >>> mrow(displaystyle='false')
# mrow(displaystyle='false')
@@ -409,23 +384,23 @@
class mtr(mrow): pass
class mtd(mrow): pass
-class mx(math):
+class MathToken(math):
"""Token Element: Base class for mo, mi, and mn.
"""
nchildren = 0
entity_table = {ord('<'): u'<', ord('>'): u'>'}
- def __init__(self, data, **kwargs):
+ def __init__(self, data, **attributes):
self.data = data
- super(mx, self).__init__(**kwargs)
+ super(MathToken, self).__init__(**attributes)
def xml_body(self):
return [unicode(self.data).translate(self.entity_table)]
-class mi(mx): pass
-class mn(mx): pass
-class mo(mx): pass
-class mtext(mx): pass
+class mi(MathToken): pass
+class mn(MathToken): pass
+class mo(MathToken): pass
+class mtext(MathToken): pass
# >>> mo(u'<')
# mo('<')
@@ -432,58 +407,50 @@
# >>> mo(u'<').xml()
# ['<mo>', '<', '</mo>']
-class msub(math):
+class MathScriptOrLimit(math):
+ """Base class for script and limit schemata."""
nchildren = 2
-class msup(math):
- nchildren = 2
+ def __init__(self, *children, **kwargs):
+ self.reversed = kwargs.pop('reversed', False)
+ math.__init__(self, *children, **kwargs)
-class mroot(math):
- nchildren = 2
-
-class mfrac(math):
- nchildren = 2
-
-class msubsup(math):
- nchildren = 3
- def __init__(self, children=None, reversed=False):
- self.reversed = reversed
- math.__init__(self, children)
-
def xml(self):
if self.reversed:
- ## self.children[1:3] = self.children[2:0:-1]
- self.children[1:3] = [self.children[2], self.children[1]]
+ self.children.reverse()
self.reversed = False
- return super(msubsup, self).xml()
+ return super(MathScriptOrLimit, self).xml()
-class mspace(math):
- nchildren = 0
+class msub(MathScriptOrLimit): pass
+class msup(MathScriptOrLimit): pass
+class msubsup(MathScriptOrLimit):
+ nchildren = 3
-class mover(math):
- nchildren = 2
- def __init__(self, children=None, reversed=False, **kwargs):
- self.reversed = reversed
- math.__init__(self, children, **kwargs)
+class munder(MathScriptOrLimit): pass
+class mover(MathScriptOrLimit): pass
+class munderover(MathScriptOrLimit):
+ nchildren = 3
- def xml(self):
- if self.reversed:
- self.children.reverse()
- self.reversed = False
- return math.xml(self)
+# >>> munder(mi('lim'), mo('-'), accent='false')
+# munder(mi('lim'), mo('-'), accent='false')
+# >>> munder(mo('-'), mi('lim'), accent='false', reversed=True)
+# munder(mo('-'), mi('lim'), reversed=True, accent='false')
+# >>> ''.join(munder(mo('-'), mi('lim'), accent='false', reversed=True).xml())
+# '<munder accent="false">\n <mi>lim</mi><mo>-</mo>\n</munder>'
+# >>> msub(mi('x'), mo('-'))
+# msub(mi('x'), mo('-'))
-# >>> mover(children=[mi('lim'), mo('-')], accent='false')
-# mover(mi('lim'), mo('-'), accent='false')
-class munder(mover):
+class mroot(math):
nchildren = 2
-class munderover(math):
- nchildren = 3
- def __init__(self, children=None):
- math.__init__(self, children)
+class mfrac(math):
+ nchildren = 2
+class mspace(math):
+ nchildren = 0
+
# LaTeX to MathML translation
# ---------------------------
@@ -584,13 +551,14 @@
# Set up: tree is the whole tree and node is the current element.
if inline:
- node = math(inline=True)
+ node = math(xmlns='http://www.w3.org/1998/Math/MathML')
tree = node
else:
# block: emulate align* environment with a math table
node = mtd()
- content = mtable(mtr(node), displaystyle='true', CLASS='align')
- tree = math(content, inline=False)
+ lines = mtable(mtr(node), displaystyle='true', CLASS='align')
+ tree = math(lines, display='block',
+ xmlns='http://www.w3.org/1998/Math/MathML')
while len(string) > 0:
# Take of first character:
@@ -614,10 +582,11 @@
elif c in "+*=<>,.!?';@":
node = node.append(mo(c))
elif c == '_':
- child = node.delete_child()
+ child = node.children.pop()
if isinstance(child, msup):
- sub = msubsup(child.children, reversed=True)
- elif isinstance(child, mo) and child.data in sumintprod:
+ sub = msubsup(*child.children, reversed=True)
+ elif isinstance(child, MathToken) and child.data in sumintprod:
+ child.attributes['movablelimits'] = 'true'
sub = munder(child)
else:
sub = msub(child)
@@ -624,14 +593,15 @@
node.append(sub)
node = sub
elif c == '^':
- child = node.delete_child()
+ child = node.children.pop()
if isinstance(child, msub):
- sup = msubsup(child.children)
- elif isinstance(child, mo) and child.data in sumintprod:
+ sup = msubsup(*child.children)
+ elif isinstance(child, MathToken) and child.data in sumintprod:
+ child.attributes['movablelimits'] = 'true'
sup = mover(child)
elif (isinstance(child, munder) and
child.children[0].data in sumintprod):
- sup = munderover(child.children)
+ sup = munderover(*child.children)
else:
sup = msup(child)
node.append(sup)
@@ -653,10 +623,14 @@
# Test:
+# >>> parse_latex_math('', inline=True)
+# math(xmlns='http://www.w3.org/1998/Math/MathML')
+# >>> parse_latex_math('', inline=False)
+# math(mtable(mtr(mtd()), CLASS='align', displaystyle='true'), display='block', xmlns='http://www.w3.org/1998/Math/MathML')
# >>> parse_latex_math(' \\sqrt{ \\alpha}')
# math(msqrt(mi('α')), xmlns='http://www.w3.org/1998/Math/MathML')
# >>> parse_latex_math('\\alpha', inline=False)
-# math(mtable(mtr(mtd(mi('α'))), CLASS='align', displaystyle='true'), xmlns='http://www.w3.org/1998/Math/MathML', display='block')
+# math(mtable(mtr(mtd(mi('α'))), CLASS='align', displaystyle='true'), display='block', xmlns='http://www.w3.org/1998/Math/MathML')
# >>> parse_latex_math('\\sqrt 2 \\ne 3')
# math(msqrt(mn('2')), mo('≠'), mn('3'), xmlns='http://www.w3.org/1998/Math/MathML')
# >>> parse_latex_math('\\sqrt{2 + 3} < 3')
@@ -701,13 +675,13 @@
identifier = mi(functions[name])
# functions with embellished names
if name == 'varliminf': # \underline\lim
- identifier = munder([identifier, mo(u'_')], accent='false')
+ identifier = munder(identifier, mo(u'_'))
elif name == 'varlimsup': # \overline\lim
- identifier = mover([identifier, mo(u'¯')], accent='false')
+ identifier = mover(identifier, mo(u'¯'), accent='false')
elif name == 'varprojlim': # \underleftarrow\lim
- identifier = munder([identifier, mo(u'\u2190')], accent='false')
+ identifier = munder(identifier, mo(u'\u2190'))
elif name == 'varinjlim': # \underrightarrow\lim
- identifier = munder([identifier, mo(u'\u2192')], accent='false')
+ identifier = munder(identifier, mo(u'\u2192'))
node = node.append(identifier)
# TODO: only add ApplyFunction when appropriate (not \sin ^2(x), say)
@@ -726,25 +700,26 @@
arg = letters.get(arg[1:], arg)
if name == 'boldsymbol':
- kwargs = {'style': 'font-weight: bold'}
+ attributes = {'style': 'font-weight: bold'}
else:
- kwargs = {'mathvariant': math_alphabets[name]}
+ attributes = {'mathvariant': math_alphabets[name]}
if name == 'mathscr':
- kwargs['style'] = 'font-family: STIX' # alternative script letter shapes
+ # alternative script letter shapes
+ attributes['style'] = 'font-family: STIX'
# one symbol (single letter, name, or number)
if arg.isalpha():
- node = node.append(mi(arg, **kwargs))
+ node = node.append(mi(arg, **attributes))
return node, remainder
if arg.replace('.', '').replace(',', '').isdigit():
- node = node.append(mn(arg, **kwargs))
+ node = node.append(mn(arg, **attributes))
return node, remainder
if len(arg) == 1 and arg != '{':
- node = node.append(mo(arg, **kwargs))
+ node = node.append(mo(arg, **attributes))
return node, remainder
# Wrap in <style>
- style = mstyle(**kwargs)
+ style = mstyle(**attributes)
node.append(style)
return style, string[1:] # take of the opening '{', <mrow> is inferred
@@ -771,6 +746,10 @@
node = node.append(mo(small_operators[name], mathsize='75%'))
return node, string
+ if name in sumintprod:
+ node = node.append(mo(operators[name]))
+ return node, string
+
if name in operators:
node = node.append(mo(operators[name]))
return node, string
@@ -823,11 +802,11 @@
# ==================================
if name == 'sqrt':
+ sqrt = msqrt()
if string.startswith('{'): # argument is a group
string = string[1:] # mrow implied, skip opening bracket
- sqrt = msqrt()
else: # no group, enclose only one element
- sqrt = msqrt(nchildren=1)
+ sqrt.nchildren = 1
node.append(sqrt)
return sqrt, string
@@ -840,23 +819,23 @@
entry = mtd()
row = mtr(entry)
node.close().close().append(row)
- node = entry
- return node, string
+ return entry, string
- if name in over or name in wideover:
+ if name in accents or name in over:
try:
- ovr = mover(mo(over[name]), reversed=True)
+ ch = over[name]
+ acc = 'false'
except KeyError:
- ovr = mover(mo(wideover[name]), reversed=True, accent='false')
+ ch = accents[name]
+ acc = 'true'
+ ovr = mover(mo(ch), reversed=True, accent=acc)
node.append(ovr)
- node = ovr
- return node, string
+ return ovr, string
- if name in wideunder:
- ovr = munder(mo(wideunder[name]), reversed=True, accent='false')
+ if name in under:
+ ovr = munder(mo(under[name]), reversed=True)
node.append(ovr)
- node = ovr
- return node, string
+ return ovr, string
if name == 'begin':
env_name, string = tex_token(string)
@@ -867,7 +846,7 @@
node = entry
elif env_name == 'cases':
entry = mtd()
- cases = mrow([mo('{'), mtable(mtr(entry))])
+ cases = mrow(mo('{'), mtable(mtr(entry)))
node.append(cases)
node = entry
else:
@@ -916,7 +895,9 @@
# >>> handle_keyword('mathrm', math(), '{out} = 3')
# (math(mi('out', mathvariant='normal')), ' = 3')
# >>> handle_keyword('overline', math(), '{981}')
-# (mover(mo('¯'), accent='false'), '{981}')
+# (mover(mo('¯'), reversed=True, accent='false'), '{981}')
+# >>> handle_keyword('bar', math(), '{x}')
+# (mover(mo('ˉ'), reversed=True, accent='true'), '{x}')
def tex2mathml(tex_math, inline=True):
Modified: trunk/docutils/test/functional/expected/math_output_mathml.html
===================================================================
--- trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:22:52 UTC (rev 8749)
+++ trunk/docutils/test/functional/expected/math_output_mathml.html 2021-05-20 12:23:06 UTC (rev 8750)
@@ -38,7 +38,7 @@
</math>, as well as displayed math via the
<cite>math</cite> directive:</p>
<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
@@ -73,7 +73,7 @@
</div>
<p>Content may start on the first line of the directive, e.g.</p>
<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
@@ -95,7 +95,7 @@
See <a class="reference internal" href="#eq-m">eq:M</a> and <a class="reference internal" href="#eq-schrodinger">eq:schrödinger</a> below.</p>
<p>The determinant of the matrix</p>
<div id="eq-m">
-<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
@@ -133,12 +133,12 @@
<p>More than one display math block can be put in one math directive.
For example, the following sum and integral with limits:</p>
<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
<munderover>
- <mo>∫</mo><mn>0</mn><mn>1</mn>
+ <mo movablelimits="true">∫</mo><mn>0</mn><mn>1</mn>
</munderover>
<msup>
<mi>x</mi><mi>n</mi>
@@ -158,12 +158,12 @@
</math>
</div>
<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
<munderover>
- <mo>∑</mo>
+ <mo movablelimits="true">∑</mo>
<mrow>
<mi>n</mi><mo>=</mo><mn>1</mn>
</mrow>
@@ -187,7 +187,7 @@
directives:</p>
<p>The Schrödinger equation</p>
<div id="eq-schrodinger">
-<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
@@ -201,11 +201,11 @@
</mrow>
</mfrac>
<mi class="capital-greek">Ψ</mi><mo>=</mo>
- <mover>
+ <mover accent="true">
<mrow>
<mi>H</mi>
</mrow>
- <mo>^</mo>
+ <mo>ˆ</mo>
</mover>
<mi class="capital-greek">Ψ</mi><mo>,</mo>
</mtd>
@@ -227,7 +227,7 @@
</colgroup>
<tbody>
<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>a</mi>
</mrow>
@@ -235,24 +235,24 @@
</mover>
</math> <span class="docutils literal">\acute{a}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>t</mi>
</mrow>
- <mo>·</mo>
+ <mo>˙</mo>
</mover>
</math> <span class="docutils literal">\dot{t}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>γ</mi>
</mrow>
- <mo>^</mo>
+ <mo>ˆ</mo>
</mover>
</math> <span class="docutils literal"><span class="pre">\hat{\gamma}</span></span></p></td>
</tr>
<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>a</mi>
</mrow>
@@ -260,24 +260,24 @@
</mover>
</math> <span class="docutils literal">\grave{a}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>t</mi>
</mrow>
- <mo>··</mo>
+ <mo>¨</mo>
</mover>
</math> <span class="docutils literal">\ddot{t}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>α</mi>
</mrow>
- <mo>∼</mo>
+ <mo>˜</mo>
</mover>
</math> <span class="docutils literal"><span class="pre">\tilde{\alpha}</span></span></p></td>
</tr>
<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>x</mi>
</mrow>
@@ -285,24 +285,24 @@
</mover>
</math> <span class="docutils literal">\breve{x}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>t</mi>
</mrow>
- <mo>···</mo>
+ <mo>⃛</mo>
</mover>
</math> <span class="docutils literal">\dddot{t}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="false">
<mrow>
<mi>ı</mi>
</mrow>
- <mo>⃗</mo>
+ <mo>→</mo>
</mover>
</math> <span class="docutils literal"><span class="pre">\vec{\imath}</span></span></p></td>
</tr>
<tr><td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>a</mi>
</mrow>
@@ -310,19 +310,19 @@
</mover>
</math> <span class="docutils literal">\check{a}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="true">
<mrow>
<mi>a</mi>
</mrow>
- <mo>-</mo>
+ <mo>ˉ</mo>
</mover>
</math> <span class="docutils literal">\bar{a}</span></p></td>
<td><p><math xmlns="http://www.w3.org/1998/Math/MathML">
- <mover>
+ <mover accent="false">
<mrow>
<mi>R</mi>
</mrow>
- <mo>⃗</mo>
+ <mo>→</mo>
</mover>
</math> <span class="docutils literal">\vec{R}</span></p></td>
</tr>
@@ -334,7 +334,7 @@
\widehat{xxx} -->
<p>Modulation Transfer Function:</p>
<div>
-<math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
+<math display="block" xmlns="http://www.w3.org/1998/Math/MathML">
<mtable class="align" displaystyle="true">
<mtr>
<mtd>
@@ -369,7 +369,7 @@
<mfrac>
<mrow>
<munderover>
- <mo>∫</mo>
+ <mo movablelimits="true">∫</mo>
<mrow>
<mo>−</mo><mo>∞</mo>
</mrow>
@@ -398,7 +398,7 @@
</mrow>
<mrow>
<munderover>
- <mo>∫</mo>
+ <mo movablelimits="true">∫</mo>
<mrow>
<mo>−</mo><mo>∞</mo>
</mrow>
@@ -424,7 +424,7 @@
<span class="docutils literal"><span class="pre">\begin{...}</span> <span class="pre">\end{...}</span></span> pair, the math code is wrapped in an <...
[truncated message content] |