pydocmaker 2.8.0__tar.gz → 2.8.2__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.
Files changed (81) hide show
  1. {pydocmaker-2.8.0/src/pydocmaker.egg-info → pydocmaker-2.8.2}/PKG-INFO +33 -19
  2. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/README.md +32 -18
  3. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/__init__.py +8 -3
  4. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_html.py +4 -2
  5. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_tex.py +171 -3
  6. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_typst.py +4 -2
  7. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/cli.py +32 -223
  8. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/core.py +28 -6
  9. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templating.py +670 -7
  10. {pydocmaker-2.8.0 → pydocmaker-2.8.2/src/pydocmaker.egg-info}/PKG-INFO +33 -19
  11. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_ex_tex.py +222 -0
  12. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_templating.py +302 -0
  13. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_templating_extensive.py +216 -1
  14. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/LICENSE +0 -0
  15. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/pyproject.toml +0 -0
  16. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/requirements.txt +0 -0
  17. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/setup.cfg +0 -0
  18. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/b64_data.py +0 -0
  19. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/__init__.py +0 -0
  20. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/baseformatter.py +0 -0
  21. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_docx.py +0 -0
  22. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_ipynb.py +0 -0
  23. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_markdown.py +0 -0
  24. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_redmine.py +0 -0
  25. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_rich.py +0 -0
  26. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/libreoffice_api.py +0 -0
  27. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/mdx_latex.py +0 -0
  28. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/pandoc_api.py +0 -0
  29. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/pandoc_batch.py +0 -0
  30. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/backend/pdf_maker_tex.py +0 -0
  31. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/__init__.py +0 -0
  32. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/adapter_base.py +0 -0
  33. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/adapter_html.py +0 -0
  34. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/adapter_tex.py +0 -0
  35. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/adapter_typ.py +0 -0
  36. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/inference.py +0 -0
  37. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/markers.py +0 -0
  38. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/model.py +0 -0
  39. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/parser.py +0 -0
  40. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/render.py +0 -0
  41. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/io/__init__.py +0 -0
  42. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/io/html_loader.py +0 -0
  43. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/io/ipynb_loader.py +0 -0
  44. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/param_mapping.py +0 -0
  45. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.html +0 -0
  46. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.html.j2 +0 -0
  47. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.tex +0 -0
  48. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.tex.j2 +0 -0
  49. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.typ +0 -0
  50. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.typ.j2 +0 -0
  51. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/paper.typ.j2 +0 -0
  52. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/report.tex +0 -0
  53. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/report.typ +0 -0
  54. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/report.typ.j2 +0 -0
  55. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/templates/word_template_with_mergefields.docx +0 -0
  56. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker/util.py +0 -0
  57. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/SOURCES.txt +0 -0
  58. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/dependency_links.txt +0 -0
  59. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/entry_points.txt +0 -0
  60. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/requires.txt +0 -0
  61. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/top_level.txt +0 -0
  62. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_backend_pandoc.py +0 -0
  63. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_blocktmpl_inference.py +0 -0
  64. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_blocktmpl_integration.py +0 -0
  65. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_blocktmpl_parser.py +0 -0
  66. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_blocktmpl_render.py +0 -0
  67. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_blocktmpl_values.py +0 -0
  68. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_cli.py +0 -0
  69. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_convert_all.py +0 -0
  70. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_core.py +0 -0
  71. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_docx_ex.py +0 -0
  72. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_ex_html.py +0 -0
  73. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_ex_rich.py +0 -0
  74. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_ex_typst.py +0 -0
  75. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_io_html.py +0 -0
  76. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_io_ipynb.py +0 -0
  77. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_param_mapping.py +0 -0
  78. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_pdf_ex.py +0 -0
  79. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_pdf_typst.py +0 -0
  80. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_snippets.py +0 -0
  81. {pydocmaker-2.8.0 → pydocmaker-2.8.2}/tests/test_util.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pydocmaker
3
- Version: 2.8.0
3
+ Version: 2.8.2
4
4
  Summary: A minimal python document maker to create and show reports (including figures and tables) from within python and export them to markdown, pdf, html, and word.
5
5
  Author: Tobias Glaubach
6
6
  License: MIT License
@@ -219,24 +219,6 @@ Supported save/load formats for `Doc.save`/`Doc.load`:
219
219
  **Note**: Saving and Loading is fundamentally different from exporting a report (e.G. to_html), since save/load allows round trip loading and saving, while exporting makes nice documents to view in other other software and not load again.
220
220
 
221
221
 
222
- ### Configuring Options:
223
-
224
- All configurable options for this package are in `pydocmaker.options`. They are always callable
225
- functions with "*_get", "*_set", "*_scan" etc.
226
-
227
- ```python
228
-
229
- import pydocmaker as pyd
230
-
231
- pyd.options.pandoc_allowed_set(False)
232
- print(pyd.options.pandoc_allowed_get())
233
-
234
- pyd.options.pdf_engine_set('typst') # default
235
- print(pyd.options.pdf_engine_get())
236
-
237
- ```
238
-
239
-
240
222
  ### Command Line Interface (CLI)
241
223
 
242
224
  `pydocmaker` also ships with a command-line interface that covers the most common workflows
@@ -308,6 +290,38 @@ pydocmaker build README.md -t report.tex -a ./assets -a logo.png
308
290
  For the full CLI reference see the documentation: [CLI Reference](https://pydocmaker.readthedocs.io/en/latest/cli_reference.html).
309
291
 
310
292
 
293
+ ### Configuring Options:
294
+
295
+ All configurable options for this package are in `pydocmaker.options`. They are always callable
296
+ functions with "*_get", "*_set", "*_scan" etc.
297
+
298
+ ```python
299
+
300
+ import pydocmaker as pyd
301
+
302
+ pyd.options.pandoc_allowed_set(False)
303
+ print(pyd.options.pandoc_allowed_get())
304
+
305
+ pyd.options.pdf_engine_set('typst') # default
306
+ print(pyd.options.pdf_engine_get())
307
+
308
+ # select the default template used by the tex/html/typst backends when no
309
+ # template is given (None -> the backend built-in default template)
310
+ pyd.options.default_template_set('report')
311
+ pyd.options.default_template_set({'html': 'base', 'typ': 'report.typ', 'tex': 'report.tex'})
312
+ pyd.options.default_template_set(None) # reset
313
+
314
+ # automatically add missing latex packages to the preamble (default True)
315
+ pyd.options.latex_add_missing_packages_set(True)
316
+ print(pyd.options.latex_add_missing_packages_get())
317
+
318
+ ```
319
+
320
+ **Default template** — `pyd.options.default_template_set(...)` accepts a template id (`'base'`, `'report'`), a dict mapping formats to template ids (`{'html': ..., 'typ': ..., 'tex': ...}`) or `None` to reset. When unset or not resolvable, the backends keep using their built-in default template. The precedence is unchanged: an explicit `template` argument always wins over the document metadata template, which wins over this config.
321
+
322
+ **LaTeX missing packages** — when exporting to LaTeX with a custom template that does not load all the packages the generated body needs (e.g. `listings`, `xltabular`, `graphicx`, `xcolor`), pydocmaker logs a warning and (unless disabled via `pyd.options.latex_add_missing_packages_set(False)`) inserts the missing `\usepackage` lines into the preamble automatically. This works for classic Jinja2 templates as well as for block templates.
323
+
324
+
311
325
  ### Block Templates (comment-delimited, standalone-compilable)
312
326
 
313
327
  Besides the classic Jinja2 templates (`.j2` files), pydocmaker supports **block templates**: plain
@@ -167,24 +167,6 @@ Supported save/load formats for `Doc.save`/`Doc.load`:
167
167
  **Note**: Saving and Loading is fundamentally different from exporting a report (e.G. to_html), since save/load allows round trip loading and saving, while exporting makes nice documents to view in other other software and not load again.
168
168
 
169
169
 
170
- ### Configuring Options:
171
-
172
- All configurable options for this package are in `pydocmaker.options`. They are always callable
173
- functions with "*_get", "*_set", "*_scan" etc.
174
-
175
- ```python
176
-
177
- import pydocmaker as pyd
178
-
179
- pyd.options.pandoc_allowed_set(False)
180
- print(pyd.options.pandoc_allowed_get())
181
-
182
- pyd.options.pdf_engine_set('typst') # default
183
- print(pyd.options.pdf_engine_get())
184
-
185
- ```
186
-
187
-
188
170
  ### Command Line Interface (CLI)
189
171
 
190
172
  `pydocmaker` also ships with a command-line interface that covers the most common workflows
@@ -256,6 +238,38 @@ pydocmaker build README.md -t report.tex -a ./assets -a logo.png
256
238
  For the full CLI reference see the documentation: [CLI Reference](https://pydocmaker.readthedocs.io/en/latest/cli_reference.html).
257
239
 
258
240
 
241
+ ### Configuring Options:
242
+
243
+ All configurable options for this package are in `pydocmaker.options`. They are always callable
244
+ functions with "*_get", "*_set", "*_scan" etc.
245
+
246
+ ```python
247
+
248
+ import pydocmaker as pyd
249
+
250
+ pyd.options.pandoc_allowed_set(False)
251
+ print(pyd.options.pandoc_allowed_get())
252
+
253
+ pyd.options.pdf_engine_set('typst') # default
254
+ print(pyd.options.pdf_engine_get())
255
+
256
+ # select the default template used by the tex/html/typst backends when no
257
+ # template is given (None -> the backend built-in default template)
258
+ pyd.options.default_template_set('report')
259
+ pyd.options.default_template_set({'html': 'base', 'typ': 'report.typ', 'tex': 'report.tex'})
260
+ pyd.options.default_template_set(None) # reset
261
+
262
+ # automatically add missing latex packages to the preamble (default True)
263
+ pyd.options.latex_add_missing_packages_set(True)
264
+ print(pyd.options.latex_add_missing_packages_get())
265
+
266
+ ```
267
+
268
+ **Default template** — `pyd.options.default_template_set(...)` accepts a template id (`'base'`, `'report'`), a dict mapping formats to template ids (`{'html': ..., 'typ': ..., 'tex': ...}`) or `None` to reset. When unset or not resolvable, the backends keep using their built-in default template. The precedence is unchanged: an explicit `template` argument always wins over the document metadata template, which wins over this config.
269
+
270
+ **LaTeX missing packages** — when exporting to LaTeX with a custom template that does not load all the packages the generated body needs (e.g. `listings`, `xltabular`, `graphicx`, `xcolor`), pydocmaker logs a warning and (unless disabled via `pyd.options.latex_add_missing_packages_set(False)`) inserts the missing `\usepackage` lines into the preamble automatically. This works for classic Jinja2 templates as well as for block templates.
271
+
272
+
259
273
  ### Block Templates (comment-delimited, standalone-compilable)
260
274
 
261
275
  Besides the classic Jinja2 templates (`.j2` files), pydocmaker supports **block templates**: plain
@@ -1,4 +1,4 @@
1
- __version__ = '2.8.0'
1
+ __version__ = '2.8.2'
2
2
 
3
3
 
4
4
  from pydocmaker.core import Doc, construct, constr, buildingblocks, print_to_pdf, make_pdf_from_tex, show_pdf, is_notebook, load_file_b64
@@ -10,7 +10,7 @@ from pydocmaker import templating
10
10
  from pydocmaker.util import upload_report_to_redmine, bcolors, txtcolor, colors_dc, _raise_missing, log, remove_undefined
11
11
 
12
12
  from pydocmaker.backend.ex_docx import DocxFile, DocxFileW32, can_use_libreoffice, can_use_w32_word
13
- from pydocmaker.backend.ex_tex import can_run_pandoc
13
+ from pydocmaker.backend.ex_tex import can_run_pandoc, config_latex_add_missing_packages_get, config_latex_add_missing_packages_set
14
14
 
15
15
  from pydocmaker.backend.pandoc_api import pandoc_convert_file, pandoc_set_allowed, pandoc_convert
16
16
  from pydocmaker.backend.pandoc_api import config_pandoc_allowed_set, config_pandoc_allowed_get
@@ -20,7 +20,8 @@ from pydocmaker.backend.pandoc_api import config_pandoc_allowed_set, config_pand
20
20
  from pydocmaker.templating import (DocTemplate, TemplateDirSource, register_new_template_dir,
21
21
  get_registered_template_dirs, get_available_template_ids,
22
22
  test_template_exists, remove_from_template_dir,
23
- get_template_params, resolve_template_id)
23
+ get_template_params, resolve_template_id,
24
+ config_default_template_get, config_default_template_set)
24
25
 
25
26
  from pydocmaker import blocktmpl
26
27
  from pydocmaker.blocktmpl import (BlockDocTemplate as BlockTemplate,
@@ -107,6 +108,10 @@ class options:
107
108
  pandoc_allowed_set = config_pandoc_allowed_set
108
109
  pandoc_allowed_get = config_pandoc_allowed_get
109
110
  typst_installed = test_typst_installed
111
+ latex_add_missing_packages_get = config_latex_add_missing_packages_get
112
+ latex_add_missing_packages_set = config_latex_add_missing_packages_set
113
+ default_template_get = config_default_template_get
114
+ default_template_set = config_default_template_set
110
115
 
111
116
  get_info_on_optional_components = info_optionals
112
117
 
@@ -9,9 +9,9 @@ except Exception as err:
9
9
  from .baseformatter import BaseFormatter
10
10
 
11
11
  try:
12
- from pydocmaker.templating import handle_template
12
+ from pydocmaker.templating import handle_template, get_default_template_id
13
13
  except Exception as err:
14
- from ..templating import handle_template
14
+ from ..templating import handle_template, get_default_template_id
15
15
 
16
16
  try:
17
17
  from pydocmaker.templating import BlockDocTemplate
@@ -137,6 +137,8 @@ def convert(doc:List[dict], template = None, template_params=None, template_engi
137
137
  tmp = list(doc.values()) if isinstance(doc, dict) else doc
138
138
  body = html_renderer().format(tmp)
139
139
 
140
+ if template is None:
141
+ template = get_default_template_id('html')
140
142
  template_obj, attachments, template_str = handle_template(template, __default_template, tformat='html', template_engine=template_engine)
141
143
 
142
144
  kw = copy.deepcopy(template_params)
@@ -4,6 +4,7 @@ import copy
4
4
  import os
5
5
  from pathlib import Path
6
6
  import json
7
+ import re
7
8
 
8
9
  import traceback
9
10
 
@@ -33,9 +34,9 @@ except Exception as err:
33
34
  from .baseformatter import BaseFormatter
34
35
 
35
36
  try:
36
- from pydocmaker.templating import handle_template, BlockDocTemplate
37
+ from pydocmaker.templating import handle_template, BlockDocTemplate, get_default_template_id
37
38
  except Exception as err:
38
- from ..templating import handle_template, BlockDocTemplate
39
+ from ..templating import handle_template, BlockDocTemplate, get_default_template_id
39
40
 
40
41
  try:
41
42
  from pydocmaker.backend import pdf_maker_tex
@@ -55,6 +56,163 @@ except Exception as err:
55
56
 
56
57
 
57
58
 
59
+ _latex_add_missing_packages = True
60
+
61
+ def config_latex_add_missing_packages_set(shall_add=True) -> bool:
62
+ """Set whether missing latex packages are added to the preamble automatically."""
63
+ global _latex_add_missing_packages
64
+ _latex_add_missing_packages = bool(shall_add)
65
+ return _latex_add_missing_packages
66
+
67
+ def config_latex_add_missing_packages_get() -> bool:
68
+ """Return whether missing latex packages are added automatically (default True)."""
69
+ return _latex_add_missing_packages
70
+
71
+
72
+ _USEPACKAGE_RE = re.compile(r'\\(?:usepackage|RequirePackage)(?:\[[^\]]*\])?\s*\{(?P<names>[^}]*)\}')
73
+
74
+ # constructs generated by pydocmaker / pandoc mapped to the package they require;
75
+ # ordered dict -> deterministic "missing" order
76
+ _LATEX_PACKAGE_PATTERNS = {
77
+ 'listings': (r'\begin{lstlisting}', r'\lstinline', r'\lstset'),
78
+ 'xltabular': (r'\begin{xltabular}',),
79
+ 'graphicx': (r'\includegraphics',),
80
+ 'xcolor': (r'\textcolor{', r'\color{', r'\definecolor'),
81
+ 'longtable': (r'\begin{longtable}',),
82
+ 'booktabs': (r'\toprule', r'\midrule', r'\bottomrule', r'\cmidrule'),
83
+ 'hyperref': (r'\href{', r'\url{'),
84
+ 'float': (r'\begin{figure}[H]',),
85
+ 'csquotes': (r'\enquote{',),
86
+ }
87
+
88
+ # packages other packages load transitively (avoid false "missing" warnings)
89
+ _LATEX_PACKAGE_PROVIDES = {
90
+ 'xltabular': ('longtable', 'tabularx', 'array'),
91
+ 'xcolor': ('color',),
92
+ 'graphicx': ('graphics',),
93
+ 'hyperref': ('url',),
94
+ }
95
+
96
+ # options to use when a package is auto-added; pydocmaker emits dvipsnames
97
+ # color names (ForestGreen, NavyBlue, ...) via the bcolors handling
98
+ _LATEX_PACKAGE_OPTIONS = {'xcolor': '[dvipsnames]'}
99
+
100
+ # strip code blocks so their content cannot trigger false positives (the
101
+ # environment markers themselves are kept so listings stays detectable)
102
+ _VERBATIM_BLOCK_RE = re.compile(r'\\begin{(lstlisting|verbatim)}.*?\\end{\1}', re.DOTALL)
103
+
104
+
105
+ def _strip_verbatim_envs(body):
106
+ """Replace verbatim/lstlisting environments with their empty markers.
107
+
108
+ The content of code blocks must not trigger package detection (e.g. an
109
+ ``\\includegraphics`` inside a code sample), but the environment markers
110
+ are kept so a body containing code still reports the ``listings``
111
+ package as needed.
112
+ """
113
+ return _VERBATIM_BLOCK_RE.sub(lambda m: '\\begin{%s}\\end{%s}' % (m.group(1), m.group(1)), body)
114
+
115
+
116
+ def _find_used_packages(doc_tex) -> set:
117
+ """Collect the packages loaded by the preamble of a latex document.
118
+
119
+ Only the region before ``\\begin{document}`` is scanned (a usepackage
120
+ after it would be a latex error anyways); commented lines are ignored.
121
+ Packages loaded transitively by other packages (see
122
+ ``_LATEX_PACKAGE_PROVIDES``) count as used as well.
123
+ """
124
+ preamble = doc_tex.split(r'\begin{document}')[0] if r'\begin{document}' in doc_tex else doc_tex
125
+ used = set()
126
+ for line in preamble.split('\n'):
127
+ if line.lstrip().startswith('%'):
128
+ continue
129
+ for m in _USEPACKAGE_RE.finditer(line):
130
+ for name in m.group('names').split(','):
131
+ name = name.strip()
132
+ if name:
133
+ used.add(name)
134
+ for pkg in list(used):
135
+ used.update(_LATEX_PACKAGE_PROVIDES.get(pkg, ()))
136
+ return used
137
+
138
+
139
+ def _find_needed_packages(body) -> list:
140
+ """Return the packages the generated body needs, in deterministic order."""
141
+ scanned = _strip_verbatim_envs(body)
142
+ return [pkg for pkg, pats in _LATEX_PACKAGE_PATTERNS.items()
143
+ if any(re.search(re.escape(p), scanned) for p in pats)]
144
+
145
+
146
+ def _add_missing_packages(doc_tex, missing, **kw) -> str:
147
+ """Insert \\usepackage lines for the missing packages into the preamble.
148
+
149
+ The lines are inserted after the last non-comment \\usepackage /
150
+ \\RequirePackage line of the preamble, or right after the (last)
151
+ \\documentclass line when the template loads no packages at all.
152
+ """
153
+ lines = doc_tex.split('\n')
154
+ preamble_end = len(lines)
155
+ for i, line in enumerate(lines):
156
+ if r'\begin{document}' in line:
157
+ preamble_end = i
158
+ break
159
+
160
+ anchor = None
161
+ for i in range(preamble_end):
162
+ line = lines[i]
163
+ if line.lstrip().startswith('%'):
164
+ continue
165
+ if r'\usepackage' in line or r'\RequirePackage' in line:
166
+ anchor = i
167
+ if anchor is None:
168
+ for i in range(preamble_end):
169
+ line = lines[i]
170
+ if line.lstrip().startswith('%'):
171
+ continue
172
+ if r'\documentclass' in line:
173
+ anchor = i
174
+ if anchor is None:
175
+ log.warning('could not find a \\usepackage or \\documentclass line to insert the missing latex packages; leaving the document unchanged')
176
+ return doc_tex
177
+
178
+ # hyperref conventionally loads last
179
+ ordered = [p for p in missing if p != 'hyperref']
180
+ if 'hyperref' in missing:
181
+ ordered.append('hyperref')
182
+
183
+ insert_lines = ['\\usepackage%s{%s}' % (_LATEX_PACKAGE_OPTIONS.get(pkg, ''), pkg) for pkg in ordered]
184
+
185
+ log.info(f'auto-adding missing latex packages: {", ".join(ordered)}')
186
+ lines[anchor + 1:anchor + 1] = insert_lines
187
+ return '\n'.join(lines)
188
+
189
+
190
+ def _check_latex_packages(doc_tex, body, verb=0) -> str:
191
+ """Check the rendered latex document for missing packages.
192
+
193
+ Warns when the template does not load packages the generated body needs
194
+ and (unless disabled via ``config_latex_add_missing_packages_set(False)``)
195
+ inserts the missing \\usepackage lines into the preamble. Fragment /
196
+ body-only output without a \\documentclass is returned unchanged.
197
+ """
198
+ if r'\documentclass' not in doc_tex:
199
+ return doc_tex
200
+
201
+ used = _find_used_packages(doc_tex)
202
+ missing = [p for p in _find_needed_packages(body) if p not in used]
203
+ if not missing:
204
+ return doc_tex
205
+
206
+ log.warning(f'the latex template does not load the package(s) {", ".join(missing)} required by the generated document body')
207
+
208
+ if not config_latex_add_missing_packages_get():
209
+ log.info('auto-adding missing latex packages is disabled (config_latex_add_missing_packages_set(False)); leaving the document unchanged')
210
+ return doc_tex
211
+
212
+ return _add_missing_packages(doc_tex, missing)
213
+
214
+
215
+
58
216
 
59
217
  USE_XLTABULAR = True
60
218
 
@@ -341,6 +499,8 @@ def convert(doc:List[dict], with_attachments=True, files_to_upload=None, templat
341
499
 
342
500
  body = '\n'.join(s) if isinstance(s, list) else s
343
501
 
502
+ if template is None:
503
+ template = get_default_template_id('tex')
344
504
  template_obj, attachments, template_str = handle_template(template, __default_template, tformat='tex', template_engine=template_engine)
345
505
 
346
506
  if template == '':
@@ -390,7 +550,11 @@ def convert(doc:List[dict], with_attachments=True, files_to_upload=None, templat
390
550
  log.info(f' {attachments.keys()=}')
391
551
 
392
552
  doc_tex = template_obj.render(**kw)
393
- formatter.attachments.update(attachments)
553
+ # merge the template assets without overwriting attachments that were
554
+ # explicitly provided with the document (files_to_upload / document
555
+ # images), so user provided files keep precedence like in the metadata flow
556
+ formatter.attachments.update({k: v for k, v in attachments.items()
557
+ if k not in formatter.attachments})
394
558
 
395
559
  # remote the pandoc specific macros
396
560
  macros = ("passthrough", "tightlist", "lstinline", "Verb")
@@ -401,6 +565,10 @@ def convert(doc:List[dict], with_attachments=True, files_to_upload=None, templat
401
565
  if verb: log.warning(f'found "{macro}" in tex source but no "{cmd}" will replace all occurances')
402
566
  doc_tex = doc_tex.replace(macro, "")
403
567
 
568
+ # check the template loads all packages the generated body needs and add
569
+ # the missing ones to the preamble if configured
570
+ doc_tex = _check_latex_packages(doc_tex, body, verb=verb)
571
+
404
572
 
405
573
  if with_attachments:
406
574
  return doc_tex, formatter.attachments
@@ -13,9 +13,9 @@ except Exception as err:
13
13
  from .baseformatter import BaseFormatter
14
14
 
15
15
  try:
16
- from pydocmaker.templating import handle_template
16
+ from pydocmaker.templating import handle_template, get_default_template_id
17
17
  except Exception as err:
18
- from ..templating import handle_template
18
+ from ..templating import handle_template, get_default_template_id
19
19
 
20
20
  try:
21
21
  from pydocmaker import util
@@ -503,6 +503,8 @@ def convert(doc:List[dict], template = None, template_params=None, ret_attachmen
503
503
  tmp = list(doc.values()) if isinstance(doc, dict) else doc
504
504
  body = formatter.digest(tmp)
505
505
 
506
+ if template is None:
507
+ template = get_default_template_id('typ')
506
508
  template_obj, attachments, template_str = handle_template(template, __default_template, tformat='typ', template_engine=template_engine)
507
509
 
508
510