novelWriter 2.5.2__py3-none-any.whl → 2.6__py3-none-any.whl

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 (129) hide show
  1. {novelWriter-2.5.2.dist-info → novelWriter-2.6.dist-info}/METADATA +5 -4
  2. {novelWriter-2.5.2.dist-info → novelWriter-2.6.dist-info}/RECORD +126 -105
  3. {novelWriter-2.5.2.dist-info → novelWriter-2.6.dist-info}/WHEEL +1 -1
  4. novelwriter/__init__.py +50 -11
  5. novelwriter/assets/i18n/nw_de_DE.qm +0 -0
  6. novelwriter/assets/i18n/nw_en_US.qm +0 -0
  7. novelwriter/assets/i18n/nw_es_419.qm +0 -0
  8. novelwriter/assets/i18n/nw_fr_FR.qm +0 -0
  9. novelwriter/assets/i18n/nw_it_IT.qm +0 -0
  10. novelwriter/assets/i18n/nw_ja_JP.qm +0 -0
  11. novelwriter/assets/i18n/nw_nb_NO.qm +0 -0
  12. novelwriter/assets/i18n/nw_nl_NL.qm +0 -0
  13. novelwriter/assets/i18n/nw_pl_PL.qm +0 -0
  14. novelwriter/assets/i18n/nw_pt_BR.qm +0 -0
  15. novelwriter/assets/i18n/nw_ru_RU.qm +0 -0
  16. novelwriter/assets/i18n/nw_zh_CN.qm +0 -0
  17. novelwriter/assets/i18n/project_de_DE.json +4 -2
  18. novelwriter/assets/i18n/project_en_GB.json +1 -0
  19. novelwriter/assets/i18n/project_en_US.json +2 -0
  20. novelwriter/assets/i18n/project_it_IT.json +2 -0
  21. novelwriter/assets/i18n/project_ja_JP.json +2 -0
  22. novelwriter/assets/i18n/project_nb_NO.json +2 -0
  23. novelwriter/assets/i18n/project_nl_NL.json +2 -0
  24. novelwriter/assets/i18n/project_pl_PL.json +2 -0
  25. novelwriter/assets/i18n/project_pt_BR.json +2 -0
  26. novelwriter/assets/i18n/project_ru_RU.json +11 -0
  27. novelwriter/assets/i18n/project_zh_CN.json +2 -0
  28. novelwriter/assets/icons/typicons_dark/icons.conf +8 -0
  29. novelwriter/assets/icons/typicons_dark/mixed_copy.svg +4 -0
  30. novelwriter/assets/icons/typicons_dark/mixed_margin-bottom.svg +6 -0
  31. novelwriter/assets/icons/typicons_dark/mixed_margin-left.svg +6 -0
  32. novelwriter/assets/icons/typicons_dark/mixed_margin-right.svg +6 -0
  33. novelwriter/assets/icons/typicons_dark/mixed_margin-top.svg +6 -0
  34. novelwriter/assets/icons/typicons_dark/mixed_size-height.svg +6 -0
  35. novelwriter/assets/icons/typicons_dark/mixed_size-width.svg +6 -0
  36. novelwriter/assets/icons/typicons_dark/nw_toolbar.svg +5 -0
  37. novelwriter/assets/icons/typicons_light/icons.conf +8 -0
  38. novelwriter/assets/icons/typicons_light/mixed_copy.svg +4 -0
  39. novelwriter/assets/icons/typicons_light/mixed_margin-bottom.svg +6 -0
  40. novelwriter/assets/icons/typicons_light/mixed_margin-left.svg +6 -0
  41. novelwriter/assets/icons/typicons_light/mixed_margin-right.svg +6 -0
  42. novelwriter/assets/icons/typicons_light/mixed_margin-top.svg +6 -0
  43. novelwriter/assets/icons/typicons_light/mixed_size-height.svg +6 -0
  44. novelwriter/assets/icons/typicons_light/mixed_size-width.svg +6 -0
  45. novelwriter/assets/icons/typicons_light/nw_toolbar.svg +5 -0
  46. novelwriter/assets/manual.pdf +0 -0
  47. novelwriter/assets/sample.zip +0 -0
  48. novelwriter/assets/text/credits_en.htm +1 -0
  49. novelwriter/assets/themes/default_light.conf +2 -2
  50. novelwriter/common.py +101 -3
  51. novelwriter/config.py +30 -17
  52. novelwriter/constants.py +189 -81
  53. novelwriter/core/buildsettings.py +74 -40
  54. novelwriter/core/coretools.py +146 -148
  55. novelwriter/core/docbuild.py +133 -171
  56. novelwriter/core/document.py +1 -1
  57. novelwriter/core/index.py +39 -38
  58. novelwriter/core/item.py +42 -9
  59. novelwriter/core/itemmodel.py +518 -0
  60. novelwriter/core/options.py +5 -2
  61. novelwriter/core/project.py +68 -90
  62. novelwriter/core/projectdata.py +8 -2
  63. novelwriter/core/projectxml.py +1 -1
  64. novelwriter/core/sessions.py +1 -1
  65. novelwriter/core/spellcheck.py +10 -15
  66. novelwriter/core/status.py +24 -8
  67. novelwriter/core/storage.py +1 -1
  68. novelwriter/core/tree.py +269 -288
  69. novelwriter/dialogs/about.py +1 -1
  70. novelwriter/dialogs/docmerge.py +8 -18
  71. novelwriter/dialogs/docsplit.py +1 -1
  72. novelwriter/dialogs/editlabel.py +1 -1
  73. novelwriter/dialogs/preferences.py +47 -34
  74. novelwriter/dialogs/projectsettings.py +149 -99
  75. novelwriter/dialogs/quotes.py +1 -1
  76. novelwriter/dialogs/wordlist.py +11 -10
  77. novelwriter/enum.py +37 -24
  78. novelwriter/error.py +2 -2
  79. novelwriter/extensions/configlayout.py +28 -13
  80. novelwriter/extensions/eventfilters.py +1 -1
  81. novelwriter/extensions/modified.py +30 -6
  82. novelwriter/extensions/novelselector.py +4 -3
  83. novelwriter/extensions/pagedsidebar.py +9 -9
  84. novelwriter/extensions/progressbars.py +4 -4
  85. novelwriter/extensions/statusled.py +3 -3
  86. novelwriter/extensions/switch.py +3 -3
  87. novelwriter/extensions/switchbox.py +1 -1
  88. novelwriter/extensions/versioninfo.py +1 -1
  89. novelwriter/formats/shared.py +156 -0
  90. novelwriter/formats/todocx.py +1191 -0
  91. novelwriter/formats/tohtml.py +454 -0
  92. novelwriter/{core → formats}/tokenizer.py +497 -495
  93. novelwriter/formats/tomarkdown.py +218 -0
  94. novelwriter/{core → formats}/toodt.py +312 -433
  95. novelwriter/formats/toqdoc.py +486 -0
  96. novelwriter/formats/toraw.py +91 -0
  97. novelwriter/gui/doceditor.py +347 -287
  98. novelwriter/gui/dochighlight.py +97 -85
  99. novelwriter/gui/docviewer.py +90 -33
  100. novelwriter/gui/docviewerpanel.py +18 -26
  101. novelwriter/gui/editordocument.py +18 -3
  102. novelwriter/gui/itemdetails.py +27 -29
  103. novelwriter/gui/mainmenu.py +130 -64
  104. novelwriter/gui/noveltree.py +46 -48
  105. novelwriter/gui/outline.py +202 -256
  106. novelwriter/gui/projtree.py +590 -1238
  107. novelwriter/gui/search.py +11 -19
  108. novelwriter/gui/sidebar.py +8 -7
  109. novelwriter/gui/statusbar.py +20 -3
  110. novelwriter/gui/theme.py +11 -6
  111. novelwriter/guimain.py +101 -201
  112. novelwriter/shared.py +67 -28
  113. novelwriter/text/counting.py +3 -1
  114. novelwriter/text/patterns.py +169 -61
  115. novelwriter/tools/dictionaries.py +3 -3
  116. novelwriter/tools/lipsum.py +1 -1
  117. novelwriter/tools/manusbuild.py +15 -13
  118. novelwriter/tools/manuscript.py +121 -79
  119. novelwriter/tools/manussettings.py +424 -291
  120. novelwriter/tools/noveldetails.py +1 -1
  121. novelwriter/tools/welcome.py +6 -6
  122. novelwriter/tools/writingstats.py +4 -4
  123. novelwriter/types.py +25 -9
  124. novelwriter/core/tohtml.py +0 -530
  125. novelwriter/core/tomarkdown.py +0 -252
  126. novelwriter/core/toqdoc.py +0 -419
  127. {novelWriter-2.5.2.dist-info → novelWriter-2.6.dist-info}/LICENSE.md +0 -0
  128. {novelWriter-2.5.2.dist-info → novelWriter-2.6.dist-info}/entry_points.txt +0 -0
  129. {novelWriter-2.5.2.dist-info → novelWriter-2.6.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,454 @@
1
+ """
2
+ novelWriter – HTML Text Converter
3
+ =================================
4
+
5
+ File History:
6
+ Created: 2019-05-07 [0.0.1] ToHtml
7
+
8
+ This file is a part of novelWriter
9
+ Copyright (C) 2019 Veronica Berglyd Olsen and novelWriter contributors
10
+
11
+ This program is free software: you can redistribute it and/or modify
12
+ it under the terms of the GNU General Public License as published by
13
+ the Free Software Foundation, either version 3 of the License, or
14
+ (at your option) any later version.
15
+
16
+ This program is distributed in the hope that it will be useful, but
17
+ WITHOUT ANY WARRANTY; without even the implied warranty of
18
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19
+ General Public License for more details.
20
+
21
+ You should have received a copy of the GNU General Public License
22
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import logging
28
+
29
+ from pathlib import Path
30
+ from time import time
31
+
32
+ from novelwriter.common import formatTimeStamp
33
+ from novelwriter.constants import nwHtmlUnicode, nwStyles
34
+ from novelwriter.core.project import NWProject
35
+ from novelwriter.formats.shared import BlockFmt, BlockTyp, T_Formats, TextFmt, stripEscape
36
+ from novelwriter.formats.tokenizer import Tokenizer
37
+ from novelwriter.types import FONT_STYLE, FONT_WEIGHTS, QtHexRgb
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+ # Each opener tag, with the id of its corresponding closer and tag format
42
+ HTML_OPENER: dict[int, tuple[int, str]] = {
43
+ TextFmt.B_B: (TextFmt.B_E, "<strong>"),
44
+ TextFmt.I_B: (TextFmt.I_E, "<em>"),
45
+ TextFmt.D_B: (TextFmt.D_E, "<del>"),
46
+ TextFmt.U_B: (TextFmt.U_E, "<span style='text-decoration: underline;'>"),
47
+ TextFmt.M_B: (TextFmt.M_E, "<mark>"),
48
+ TextFmt.SUP_B: (TextFmt.SUP_E, "<sup>"),
49
+ TextFmt.SUB_B: (TextFmt.SUB_E, "<sub>"),
50
+ TextFmt.COL_B: (TextFmt.COL_E, "<span style='color: {0}'>"),
51
+ TextFmt.ANM_B: (TextFmt.ANM_E, "<a name='{0}'>"),
52
+ TextFmt.ARF_B: (TextFmt.ARF_E, "<a href='{0}'>"),
53
+ TextFmt.HRF_B: (TextFmt.HRF_E, "<a href='{0}'>"),
54
+ }
55
+
56
+ # Each closer tag, with the id of its corresponding opener and tag format
57
+ HTML_CLOSER: dict[int, tuple[int, str]] = {
58
+ TextFmt.B_E: (TextFmt.B_B, "</strong>"),
59
+ TextFmt.I_E: (TextFmt.I_B, "</em>"),
60
+ TextFmt.D_E: (TextFmt.D_B, "</del>"),
61
+ TextFmt.U_E: (TextFmt.U_B, "</span>"),
62
+ TextFmt.M_E: (TextFmt.M_B, "</mark>"),
63
+ TextFmt.SUP_E: (TextFmt.SUP_B, "</sup>"),
64
+ TextFmt.SUB_E: (TextFmt.SUB_B, "</sub>"),
65
+ TextFmt.COL_E: (TextFmt.COL_B, "</span>"),
66
+ TextFmt.ANM_E: (TextFmt.ANM_B, "</a>"),
67
+ TextFmt.ARF_E: (TextFmt.ARF_B, "</a>"),
68
+ TextFmt.HRF_E: (TextFmt.HRF_B, "</a>"),
69
+ }
70
+
71
+ # Empty HTML tag record
72
+ HTML_NONE = (0, "")
73
+
74
+
75
+ class ToHtml(Tokenizer):
76
+ """Core: HTML Document Writer
77
+
78
+ Extend the Tokenizer class to writer HTML output. This class is
79
+ also used by the Document Viewer, and Manuscript Build Preview.
80
+ """
81
+
82
+ def __init__(self, project: NWProject) -> None:
83
+ super().__init__(project)
84
+ self._trMap = {}
85
+ self._cssStyles = True
86
+ self._usedNotes: dict[str, int] = {}
87
+ self._usedFields: list[tuple[int, str]] = []
88
+ self.setReplaceUnicode(False)
89
+ return
90
+
91
+ ##
92
+ # Setters
93
+ ##
94
+
95
+ def setStyles(self, cssStyles: bool) -> None:
96
+ """Enable or disable CSS styling. Some elements may still have
97
+ class tags.
98
+ """
99
+ self._cssStyles = cssStyles
100
+ return
101
+
102
+ def setReplaceUnicode(self, doReplace: bool) -> None:
103
+ """Set the translation map to either minimal or full unicode for
104
+ html entities replacement.
105
+ """
106
+ # Control characters must always be replaced
107
+ # Angle brackets are replaced later as they are also used in
108
+ # formatting codes
109
+ self._trMap = str.maketrans({"&": "&amp;"})
110
+ if doReplace:
111
+ # Extend to all relevant Unicode characters
112
+ self._trMap.update(str.maketrans(nwHtmlUnicode.U_TO_H))
113
+ return
114
+
115
+ ##
116
+ # Class Methods
117
+ ##
118
+
119
+ def getFullResultSize(self) -> int:
120
+ """Return the size of the full HTML result."""
121
+ return sum(len(x) for x in self._pages)
122
+
123
+ def doPreProcessing(self) -> None:
124
+ """Extend the auto-replace to also properly encode some unicode
125
+ characters into their respective HTML entities.
126
+ """
127
+ super().doPreProcessing()
128
+ self._text = self._text.translate(self._trMap)
129
+ return
130
+
131
+ def doConvert(self) -> None:
132
+ """Convert the list of text tokens into an HTML document."""
133
+ lines = []
134
+ for tType, tMeta, tText, tFmt, tStyle in self._blocks:
135
+
136
+ # Replace < and > with HTML entities
137
+ if tFmt:
138
+ # If we have formatting, we must recompute the locations
139
+ cText = []
140
+ i = 0
141
+ for c in tText:
142
+ if c == "<":
143
+ cText.append("&lt;")
144
+ tFmt = [(p + 3 if p > i else p, f, k) for p, f, k in tFmt]
145
+ i += 4
146
+ elif c == ">":
147
+ cText.append("&gt;")
148
+ tFmt = [(p + 3 if p > i else p, f, k) for p, f, k in tFmt]
149
+ i += 4
150
+ else:
151
+ cText.append(c)
152
+ i += 1
153
+ tText = "".join(cText)
154
+ else:
155
+ # If we don't have formatting, we can do a plain replace
156
+ tText = tText.replace("<", "&lt;").replace(">", "&gt;")
157
+
158
+ # Styles
159
+ aStyle = []
160
+ if self._cssStyles:
161
+ if tStyle & BlockFmt.LEFT:
162
+ aStyle.append("text-align: left;")
163
+ elif tStyle & BlockFmt.RIGHT:
164
+ aStyle.append("text-align: right;")
165
+ elif tStyle & BlockFmt.CENTRE:
166
+ aStyle.append("text-align: center;")
167
+ elif tStyle & BlockFmt.JUSTIFY:
168
+ aStyle.append("text-align: justify;")
169
+
170
+ if tStyle & BlockFmt.PBB:
171
+ aStyle.append("page-break-before: always;")
172
+ if tStyle & BlockFmt.PBA:
173
+ aStyle.append("page-break-after: always;")
174
+
175
+ if tStyle & BlockFmt.Z_BTM:
176
+ aStyle.append("margin-bottom: 0;")
177
+ if tStyle & BlockFmt.Z_TOP:
178
+ aStyle.append("margin-top: 0;")
179
+
180
+ if tStyle & BlockFmt.IND_L:
181
+ aStyle.append(f"margin-left: {self._blockIndent:.2f}em;")
182
+ if tStyle & BlockFmt.IND_R:
183
+ aStyle.append(f"margin-right: {self._blockIndent:.2f}em;")
184
+ if tStyle & BlockFmt.IND_T:
185
+ aStyle.append(f"text-indent: {self._firstWidth:.2f}em;")
186
+
187
+ if aStyle:
188
+ stVals = " ".join(aStyle)
189
+ hStyle = f" style='{stVals}'"
190
+ else:
191
+ hStyle = ""
192
+
193
+ if self._linkHeadings and tMeta:
194
+ aNm = f"<a name='{tMeta}'></a>"
195
+ else:
196
+ aNm = ""
197
+
198
+ # Process Text Type
199
+ if tType == BlockTyp.TEXT:
200
+ lines.append(f"<p{hStyle}>{self._formatText(tText, tFmt)}</p>\n")
201
+
202
+ elif tType in (BlockTyp.TITLE, BlockTyp.PART):
203
+ tHead = tText.replace("\n", "<br>")
204
+ lines.append(f"<h1 class='title'{hStyle}>{aNm}{tHead}</h1>\n")
205
+
206
+ elif tType == BlockTyp.HEAD1:
207
+ tHead = tText.replace("\n", "<br>")
208
+ lines.append(f"<h1{hStyle}>{aNm}{tHead}</h1>\n")
209
+
210
+ elif tType == BlockTyp.HEAD2:
211
+ tHead = tText.replace("\n", "<br>")
212
+ lines.append(f"<h2{hStyle}>{aNm}{tHead}</h2>\n")
213
+
214
+ elif tType == BlockTyp.HEAD3:
215
+ tHead = tText.replace("\n", "<br>")
216
+ lines.append(f"<h3{hStyle}>{aNm}{tHead}</h3>\n")
217
+
218
+ elif tType == BlockTyp.HEAD4:
219
+ tHead = tText.replace("\n", "<br>")
220
+ lines.append(f"<h4{hStyle}>{aNm}{tHead}</h4>\n")
221
+
222
+ elif tType == BlockTyp.SEP:
223
+ lines.append(f"<p class='sep'{hStyle}>{tText}</p>\n")
224
+
225
+ elif tType == BlockTyp.SKIP:
226
+ lines.append(f"<p{hStyle}>&nbsp;</p>\n")
227
+
228
+ elif tType == BlockTyp.COMMENT:
229
+ lines.append(f"<p class='comment'{hStyle}>{self._formatText(tText, tFmt)}</p>\n")
230
+
231
+ elif tType == BlockTyp.KEYWORD:
232
+ tClass = f"meta meta-{tMeta}"
233
+ lines.append(f"<p class='{tClass}'{hStyle}>{self._formatText(tText, tFmt)}</p>\n")
234
+
235
+ self._pages.append("".join(lines))
236
+
237
+ return
238
+
239
+ def closeDocument(self) -> None:
240
+ """Run close document tasks."""
241
+ # Replace fields if there are stats available
242
+ if self._usedFields and self._counts:
243
+ pages = len(self._pages)
244
+ for doc, field in self._usedFields:
245
+ if doc >= 0 and doc < pages and (value := self._counts.get(field)) is not None:
246
+ self._pages[doc] = self._pages[doc].replace(
247
+ f"{{{{{field}}}}}", self._formatInt(value)
248
+ )
249
+
250
+ # Add footnotes
251
+ if self._usedNotes:
252
+ footnotes = self._localLookup("Footnotes")
253
+
254
+ lines = []
255
+ lines.append(f"<h3>{footnotes}</h3>\n")
256
+ lines.append("<ol>\n")
257
+ for key, index in self._usedNotes.items():
258
+ if content := self._footnotes.get(key):
259
+ text = self._formatText(*content)
260
+ lines.append(f"<li id='footnote_{index}'><p>{text}</p></li>\n")
261
+ lines.append("</ol>\n")
262
+
263
+ self._pages.append("".join(lines))
264
+
265
+ return
266
+
267
+ def saveDocument(self, path: Path) -> None:
268
+ """Save the data to an HTML file."""
269
+ if path.suffix.lower() == ".json":
270
+ ts = time()
271
+ data = {
272
+ "meta": {
273
+ "projectName": self._project.data.name,
274
+ "novelAuthor": self._project.data.author,
275
+ "buildTime": int(ts),
276
+ "buildTimeStr": formatTimeStamp(ts),
277
+ },
278
+ "text": {
279
+ "css": self.getStyleSheet(),
280
+ "html": [t.replace("\t", "&#09;").rstrip().split("\n") for t in self._pages],
281
+ }
282
+ }
283
+ with open(path, mode="w", encoding="utf-8") as fObj:
284
+ json.dump(data, fObj, indent=2)
285
+
286
+ else:
287
+ with open(path, mode="w", encoding="utf-8") as fObj:
288
+ fObj.write((
289
+ "<!DOCTYPE html>\n"
290
+ "<html>\n"
291
+ "<head>\n"
292
+ "<meta charset='utf-8'>\n"
293
+ "<title>{title:s}</title>\n"
294
+ "<style>\n"
295
+ "{style:s}\n"
296
+ "</style>\n"
297
+ "</head>\n"
298
+ "<body>\n"
299
+ "{body:s}\n"
300
+ "</body>\n"
301
+ "</html>\n"
302
+ ).format(
303
+ title=self._project.data.name,
304
+ style="\n".join(self.getStyleSheet()),
305
+ body=("".join(self._pages)).replace("\t", "&#09;").rstrip(),
306
+ ))
307
+
308
+ logger.info("Wrote file: %s", path)
309
+
310
+ return
311
+
312
+ def replaceTabs(self, nSpaces: int = 8, spaceChar: str = "&nbsp;") -> None:
313
+ """Replace tabs with spaces in the html."""
314
+ pages = []
315
+ tabSpace = spaceChar*nSpaces
316
+ for aLine in self._pages:
317
+ pages.append(aLine.replace("\t", tabSpace))
318
+ self._pages = pages
319
+ return
320
+
321
+ def getStyleSheet(self) -> list[str]:
322
+ """Generate a stylesheet for the current settings."""
323
+ if not self._cssStyles:
324
+ return []
325
+
326
+ tColor = self._theme.text.name(QtHexRgb)
327
+ hColor = self._theme.head.name(QtHexRgb) if self._colorHeads else tColor
328
+ lColor = self._theme.head.name(QtHexRgb)
329
+ mColor = self._theme.highlight.name(QtHexRgb)
330
+
331
+ mtH0 = self._marginTitle[0]
332
+ mbH0 = self._marginTitle[1]
333
+ mtH1 = self._marginHead1[0]
334
+ mbH1 = self._marginHead1[1]
335
+ mtH2 = self._marginHead2[0]
336
+ mbH2 = self._marginHead2[1]
337
+ mtH3 = self._marginHead3[0]
338
+ mbH3 = self._marginHead3[1]
339
+ mtH4 = self._marginHead4[0]
340
+ mbH4 = self._marginHead4[1]
341
+ mtTT = self._marginText[0]
342
+ mbTT = self._marginText[1]
343
+ mtSP = self._marginSep[0]
344
+ mbSP = self._marginSep[1]
345
+
346
+ fSz0 = nwStyles.H_SIZES[0]
347
+ fSz1 = nwStyles.H_SIZES[1]
348
+ fSz2 = nwStyles.H_SIZES[2]
349
+ fSz3 = nwStyles.H_SIZES[3]
350
+ fSz4 = nwStyles.H_SIZES[4]
351
+
352
+ font = self._textFont
353
+ fFam = font.family()
354
+ fSz = font.pointSize()
355
+ fW = FONT_WEIGHTS.get(font.weight(), 400)
356
+ fS = FONT_STYLE.get(font.style(), "normal")
357
+
358
+ lHeight = round(100 * self._lineHeight)
359
+
360
+ styles = []
361
+ styles.append(
362
+ f"body {{color: {tColor}; font-family: '{fFam}'; font-size: {fSz}pt; "
363
+ f"font-weight: {fW}; font-style: {fS};}}"
364
+ )
365
+ styles.append(
366
+ f"p {{text-align: {self._defaultAlign}; line-height: {lHeight}%; "
367
+ f"margin-top: {mtTT:.2f}em; margin-bottom: {mbTT:.2f}em;}}"
368
+ )
369
+ styles.append(f"a {{color: {lColor};}}")
370
+ styles.append(f"mark {{background: {mColor};}}")
371
+ styles.append(f"h1, h2, h3, h4 {{color: {hColor}; page-break-after: avoid;}}")
372
+ styles.append(
373
+ f"h1 {{font-size: {fSz1:.2f}em; "
374
+ f"margin-top: {mtH1:.2f}em; margin-bottom: {mbH1:.2f}em;}}"
375
+ )
376
+ styles.append(
377
+ f"h2 {{font-size: {fSz2:.2f}em; "
378
+ f"margin-top: {mtH2:.2f}em; margin-bottom: {mbH2:.2f}em;}}"
379
+ )
380
+ styles.append(
381
+ f"h3 {{font-size: {fSz3:.2f}em; "
382
+ f"margin-top: {mtH3:.2f}em; margin-bottom: {mbH3:.2f}em;}}"
383
+ )
384
+ styles.append(
385
+ f"h4 {{font-size: {fSz4:.2f}em; "
386
+ f"margin-top: {mtH4:.2f}em; margin-bottom: {mbH4:.2f}em;}}"
387
+ )
388
+ styles.append(
389
+ f".title {{font-size: {fSz0:.2f}em; "
390
+ f"margin-top: {mtH0:.2f}em; margin-bottom: {mbH0:.2f}em;}}"
391
+ )
392
+ styles.append(
393
+ f".sep {{text-align: center; margin-top: {mtSP:.2f}em; margin-bottom: {mbSP:.2f}em;}}"
394
+ )
395
+
396
+ return styles
397
+
398
+ ##
399
+ # Internal Functions
400
+ ##
401
+
402
+ def _formatText(self, text: str, tFmt: T_Formats) -> str:
403
+ """Apply formatting tags to text."""
404
+ temp = text
405
+
406
+ # Build a list of all html tags that need to be inserted in the text.
407
+ # This is done in the forward direction, and a tag is only opened if it
408
+ # isn't already open, and only closed if it has previously been opened.
409
+ tags: list[tuple[int, str]] = []
410
+ state = dict.fromkeys(HTML_OPENER, False)
411
+ for pos, fmt, data in tFmt:
412
+ if m := HTML_OPENER.get(fmt):
413
+ if not state.get(fmt, True):
414
+ if fmt == TextFmt.COL_B and (color := self._classes.get(data)):
415
+ tags.append((pos, m[1].format(color.name(QtHexRgb))))
416
+ elif fmt in (TextFmt.ANM_B, TextFmt.ARF_B, TextFmt.HRF_B):
417
+ tags.append((pos, m[1].format(data or "#")))
418
+ else:
419
+ tags.append((pos, m[1]))
420
+ state[fmt] = True
421
+ elif m := HTML_CLOSER.get(fmt):
422
+ if state.get(m[0], False):
423
+ tags.append((pos, m[1]))
424
+ state[m[0]] = False
425
+ elif fmt == TextFmt.FNOTE:
426
+ if data in self._footnotes:
427
+ index = len(self._usedNotes) + 1
428
+ self._usedNotes[data] = index
429
+ tags.append((pos, f"<sup><a href='#footnote_{index}'>{index}</a></sup>"))
430
+ else:
431
+ tags.append((pos, "<sup>ERR</sup>"))
432
+ elif fmt == TextFmt.FIELD:
433
+ if field := data.partition(":")[2]:
434
+ self._usedFields.append((len(self._pages), field))
435
+ tags.append((pos, f"{{{{{field}}}}}"))
436
+
437
+ # Check all format types and close any tag that is still open. This
438
+ # ensures that unclosed tags don't spill over to the next paragraph.
439
+ end = len(text)
440
+ for opener, active in state.items():
441
+ if active:
442
+ closer = HTML_OPENER.get(opener, HTML_NONE)[0]
443
+ tags.append((end, HTML_CLOSER.get(closer, HTML_NONE)[1]))
444
+
445
+ # Insert all tags at their correct position, starting from the back.
446
+ # The reverse order ensures that the positions are not shifted while we
447
+ # insert tags.
448
+ for pos, tag in reversed(tags):
449
+ temp = f"{temp[:pos]}{tag}{temp[pos:]}"
450
+
451
+ # Replace all line breaks with proper HTML break tags
452
+ temp = temp.replace("\n", "<br>")
453
+
454
+ return stripEscape(temp)