Update linting for main code

This commit is contained in:
Veronica Berglyd Olsen
2025-08-27 21:00:09 +02:00
parent 84ff1f4640
commit c174f8f931
80 changed files with 461 additions and 1653 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import re
+12 -34
View File
@@ -21,7 +21,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -100,7 +100,7 @@ def _wText(parent: ET.Element, text: str) -> ET.Element:
def _mmToSz(value: float) -> int:
"""Convert millimetres to internal margin size units"""
"""Convert millimetres to internal margin size units."""
return int(value*20.0*72.0/25.4)
@@ -143,6 +143,7 @@ S_FNOTE = "FootnoteText"
class DocXXmlRel(NamedTuple):
"""DocX XML Rel Data."""
rId: str
relType: str
@@ -150,6 +151,7 @@ class DocXXmlRel(NamedTuple):
class DocXXmlFile(NamedTuple):
"""DocX XML File Data."""
xml: ET.Element
path: str
@@ -157,6 +159,7 @@ class DocXXmlFile(NamedTuple):
class DocXParStyle(NamedTuple):
"""DocX XML Paragraph Style Data."""
name: str
styleId: str
@@ -176,7 +179,7 @@ class DocXParStyle(NamedTuple):
class ToDocX(Tokenizer):
"""Core: DocX Document Writer
"""Core: DocX Document Writer.
Extend the Tokenizer class to writer DocX Document files.
"""
@@ -202,8 +205,6 @@ class ToDocX(Tokenizer):
self._usedNotes: dict[str, int] = {}
self._usedFields: list[tuple[ET.Element, str]] = []
return
##
# Setters
##
@@ -214,25 +215,22 @@ class ToDocX(Tokenizer):
"""Set the document page size and margins in millimetres."""
self._pageSize = QSize(_mmToSz(width), _mmToSz(height))
self._pageMargins = QMargins(_mmToSz(left), _mmToSz(top), _mmToSz(right), _mmToSz(bottom))
return
def setHeaderFormat(self, value: str, offset: int) -> None:
"""Set the document header format."""
self._headerFormat = value.strip()
self._pageOffset = offset
return
##
# Class Methods
##
def initDocument(self) -> None:
"""Initialises the DocX document structure."""
"""Initialise the DocX document structure."""
super().initDocument()
self._fontFamily = self._textFont.family()
self._fontSize = self._textFont.pointSizeF()
self._generateStyles()
return
def doConvert(self) -> None:
"""Convert the list of text tokens into XML elements."""
@@ -302,8 +300,6 @@ class ToDocX(Tokenizer):
elif tType == BlockTyp.KEYWORD:
self._processFragments(par, S_META, tText, tFormat)
return
def closeDocument(self) -> None:
"""Generate all the XML."""
self._coreXml()
@@ -322,8 +318,6 @@ class ToDocX(Tokenizer):
if self._usedNotes:
self._footnotesXml()
return
def saveDocument(self, path: Path) -> None:
"""Save the data to a .docx file."""
# Content Lists
@@ -373,8 +367,6 @@ class ToDocX(Tokenizer):
xmlToZip(f"{rel.path}/{name}", rel.xml, outZip)
xmlToZip("[Content_Types].xml", dTypes, outZip)
return
##
# Internal Functions
##
@@ -454,8 +446,6 @@ class ToDocX(Tokenizer):
if temp := text[fStart:]:
par.addContent(self._textRunToXml(temp, xFmt, fClass, fLink))
return
def _textRunToXml(self, text: str | None, fmt: int, fClass: str, fLink: str) -> ET.Element:
"""Encode the text run into XML."""
xR = xmlElement(_wTag("r"))
@@ -668,8 +658,6 @@ class ToDocX(Tokenizer):
for style in styles:
self._styles[style.styleId] = style
return
def _nextRelId(self) -> str:
"""Generate the next unique rId."""
return f"rId{len(self._rels) + 1}"
@@ -1054,6 +1042,10 @@ class ToDocX(Tokenizer):
class DocXParagraph:
"""DocX Text Paragraph.
This class holds a single paragraph of a DocX document.
"""
__slots__ = (
"_bottomMargin", "_breakAfter", "_breakBefore", "_content",
@@ -1073,7 +1065,6 @@ class DocXParagraph:
self._breakBefore = False
self._breakAfter = False
self._footnoteRef = False
return
##
# Properties
@@ -1091,53 +1082,43 @@ class DocXParagraph:
def setStyle(self, style: DocXParStyle | None) -> None:
"""Set the paragraph style."""
self._style = style
return
def setAlignment(self, value: str) -> None:
"""Set paragraph alignment."""
if value in ("left", "center", "right", "both"):
self._textAlign = value
return
def setMarginTop(self, value: float) -> None:
"""Set margin above in pt."""
self._topMargin = value
return
def setMarginBottom(self, value: float) -> None:
"""Set margin below in pt."""
self._bottomMargin = value
return
def setMarginLeft(self, value: float) -> None:
"""Set margin left in pt."""
self._leftMargin = value
return
def setMarginRight(self, value: float) -> None:
"""Set margin right in pt."""
self._rightMargin = value
return
def setIndentFirst(self, state: bool) -> None:
"""Set first line indent."""
self._indentFirst = state
return
def setPageBreakBefore(self, state: bool) -> None:
"""Set page break before flag."""
self._breakBefore = state
return
def setPageBreakAfter(self, state: bool) -> None:
"""Set page break after flag."""
self._breakAfter = state
return
def setIsFootnote(self, state: bool) -> None:
"""Set is footnote flag."""
self._footnoteRef = state
return
##
# Methods
@@ -1146,10 +1127,9 @@ class DocXParagraph:
def addContent(self, run: ET.Element) -> None:
"""Add a run segment to the paragraph."""
self._content.append(run)
return
def toXml(self, body: ET.Element) -> None:
"""Called after all content is set."""
"""Generate the XML. Call after all content is set."""
if style := self._style:
xP = xmlSubElem(body, _wTag("p"))
@@ -1191,5 +1171,3 @@ class DocXParagraph:
if self._breakAfter:
xR = xmlSubElem(xP, _wTag("r"))
xmlSubElem(xR, _wTag("br"), attrib={_wTag("type"): "page"})
return
+2 -13
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import json
@@ -77,7 +77,7 @@ HTML_NONE = (0, "")
class ToHtml(Tokenizer):
"""Core: HTML Document Writer
"""Core: HTML Document Writer.
Extend the Tokenizer class to writer HTML output. This class is
also used by the Document Viewer, and Manuscript Build Preview.
@@ -90,7 +90,6 @@ class ToHtml(Tokenizer):
self._usedNotes: dict[str, int] = {}
self._usedFields: list[tuple[int, str]] = []
self.setReplaceUnicode(False)
return
##
# Setters
@@ -101,7 +100,6 @@ class ToHtml(Tokenizer):
class tags.
"""
self._cssStyles = cssStyles
return
def setReplaceUnicode(self, doReplace: bool) -> None:
"""Set the translation map to either minimal or full unicode for
@@ -114,7 +112,6 @@ class ToHtml(Tokenizer):
if doReplace:
# Extend to all relevant Unicode characters
self._trMap.update(str.maketrans(nwHtmlUnicode.U_TO_H))
return
##
# Class Methods
@@ -130,7 +127,6 @@ class ToHtml(Tokenizer):
"""
super().doPreProcessing()
self._text = self._text.translate(self._trMap)
return
def doConvert(self) -> None:
"""Convert the list of text tokens into an HTML document."""
@@ -237,8 +233,6 @@ class ToHtml(Tokenizer):
self._pages.append("".join(lines))
return
def closeDocument(self) -> None:
"""Run close document tasks."""
# Replace fields if there are stats available
@@ -265,8 +259,6 @@ class ToHtml(Tokenizer):
self._pages.append("".join(lines))
return
def saveDocument(self, path: Path) -> None:
"""Save the data to an HTML file."""
if path.suffix.lower() == ".json":
@@ -309,14 +301,11 @@ class ToHtml(Tokenizer):
logger.info("Wrote file: %s", path)
return
def replaceTabs(self, nSpaces: int = 8, spaceChar: str = "&nbsp;") -> None:
"""Replace tabs with spaces in the html."""
tabSpace = spaceChar*nSpaces
pages = [aLine.replace("\t", tabSpace) for aLine in self._pages]
self._pages = pages
return
def getStyleSheet(self) -> list[str]:
"""Generate a stylesheet for the current settings."""
+11 -55
View File
@@ -21,7 +21,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -55,6 +55,7 @@ logger = logging.getLogger(__name__)
class ComStyle(NamedTuple):
"""Comment style info."""
label: str = ""
labelClass: str = ""
@@ -92,7 +93,7 @@ B_EMPTY: T_Block = (BlockTyp.EMPTY, "", "", [], BlockFmt.NONE)
class Tokenizer(ABC):
"""Core: Text Tokenizer Abstract Base Class
"""Core: Text Tokenizer Abstract Base Class.
This is the base class for all document build classes. It parses the
novelWriter markup format and generates a registry of tokens and
@@ -224,8 +225,6 @@ class Tokenizer(ABC):
self._dialogParser = DialogParser()
self._dialogParser.initParser()
return
##
# Properties
##
@@ -253,94 +252,78 @@ class Tokenizer(ABC):
"""Set language for the document."""
if language:
self._dLocale = QLocale(language)
return
def setTheme(self, theme: TextDocumentTheme) -> None:
"""Set the document colour theme."""
self._theme = theme
return
def setPartitionFormat(self, hFormat: str, hide: bool = False) -> None:
"""Set the partition format pattern."""
self._fmtPart = hFormat.strip()
self._hidePart = hide
return
def setChapterFormat(self, hFormat: str, hide: bool = False) -> None:
"""Set the chapter format pattern."""
self._fmtChapter = hFormat.strip()
self._hideChapter = hide
return
def setUnNumberedFormat(self, hFormat: str, hide: bool = False) -> None:
"""Set the unnumbered format pattern."""
self._fmtUnNum = hFormat.strip()
self._hideUnNum = hide
return
def setSceneFormat(self, hFormat: str, hide: bool = False) -> None:
"""Set the scene format pattern and hidden status."""
self._fmtScene = hFormat.strip()
self._hideScene = hide
return
def setHardSceneFormat(self, hFormat: str, hide: bool = False) -> None:
"""Set the hard scene format pattern and hidden status."""
self._fmtHScene = hFormat.strip()
self._hideHScene = hide
return
def setSectionFormat(self, hFormat: str, hide: bool = False) -> None:
"""Set the section format pattern and hidden status."""
self._fmtSection = hFormat.strip()
self._hideSection = hide
return
def setTitleStyle(self, center: bool, pageBreak: bool) -> None:
"""Set the title heading style."""
self._titleStyle = BlockFmt.CENTRE if center else BlockFmt.NONE
self._titleStyle |= BlockFmt.PBB if pageBreak else BlockFmt.NONE
return
def setPartitionStyle(self, center: bool, pageBreak: bool) -> None:
"""Set the partition heading style."""
self._partStyle = BlockFmt.CENTRE if center else BlockFmt.NONE
self._partStyle |= BlockFmt.PBB if pageBreak else BlockFmt.NONE
return
def setChapterStyle(self, center: bool, pageBreak: bool) -> None:
"""Set the chapter heading style."""
self._chapterStyle = BlockFmt.CENTRE if center else BlockFmt.NONE
self._chapterStyle |= BlockFmt.PBB if pageBreak else BlockFmt.NONE
return
def setSceneStyle(self, center: bool, pageBreak: bool) -> None:
"""Set the scene heading style."""
self._sceneStyle = BlockFmt.CENTRE if center else BlockFmt.NONE
self._sceneStyle |= BlockFmt.PBB if pageBreak else BlockFmt.NONE
return
def setTextFont(self, font: QFont) -> None:
"""Set the build font."""
self._textFont = fontMatcher(font)
return
def setLineHeight(self, height: float) -> None:
"""Set the line height between 0.5 and 5.0."""
self._lineHeight = min(max(float(height), 0.5), 5.0)
return
def setHeadingStyles(self, color: bool, scale: bool, bold: bool) -> None:
"""Set text style for headings."""
self._colorHeads = color
self._scaleHeads = scale
self._boldHeads = bold
return
def setBlockIndent(self, indent: float) -> None:
"""Set the block indent between 0.0 and 10.0."""
self._blockIndent = min(max(float(indent), 0.0), 10.0)
return
def setFirstLineIndent(self, state: bool, indent: float, first: bool) -> None:
"""Set first line indent and whether to also indent first
@@ -349,67 +332,54 @@ class Tokenizer(ABC):
self._firstIndent = state
self._firstWidth = indent
self._indentFirst = first
return
def setJustify(self, state: bool) -> None:
"""Enable or disable text justification."""
self._doJustify = state
return
def setDialogHighlight(self, state: bool) -> None:
"""Enable or disable dialogue highlighting."""
self._hlightDialog = state
return
def setTitleMargins(self, upper: float, lower: float) -> None:
"""Set the upper and lower title margin."""
self._marginTitle = (float(upper), float(lower))
return
def setHead1Margins(self, upper: float, lower: float) -> None:
"""Set the upper and lower heading 1 margin."""
self._marginHead1 = (float(upper), float(lower))
return
def setHead2Margins(self, upper: float, lower: float) -> None:
"""Set the upper and lower heading 2 margin."""
self._marginHead2 = (float(upper), float(lower))
return
def setHead3Margins(self, upper: float, lower: float) -> None:
"""Set the upper and lower heading 3 margin."""
self._marginHead3 = (float(upper), float(lower))
return
def setHead4Margins(self, upper: float, lower: float) -> None:
"""Set the upper and lower heading 4 margin."""
self._marginHead4 = (float(upper), float(lower))
return
def setTextMargins(self, upper: float, lower: float) -> None:
"""Set the upper and lower text margin."""
self._marginText = (float(upper), float(lower))
return
def setMetaMargins(self, upper: float, lower: float) -> None:
"""Set the upper and lower meta text margin."""
self._marginMeta = (float(upper), float(lower))
return
def setSeparatorMargins(self, upper: float, lower: float) -> None:
"""Set the upper and lower meta text margin."""
self._marginSep = (float(upper), float(lower))
return
def setLinkHeadings(self, state: bool) -> None:
"""Enable or disable adding an anchor before headings."""
self._linkHeadings = state
return
def setBodyText(self, state: bool) -> None:
"""Include body text in build."""
self._doBodyText = state
return
def setCommentType(self, comment: nwComment, state: bool) -> None:
"""Toggle the inclusion og certain comment types."""
@@ -417,22 +387,18 @@ class Tokenizer(ABC):
self._doComments.add(comment)
else:
self._doComments.discard(comment)
return
def setKeywords(self, state: bool) -> None:
"""Include keywords in build."""
self._doKeywords = state
return
def setIgnoredKeywords(self, keywords: str) -> None:
"""Comma separated string of keywords to ignore."""
self._skipKeywords = set(x.lower().strip() for x in keywords.split(","))
return
def setKeepLineBreaks(self, state: bool) -> None:
"""Keep line breaks in paragraphs."""
self._keepBreaks = state
return
##
# Class Methods
@@ -460,12 +426,10 @@ class Tokenizer(ABC):
self._classes["tag"] = self._theme.tag
self._classes["keyword"] = self._theme.keyword
self._classes["optional"] = self._theme.optional
return
def setBreakNext(self) -> None:
"""Set a page break for next block."""
self._breakNext = True
return
def addRootHeading(self, tHandle: str) -> None:
"""Add a heading at the start of a new root folder."""
@@ -491,8 +455,6 @@ class Tokenizer(ABC):
if self._keepRaw:
self._raw.append(f"#! {title}\n\n")
return
def setText(self, tHandle: str, text: str | None = None) -> None:
"""Set the text for the tokenizer from a handle. If text is not
set, it's is loaded from the file.
@@ -503,7 +465,6 @@ class Tokenizer(ABC):
self._text = text or self._project.storage.getDocumentText(tHandle)
self._handle = tHandle
self._isNovel = nwItem.itemLayout == nwItemLayout.DOCUMENT
return
def doPreProcessing(self) -> None:
"""Run pre-processing jobs before the text is tokenized."""
@@ -512,7 +473,6 @@ class Tokenizer(ABC):
replace = {f"<{k}>": v for k, v in entry.items()}
rxRep = re.compile("|".join([re.escape(k) for k in replace]), flags=re.DOTALL)
self._text = rxRep.sub(lambda x: replace[x.group(0)], self._text)
return
def tokenizeText(self) -> None:
"""Scan the text for either lines starting with specific
@@ -590,13 +550,13 @@ class Tokenizer(ABC):
self._breakNext = True
continue
elif sLine == "[vspace]":
if sLine == "[vspace]":
tBlocks.append(
(BlockTyp.SKIP, "", "", [], tStyle)
)
continue
elif sLine.startswith("[vspace:") and sLine.endswith("]"):
if sLine.startswith("[vspace:") and sLine.endswith("]"):
nSkip = checkInt(sLine[8:-1], 0)
if nSkip >= 1:
tBlocks.append(
@@ -962,8 +922,6 @@ class Tokenizer(ABC):
text = tText.replace(nwHeadFmt.BR, " ").replace("&amp;", "&")
self._outline[tKey] = f"{prefix}|{text}"
return
def countStats(self) -> None:
"""Count stats on the tokenized text."""
titleCount = self._counts.get(nwStats.TITLES, 0)
@@ -1039,8 +997,6 @@ class Tokenizer(ABC):
self._counts[nwStats.WCHARS_TEXT] = textWordChars
self._counts[nwStats.WCHARS_TITLE] = titleWordChars
return
##
# Internal Functions
##
@@ -1182,6 +1138,12 @@ class Tokenizer(ABC):
class HeadingFormatter:
"""Core: Format Text Headings.
This class holds the various chapter and scene counters and can
apply the Build Settings header format settings based on internal
counter state.
"""
def __init__(
self,
@@ -1195,35 +1157,29 @@ class HeadingFormatter:
self._chapter = chapter
self._scene = scene
self._absolute = absolute
return
def setHandle(self, tHandle: str | None) -> None:
"""Set the handle currently being processed."""
self._handle = tHandle
return
def incChapter(self) -> None:
"""Increment the chapter counter."""
self._chapter += 1
return
def incScene(self) -> None:
"""Increment the scene counters."""
self._scene += 1
self._absolute += 1
return
def resetAll(self) -> None:
"""Reset all counters."""
self._chapter = 0
self._scene = 0
self._absolute = 0
return
def resetScene(self) -> None:
"""Reset the chapter scene counter."""
self._scene = 0
return
def apply(self, hFormat: str, text: str, nHead: int) -> str:
"""Apply formatting to a specific heading."""
+2 -9
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -79,7 +79,7 @@ EXT_MD = {
class ToMarkdown(Tokenizer):
"""Core: Markdown Document Writer
"""Core: Markdown Document Writer.
Extend the Tokenizer class to writer Markdown output. It supports
both Standard Markdown and Extended Markdown. The class also
@@ -91,7 +91,6 @@ class ToMarkdown(Tokenizer):
self._extended = extended
self._usedNotes: dict[str, int] = {}
self._usedFields: list[tuple[int, str]] = []
return
##
# Class Methods
@@ -153,8 +152,6 @@ class ToMarkdown(Tokenizer):
self._pages.append("".join(lines))
return
def closeDocument(self) -> None:
"""Run close document tasks."""
# Replace fields if there are stats available
@@ -181,20 +178,16 @@ class ToMarkdown(Tokenizer):
lines.append("\n")
self._pages.append("".join(lines))
return
def saveDocument(self, path: Path) -> None:
"""Save the data to a plain text file."""
with open(path, mode="w", encoding="utf-8") as outFile:
outFile.write("".join(self._pages))
logger.info("Wrote file: %s", path)
return
def replaceTabs(self, nSpaces: int = 8, spaceChar: str = " ") -> None:
"""Replace tabs with spaces."""
spaces = spaceChar*nSpaces
self._pages = [p.replace("\t", spaces) for p in self._pages]
return
##
# Internal Functions
+10 -69
View File
@@ -23,7 +23,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -128,7 +128,7 @@ FONT_WEIGHT_MAP = {"400": "normal", "700": "bold"}
class ToOdt(Tokenizer):
"""Core: Open Document Writer
"""Core: Open Document Writer.
Extend the Tokenizer class to writer Open Document files. The output
should conform to the 1.3 Extended standard.
@@ -189,8 +189,6 @@ class ToOdt(Tokenizer):
self._mDocLeft = "2.000cm"
self._mDocRight = "2.000cm"
return
##
# Setters
##
@@ -205,20 +203,18 @@ class ToOdt(Tokenizer):
self._mDocBtm = f"{bottom/10.0:.3f}cm"
self._mDocLeft = f"{left/10.0:.3f}cm"
self._mDocRight = f"{right/10.0:.3f}cm"
return
def setHeaderFormat(self, value: str, offset: int) -> None:
"""Set the document header format."""
self._headerFormat = value.strip()
self._pageOffset = offset
return
##
# Class Methods
##
def initDocument(self) -> None:
"""Initialises a new open document XML tree."""
"""Initialise a new open document XML tree."""
super().initDocument()
# Initialise Variables
@@ -325,8 +321,6 @@ class ToOdt(Tokenizer):
self._useableStyles()
self._writeHeader()
return
def doConvert(self) -> None:
"""Convert the list of text tokens into XML elements."""
xText = self._xText
@@ -395,8 +389,6 @@ class ToOdt(Tokenizer):
elif tType == BlockTyp.KEYWORD:
self._addTextPar(xText, S_META, oStyle, tText, tFmt=tFormat)
return
def closeDocument(self) -> None:
"""Add additional collected information to the XML."""
for style in self._autoPara.values():
@@ -412,7 +404,6 @@ class ToOdt(Tokenizer):
_mkTag("text", "name"): f"Manuscript{key[:1].upper()}{key[1:]}",
})
self._xText.insert(0, xFields)
return
def saveDocument(self, path: Path) -> None:
"""Save the data to an .fodt or .odt file."""
@@ -456,8 +447,6 @@ class ToOdt(Tokenizer):
logger.info("Wrote file: %s", path)
return
##
# Internal Functions
##
@@ -670,7 +659,7 @@ class ToOdt(Tokenizer):
return None
def _emToCm(self, value: float) -> str:
"""Converts an em value to centimetres."""
"""Convert an em value to centimetres."""
return f"{value*self._fontSize*2.54/72.0:.3f}cm"
def _emToPt(self, scale: float) -> str:
@@ -705,8 +694,6 @@ class ToOdt(Tokenizer):
_mkTag("fo", "margin-bottom"): self._emToCm(0.5),
})
return
def _defaultStyles(self) -> None:
"""Set the default styles."""
hScale = self._scaleHeads
@@ -783,8 +770,6 @@ class ToOdt(Tokenizer):
_mkTag("number", "min-integer-digits"): "1",
})
return
def _useableStyles(self) -> None:
"""Set the usable styles."""
hScale = self._scaleHeads
@@ -954,8 +939,6 @@ class ToOdt(Tokenizer):
style.packXML(self._xStyl)
self._mainPara[style.name] = style
return
def _writeHeader(self) -> None:
"""Write the header elements."""
xPage = ET.SubElement(self._xMast, _mkTag("style", "master-page"), attrib={
@@ -993,8 +976,6 @@ class ToOdt(Tokenizer):
_mkTag("text", "style-name"): "Header"
})
return
# Auto-Style Classes
# ==================
@@ -1004,6 +985,7 @@ class ODTParagraphStyle:
exporter. Only the used settings are exposed here to keep the class
minimal and fast.
"""
VALID_ALIGN: Final[list[str]] = ["start", "center", "end", "justify", "left", "right"]
VALID_BREAK: Final[list[str]] = ["auto", "page", "even-page", "odd-page", "inherit"]
VALID_LEVEL: Final[list[str]] = ["1", "2", "3", "4"]
@@ -1046,8 +1028,6 @@ class ODTParagraphStyle:
"opacity": ["loext", None],
}
return
@property
def name(self) -> str:
return self._name
@@ -1059,7 +1039,6 @@ class ODTParagraphStyle:
def setName(self, name: str) -> None:
"""Set the paragraph style name."""
self._name = name
return
##
# Attribute Setters
@@ -1068,17 +1047,14 @@ class ODTParagraphStyle:
def setDisplayName(self, value: str | None) -> None:
"""Set style display name."""
self._mAttr["display-name"][1] = value
return
def setParentStyleName(self, value: str | None) -> None:
"""Set parent style name."""
self._mAttr["parent-style-name"][1] = value
return
def setNextStyleName(self, value: str | None) -> None:
"""Set next style name."""
self._mAttr["next-style-name"][1] = value
return
def setOutlineLevel(self, value: str | None) -> None:
"""Set paragraph outline level."""
@@ -1086,7 +1062,6 @@ class ODTParagraphStyle:
self._mAttr["default-outline-level"][1] = value
else:
self._mAttr["default-outline-level"][1] = None
return
def setClass(self, value: str | None) -> None:
"""Set paragraph class."""
@@ -1094,7 +1069,6 @@ class ODTParagraphStyle:
self._mAttr["class"][1] = value
else:
self._mAttr["class"][1] = None
return
##
# Paragraph Setters
@@ -1103,32 +1077,26 @@ class ODTParagraphStyle:
def setMarginTop(self, value: str | None) -> None:
"""Set paragraph top margin."""
self._pAttr["margin-top"][1] = value
return
def setMarginBottom(self, value: str | None) -> None:
"""Set paragraph bottom margin."""
self._pAttr["margin-bottom"][1] = value
return
def setMarginLeft(self, value: str | None) -> None:
"""Set paragraph left margin."""
self._pAttr["margin-left"][1] = value
return
def setMarginRight(self, value: str | None) -> None:
"""Set paragraph right margin."""
self._pAttr["margin-right"][1] = value
return
def setTextIndent(self, value: str | None) -> None:
"""Set text indentation."""
self._pAttr["text-indent"][1] = value
return
def setLineHeight(self, value: str | None) -> None:
"""Set line height."""
self._pAttr["line-height"][1] = value
return
def setTextAlign(self, value: str | None) -> None:
"""Set paragraph text alignment."""
@@ -1136,7 +1104,6 @@ class ODTParagraphStyle:
self._pAttr["text-align"][1] = value
else:
self._pAttr["text-align"][1] = None
return
def setBreakBefore(self, value: str | None) -> None:
"""Set page break before policy."""
@@ -1144,7 +1111,6 @@ class ODTParagraphStyle:
self._pAttr["break-before"][1] = value
else:
self._pAttr["break-before"][1] = None
return
def setBreakAfter(self, value: str | None) -> None:
"""Set page break after policy."""
@@ -1152,7 +1118,6 @@ class ODTParagraphStyle:
self._pAttr["break-after"][1] = value
else:
self._pAttr["break-after"][1] = None
return
##
# Text Setters
@@ -1161,17 +1126,14 @@ class ODTParagraphStyle:
def setFontName(self, value: str | None) -> None:
"""Set font name."""
self._tAttr["font-name"][1] = value
return
def setFontFamily(self, value: str | None) -> None:
"""Set font family."""
self._tAttr["font-family"][1] = value
return
def setFontSize(self, value: str | None) -> None:
"""Set font size."""
self._tAttr["font-size"][1] = value
return
def setFontWeight(self, value: str | None) -> None:
"""Set font weight."""
@@ -1179,7 +1141,6 @@ class ODTParagraphStyle:
self._tAttr["font-weight"][1] = value
else:
self._tAttr["font-weight"][1] = None
return
def setColor(self, value: QColor | None) -> None:
"""Set text colour."""
@@ -1189,7 +1150,6 @@ class ODTParagraphStyle:
else:
self._tAttr["color"][1] = None
self._tAttr["opacity"][1] = None
return
##
# Methods
@@ -1233,14 +1193,13 @@ class ODTParagraphStyle:
if attr := {_mkTag(n, m): v for m, (n, v) in self._tAttr.items() if v}:
ET.SubElement(xEntry, _mkTag("style", "text-properties"), attrib=attr)
return
class ODTTextStyle:
"""Wrapper class for the text style setting used by the exporter.
Only the used settings are exposed here to keep the class minimal
and fast.
"""
VALID_WEIGHT: Final[list[str]] = ["normal", "bold", *FONT_WEIGHT_NUM]
VALID_STYLE: Final[list[str]] = ["normal", "italic", "oblique"]
VALID_POS: Final[list[str]] = ["super", "sub"]
@@ -1263,7 +1222,6 @@ class ODTTextStyle:
"text-underline-width": ["style", None],
"text-underline-color": ["style", None],
}
return
@property
def name(self) -> str:
@@ -1279,7 +1237,6 @@ class ODTTextStyle:
self._tAttr["font-weight"][1] = value
else:
self._tAttr["font-weight"][1] = None
return
def setFontStyle(self, value: str | None) -> None:
"""Set text font style."""
@@ -1287,7 +1244,6 @@ class ODTTextStyle:
self._tAttr["font-style"][1] = value
else:
self._tAttr["font-style"][1] = None
return
def setColor(self, value: QColor | None) -> None:
"""Set text colour."""
@@ -1295,7 +1251,6 @@ class ODTTextStyle:
self._tAttr["color"][1] = value.name(QtHexRgb)
else:
self._tAttr["color"][1] = None
return
def setBackgroundColor(self, value: QColor | None) -> None:
"""Set text background colour."""
@@ -1303,7 +1258,6 @@ class ODTTextStyle:
self._tAttr["background-color"][1] = value.name(QtHexRgb)
else:
self._tAttr["background-color"][1] = None
return
def setTextPosition(self, value: str | None) -> None:
"""Set text vertical position."""
@@ -1311,7 +1265,6 @@ class ODTTextStyle:
self._tAttr["text-position"][1] = f"{value} 58%"
else:
self._tAttr["text-position"][1] = None
return
def setStrikeStyle(self, value: str | None) -> None:
"""Set text line-trough style."""
@@ -1319,7 +1272,6 @@ class ODTTextStyle:
self._tAttr["text-line-through-style"][1] = value
else:
self._tAttr["text-line-through-style"][1] = None
return
def setStrikeType(self, value: str | None) -> None:
"""Set text line-through type."""
@@ -1327,7 +1279,6 @@ class ODTTextStyle:
self._tAttr["text-line-through-type"][1] = value
else:
self._tAttr["text-line-through-type"][1] = None
return
def setUnderlineStyle(self, value: str | None) -> None:
"""Set text underline style."""
@@ -1335,7 +1286,6 @@ class ODTTextStyle:
self._tAttr["text-underline-style"][1] = value
else:
self._tAttr["text-underline-style"][1] = None
return
def setUnderlineWidth(self, value: str | None) -> None:
"""Set text underline width."""
@@ -1343,7 +1293,6 @@ class ODTTextStyle:
self._tAttr["text-underline-width"][1] = value
else:
self._tAttr["text-underline-width"][1] = None
return
def setUnderlineColor(self, value: str | None) -> None:
"""Set text underline colour."""
@@ -1351,7 +1300,6 @@ class ODTTextStyle:
self._tAttr["text-underline-color"][1] = value
else:
self._tAttr["text-underline-color"][1] = None
return
##
# Methods
@@ -1365,7 +1313,6 @@ class ODTTextStyle:
})
if attr := {_mkTag(n, m): v for m, (n, v) in self._tAttr.items() if v}:
ET.SubElement(xEntry, _mkTag("style", "text-properties"), attrib=attr)
return
# XML Complex Element Helper Class
@@ -1378,7 +1325,9 @@ X_SPAN_SING = 3
class XMLParagraph:
"""This is a helper class to manage the text content of a single
"""ODT Text Paragraph.
This is a helper class to manage the text content of a single
XML element using mixed content tags.
Rules:
@@ -1408,8 +1357,6 @@ class XMLParagraph:
self._rawTxt = ""
self._xRoot.text = ""
return
def appendText(self, text: str) -> None:
"""Append text to the XML element. We do this one character at
the time in order to be able to process line breaks, tabs and
@@ -1424,7 +1371,7 @@ class XMLParagraph:
if c == " ":
nSpaces += 1
continue
elif nSpaces > 0:
if nSpaces > 0:
self._processSpaces(nSpaces)
nSpaces = 0
@@ -1468,8 +1415,6 @@ class XMLParagraph:
# Handle trailing spaces
self._processSpaces(nSpaces)
return
def appendSpan(self, text: str, style: str, link: str) -> None:
"""Append a text span to the XML element. The span is always
closed since we do not produce nested spans (like Libre Office).
@@ -1491,7 +1436,6 @@ class XMLParagraph:
self._nState = X_SPAN_TEXT
self.appendText(text)
self._nState = X_ROOT_TAIL
return
def appendNode(self, xNode: ET.Element | None) -> None:
"""Append an XML node to the paragraph. We only check for the
@@ -1504,7 +1448,6 @@ class XMLParagraph:
self._xTail = xNode
self._xTail.tail = ""
self._nState = X_ROOT_TAIL
return
def checkError(self) -> tuple[int, str]:
"""Check that the number of characters written matches the
@@ -1575,5 +1518,3 @@ class XMLParagraph:
self._xSing.tail = ""
self._nState = X_SPAN_SING
self._chrPos += nSpaces - 1
return
+3 -17
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import logging
@@ -56,6 +56,7 @@ T_TextStyle = tuple[QTextBlockFormat, QTextCharFormat]
def newBlock(cursor: QTextCursor, bFmt: QTextBlockFormat) -> None:
"""Insert a new block if not at the beginning of the document."""
if cursor.position() > 0:
cursor.insertBlock(bFmt)
else:
@@ -63,7 +64,7 @@ def newBlock(cursor: QTextCursor, bFmt: QTextBlockFormat) -> None:
class ToQTextDocument(Tokenizer):
"""Core: QTextDocument Writer
"""Core: QTextDocument Writer.
Extend the Tokenizer class to generate a QTextDocument output. This
is intended for usage in the document viewer and build tool preview.
@@ -92,8 +93,6 @@ class ToQTextDocument(Tokenizer):
self._pageSize = QPageSize(QPageSize.PageSizeId.A4)
self._pageMargins = QMarginsF(20.0, 20.0, 20.0, 20.0)
return
##
# Properties
##
@@ -113,17 +112,14 @@ class ToQTextDocument(Tokenizer):
"""Set the document page size and margins in millimetres."""
self._pageSize = QPageSize(QSizeF(width, height), QPageSize.Unit.Millimeter)
self._pageMargins = QMarginsF(left, top, right, bottom)
return
def setShowNewPage(self, state: bool) -> None:
"""Add markers for page breaks."""
self._newPage = state
return
def disableAnchors(self) -> None:
"""Disable anchors for when writing to file."""
self._anchors = False
return
##
# Class Methods
@@ -200,8 +196,6 @@ class ToQTextDocument(Tokenizer):
self._init = True
return
def doConvert(self) -> None:
"""Write text tokens into the document."""
if not self._init:
@@ -297,8 +291,6 @@ class ToQTextDocument(Tokenizer):
self._document.setPageSize(printer.pageRect(QPrinter.Unit.DevicePixel).size())
self._document.print(printer)
return
def closeDocument(self) -> None:
"""Run close document tasks."""
self._document.blockSignals(True)
@@ -333,8 +325,6 @@ class ToQTextDocument(Tokenizer):
self._document.blockSignals(False)
return
##
# Internal Functions
##
@@ -439,8 +429,6 @@ class ToQTextDocument(Tokenizer):
# Insert whatever is left in the buffer
cursor.insertText(stripEscape(temp[start:]), cFmt)
return
def _insertNewPageMarker(self, cursor: QTextCursor) -> None:
"""Insert a new page marker."""
if self._newPage:
@@ -475,8 +463,6 @@ class ToQTextDocument(Tokenizer):
if root := self._document.rootFrame():
cursor.swap(root.lastCursorPosition())
return
def _genHeadStyle(self, hType: BlockTyp, hKey: str, rFmt: QTextBlockFormat) -> T_TextStyle:
"""Generate a heading style set."""
mTop, mBottom = self._mHead.get(hType, (0.0, 0.0))
+2 -6
View File
@@ -20,7 +20,7 @@ General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
""" # noqa
from __future__ import annotations
import json
@@ -41,7 +41,7 @@ logger = logging.getLogger(__name__)
class ToRaw(Tokenizer):
"""Core: Raw novelWriter Text Writer
"""Core: Raw novelWriter Text Writer.
A class that will collect the minimally altered original source text
and write it to either a text or JSON file.
@@ -51,7 +51,6 @@ class ToRaw(Tokenizer):
super().__init__(project)
self._keepRaw = True
self._noTokens = True
return
def doConvert(self) -> None:
"""No conversion to perform."""
@@ -86,10 +85,7 @@ class ToRaw(Tokenizer):
logger.info("Wrote file: %s", path)
return
def replaceTabs(self, nSpaces: int = 8, spaceChar: str = " ") -> None:
"""Replace tabs with spaces."""
spaces = spaceChar*nSpaces
self._raw = [p.replace("\t", spaces) for p in self._raw]
return