mdhtml2docx 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mdhtml2docx-0.1.0/CHANGELOG.md +11 -0
- mdhtml2docx-0.1.0/LICENSE +202 -0
- mdhtml2docx-0.1.0/MANIFEST.in +3 -0
- mdhtml2docx-0.1.0/PKG-INFO +96 -0
- mdhtml2docx-0.1.0/README.md +75 -0
- mdhtml2docx-0.1.0/mdhtml2docx/__init__.py +3 -0
- mdhtml2docx-0.1.0/mdhtml2docx/asvocab.py +88 -0
- mdhtml2docx-0.1.0/mdhtml2docx/convert.py +919 -0
- mdhtml2docx-0.1.0/mdhtml2docx/hilite.py +27 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/SOURCES.md +7 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/dml-chart.xsd +1499 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/dml-chartDrawing.xsd +146 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/dml-diagram.xsd +1085 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/dml-lockedCanvas.xsd +11 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/dml-main.xsd +3081 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/dml-picture.xsd +23 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/dml-wordprocessingDrawing.xsd +287 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/shared-commonSimpleTypes.xsd +172 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/shared-customXmlSchemaProperties.xsd +18 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/shared-math.xsd +582 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/shared-relationshipReference.xsd +25 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/wml.xsd +3643 -0
- mdhtml2docx-0.1.0/mdhtml2docx/schemas/xml.xsd +287 -0
- mdhtml2docx-0.1.0/mdhtml2docx/styles.py +85 -0
- mdhtml2docx-0.1.0/mdhtml2docx/templates/reference.docx +0 -0
- mdhtml2docx-0.1.0/mdhtml2docx/validate.py +38 -0
- mdhtml2docx-0.1.0/mdhtml2docx/wml.py +110 -0
- mdhtml2docx-0.1.0/mdhtml2docx/word.py +136 -0
- mdhtml2docx-0.1.0/mdhtml2docx/word.sdef +9661 -0
- mdhtml2docx-0.1.0/mdhtml2docx.egg-info/PKG-INFO +96 -0
- mdhtml2docx-0.1.0/mdhtml2docx.egg-info/SOURCES.txt +37 -0
- mdhtml2docx-0.1.0/mdhtml2docx.egg-info/dependency_links.txt +1 -0
- mdhtml2docx-0.1.0/mdhtml2docx.egg-info/requires.txt +8 -0
- mdhtml2docx-0.1.0/mdhtml2docx.egg-info/top_level.txt +1 -0
- mdhtml2docx-0.1.0/pyproject.toml +44 -0
- mdhtml2docx-0.1.0/setup.cfg +4 -0
- mdhtml2docx-0.1.0/tests/test_convert.py +421 -0
- mdhtml2docx-0.1.0/tests/test_validate.py +34 -0
- mdhtml2docx-0.1.0/tests/test_word.py +16 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
<!-- do not remove -->
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### New Features
|
|
6
|
+
|
|
7
|
+
- Migrate from JustHTML to fast5ever, using isinstance node checks and direct attrs access ([#5](https://github.com/AnswerDotAI/mdhtml2docx/issues/5))
|
|
8
|
+
- Rename to mdhtml2docx and switch input from xhtmlmd XHTML to mdhtml JustHTML DOM with support for raw-data encodings, reference tokens/groups, HTML5 repair, inert templates, and figcaption alt text ([#2](https://github.com/AnswerDotAI/mdhtml2docx/issues/2))
|
|
9
|
+
- Add xhtml2docx conversion engine, WML helpers, style management, validation, Word scripting, and syntax highlighting modules ([#1](https://github.com/AnswerDotAI/mdhtml2docx/issues/1))
|
|
10
|
+
- Support MDHTML raw-data encodings, reference tokens and groups, HTML5 body repair, inert templates, and figure accessibility text from `figcaption`.
|
|
11
|
+
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mdhtml2docx
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Convert MDHTML to Word docx files
|
|
5
|
+
Author-email: Jeremy Howard <j@fast.ai>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/AnswerDotAI/mdhtml2docx
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: lxml
|
|
14
|
+
Requires-Dist: mdhtml>=0.1.15
|
|
15
|
+
Requires-Dist: fast5ever>=0.1.1
|
|
16
|
+
Provides-Extra: dev
|
|
17
|
+
Requires-Dist: fastship; extra == "dev"
|
|
18
|
+
Requires-Dist: build; extra == "dev"
|
|
19
|
+
Requires-Dist: twine; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# mdhtml2docx
|
|
23
|
+
|
|
24
|
+
Convert [MDHTML](https://github.com/AnswerDotAI/mdhtml) to Word docx files.
|
|
25
|
+
|
|
26
|
+
`mdhtml` renders Markdown to an HTML5 document format shared by format-specific exporters. This package converts its portable core to docx from scratch. It uses [fast5ever](https://github.com/AnswerDotAI/fast5ever)'s mutable WHATWG DOM for input and lxml for the generated WordprocessingML.
|
|
27
|
+
|
|
28
|
+
MDHTML accepts the full HTML vocabulary. This exporter supports the portable elements and annotations listed below. It preserves the text of unknown inline elements, recurses through block containers, and warns when an unsupported block must become a plain paragraph. HTML parsing and repair belong to `mdhtml`; this package only walks the resulting tree.
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from mdhtml import to_mdhtml
|
|
34
|
+
from mdhtml2docx import convert
|
|
35
|
+
|
|
36
|
+
html = to_mdhtml(markdown_text)
|
|
37
|
+
warnings = convert(html, 'out.docx')
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`convert` takes an MDHTML string, writes a docx, and returns a list of warning strings. It parses strings with `mdhtml.parse_mdhtml`, so normal HTML5 repair applies and XML well-formedness is irrelevant. It also accepts an existing mutable fast5ever DOM:
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from mdhtml import parse_mdhtml
|
|
44
|
+
|
|
45
|
+
document = parse_mdhtml(html)
|
|
46
|
+
document.children[0].attrs['custom-style'] = 'Contract Title'
|
|
47
|
+
warnings = convert(document, 'out.docx')
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Body-position text and phrasing content become implicit Word paragraphs. Whitespace between blocks remains inert. HTML templates remain inert and are not rendered.
|
|
51
|
+
|
|
52
|
+
Supported: headings, paragraphs, bold, italic, strikethrough, underline (the `u` element), highlight, superscript and subscript, inline code, links (external and internal, via bookmarks), images (local files are embedded with correct dimensions; remote URLs degrade to links), block quotes, fenced and indented code blocks, bullet and numbered lists (including nesting, `start`, and task-list checkboxes), pipe and grid tables (including row and column spans and header rows), definition lists, footnotes, horizontal rules, and abbreviations. Math spans and blocks become native Word math zones (`m:oMath`) holding the source text as-is, whatever the dialect (TeX, UnicodeMath, AsciiMath). Build-up/rendering is left downstream, and pandoc reads the zones back as math.
|
|
53
|
+
|
|
54
|
+
Code blocks with a language are syntax colored when [fastpylight](https://github.com/AnswerDotAI/fastpylight) is installed: tokens get `Hl*` character styles (e.g. `Hl Keyword`), whose colors come from the theme entry in the reference list below, so a finished document can be restyled in Word like everything else.
|
|
55
|
+
|
|
56
|
+
## Styling
|
|
57
|
+
|
|
58
|
+
The generated document uses named styles, never inline formatting, so appearance is controlled by restyling. Prose paragraphs get Body Text (First Paragraph directly after a heading or similar block, following pandoc's convention), and the other styles are the ones you would expect: heading 1 through 6, Quote, Source Code, Verbatim Char, Hyperlink, List Paragraph, Compact (table cells), Definition Term, Definition, caption, footnote styles, and Table Grid (plus the author-selectable Borderless Table).
|
|
59
|
+
|
|
60
|
+
Pass `reference='mydoc.docx'` to use your own document's styles instead of the built-in template, exactly like pandoc's `--reference-doc`. `reference` may also be a list: the first entry supplies the document (page setup, fonts, and all base styles), and each later entry contributes just its styles, replacing same-named earlier ones - either another `.docx`, or a fastpylight theme name such as `'dracula'`, which generates the code-color styles on the fly. The default is the built-in template plus `'github_light'`; pass a bare reference for plain uncolored code, or `mdhtml2docx.styles.theme_ref('dracula', 'dracula.docx')` to write a theme's styles as a standalone docx you can inspect or tweak. A `custom-style="Name"` attribute (from `{custom-style="Name"}` in Markdown) applies that style from your reference doc; if the style is missing, a stub is injected and a warning returned. A plain class like `{.note}` applies a style only when your reference doc defines one named `note`, and is otherwise ignored. Both work on tables too: a table whose `custom-style` or class names a table style in the reference doc uses it in place of Table Grid - the built-in template ships `Borderless Table` (no gridlines, for signature blocks and other layout tables).
|
|
61
|
+
|
|
62
|
+
Tables can mix fixed and proportional column widths with a `colwidths` attribute, written in Markdown as an attribute list after the table: `{: colwidths="10em 2fr 1fr"}`. Lengths fix a column; `fr` values share the remaining width, as in CSS grid.
|
|
63
|
+
|
|
64
|
+
The built-in template is generated by `tools/createref.py` from a stock Word document; it defines exactly the styles the converter emits, plus next-paragraph chains so documents stay well-styled while edited by hand in Word.
|
|
65
|
+
|
|
66
|
+
## Raw docx
|
|
67
|
+
|
|
68
|
+
This converter consumes MDHTML raw data whose `data-format` is `docx`:
|
|
69
|
+
|
|
70
|
+
```html
|
|
71
|
+
<script type="application/vnd.mdhtml.raw" data-format="docx">…</script>
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
A ```` ```{=docx} ```` fenced block in Markdown, or inline code followed by `{=docx}`, produces that carrier. The payload is parsed as WordprocessingML and inserted verbatim. Block payloads supply content such as `w:p` or `w:tbl`; inline payloads supply content such as `w:r`. The prefixes `w`, `r`, `wp`, `a`, `pic`, and `m` are predeclared, so no namespace boilerplate is needed.
|
|
75
|
+
|
|
76
|
+
Literal payloads have no `data-encoding`. The exporter performs one character-reference decoding pass for `data-encoding="html"`, and accepts UTF-8 payloads encoded with `data-encoding="base64"`. Malformed payloads and unknown encodings are dropped with a warning. Raw data for other formats is skipped silently.
|
|
77
|
+
|
|
78
|
+
The canonical example is a page break:
|
|
79
|
+
|
|
80
|
+
```{=docx}
|
|
81
|
+
<w:p><w:r><w:br w:type="page"/></w:r></w:p>
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Cross-references
|
|
85
|
+
|
|
86
|
+
Markdown references like `[@sec-payment]` become MDHTML `a` elements marked with `data-ref`, which this exporter turns into live Word REF fields rather than baked text. The default field is `REF <bookmark> \w \h`, the full-context paragraph number ("3.(c)(iii)") as a hyperlink; `settings.xml` gets `updateFields`, so Word refreshes on open. The `leaf`, `rel`, `text`, and `page` tokens select other fields, while the independent `bare` token suppresses the prefix word. Unknown or conflicting tokens are conversion errors.
|
|
87
|
+
|
|
88
|
+
The word before the number comes from the reference's type, the id up to its first `-`: `sec` maps to Section/Sections out of the box, and `reftypes=dict(exh=('Exhibit', 'Exhibits'))` adds more. `[Clause @sec-x]` overrides the word for one reference; `[-@sec-x]` suppresses it. Grouped references use a `span` marked with `data-refs` and join as "Sections 3.1 and 4.2" with one field per number. They are never collapsed into ranges, because "3.1-3.3" is static text whose meaning silently changes when a clause is inserted. A reference whose target id does not exist, or whose type has no prefix defined when one is needed, raises rather than warning: a lawyer's document must not open showing "Error! Reference source not found."
|
|
89
|
+
|
|
90
|
+
Number fields need numbered headings. If your reference docx already numbers its heading styles (most firm templates do), nothing more is required, and the converter leaves that numbering alone. Otherwise pass `number_headings='legal'` for 1. / (a) / (i) numbering or `'decimal'` for 1 / 1.1 / 1.1.1 (the names index `styles.SCHEMES`), or pass your own scheme as a `{lvlText: numFmt}` dict, one entry per heading level. A reference-list entry ending in `.xml` is a third route: a raw file of `w:style`, `w:abstractNum`, and `w:num` elements contributing styles and numbering together, with ids remapped to avoid collisions.
|
|
91
|
+
|
|
92
|
+
Figures and captioned tables number themselves with SEQ fields: a figure renders as its image plus a "Figure 1: caption" paragraph below (caption style), a table caption as "Table 1: caption" above the table, both live. When the element has an id, the label-and-number span is bookmarked, so `[@fig-plot]` inserts a live "Figure 1" (no extra prefix word; the label is part of the bookmarked text) and `[-@tbl-stages]` the bare number via a second number-only bookmark. `fig` and `tbl` are built-in reftypes alongside `sec`, and their label words come from the same table. Mixed-type groups render each item with its own singular prefix ("Figure 1 and Table 2"); same-type groups pluralize once. Reference targets must be things that get bookmarks - headings, paragraphs, figures, and tables with ids - and a ref to anything else is an error at convert time.
|
|
93
|
+
|
|
94
|
+
## Validation
|
|
95
|
+
|
|
96
|
+
Every generated file is checked three ways in the test suite: lxml validation against the ECMA-376 schemas (container, CRC, XML, XSD), a semantic round trip through pandoc's independent docx reader, and occasional acceptance runs in Microsoft Word itself, driven live via AppleScript.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# mdhtml2docx
|
|
2
|
+
|
|
3
|
+
Convert [MDHTML](https://github.com/AnswerDotAI/mdhtml) to Word docx files.
|
|
4
|
+
|
|
5
|
+
`mdhtml` renders Markdown to an HTML5 document format shared by format-specific exporters. This package converts its portable core to docx from scratch. It uses [fast5ever](https://github.com/AnswerDotAI/fast5ever)'s mutable WHATWG DOM for input and lxml for the generated WordprocessingML.
|
|
6
|
+
|
|
7
|
+
MDHTML accepts the full HTML vocabulary. This exporter supports the portable elements and annotations listed below. It preserves the text of unknown inline elements, recurses through block containers, and warns when an unsupported block must become a plain paragraph. HTML parsing and repair belong to `mdhtml`; this package only walks the resulting tree.
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from mdhtml import to_mdhtml
|
|
13
|
+
from mdhtml2docx import convert
|
|
14
|
+
|
|
15
|
+
html = to_mdhtml(markdown_text)
|
|
16
|
+
warnings = convert(html, 'out.docx')
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
`convert` takes an MDHTML string, writes a docx, and returns a list of warning strings. It parses strings with `mdhtml.parse_mdhtml`, so normal HTML5 repair applies and XML well-formedness is irrelevant. It also accepts an existing mutable fast5ever DOM:
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from mdhtml import parse_mdhtml
|
|
23
|
+
|
|
24
|
+
document = parse_mdhtml(html)
|
|
25
|
+
document.children[0].attrs['custom-style'] = 'Contract Title'
|
|
26
|
+
warnings = convert(document, 'out.docx')
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Body-position text and phrasing content become implicit Word paragraphs. Whitespace between blocks remains inert. HTML templates remain inert and are not rendered.
|
|
30
|
+
|
|
31
|
+
Supported: headings, paragraphs, bold, italic, strikethrough, underline (the `u` element), highlight, superscript and subscript, inline code, links (external and internal, via bookmarks), images (local files are embedded with correct dimensions; remote URLs degrade to links), block quotes, fenced and indented code blocks, bullet and numbered lists (including nesting, `start`, and task-list checkboxes), pipe and grid tables (including row and column spans and header rows), definition lists, footnotes, horizontal rules, and abbreviations. Math spans and blocks become native Word math zones (`m:oMath`) holding the source text as-is, whatever the dialect (TeX, UnicodeMath, AsciiMath). Build-up/rendering is left downstream, and pandoc reads the zones back as math.
|
|
32
|
+
|
|
33
|
+
Code blocks with a language are syntax colored when [fastpylight](https://github.com/AnswerDotAI/fastpylight) is installed: tokens get `Hl*` character styles (e.g. `Hl Keyword`), whose colors come from the theme entry in the reference list below, so a finished document can be restyled in Word like everything else.
|
|
34
|
+
|
|
35
|
+
## Styling
|
|
36
|
+
|
|
37
|
+
The generated document uses named styles, never inline formatting, so appearance is controlled by restyling. Prose paragraphs get Body Text (First Paragraph directly after a heading or similar block, following pandoc's convention), and the other styles are the ones you would expect: heading 1 through 6, Quote, Source Code, Verbatim Char, Hyperlink, List Paragraph, Compact (table cells), Definition Term, Definition, caption, footnote styles, and Table Grid (plus the author-selectable Borderless Table).
|
|
38
|
+
|
|
39
|
+
Pass `reference='mydoc.docx'` to use your own document's styles instead of the built-in template, exactly like pandoc's `--reference-doc`. `reference` may also be a list: the first entry supplies the document (page setup, fonts, and all base styles), and each later entry contributes just its styles, replacing same-named earlier ones - either another `.docx`, or a fastpylight theme name such as `'dracula'`, which generates the code-color styles on the fly. The default is the built-in template plus `'github_light'`; pass a bare reference for plain uncolored code, or `mdhtml2docx.styles.theme_ref('dracula', 'dracula.docx')` to write a theme's styles as a standalone docx you can inspect or tweak. A `custom-style="Name"` attribute (from `{custom-style="Name"}` in Markdown) applies that style from your reference doc; if the style is missing, a stub is injected and a warning returned. A plain class like `{.note}` applies a style only when your reference doc defines one named `note`, and is otherwise ignored. Both work on tables too: a table whose `custom-style` or class names a table style in the reference doc uses it in place of Table Grid - the built-in template ships `Borderless Table` (no gridlines, for signature blocks and other layout tables).
|
|
40
|
+
|
|
41
|
+
Tables can mix fixed and proportional column widths with a `colwidths` attribute, written in Markdown as an attribute list after the table: `{: colwidths="10em 2fr 1fr"}`. Lengths fix a column; `fr` values share the remaining width, as in CSS grid.
|
|
42
|
+
|
|
43
|
+
The built-in template is generated by `tools/createref.py` from a stock Word document; it defines exactly the styles the converter emits, plus next-paragraph chains so documents stay well-styled while edited by hand in Word.
|
|
44
|
+
|
|
45
|
+
## Raw docx
|
|
46
|
+
|
|
47
|
+
This converter consumes MDHTML raw data whose `data-format` is `docx`:
|
|
48
|
+
|
|
49
|
+
```html
|
|
50
|
+
<script type="application/vnd.mdhtml.raw" data-format="docx">…</script>
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
A ```` ```{=docx} ```` fenced block in Markdown, or inline code followed by `{=docx}`, produces that carrier. The payload is parsed as WordprocessingML and inserted verbatim. Block payloads supply content such as `w:p` or `w:tbl`; inline payloads supply content such as `w:r`. The prefixes `w`, `r`, `wp`, `a`, `pic`, and `m` are predeclared, so no namespace boilerplate is needed.
|
|
54
|
+
|
|
55
|
+
Literal payloads have no `data-encoding`. The exporter performs one character-reference decoding pass for `data-encoding="html"`, and accepts UTF-8 payloads encoded with `data-encoding="base64"`. Malformed payloads and unknown encodings are dropped with a warning. Raw data for other formats is skipped silently.
|
|
56
|
+
|
|
57
|
+
The canonical example is a page break:
|
|
58
|
+
|
|
59
|
+
```{=docx}
|
|
60
|
+
<w:p><w:r><w:br w:type="page"/></w:r></w:p>
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Cross-references
|
|
64
|
+
|
|
65
|
+
Markdown references like `[@sec-payment]` become MDHTML `a` elements marked with `data-ref`, which this exporter turns into live Word REF fields rather than baked text. The default field is `REF <bookmark> \w \h`, the full-context paragraph number ("3.(c)(iii)") as a hyperlink; `settings.xml` gets `updateFields`, so Word refreshes on open. The `leaf`, `rel`, `text`, and `page` tokens select other fields, while the independent `bare` token suppresses the prefix word. Unknown or conflicting tokens are conversion errors.
|
|
66
|
+
|
|
67
|
+
The word before the number comes from the reference's type, the id up to its first `-`: `sec` maps to Section/Sections out of the box, and `reftypes=dict(exh=('Exhibit', 'Exhibits'))` adds more. `[Clause @sec-x]` overrides the word for one reference; `[-@sec-x]` suppresses it. Grouped references use a `span` marked with `data-refs` and join as "Sections 3.1 and 4.2" with one field per number. They are never collapsed into ranges, because "3.1-3.3" is static text whose meaning silently changes when a clause is inserted. A reference whose target id does not exist, or whose type has no prefix defined when one is needed, raises rather than warning: a lawyer's document must not open showing "Error! Reference source not found."
|
|
68
|
+
|
|
69
|
+
Number fields need numbered headings. If your reference docx already numbers its heading styles (most firm templates do), nothing more is required, and the converter leaves that numbering alone. Otherwise pass `number_headings='legal'` for 1. / (a) / (i) numbering or `'decimal'` for 1 / 1.1 / 1.1.1 (the names index `styles.SCHEMES`), or pass your own scheme as a `{lvlText: numFmt}` dict, one entry per heading level. A reference-list entry ending in `.xml` is a third route: a raw file of `w:style`, `w:abstractNum`, and `w:num` elements contributing styles and numbering together, with ids remapped to avoid collisions.
|
|
70
|
+
|
|
71
|
+
Figures and captioned tables number themselves with SEQ fields: a figure renders as its image plus a "Figure 1: caption" paragraph below (caption style), a table caption as "Table 1: caption" above the table, both live. When the element has an id, the label-and-number span is bookmarked, so `[@fig-plot]` inserts a live "Figure 1" (no extra prefix word; the label is part of the bookmarked text) and `[-@tbl-stages]` the bare number via a second number-only bookmark. `fig` and `tbl` are built-in reftypes alongside `sec`, and their label words come from the same table. Mixed-type groups render each item with its own singular prefix ("Figure 1 and Table 2"); same-type groups pluralize once. Reference targets must be things that get bookmarks - headings, paragraphs, figures, and tables with ids - and a ref to anything else is an error at convert time.
|
|
72
|
+
|
|
73
|
+
## Validation
|
|
74
|
+
|
|
75
|
+
Every generated file is checked three ways in the test suite: lxml validation against the ECMA-376 schemas (container, CRC, XML, XSD), a semantic round trip through pandoc's independent docx reader, and occasional acceptance runs in Microsoft Word itself, driven live via AppleScript.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"Ergonomic exploration of an appscript app's scripting vocabulary: live terminology tables, plus the sdef XML for full docs."
|
|
2
|
+
import re
|
|
3
|
+
from functools import cache
|
|
4
|
+
from importlib.resources import files
|
|
5
|
+
from aem import AEEnum
|
|
6
|
+
from lxml import etree
|
|
7
|
+
|
|
8
|
+
__all__ = ['vocab', 'props', 'sd', 'sdfind']
|
|
9
|
+
|
|
10
|
+
SDEF = files('mdhtml2docx')/'word.sdef'
|
|
11
|
+
_kinds = {b'p': 'property', b'e': 'element', b'c': 'command'}
|
|
12
|
+
|
|
13
|
+
def vocab(app, pat=''):
|
|
14
|
+
"Search `app`'s terminology for names matching regex `pat` (case-insensitive), as sorted (kind, name) rows"
|
|
15
|
+
r = re.compile(pat, re.I)
|
|
16
|
+
ad = app.AS_appdata
|
|
17
|
+
res = [(_kinds[v[0]], n) for n,v in ad.referencebyname().items() if r.search(n)]
|
|
18
|
+
res += [('enum' if isinstance(v, AEEnum) else 'class', n) for n,v in ad.typebyname().items() if r.search(n)]
|
|
19
|
+
return sorted(res)
|
|
20
|
+
|
|
21
|
+
def props(ref, pat=None, maxlen=80, timeout=15):
|
|
22
|
+
"`ref.properties.get()` as a readable {name: truncated-repr} dict, optionally filtered by regex `pat`"
|
|
23
|
+
r = re.compile(pat, re.I) if pat else None
|
|
24
|
+
res = {}
|
|
25
|
+
for key, v in ref.properties.get(timeout=timeout).items():
|
|
26
|
+
n = str(key).removeprefix('k.')
|
|
27
|
+
if r and not r.search(n): continue
|
|
28
|
+
s = repr(v)
|
|
29
|
+
res[n] = s if len(s) <= maxlen else s[:maxlen] + '...'
|
|
30
|
+
return res
|
|
31
|
+
|
|
32
|
+
class _Doc(str):
|
|
33
|
+
def __repr__(self): return str(self)
|
|
34
|
+
|
|
35
|
+
@cache
|
|
36
|
+
def _sdef(path): return etree.parse(str(path))
|
|
37
|
+
|
|
38
|
+
def _typ(e):
|
|
39
|
+
if e.get('type'): return e.get('type')
|
|
40
|
+
return ' | '.join(('list of ' if t.get('list') else '')+t.get('type','') for t in e.findall('type'))
|
|
41
|
+
|
|
42
|
+
def _desc(e): return f' -- {e.get("description")}' if e.get('description') else ''
|
|
43
|
+
|
|
44
|
+
def _fmt_cmd(c):
|
|
45
|
+
lines = [f'command {c.get("name")}{_desc(c)}']
|
|
46
|
+
dp = c.find('direct-parameter')
|
|
47
|
+
if dp is not None: lines.append(f' direct: {_typ(dp)}{_desc(dp)}')
|
|
48
|
+
for p in c.findall('parameter'):
|
|
49
|
+
opt = ' (optional)' if p.get('optional')=='yes' else ''
|
|
50
|
+
lines.append(f' {p.get("name")}: {_typ(p)}{opt}{_desc(p)}')
|
|
51
|
+
r = c.find('result')
|
|
52
|
+
if r is not None: lines.append(f' result: {_typ(r)}{_desc(r)}')
|
|
53
|
+
return lines
|
|
54
|
+
|
|
55
|
+
def _fmt_cls(c):
|
|
56
|
+
inh = f' < {c.get("inherits")}' if c.get('inherits') else ''
|
|
57
|
+
lines = [f'class {c.get("name")}{inh}{_desc(c)}']
|
|
58
|
+
for e in c.findall('element'): lines.append(f' element: {e.get("type")}')
|
|
59
|
+
for p in c.findall('property'):
|
|
60
|
+
acc = ' (r/o)' if p.get('access')=='r' else ''
|
|
61
|
+
lines.append(f' {p.get("name")}: {p.get("type")}{acc}{_desc(p)}')
|
|
62
|
+
return lines
|
|
63
|
+
|
|
64
|
+
def _fmt_enum(c):
|
|
65
|
+
lines = [f'enumeration {c.get("name")}']
|
|
66
|
+
for e in c.findall('enumerator'): lines.append(f' {e.get("name")}{_desc(e)}')
|
|
67
|
+
return lines
|
|
68
|
+
|
|
69
|
+
_fmts = {'command': _fmt_cmd, 'class': _fmt_cls, 'enumeration': _fmt_enum}
|
|
70
|
+
_children = ('parameter', 'property', 'enumerator')
|
|
71
|
+
|
|
72
|
+
def sd(name, path=SDEF):
|
|
73
|
+
"Full sdef doc for `name` (a command, class, or enumeration; underscore and space spellings both work), with types and descriptions"
|
|
74
|
+
n = name.replace('_', ' ')
|
|
75
|
+
nodes = [e for tag in _fmts for e in _sdef(path).iter(tag) if e.get('name') in (n, name)]
|
|
76
|
+
if not nodes: raise KeyError(f'{name!r} not found in sdef; try sdfind')
|
|
77
|
+
return _Doc('\n\n'.join('\n'.join(_fmts[e.tag](e)) for e in nodes))
|
|
78
|
+
|
|
79
|
+
def sdfind(pat, path=SDEF, maxlen=80):
|
|
80
|
+
"Search sdef names and descriptions for regex `pat`, as (kind, name, description) rows; child nodes show as parent.name"
|
|
81
|
+
r = re.compile(pat, re.I)
|
|
82
|
+
res = []
|
|
83
|
+
for e in _sdef(path).iter(*_fmts, *_children):
|
|
84
|
+
n, d = e.get('name') or '', e.get('description') or ''
|
|
85
|
+
if not (r.search(n) or r.search(d)): continue
|
|
86
|
+
if e.tag in _children: n = f'{e.getparent().get("name")}.{n}'
|
|
87
|
+
res.append((e.tag, n, d if len(d)<=maxlen else d[:maxlen]+'...'))
|
|
88
|
+
return res
|