pydocmaker 2.8.1__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.1/src/pydocmaker.egg-info → pydocmaker-2.8.2}/PKG-INFO +33 -19
  2. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/README.md +32 -18
  3. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/__init__.py +8 -3
  4. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_html.py +4 -2
  5. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_tex.py +171 -3
  6. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_typst.py +4 -2
  7. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templating.py +136 -5
  8. {pydocmaker-2.8.1 → pydocmaker-2.8.2/src/pydocmaker.egg-info}/PKG-INFO +33 -19
  9. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_ex_tex.py +222 -0
  10. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_templating.py +302 -0
  11. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_templating_extensive.py +26 -0
  12. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/LICENSE +0 -0
  13. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/pyproject.toml +0 -0
  14. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/requirements.txt +0 -0
  15. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/setup.cfg +0 -0
  16. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/b64_data.py +0 -0
  17. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/__init__.py +0 -0
  18. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/baseformatter.py +0 -0
  19. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_docx.py +0 -0
  20. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_ipynb.py +0 -0
  21. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_markdown.py +0 -0
  22. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_redmine.py +0 -0
  23. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/ex_rich.py +0 -0
  24. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/libreoffice_api.py +0 -0
  25. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/mdx_latex.py +0 -0
  26. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/pandoc_api.py +0 -0
  27. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/pandoc_batch.py +0 -0
  28. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/backend/pdf_maker_tex.py +0 -0
  29. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/__init__.py +0 -0
  30. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/adapter_base.py +0 -0
  31. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/adapter_html.py +0 -0
  32. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/adapter_tex.py +0 -0
  33. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/adapter_typ.py +0 -0
  34. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/inference.py +0 -0
  35. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/markers.py +0 -0
  36. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/model.py +0 -0
  37. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/parser.py +0 -0
  38. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/blocktmpl/render.py +0 -0
  39. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/cli.py +0 -0
  40. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/core.py +0 -0
  41. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/io/__init__.py +0 -0
  42. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/io/html_loader.py +0 -0
  43. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/io/ipynb_loader.py +0 -0
  44. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/param_mapping.py +0 -0
  45. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.html +0 -0
  46. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.html.j2 +0 -0
  47. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.tex +0 -0
  48. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.tex.j2 +0 -0
  49. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.typ +0 -0
  50. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/base.typ.j2 +0 -0
  51. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/paper.typ.j2 +0 -0
  52. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/report.tex +0 -0
  53. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/report.typ +0 -0
  54. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/report.typ.j2 +0 -0
  55. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/templates/word_template_with_mergefields.docx +0 -0
  56. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker/util.py +0 -0
  57. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/SOURCES.txt +0 -0
  58. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/dependency_links.txt +0 -0
  59. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/entry_points.txt +0 -0
  60. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/requires.txt +0 -0
  61. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/src/pydocmaker.egg-info/top_level.txt +0 -0
  62. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_backend_pandoc.py +0 -0
  63. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_blocktmpl_inference.py +0 -0
  64. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_blocktmpl_integration.py +0 -0
  65. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_blocktmpl_parser.py +0 -0
  66. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_blocktmpl_render.py +0 -0
  67. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_blocktmpl_values.py +0 -0
  68. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_cli.py +0 -0
  69. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_convert_all.py +0 -0
  70. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_core.py +0 -0
  71. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_docx_ex.py +0 -0
  72. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_ex_html.py +0 -0
  73. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_ex_rich.py +0 -0
  74. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_ex_typst.py +0 -0
  75. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_io_html.py +0 -0
  76. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_io_ipynb.py +0 -0
  77. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_param_mapping.py +0 -0
  78. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_pdf_ex.py +0 -0
  79. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_pdf_typst.py +0 -0
  80. {pydocmaker-2.8.1 → pydocmaker-2.8.2}/tests/test_snippets.py +0 -0
  81. {pydocmaker-2.8.1 → 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.1
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.1'
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
 
@@ -49,6 +49,7 @@ __all__ = ['DocTemplate', 'BlockDocTemplate', 'TemplateDirSource', 'handle_templ
49
49
  'get_template_params', 'resolve_template_id', 'determine_engine_from_template',
50
50
  'register_raw_template_file', 'find_template_file_references',
51
51
  'load_param_file_values', 'template_file_tformat', 'resolve_template_argument',
52
+ 'config_default_template_set', 'config_default_template_get', 'get_default_template_id',
52
53
  'parse', 'scaffold', 'update_params', 'render', 'detect',
53
54
  'map_legacy_params', 'LEGACY_PARAM_MAP']
54
55
 
@@ -163,16 +164,39 @@ def handle_template(template, default_template, tformat=None, template_engine='a
163
164
  # candidates first) so the direct and the metadata template flows
164
165
  # always end up on the same template file
165
166
  template_obj = None
167
+ resolved_id = None
166
168
  tdir = TemplateDirSource(tformat=tformat)
167
169
  for cand in _candidate_template_ids(template, tformat):
168
- template_obj = tdir.get(cand, None)
169
- if template_obj is not None:
170
+ try:
171
+ resolved_id = tdir.resolve_template_id(cand)
170
172
  break
171
- if template_obj is None:
172
- template_obj = tdir.get(template, None)
173
+ except KeyError:
174
+ pass
175
+ if resolved_id is None:
176
+ try:
177
+ resolved_id = tdir.resolve_template_id(template)
178
+ except KeyError:
179
+ pass
180
+ if resolved_id is not None:
181
+ template_obj = tdir.get(resolved_id, None)
182
+ if template_obj is None:
183
+ resolved_id = None
173
184
  if template_obj is None:
174
185
  template_obj = Template(template)
175
186
  template_str = str(template)
187
+ else:
188
+ # load the template's assets (the global "assets/" folder and the
189
+ # template specific "<id>.assets/" folder of the registered template
190
+ # directories) exactly like DocTemplate.from_tid does for the
191
+ # metadata flow, so template ids given directly (e.g.
192
+ # doc.to_pdf(..., template="default")) find their asset files too
193
+ try:
194
+ template_attachments = tdir.get_attachments([resolved_id])
195
+ attachments.update(template_attachments.get('', {}))
196
+ attachments.update(template_attachments.get(resolved_id, {}))
197
+ except Exception as err:
198
+ util.log.warning(f'failed to load the attachments of template '
199
+ f'{resolved_id!r}: {err}')
176
200
 
177
201
  else:
178
202
  raise KeyError(f'Unknown template type! {type(template)=}')
@@ -378,6 +402,110 @@ def resolve_template_id(template_id, template_dir=None, tformat=None, on_error='
378
402
  return on_error
379
403
 
380
404
 
405
+ # --------------------------------------------------------------------------- #
406
+ # default template config (used by the convert backends when no template is
407
+ # given; see get_default_template_id)
408
+ # --------------------------------------------------------------------------- #
409
+
410
+ _default_template = None # None | str | dict
411
+
412
+ _DEFAULT_TEMPLATE_FORMATS = ('html', 'typ', 'tex')
413
+ _DEFAULT_TEMPLATE_ALIASES = {'typst': 'typ', 'latex': 'tex'}
414
+
415
+ def config_default_template_set(value=None):
416
+ """Set the default template used when no template is given.
417
+
418
+ Args:
419
+ value (None | str | dict): None resets the config so the backends use
420
+ their built-in default template again; a str is a template id
421
+ (e.g. 'base' or 'report') resolved per requested format; a dict
422
+ maps formats to template ids, e.g.
423
+ ``{'html': 'base.html', 'typ': 'report.typ', 'tex': 'report.tex'}``
424
+ (alias keys 'typst' and 'latex' are accepted).
425
+
426
+ Raises:
427
+ ValueError: for an empty string or a dict key that is not a known
428
+ template format.
429
+ TypeError: for values that are neither None, str nor dict, or for
430
+ dict values that are not strings.
431
+
432
+ Existence is NOT validated here (template dirs can be registered later);
433
+ resolution + fallback happens per convert call via get_default_template_id().
434
+ """
435
+ global _default_template
436
+ if value is None:
437
+ _default_template = None
438
+ elif isinstance(value, str):
439
+ value = value.strip()
440
+ if not value:
441
+ raise ValueError("default template must be a non-empty template id, a {'html': ..., 'typ': ..., 'tex': ...} dict or None")
442
+ _default_template = value
443
+ elif isinstance(value, dict):
444
+ normalized = {}
445
+ for key, val in value.items():
446
+ if not isinstance(key, str):
447
+ raise TypeError(f'default template format keys must be strings, got {key!r}')
448
+ fmt = key.strip().lower()
449
+ fmt = _DEFAULT_TEMPLATE_ALIASES.get(fmt, fmt)
450
+ if fmt not in _DEFAULT_TEMPLATE_FORMATS:
451
+ raise ValueError(f"invalid default template format key {key!r}; must be one of {', '.join(_DEFAULT_TEMPLATE_FORMATS)}")
452
+ if not isinstance(val, str):
453
+ raise TypeError(f'default template for format {fmt!r} must be a non-empty template id string, got {val!r}')
454
+ val = val.strip()
455
+ if not val:
456
+ raise ValueError(f'default template for format {fmt!r} must be a non-empty template id')
457
+ normalized[fmt] = val
458
+ _default_template = normalized
459
+ else:
460
+ raise TypeError(f'default template must be None, a template id string or a dict of format -> template ids, got {type(value).__name__}')
461
+ return _default_template
462
+
463
+ def config_default_template_get():
464
+ """Return the configured default template (None, str or dict)."""
465
+ return _default_template
466
+
467
+ def get_default_template_id(tformat=None):
468
+ """Resolve the configured default template id for a format (or None).
469
+
470
+ Mirrors handle_template's candidate resolution so the returned id renders
471
+ through the exact same path. None/str/dict handling:
472
+ - raw is None -> None
473
+ - dict -> candidate = raw.get(normalized tformat); str -> candidate = raw
474
+ - verify with _candidate_template_ids(candidate, tformat) and
475
+ resolve_template_id(cand, tformat=tformat, on_error=None); on success
476
+ return the raw candidate (e.g. 'base'), on failure log a warning
477
+ ('configured default template ... was not found; using the built-in
478
+ default template instead') and return None.
479
+ - tformat None + dict value -> None (ambiguous)
480
+ """
481
+ raw = _default_template
482
+ if raw is None:
483
+ return None
484
+
485
+ norm = _normalize_tformat_arg(tformat)
486
+
487
+ if isinstance(raw, dict):
488
+ if norm is None:
489
+ return None
490
+ candidate = raw.get(norm)
491
+ if not candidate:
492
+ return None
493
+ else:
494
+ candidate = raw
495
+
496
+ try:
497
+ for cand in _candidate_template_ids(candidate, norm):
498
+ if resolve_template_id(cand, tformat=norm, on_error=None):
499
+ return candidate
500
+ if resolve_template_id(candidate, tformat=norm, on_error=None):
501
+ return candidate
502
+ except Exception:
503
+ pass
504
+
505
+ util.log.warning(f'configured default template {candidate!r} was not found; using the built-in default template instead')
506
+ return None
507
+
508
+
381
509
  # --------------------------------------------------------------------------- #
382
510
  # raw template files, template source attachment collection and template
383
511
  # argument resolution (shared between the library API and the CLI)
@@ -1323,7 +1451,10 @@ class TemplateDirSource():
1323
1451
  folderpath = os.path.join(template_dir, folder)
1324
1452
  if os.path.exists(folderpath) and os.path.isdir(folderpath):
1325
1453
  for file in os.listdir(folderpath):
1326
- with open(os.path.join(folderpath, file), 'rb') as f:
1454
+ filepath = os.path.join(folderpath, file)
1455
+ if not os.path.isfile(filepath):
1456
+ continue # skip sub directories
1457
+ with open(filepath, 'rb') as f:
1327
1458
  dc[file] = f.read()
1328
1459
  return dc
1329
1460
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pydocmaker
3
- Version: 2.8.1
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