From a1153fd84895b28e30cb3f8c81a7753d9868833c Mon Sep 17 00:00:00 2001 From: Anders Eskildsen <22001464+aeskildsen@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:59:24 +0100 Subject: [PATCH] style: format with ruff at line length 120 Format the Python code with `ruff format`, line length 120, and add `ruff.toml`. There are no hand-made changes. Checked: the syntax tree of each file is the same as before, except the trailing white space in one docstring. All tests pass with `sclang`, and the test fixtures have no change. Stacked on #2. --- md2misc/__init__.py | 12 +- md2misc/backends/minted.py | 5 +- md2misc/backends/schelp.py | 212 +++++++++++++++++++--------- md2misc/backends/tex.py | 22 ++- md2misc/citations.py | 12 +- md2misc/converters.py | 117 +++++++++------- md2misc/core.py | 34 +++-- md2misc/errors_warnings.py | 13 +- md2misc/helpers.py | 22 +-- md2misc/tables.py | 9 +- ruff.toml | 16 +++ tests/battery.py | 23 +-- tests/schelp_cases.py | 247 +++++++++++++++++++-------------- tests/schelp_fixtures.py | 13 +- tests/test_schelp_behavior.py | 85 +++++++----- tests/test_schelp_citations.py | 50 ++++--- tests/test_schelp_errors.py | 12 +- tests/test_schelp_golden.py | 1 + tests/test_schelp_methods.py | 224 ++++++++++++++++++++---------- tests/test_schelp_render.py | 1 + tests/test_schelp_tables.py | 55 +++++--- tests/test_schelp_writer.py | 1 + tests/test_tables.py | 182 ++++++++++++++++-------- tests/test_tex_battery.py | 1 + tests/test_tex_library.py | 6 +- 25 files changed, 888 insertions(+), 487 deletions(-) create mode 100644 ruff.toml diff --git a/md2misc/__init__.py b/md2misc/__init__.py index 3df0d53..fb9f692 100644 --- a/md2misc/__init__.py +++ b/md2misc/__init__.py @@ -1,5 +1,13 @@ from .core import convert, convert_schelp, default_template from .errors_warnings import DocumentError, Md2miscError, Md2miscWarning, ParsingException, UnsupportedConstruct -__all__ = ["convert", "convert_schelp", "default_template", - "Md2miscError", "Md2miscWarning", "DocumentError", "ParsingException", "UnsupportedConstruct"] +__all__ = [ + "convert", + "convert_schelp", + "default_template", + "Md2miscError", + "Md2miscWarning", + "DocumentError", + "ParsingException", + "UnsupportedConstruct", +] diff --git a/md2misc/backends/minted.py b/md2misc/backends/minted.py index 854a49e..b68974e 100644 --- a/md2misc/backends/minted.py +++ b/md2misc/backends/minted.py @@ -1,4 +1,3 @@ - # -------------------------------------------------------------------------- # list of languages supported by pygments/minted (01.11.2024) # source: https://pygments.org/languages/ @@ -909,5 +908,5 @@ "bro", "zephir", "zig", - "zone" -] \ No newline at end of file + "zone", +] diff --git a/md2misc/backends/schelp.py b/md2misc/backends/schelp.py index a7cdb0c..1eda861 100644 --- a/md2misc/backends/schelp.py +++ b/md2misc/backends/schelp.py @@ -46,8 +46,12 @@ class SchelpBackend(Backend): tag_regex = r"\w::" # the sections that SCDoc tells apart from other sections, by the text of a level 2 heading - special_sections = {"description": "DESCRIPTION", "examples": "EXAMPLES", "class methods": "CLASSMETHODS", - "instance methods": "INSTANCEMETHODS"} + special_sections = { + "description": "DESCRIPTION", + "examples": "EXAMPLES", + "class methods": "CLASSMETHODS", + "instance methods": "INSTANCEMETHODS", + } # the sections whose methods and argument tables the converters write as `METHOD::` and `ARGUMENT::`, and the # mark before the name of each method in a method heading. SCDoc uses the same marks in the anchors of methods @@ -93,7 +97,9 @@ def _header_value(cls, key: str, value, line: int = None): else a string. """ if key not in cls.header_keys: - raise UnsupportedConstruct(cls.name, f"front matter key `{key}` (the keys are {', '.join(cls.header_keys)})", line) + raise UnsupportedConstruct( + cls.name, f"front matter key `{key}` (the keys are {', '.join(cls.header_keys)})", line + ) if key in cls.list_keys: if isinstance(value, str): value = value.split(",") @@ -150,7 +156,7 @@ def take_front_matter(self, markdown: str) -> tuple: if isinstance(value, str): value = self._unquote(value) values[key] = self._header_value(key, value, line_number) - return values, "\n" * (end + 1) + "\n".join(lines[end + 1:]) + return values, "\n" * (end + 1) + "\n".join(lines[end + 1 :]) def header(self, values: dict) -> str: """ @@ -165,8 +171,10 @@ def header(self, values: dict) -> str: if not values: return "" if "title" not in values and "class" not in values: - raise DocumentError("the header of a schelp document needs a title or a class: " - "use `title:` or `class:` in the front matter, a level 1 heading, or give the value") + raise DocumentError( + "the header of a schelp document needs a title or a class: " + "use `title:` or `class:` in the front matter, a level 1 heading, or give the value" + ) out = "" for key in self.header_keys: if key in values: @@ -189,8 +197,13 @@ def check_insertions(self): """ unused = sorted(set(self.insertions) - self.used_insertions) if unused: - raise DocumentError("the document has no insertion point for: " + ", ".join(unused) - + " (a line like ``)") + raise DocumentError( + "the document has no insertion point for: " + + ", ".join(unused) + + " (a line like ``)" + ) # ------------------------------------------------------------ checks @@ -200,8 +213,9 @@ def check_insertions(self): # a source in a citation: `@key`, with an optional locator after a comma. `-@key` is the form that does not # name the author in the text, which has no use in a footnote: the `-` is ignored citation_item_regex = r"\s*-?@([^\s,;@\]]+)(?:\s*,\s*([^;@]*?))?\s*" - markup_in_quote_construct = ("code, math, a link, a footnote, a citation, or bold or italic text in a block " - "quote (the quote is in italics)") + markup_in_quote_construct = ( + "code, math, a link, a footnote, a citation, or bold or italic text in a block quote (the quote is in italics)" + ) footnote_definition_regex = r"\[\^\d+\]:" footnote_mark_regex = r"\[\^\d+\]" thematic_break_regex = r" {0,3}([-*_])([ \t]*\1){2,}[ \t]*$" @@ -214,17 +228,20 @@ def _is_paragraph_line(self, line: str) -> bool: whether the line can be a line of a paragraph: it is not empty and it does not start another construct. """ return bool(line.strip()) and not ( - re.match(self.list_item_regex, line) or re.match(syntax.HEADING_STRICT, line) + re.match(self.list_item_regex, line) + or re.match(syntax.HEADING_STRICT, line) or line.lstrip().startswith((">", syntax.CODE_FENCE, "|")) ) def _check_heading_source(self, text: str, line: int): # the name of a section is plain text - if (self.code_token[0] in text or re.search(r"\*[^*\n]+\*", text) - or re.search(syntax.INLINE_MATH_STRICT, text)): + if self.code_token[0] in text or re.search(r"\*[^*\n]+\*", text) or re.search(syntax.INLINE_MATH_STRICT, text): self.unsupported("bold, italic text, code or math in a heading", line) - if (re.search(syntax.LINK, text) or re.search(self.footnote_mark_regex, text) - or re.search(syntax.CITATION, text)): + if ( + re.search(syntax.LINK, text) + or re.search(self.footnote_mark_regex, text) + or re.search(syntax.CITATION, text) + ): self.unsupported("link, footnote or citation in a heading", line) def _check_citation(self, citation: str, line: int = None): @@ -233,12 +250,12 @@ def _check_citation(self, citation: str, line: int = None): source is a key with `@` before it, and an optional locator after a comma: `@doe1999, p. 30`. """ if not self.bibliography: - self.unsupported("citation (give a bibliography to the conversion, or write the citation as text)", - line) + self.unsupported("citation (give a bibliography to the conversion, or write the citation as text)", line) for item in citation.split(";"): if not re.fullmatch(self.citation_item_regex, item): - self.unsupported(f"citation `[{citation}]` (the forms are `[@key]`, `[@key, p. 30]` and " - "`[@key; @other]`)", line) + self.unsupported( + f"citation `[{citation}]` (the forms are `[@key]`, `[@key, p. 30]` and `[@key; @other]`)", line + ) def _check_table(self, lines: list, number: int, in_methods: bool, in_method: bool) -> int: """ @@ -261,8 +278,9 @@ def _check_table(self, lines: list, number: int, in_methods: bool, in_method: bo self.unsupported("`|` in code in a table (write `\\|`)", index + 1) header = tables.split_row(lines[number]) if len(tables.split_row(lines[number + 1])) != len(header): - self.unsupported("table whose delimiter row has another number of cells than its header row", - header_line + 1) + self.unsupported( + "table whose delimiter row has another number of cells than its header row", header_line + 1 + ) if end == number + 2: self.unsupported("table without rows", header_line) for index in range(number + 2, end): @@ -276,11 +294,19 @@ def _check_table(self, lines: list, number: int, in_methods: bool, in_method: bo else: for cell in header: # the header row is bold, and SCDoc's `strong::` cannot hold other tags - if ("`" in cell or "*" in cell or re.search(syntax.INLINE_MATH_STRICT, cell) - or re.search(syntax.LINK, cell) or re.search(self.footnote_mark_regex, cell) - or re.search(syntax.CITATION, cell)): - self.unsupported("code, math, a link, a footnote, a citation, or bold or italic text in the " - "header row of a table (the header row is bold)", header_line) + if ( + "`" in cell + or "*" in cell + or re.search(syntax.INLINE_MATH_STRICT, cell) + or re.search(syntax.LINK, cell) + or re.search(self.footnote_mark_regex, cell) + or re.search(syntax.CITATION, cell) + ): + self.unsupported( + "code, math, a link, a footnote, a citation, or bold or italic text in the " + "header row of a table (the header row is bold)", + header_line, + ) return end def _check_argument_table(self, lines: list, number: int, end: int): @@ -291,8 +317,9 @@ def _check_argument_table(self, lines: list, number: int, end: int): header_line = number + 1 header = tables.split_row(lines[number]) if len(header) < 2: - self.unsupported("argument table with one column (the first column is the name, the last the text)", - header_line) + self.unsupported( + "argument table with one column (the first column is the name, the last the text)", header_line + ) if not all(header[1:-1]): self.unsupported("argument table column without a heading", header_line) names = set() @@ -329,9 +356,14 @@ def image_problem(cls, caption: str, path: str): if "#" in path or "#" in caption: return "`#` in the caption or the path of an image" # SCDoc shows the caption as plain text - if (cls.code_token[0] in caption or "`" in caption or "*" in caption - or re.search(syntax.INLINE_MATH_STRICT, caption) or re.search(syntax.MATH_TOKEN_REGEX, caption) - or re.search(r"\[[^\]]*\]", caption)): + if ( + cls.code_token[0] in caption + or "`" in caption + or "*" in caption + or re.search(syntax.INLINE_MATH_STRICT, caption) + or re.search(syntax.MATH_TOKEN_REGEX, caption) + or re.search(r"\[[^\]]*\]", caption) + ): return "code, math, a link, a footnote, or bold or italic text in the caption of an image" return None @@ -347,9 +379,14 @@ def _check_quote_line(self, text: str, line: int): self.unsupported("list in a block quote", line) if re.match(syntax.HEADING_STRICT, content): self.unsupported("heading in a block quote", line) - if (self.code_token[0] in content or "*" in content or re.search(syntax.INLINE_MATH_STRICT, content) - or re.search(syntax.LINK, content) or re.search(self.footnote_mark_regex, content) - or re.search(syntax.CITATION, content)): + if ( + self.code_token[0] in content + or "*" in content + or re.search(syntax.INLINE_MATH_STRICT, content) + or re.search(syntax.LINK, content) + or re.search(self.footnote_mark_regex, content) + or re.search(syntax.CITATION, content) + ): self.unsupported(self.markup_in_quote_construct, line) indented_regex = r"( {4}|\t)\S" @@ -372,7 +409,8 @@ def footnote_paragraphs(self, lines: list, number: int) -> list: index = following + 1 continue if re.match(self.footnote_definition_regex, line) or not ( - self._is_paragraph_line(line) or re.match(self.indented_regex, line)): + self._is_paragraph_line(line) or re.match(self.indented_regex, line) + ): break paragraphs[-1].append(index) index += 1 @@ -392,8 +430,11 @@ def join_footnotes(self, string: str) -> str: number += 1 continue paragraphs = self.footnote_paragraphs(lines, number) - out.append(self.footnote_paragraph_mark.join(" ".join(lines[i].strip() for i in paragraph) - for paragraph in paragraphs)) + out.append( + self.footnote_paragraph_mark.join( + " ".join(lines[i].strip() for i in paragraph) for paragraph in paragraphs + ) + ) number = paragraphs[-1][-1] + 1 return "\n".join(out) @@ -407,18 +448,28 @@ def _check_method_part(self, lines: list, number: int, in_methods: bool, part): checked in `check_source()`. """ line = lines[number] - if (not in_methods or part in (None, "discussion") or not line.strip() - or re.match(syntax.HEADING_STRICT, line) or tables.starts_table(lines, number)): + if ( + not in_methods + or part in (None, "discussion") + or not line.strip() + or re.match(syntax.HEADING_STRICT, line) + or tables.starts_table(lines, number) + ): return part paragraph_start = number == 0 or not lines[number - 1].strip() if paragraph_start and line.startswith(self.returns_mark) and part != "returns": return "returns" if part == "table": - self.unsupported("text after the argument table of a method (only a `Returns:` paragraph or a " - "`#### Discussion` heading can follow it)", number + 1) + self.unsupported( + "text after the argument table of a method (only a `Returns:` paragraph or a " + "`#### Discussion` heading can follow it)", + number + 1, + ) if part == "returns" and paragraph_start: - self.unsupported("text after the `Returns:` paragraph of a method (put a `#### Discussion` heading " - "before it)", number + 1) + self.unsupported( + "text after the `Returns:` paragraph of a method (put a `#### Discussion` heading before it)", + number + 1, + ) return part def check_source(self, markdown: str): @@ -479,20 +530,29 @@ def check_source(self, markdown: str): if level == 1: level_1_headings += 1 if level_1_headings > 1: - self.unsupported("second level 1 heading (the first one is the title of the document: use level 2 for sections)", line_number) + self.unsupported( + "second level 1 heading (the first one is the title of the document: use level 2 for sections)", + line_number, + ) if level == 2: methods_mark = self.methods_sections.get(heading[3].strip().lower()) method_part = None if methods_mark and level == 3 and re.match(self.method_heading_regex(methods_mark), line): method_part = "text" - elif (methods_mark and method_part not in (None, "discussion") - and re.match(self.discussion_heading_regex, line)): + elif ( + methods_mark + and method_part not in (None, "discussion") + and re.match(self.discussion_heading_regex, line) + ): method_part = "discussion" elif methods_mark and level >= 3: - self.unsupported(f"heading in a methods section that is not a method or the discussion of a " - f"method (a method heading is like `### {methods_mark}ar` or " - f"`### {methods_mark}ar, {methods_mark}kr`; one `#### Discussion` heading " - f"can follow it)", line_number) + self.unsupported( + f"heading in a methods section that is not a method or the discussion of a " + f"method (a method heading is like `### {methods_mark}ar` or " + f"`### {methods_mark}ar, {methods_mark}kr`; one `#### Discussion` heading " + f"can follow it)", + line_number, + ) else: self._check_heading_source(heading[3], line_number) if number >= table_end and tables.starts_table(lines, number): @@ -517,8 +577,9 @@ def check_source(self, markdown: str): if re.search(syntax.AUDIO, text): self.unsupported("audio file", line_number) for image in re.finditer(syntax.IMAGE, text): - self._check_image(image, text, previous, lines[number + 1] if number + 1 < len(lines) else "", - line_number) + self._check_image( + image, text, previous, lines[number + 1] if number + 1 < len(lines) else "", line_number + ) for citation in re.finditer(syntax.CITATION, text): self._check_citation(citation[1], line_number) if re.search(self.autolink_regex, prose): @@ -537,8 +598,11 @@ def check_source(self, markdown: str): for emphasis in chain(re.finditer(syntax.BOLD, text), re.finditer(syntax.ITALIC, text)): if self.code_token[0] in emphasis[1]: self.unsupported("code inside bold or italic text", line_number) - if (re.search(syntax.LINK, emphasis[1]) or re.search(self.footnote_mark_regex, emphasis[1]) - or re.search(syntax.CITATION, emphasis[1])): + if ( + re.search(syntax.LINK, emphasis[1]) + or re.search(self.footnote_mark_regex, emphasis[1]) + or re.search(syntax.CITATION, emphasis[1]) + ): self.unsupported("link, footnote or citation inside bold or italic text", line_number) if re.match(self.footnote_definition_regex, text): # the lines after the definition line @@ -550,8 +614,10 @@ def check_source(self, markdown: str): is_quote = text.startswith(">") if is_quote and not previous_is_quote: if re.match(self.alert_mark_regex, text) and not self.admonition_tag(text): - self.unsupported("alert of a kind that is not known (the kinds are " - + ", ".join(self.admonitions) + ")", line_number) + self.unsupported( + "alert of a kind that is not known (the kinds are " + ", ".join(self.admonitions) + ")", + line_number, + ) plain_quote = not self.admonition_tag(text) if is_quote and plain_quote: self._check_quote_line(text, line_number) @@ -592,7 +658,9 @@ def heading(self, level: int, text: str) -> str: if level == 1: # the title of the document: it goes in the header, which escapes it if self.title_heading is not None: - self.unsupported("second level 1 heading (the first one is the title of the document: use level 2 for sections)") + self.unsupported( + "second level 1 heading (the first one is the title of the document: use level 2 for sections)" + ) self.title_heading = self._unescape(text.strip()) return "" special = self.special_sections.get(text.strip().lower()) if level == 2 else None @@ -675,9 +743,14 @@ def _quote(self, lines: list) -> str: mark = re.escape(self.code_token[0]) if any("\n" in self.stash[token] for token in re.findall(mark + r"\d+" + mark, paragraph)): self.unsupported("code block in a block quote") - if (self.code_token[0] in paragraph or "*" in paragraph - or re.search(syntax.MATH_TOKEN_REGEX, paragraph) or re.search(self.tag_regex, paragraph) - or re.search(syntax.LINK, paragraph) or re.search(self.footnote_mark_regex, paragraph)): + if ( + self.code_token[0] in paragraph + or "*" in paragraph + or re.search(syntax.MATH_TOKEN_REGEX, paragraph) + or re.search(self.tag_regex, paragraph) + or re.search(syntax.LINK, paragraph) + or re.search(self.footnote_mark_regex, paragraph) + ): self.unsupported(self.markup_in_quote_construct) if not paragraphs: return "" @@ -831,7 +904,7 @@ def write_citations(self, string: str) -> str: out, position = [], 0 for index, citation in enumerate(found): - before = string[position:citation.start()] + before = string[position : citation.start()] if index in in_footnote: text = parts[index][0] else: @@ -875,7 +948,7 @@ def _entries(self, entries: dict) -> dict: text = self._pandoc_text(inlines) authors = re.match(r"(.+?)\.\s(?=\d{4}|n\.d\.)", previous) if text.startswith("———") and authors: - text = authors[1] + text[len("———"):].lstrip("—") + text = authors[1] + text[len("———") :].lstrip("—") out[key] = previous = text return out @@ -968,9 +1041,18 @@ def clean(self, string: str) -> str: # already (see `write_citations()`) string = re.sub(self.after_letter + r"footnote::", " footnote::", string) # the other inline tags get a word joiner. code and math are still tokens here - string = re.sub(self.after_letter + r"(?=(strong|emphasis|link)::|" + syntax.MATH_TOKEN_REGEX + "|" - + re.escape(self.code_token[0]) + r"\d+" + re.escape(self.code_token[0]) + ")", - self.word_joiner, string) + string = re.sub( + self.after_letter + + r"(?=(strong|emphasis|link)::|" + + syntax.MATH_TOKEN_REGEX + + "|" + + re.escape(self.code_token[0]) + + r"\d+" + + re.escape(self.code_token[0]) + + ")", + self.word_joiner, + string, + ) # paragraphs are separated by one empty line; the document ends with one line ending string = re.sub(r"\n{3,}", "\n\n", string).strip("\n") return string + "\n" if string else "" diff --git a/md2misc/backends/tex.py b/md2misc/backends/tex.py index 26489b7..465c6de 100644 --- a/md2misc/backends/tex.py +++ b/md2misc/backends/tex.py @@ -24,8 +24,14 @@ class TeXBackend(Backend): "article": ["section", "subsection", "subsubsection"], "book": ["chapter", "section", "subsection", "subsubsection"], } - def __init__(self, unnumbered: bool = False, document_class: str = "article", - minted_language: str = "text", override_language: bool = False): + + def __init__( + self, + unnumbered: bool = False, + document_class: str = "article", + minted_language: str = "text", + override_language: bool = False, + ): self.unnumbered = unnumbered self.document_class = document_class self.minted_language = minted_language @@ -47,7 +53,7 @@ def escape(self, string: str) -> str: string = string.replace("$", r"\$") string = string.replace("%", r"\%") string = string.replace(r"$", r"\&") - #string = string.replace(r"~", r"\~") # leads to an error if ~ is used in an inline quote + # string = string.replace(r"~", r"\~") # leads to an error if ~ is used in an inline quote string = string.replace("_", r"\_") string = string.replace("&", r"\&") string = re.sub(r"\^", r"\\^", string, flags=re.M) @@ -199,7 +205,7 @@ def code_block(self, code: str, language: str = None, title: str = None, highlig # titles are converted to captions if title: - env = env.replace("@@CAPTIONTOKEN@@", r'\caption{' + title + r'}') + env = env.replace("@@CAPTIONTOKEN@@", r"\caption{" + title + r"}") else: # remove captiontoken line env = env.replace("@@CAPTIONTOKEN@@\n", "") @@ -246,6 +252,10 @@ def clean(self, string: str) -> str: # string = re.sub(r"{\s+", r"{", string, flags=re.M) # remove whitespace after opening curly brace # string = re.sub(r"\s+}", r"}", string, flags=re.M) # remove whitespace before closing curly brace string = re.sub(r"\n{2,}", r"\n\n", string, flags=re.M) # reduce 2+ consecutive newlines to 2 - string = re.sub(r"(\\begin\{.*?)\n{2,}", r"\1\n", string, flags=re.M) # replace multiple consecutive newlines after \begin with just one - string = re.sub(r"\n{2,}( *\\end\{)", r"\n\1", string, flags=re.M) # replace multiple consecutive newlines before \end with just one + string = re.sub( + r"(\\begin\{.*?)\n{2,}", r"\1\n", string, flags=re.M + ) # replace multiple consecutive newlines after \begin with just one + string = re.sub( + r"\n{2,}( *\\end\{)", r"\n\1", string, flags=re.M + ) # replace multiple consecutive newlines before \end with just one return string diff --git a/md2misc/citations.py b/md2misc/citations.py index 0d824cd..39fdb5b 100644 --- a/md2misc/citations.py +++ b/md2misc/citations.py @@ -6,6 +6,7 @@ the output of Pandoc is its JSON form (the document tree), so that the text of a citation does not need to be read as Markdown again. """ + import json import os import shutil @@ -25,8 +26,10 @@ def find_pandoc() -> str: """ path = os.environ.get("PANDOC") or shutil.which("pandoc") if not path: - raise DocumentError("citations need the program `pandoc`: put it on the PATH, or set the environment " - "variable PANDOC to its path") + raise DocumentError( + "citations need the program `pandoc`: put it on the PATH, or set the environment " + "variable PANDOC to its path" + ) return path @@ -45,8 +48,9 @@ def process(citations: list, bibliography) -> tuple: source = "".join(citation + "\n\n" for citation in citations) + "::: {#refs}\n:::\n" pandoc = find_pandoc() try: - done = subprocess.run([pandoc, *PANDOC_ARGUMENTS, "--bibliography", str(path)], - input=source, capture_output=True, text=True) + done = subprocess.run( + [pandoc, *PANDOC_ARGUMENTS, "--bibliography", str(path)], input=source, capture_output=True, text=True + ) except OSError as error: raise DocumentError(f"md2misc could not run pandoc (`{pandoc}`): {error}") from error if done.returncode != 0: diff --git a/md2misc/converters.py b/md2misc/converters.py index 3cd0df9..13aaaee 100644 --- a/md2misc/converters.py +++ b/md2misc/converters.py @@ -18,6 +18,7 @@ class MDSimple: simple substitutions: bold, italics, audio files, horizontal rules, line breaks. the output is written by the backend. """ + bold_regex = syntax.BOLD italic_regex = syntax.ITALIC audio_regex = syntax.AUDIO @@ -50,6 +51,7 @@ class MDHeader: - mark(): replace the `#` characters of each header by a marker that holds the header level - convert(): replace the marked headers by the output of the backend """ + marker = "\x00{}\x00" marker_regex = r"\x00(\d+)\x00" @@ -63,11 +65,7 @@ def mark(string: str, backend: Backend): :return: the text with marked headers """ # a `>` is replaced by a space by the block quote step, thus a header can follow it - return re.sub( - backend.heading_regex, - lambda m: m[1] + MDHeader.marker.format(len(m[2])), - string, flags=re.M - ) + return re.sub(backend.heading_regex, lambda m: m[1] + MDHeader.marker.format(len(m[2])), string, flags=re.M) @staticmethod def convert(string: str, backend: Backend): @@ -82,15 +80,14 @@ def convert(string: str, backend: Backend): # one pass per header level, from the first level up. the last pass takes all # remaining levels. a later pass removes the blank lines that an earlier pass left for group in range(1, backend.heading_groups + 1): + def write_heading(m): level = int(m[1]) if level == group or (group == backend.heading_groups and level > group): return backend.heading(level, m[2]) return m[0] # a header of another pass - string = re.sub( - r"^\s*" + MDHeader.marker_regex + r" *(.*?)$", - write_heading, string, flags=re.M - ) + + string = re.sub(r"^\s*" + MDHeader.marker_regex + r" *(.*?)$", write_heading, string, flags=re.M) string = re.sub(MDHeader.marker_regex, lambda m: backend.escape("#" * int(m[1])), string) return string @@ -104,6 +101,7 @@ class MDQuote: block_quote(): replace multiline markdown quotes (">") into quotes of the output format inline_quote(): transform markdown quotes (`"`, `'`) into quotes of the output format """ + @staticmethod def block_quote(string: str, backend: Backend): r""" @@ -114,11 +112,7 @@ def block_quote(string: str, backend: Backend): :param backend: the output format :return: the updated string representation of a markdown file """ - string = re.sub( - backend.block_quote_regex, - lambda m: backend.block_quote(m[1]), - string, flags=re.M - ) + string = re.sub(backend.block_quote_regex, lambda m: backend.block_quote(m[1]), string, flags=re.M) return backend.remove_quote_marks(string) @staticmethod @@ -149,6 +143,7 @@ class MDList: ordered_l(): create ordered lists from md numbered lists definition_l(): create definition lists from md definition lists """ + @staticmethod def unordered_l(string: str, backend: Backend): """ @@ -195,7 +190,7 @@ def ordered_l(string: str, backend: Backend): string = string.replace("@@LISTTOKEN@@", backend.ordered_list(lsitems)) return string - + @staticmethod def definition_l(string: str, backend: Backend): """ @@ -224,9 +219,9 @@ def definition_l(string: str, backend: Backend): if current_list: lists.append(current_list) - + for ls in lists: - ls_block = ''.join([l[0] for l in ls]) + ls_block = "".join([l[0] for l in ls]) entries = [] # list of (term, definition) for item in ls: @@ -250,6 +245,7 @@ class MDCode: block_code(): create a code block of the output format from a md block of code inline_code(): create inline code of the output format from inline md code """ + @staticmethod def inline_code(string: str, backend: Backend): """ @@ -259,19 +255,19 @@ def inline_code(string: str, backend: Backend): :param backend: the output format :return: the updated string representation """ - + matches = re.finditer(syntax.INLINE_CODE, string) for m in matches: code = m[0] string = string.replace(code, backend.inline_code(m[1])) - + return string @staticmethod def block_code(string: str, backend: Backend): """ translate a markdown block of code into a code block of the output format. - + the function tries to match a md block code "```...```". if the block of code is matched, the code body is given to the backend. @@ -298,14 +294,14 @@ def block_code(string: str, backend: Backend): if backend.strip_quote_marks_in_code: # a code block in a block quote: each line of the code starts with the quote marks of the fence line - prefix = source[source.rfind("\n", 0, m.start()) + 1:m.start()] + prefix = source[source.rfind("\n", 0, m.start()) + 1 : m.start()] if re.fullmatch(r"[ \t]*(>[ \t]*)+", prefix): depth = prefix.count(">") code_body = re.sub(r"^[ \t]*(?:>[ \t]?){1,%d}" % depth, "", code_body, flags=re.M) # assume language is the first word in the info string # cf. https://spec.commonmark.org/0.31.2/#fenced-code-blocks - lang_info = re.search(r'^([0-9A-Za-z_-]+) *', info_string) + lang_info = re.search(r"^([0-9A-Za-z_-]+) *", info_string) language = lang_info[1] if lang_info else None # titles specified like title="A nice code block" in the info string @@ -325,13 +321,14 @@ def block_code(string: str, backend: Backend): class MDReference: r""" substitutions for references inside a markdown document. - + contains -------- footnote(): replace markdown footnotes (`[\^\d+]`) into footnotes of the output format hyperlink(): replace markdown hyperlinks into hyperlinks of the output format citation(): replace pandoc-style references `[@doe1979]` into citations of the output format """ + @staticmethod def footnote(string: str, backend: Backend): r""" @@ -360,8 +357,7 @@ def footnote(string: str, backend: Backend): pointer = match[0] # extract the footnote pointer (the pointer to the actual footnote) fnote_num = re.search(r"\d+", pointer)[0] # extract the footnote n° fnote_text = re.search( - r"^(\[" + caret + fnote_num + r"\]:) *(.+\n?)", - string, flags=re.M + r"^(\[" + caret + fnote_num + r"\]:) *(.+\n?)", string, flags=re.M ) # match the proper footnote (with the good fnote_num) # remove the pointer + normalize space note = re.sub(r"\s+", " ", fnote_text[0].replace(fnote_text[1], "")).strip() @@ -385,7 +381,7 @@ def footnote(string: str, backend: Backend): string = re.sub(r"(\[" + caret + r"\d+\]:)(.+\n?)*", "", string, flags=re.M) return string - + @staticmethod def hyperlink(string: str, backend: Backend): r""" @@ -400,7 +396,7 @@ def hyperlink(string: str, backend: Backend): if link[2].startswith("http"): # External URL string = string.replace(link[0], backend.link(link[2], link[1])) - else: # We are dealing with some other link, likely to another internal document + else: # We are dealing with some other link, likely to another internal document written = backend.internal_link(link[2], link[1]) if written is not None: string = string.replace(link[0], written) @@ -412,7 +408,7 @@ def hyperlink(string: str, backend: Backend): Warnings("link_type_not_supported", link[2]) return string - + @staticmethod def citation(string: str, backend: Backend): r""" @@ -422,12 +418,12 @@ def citation(string: str, backend: Backend): pandoc citation syntax spec: https://pandoc.org/chunkedhtml-demo/8.20-citation-syntax.html biblatex docs: https://ctan.org/pkg/biblatex - + Input syntax: - Citation form: [citationkey, locator] - Citation key: `@doe1999` (`-@doe1999` will omit author name with the \parencite* command) - Locator syntax: `p. 30`, `30`, `pp. 30-35`, `30-35` are the only valid forms - + Conversion examples: - [@doe1999] -> \parencite{doe1999} - [-@doe1999] -> \parencite*{doe1999} @@ -436,7 +432,7 @@ def citation(string: str, backend: Backend): - [@doe1999, 30-35] -> \parencite[pp. 30-35]{doe1999} - [@doe1999, pp. 30-35] -> \parencite[pp. 30-35]{doe1999} - [@doe1999; @smith] -> \parencites{doe1999, smith} - + Limitations: - Prefix or suffix not supported currently - Multiple sources in same citation are only supported in the basic form `[@doe1999; @smith2000]`, i.e. without locator or pre-/suffix @@ -454,24 +450,24 @@ def citation(string: str, backend: Backend): # Use negative lookahead so we don't match links or images ref_strings = re.finditer(syntax.CITATION, string, re.M) for ref_string in ref_strings: - if ';' in ref_string[1]: + if ";" in ref_string[1]: # multiple references in one citation # -> simple mode - keys = ref_string[1].replace(';', ',').replace('@', '') + keys = ref_string[1].replace(";", ",").replace("@", "") citation_text = backend.citations(keys) else: # only one citation, so we split into citation key and locator ref_components = re.match(r"(-?@[^, ]+)(, (?:p\. )?(\d+\b(?!-))|, (?:pp\. )?(\d+-\d+))?", ref_string[1]) citation_key = ref_components[1] locator = ref_components[3] or ref_components[4] - omit_author = citation_key.startswith('-') + omit_author = citation_key.startswith("-") citation_text = backend.citation( citation_key[2:] if omit_author else citation_key[1:], locator, is_range=not ref_components[3], - omit_author=omit_author + omit_author=omit_author, ) - + string = string.replace(ref_string[0], citation_text) return string @@ -487,6 +483,7 @@ class MDCleaner: from the rest of the pipeline clean_output(): clean the text created and reinsert code substrings at the end of the pipeline """ + @staticmethod def prepare_markdown(string: str, backend: Backend): """ @@ -513,8 +510,8 @@ def prepare_markdown(string: str, backend: Backend): # the code is replaced in `string` with a special token string, codedict = backend.stash_code(string) - string = string.replace("{==", "") # begin highlight (removed) - string = string.replace("==}", "") # end highlight (removed) + string = string.replace("{==", "") # begin highlight (removed) + string = string.replace("==}", "") # end highlight (removed) return string, codedict @@ -547,7 +544,7 @@ class MDFrontmatter: """ remove Markdown file frontmatter written in YAML format """ - + @staticmethod def convert(string: str): """ @@ -555,7 +552,7 @@ def convert(string: str): :param string: the string rpr of the markdown file to convert :return: string with the conversion performed """ - + flags = re.MULTILINE | re.DOTALL string = re.sub(r"^---.*---", "", string, flags=flags) @@ -566,7 +563,7 @@ class MDMedia: """ Convert embedded media (currently only images) """ - + @staticmethod def image(string: str, backend: Backend): r""" @@ -582,7 +579,7 @@ def image(string: str, backend: Backend): :param backend: the output format :return: string with the conversion performed """ - default_width = "85" # percent + default_width = "85" # percent # this regex looks a little weird, but we need to match the escaped chars introduced earlier... open_brace = re.escape(backend.escape("{")) @@ -590,12 +587,13 @@ def image(string: str, backend: Backend): percent = re.escape(backend.escape("%")) images = re.finditer( syntax.IMAGE + r"(?:" + open_brace + r".*?width=\"(\d+)" + percent + r"\".*?" + close_brace + r")?", - string, re.M + string, + re.M, ) for match in images: width = match[3] if match[3] else default_width string = string.replace(match[0], backend.image(match[1], match[2], width)) - + return string @@ -655,6 +653,7 @@ class MDInsertion: insertion points: a line with an HTML comment, like ``, marks a place where the caller of the conversion can put text. the comment is not shown by Markdown viewers. """ + placeholder = syntax.INSERTION @staticmethod @@ -681,6 +680,7 @@ class MDMethods: `convert()` writes the tags after the other steps. the marker lines start with a control character, so that no other step takes a cell text for a list, a quote or a heading. """ + marker = "\x02" separator = "\x03" # between the text of an argument and the values of the other columns level_2_regex = r"^##(?!#)[ \t]+(.*?)[ \t]*$" @@ -692,13 +692,20 @@ def _arguments(lines: list, number: int, end: int) -> list: """ header = [tables.unescape(cell) for cell in tables.split_row(lines[number])] out = [] - for row in lines[number + 2:end]: + for row in lines[number + 2 : end]: cells = [tables.unescape(cell) for cell in tables.split_row(row)] cells += [""] * (len(header) - len(cells)) name = cells[0].strip("`") others = [f"{header[i]}: {cells[i]}" for i in range(1, len(header) - 1) if cells[i]] - out.append(MDMethods.marker + "ARGUMENT" + MDMethods.marker + name + MDMethods.marker + cells[-1] - + "".join(MDMethods.separator + other for other in others)) + out.append( + MDMethods.marker + + "ARGUMENT" + + MDMethods.marker + + name + + MDMethods.marker + + cells[-1] + + "".join(MDMethods.separator + other for other in others) + ) return out @staticmethod @@ -740,10 +747,13 @@ def mark(string: str, backend: Backend): out += [""] + "\n\n".join(MDMethods._arguments(lines, number, end)).split("\n") + [""] number = end continue - elif (in_method and not in_discussion and line.startswith(backend.returns_mark) - and (number == 0 or not lines[number - 1].strip())): - line = (MDMethods.marker + "RETURNS" + MDMethods.marker - + line[len(backend.returns_mark):].strip()) + elif ( + in_method + and not in_discussion + and line.startswith(backend.returns_mark) + and (number == 0 or not lines[number - 1].strip()) + ): + line = MDMethods.marker + "RETURNS" + MDMethods.marker + line[len(backend.returns_mark) :].strip() out.append(line) number += 1 return "\n".join(out) @@ -771,6 +781,7 @@ class MDTable: `convert()` gives the rows to the backend after the other steps. a marker line starts with a control character, so that no other step takes a cell text for a list, a quote or a heading. """ + marker = "\x04" separator = "\x05" # between the cells of a row start = marker + "TABLE" @@ -819,9 +830,9 @@ def write(match): header, rows = None, [] for line in match[1].split("\n"): if line.startswith(MDTable.header): - header = line[len(MDTable.header):].split(MDTable.separator) + header = line[len(MDTable.header) :].split(MDTable.separator) elif line.startswith(MDTable.row): - rows.append(line[len(MDTable.row):].split(MDTable.separator)) + rows.append(line[len(MDTable.row) :].split(MDTable.separator)) return backend.table(header, rows) return re.sub(re.escape(MDTable.start) + r"\n(.*?)\n" + re.escape(MDTable.end), write, string, flags=re.S) diff --git a/md2misc/core.py b/md2misc/core.py index 6fa202b..35c0b9f 100644 --- a/md2misc/core.py +++ b/md2misc/core.py @@ -2,7 +2,21 @@ from .backends import SchelpBackend, TeXBackend from .errors_warnings import DocumentError -from .converters import MDSimple, MDQuote, MDList, MDCode, MDCleaner, MDReference, MDHeader, MDFrontmatter, MDInsertion, MDMedia, MDMath, MDMethods, MDTable +from .converters import ( + MDSimple, + MDQuote, + MDList, + MDCode, + MDCleaner, + MDReference, + MDHeader, + MDFrontmatter, + MDInsertion, + MDMedia, + MDMath, + MDMethods, + MDTable, +) def default_template() -> str: @@ -28,8 +42,10 @@ def convert(data, unnumbered=False, document_class="article", minted_language="t """ if document_class not in TeXBackend.sectioning: - raise DocumentError(f"the document class `{document_class}` is not supported: " - + "the document classes are `article` and `book`") + raise DocumentError( + f"the document class `{document_class}` is not supported: " + + "the document classes are `article` and `book`" + ) backend = TeXBackend(unnumbered, document_class, minted_language, override_language) return run_pipeline(data, backend) @@ -74,19 +90,19 @@ def run_pipeline(data, backend): backend.check_source(data) # complex replacements - data = MDCode.block_code(data, backend) # the contents of code blocks and inline code strings + data = MDCode.block_code(data, backend) # the contents of code blocks and inline code strings # must be interpreted verbatim. therefore, # these functions come first so that they won't be changed # by `prepare_markdown()` - data = MDMethods.mark(data, backend) # argument tables: after code blocks, and before inline code, + data = MDMethods.mark(data, backend) # argument tables: after code blocks, and before inline code, # because a `\|` in inline code in a cell is a `|` - data = MDTable.mark(data, backend) # the other tables, for the same reason + data = MDTable.mark(data, backend) # the other tables, for the same reason data = MDCode.inline_code(data, backend) - data = MDInsertion.apply(data, backend) # text of the caller is not changed, either + data = MDInsertion.apply(data, backend) # text of the caller is not changed, either data, mathdict = MDMath.stash_math(data, backend) data, codedict = MDCleaner.prepare_markdown(data, backend) # remove code from the pipeline - data = MDHeader.mark(data, backend) # headers are located before the text is escaped - data = backend.escape(data) # escape special chars + data = MDHeader.mark(data, backend) # headers are located before the text is escaped + data = backend.escape(data) # escape special chars data = MDFrontmatter.convert(data) data = MDMedia.image(data, backend) data = MDQuote.inline_quote(data, backend) diff --git a/md2misc/errors_warnings.py b/md2misc/errors_warnings.py index 4d0dafb..fbc8eee 100644 --- a/md2misc/errors_warnings.py +++ b/md2misc/errors_warnings.py @@ -11,6 +11,7 @@ class Md2miscError(Exception): """ base class for all errors of md2misc. `message` holds the text of the error. """ + def __init__(self, message: str): super().__init__(message) self.message = message @@ -31,6 +32,7 @@ class UnsupportedConstruct(Md2miscError): a Markdown construct that the output format cannot write. `line` is the line of the construct, if known. `describe(source)` gives the message with the name of the Markdown file. """ + def __init__(self, backend: str, construct: str, line: int = None): """ :param backend: the name of the output format @@ -72,14 +74,14 @@ class IndentationException(ParsingException): """ error logs relative to list indentation """ + logs = { "firstindent": "ERROR. - inconsistant indentation in markdown list \n" - + "`@@TOKEN@@` \n" - + "all items must be as indented than the first list item or more.", + + "`@@TOKEN@@` \n" + + "all items must be as indented than the first list item or more.", "multiplier": "ERROR. inconsistant indentation level in list \n" - + "`@@TOKEN@@` \nall list items must share a common indentation multiplier.\n" - + "the first indented item defines the indentation multiplier." - + + "`@@TOKEN@@` \nall list items must share a common indentation multiplier.\n" + + "the first indented item defines the indentation multiplier.", } # all possible error logs def __init__(self, key, lstext): @@ -94,6 +96,7 @@ class Warnings: """ class to give custom warnings, with the category `Md2miscWarning`. the warnings do not change the output. """ + logs = { "list_deep_nesting": "deep list nesting. you may need to change base tex options in the header.", "lang_not_supported": "language `@@TOKEN@@` is not supported by minted/Pygments. see https://pygments.org/languages/ for a list of supported languages.", diff --git a/md2misc/helpers.py b/md2misc/helpers.py index 1a02dc9..a9368aa 100644 --- a/md2misc/helpers.py +++ b/md2misc/helpers.py @@ -48,10 +48,12 @@ def process_list_indentation(lstext): if indent < 0: raise IndentationException(key="firstindent", lstext=lstext) # raise an error, print error msg, exit else: - lsitems.append([ - re.sub(r"^\s*-\s*", "", item), # item content - indent # indentation (n° of spaces) - ]) + lsitems.append( + [ + re.sub(r"^\s*-\s*", "", item), # item content + indent, # indentation (n° of spaces) + ] + ) # if there are different indentation levels, # - check that all levels have a common multiplier @@ -79,11 +81,11 @@ def process_list_indentation(lstext): def get_matching_brackets(code: str): r""" - Finds and returns the substring of the input code contained by an + Finds and returns the substring of the input code contained by an outer pair of matching opening and closing curly brackets `{...}`, assuming that any inner pairs of brackets which are opened are closed again. - + Escaped brackets `\{` and `\}` are ignored. - + :param code: The input string containing code with curly brackets. :return: The substring from the start of the input code up to and including the matching closing bracket. @@ -92,14 +94,14 @@ def get_matching_brackets(code: str): numOpened = 0 hasOpened = False for c in code: - if c == '{' and code[pos-1] != "\\": + if c == "{" and code[pos - 1] != "\\": numOpened += 1 hasOpened = True - elif c == '}' and code[pos-1] != "\\": + elif c == "}" and code[pos - 1] != "\\": numOpened -= 1 if numOpened == 0 and hasOpened: # we found the closing bracket pos += 1 break pos += 1 - return code[:pos] \ No newline at end of file + return code[:pos] diff --git a/md2misc/tables.py b/md2misc/tables.py index a57006b..646ce5c 100644 --- a/md2misc/tables.py +++ b/md2misc/tables.py @@ -8,6 +8,7 @@ the backends use these functions to find tables in the source and in the converters, so that both find the same tables. """ + import re # a cell of the delimiter row. the colons give the alignment, which no backend uses @@ -74,8 +75,12 @@ def starts_table(lines: list, number: int) -> bool: if number + 1 >= len(lines): return False header = lines[number] - return (bool(header.strip()) and has_pipe(header) and indent(header) <= MAX_INDENT - and is_delimiter_row(lines[number + 1])) + return ( + bool(header.strip()) + and has_pipe(header) + and indent(header) <= MAX_INDENT + and is_delimiter_row(lines[number + 1]) + ) # a line that starts another block ends a table. other lines without a pipe would be rows in GFM, but not in diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..5470aa8 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,16 @@ +line-length = 120 +include = ["*.py", "*.pyi"] +force-exclude = true +preview = false +unsafe-fixes = false + +[lint] +select = [ + "E4", "E7", "E9", "F", "I", "UP", "C4", + "B006", "B007", "B012", "B018", "B023", "B024", "B027", + "RUF100", +] + +[lint.pyupgrade] +# Runtime annotation consumers still need syntax that the Python floor supports. +keep-runtime-typing = true diff --git a/tests/battery.py b/tests/battery.py index 2397a14..cde1612 100644 --- a/tests/battery.py +++ b/tests/battery.py @@ -20,6 +20,7 @@ python3 tests/battery.py build """ + import argparse import contextlib import importlib @@ -121,6 +122,7 @@ def count_constructs(md: str) -> dict: # ------------------------------------------------------------------ build + def export_book(): """Export the docs folder of the book at the fixed commit.""" if BOOK_EXPORT.exists(): @@ -128,7 +130,8 @@ def export_book(): BOOK_EXPORT.mkdir() archive = subprocess.run( ["git", "-C", str(BOOK_REPO), "archive", BOOK_COMMIT], - check=True, capture_output=True, + check=True, + capture_output=True, ).stdout subprocess.run(["tar", "-x", "-C", str(BOOK_EXPORT)], input=archive, check=True) @@ -223,7 +226,8 @@ def build(args): md = path.read_text() counts = count_constructs(md) synthetic[path.stem] = { - "md": md, "counts": counts, + "md": md, + "counts": counts, "covers": {k for k, v in counts.items() if v}, } @@ -298,12 +302,15 @@ def main(): sub = p.add_subparsers(dest="cmd", required=True) for name, fn in (("build", build),): s = sub.add_parser(name) - s.add_argument("--converter", default=str(REPO), - help="folder that holds the converter module (default: %(default)s)") - s.add_argument("--installed", action="store_true", - help="import the converter from the Python environment, not from --converter") - s.add_argument("--module", default="md2misc", - help="module that exposes convert() (default: %(default)s)") + s.add_argument( + "--converter", default=str(REPO), help="folder that holds the converter module (default: %(default)s)" + ) + s.add_argument( + "--installed", + action="store_true", + help="import the converter from the Python environment, not from --converter", + ) + s.add_argument("--module", default="md2misc", help="module that exposes convert() (default: %(default)s)") s.set_defaults(fn=fn) args = p.parse_args() args.fn(args) diff --git a/tests/schelp_cases.py b/tests/schelp_cases.py index 5bd68b4..86bb785 100644 --- a/tests/schelp_cases.py +++ b/tests/schelp_cases.py @@ -24,8 +24,8 @@ ("![An image[^1]](image.png)\n\n[^1]: A note.\n", "in the caption of an image", 1), ("![type:audio](sound.wav)\n", "audio file", 1), ("Above.\n\n---\n\nBelow.\n", "horizontal rule", 3), - ("Text.\n\n```supercollider title=\"Example\"\nx = 1;\n```\n", "code block title", 3), - ("```sc hl_lines=\"1\"\nx = 1;\n```\n", "highlighted lines", 1), + ('Text.\n\n```supercollider title="Example"\nx = 1;\n```\n', "code block title", 3), + ('```sc hl_lines="1"\nx = 1;\n```\n', "highlighted lines", 1), ("Use **`code` in bold**.\n", "code inside bold or italic text", 1), ("A line
break.\n", "line break", 1), ("> [!FOO]\n> An alert that is not known.\n", "alert of a kind that is not known", 1), @@ -54,85 +54,102 @@ M = "## Class methods\n\n" # Markdown that has no schelp form, which the converters take for text: only the check of the source stops at it. -SOURCE_ONLY = [ - ("* One\n* Two\n", "list with `*` or `+` marks", 1), - ("Text.\n\n+ One\n", "list with `*` or `+` marks", 3), - ("1) One\n2) Two\n", "numbered list with `)`", 1), - ("Above.\n\n***\n\nBelow.\n", "horizontal rule", 3), - ("Above.\n\n_ _ _\n\nBelow.\n", "horizontal rule", 3), - ("A title\n=======\n\nText.\n", "heading underlined with `=` or `-`", 2), - ("Text.\n\nA title\n-------\n", "heading underlined with `=` or `-`", 4), - ("Text with ![an image](image.png) in it.\n", "image in a line of text", 1), - ("Text.\n![An image](image.png)\n", "image in a line of text", 2), - ("![An image](image.png)\nText.\n", "image in a line of text", 1), - ("Text.\n\n| a | b |\n|---|\n| 1 | 2 |\n", "delimiter row has another number of cells", 4), - ("Text.\n\n| a | b |\n|---|---|\n| 1 | 2 | 3 |\n", "more cells than the header", 5), - ("Text.\n\n| a | b |\n|---|---|\n| 1 | `a|b` |\n", "`|` in code in a table", 5), - ("Text.\n\n| a | b |\n|---|---|\n| 1 | a \\\\| b |\n", "`\\\\|` in a table row", 5), - ("Text.\n\n| a | b |\n|---|---|\n| 1 | 2 |\nMore text.\n", "line without `|` after a table", 6), - ("Text.\n\n| a | b |\n|---|---|\n", "table without rows", 3), - ("| `a` | b |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), - ("| *a* | b |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), - ("| a | [b](https://a.org) |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), - ("| a | $x$ |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), -] + [(M + markdown, construct, line + 2) for markdown, construct, line in [ - # the class methods section (M is its heading): the markdown starts at line 3 - ("| a | b |\n|---|---|\n| x | y |\n", "table outside a method", 1), - ("Intro.\n\n| a | b |\n|---|---|\n| x | y |\n", "table outside a method", 3), - ("### *ar\n\n| a | b |\n|---|\n| x | y |\n", "delimiter row has another number of cells", 4), - ("### *ar\n\n| a | b |\n|---|---|---|\n| x | y |\n", "delimiter row has another number of cells", 4), - ("### *ar\n\n| a |\n|---|\n| x |\n", "argument table with one column", 3), - ("### *ar\n\n| a | | b |\n|---|---|---|\n| x | 1 | y |\n", "column without a heading", 3), - ("### *ar\n\n| a | b |\n|---|---|\n", "table without rows", 3), - ("### *ar\n\n| a | b |\n|---|---|\n\nText.\n", "table without rows", 3), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\nMore text.\n", "line without `|` after a table", 6), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y | z |\n", "more cells than the header", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n| w | v | u |\n", "more cells than the header", 6), - ("### *ar\n\n| a | b |\n|---|---|\n| two words | y |\n", "argument name `two words`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| *ar | y |\n", "argument name `*ar`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| 1x | y |\n", "argument name `1x`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| **x** | y |\n", "argument name `**x**`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| | y |\n", "argument name ``", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| `x | y |\n", "argument name", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n| `x` | z |\n", "argument `x` twice", 6), - ("### *ar\n\n| a | b |\n|---|---|\n| x | |\n", "argument `x` without text", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x |\n", "argument `x` without text", 5), - ("### *ar\n\n| a | r | b |\n|---|---|---|\n| x | 1 |\n", "argument `x` without text", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | Code `a|b`. |\n", "`|` in code in a table", 5), - ("### *ar\n\n| `a|b` | c |\n|---|---|\n| x | y |\n", "`|` in code in a table", 3), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y \\\\| z |\n", "`\\\\|` in a table row", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n| a | b |\n|---|---|\n| w | v |\n", "second table", 7), - ("### *ar\n\nReturns: x.\n\n| a | b |\n|---|---|\n| w | v |\n", "table after `Returns:`", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\nMore text.\n", "text after the argument table", 7), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n- A list.\n", "text after the argument table", 6), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n```\nx = 1;\n```\n", "text after the argument table", 7), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n> [!NOTE]\n> A note.\n", "text after the argument table", 7), - ("### *ar\n\nReturns: x.\n\nMore text.\n", "text after the `Returns:` paragraph", 5), - ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\nReturns: x.\n\nReturns: y.\n", "text after the `Returns:`", 9), - ("### Arguments\n\nText.\n", "heading in a methods section that is not a method", 1), - ("### ar\n\nText.\n", "heading in a methods section that is not a method", 1), - ("### *ar *kr\n\nText.\n", "heading in a methods section that is not a method", 1), - ("### *ar\n\n#### Details\n\nText.\n", "heading in a methods section that is not a method", 3), - ("### -ar\n\nText.\n", "heading in a methods section that is not a method", 1), - ("#### Discussion\n\nText.\n", "heading in a methods section that is not a method", 1), - ("### *ar\n\n#### Discussion\n\nA.\n\n#### Discussion\n\nB.\n", "heading in a methods section", 7), - ("### *ar\n\n#### Discussion\n\n| a | b |\n|---|---|\n| x | y |\n", "table in the discussion", 5), - ("### *ar\n\n#### Discussion\n\nA.\n\n##### More\n\nB.\n", "heading in a methods section", 7), -]] + [ - # the instance methods section: the markdown starts at line 3 - ("## Instance methods\n\n" + markdown, construct, line + 2) for markdown, construct, line in [ - ("### *ar\n\nText.\n", "a method heading is like `### -ar`", 1), - ("### -play\n\n| a | b |\n|---|---|\n| x | y |\n\nMore text.\n", "text after the argument table", 7), - ("### -play\n\nReturns: x.\n\nMore text.\n", "put a `#### Discussion` heading before it", 5), +SOURCE_ONLY = ( + [ + ("* One\n* Two\n", "list with `*` or `+` marks", 1), + ("Text.\n\n+ One\n", "list with `*` or `+` marks", 3), + ("1) One\n2) Two\n", "numbered list with `)`", 1), + ("Above.\n\n***\n\nBelow.\n", "horizontal rule", 3), + ("Above.\n\n_ _ _\n\nBelow.\n", "horizontal rule", 3), + ("A title\n=======\n\nText.\n", "heading underlined with `=` or `-`", 2), + ("Text.\n\nA title\n-------\n", "heading underlined with `=` or `-`", 4), + ("Text with ![an image](image.png) in it.\n", "image in a line of text", 1), + ("Text.\n![An image](image.png)\n", "image in a line of text", 2), + ("![An image](image.png)\nText.\n", "image in a line of text", 1), + ("Text.\n\n| a | b |\n|---|\n| 1 | 2 |\n", "delimiter row has another number of cells", 4), + ("Text.\n\n| a | b |\n|---|---|\n| 1 | 2 | 3 |\n", "more cells than the header", 5), + ("Text.\n\n| a | b |\n|---|---|\n| 1 | `a|b` |\n", "`|` in code in a table", 5), + ("Text.\n\n| a | b |\n|---|---|\n| 1 | a \\\\| b |\n", "`\\\\|` in a table row", 5), + ("Text.\n\n| a | b |\n|---|---|\n| 1 | 2 |\nMore text.\n", "line without `|` after a table", 6), + ("Text.\n\n| a | b |\n|---|---|\n", "table without rows", 3), + ("| `a` | b |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), + ("| *a* | b |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), + ("| a | [b](https://a.org) |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), + ("| a | $x$ |\n|---|---|\n| 1 | 2 |\n", "in the header row of a table", 1), ] -] + [ - ("See .\n", "link in `<` and `>`", 1), - ("Mail .\n", "link in `<` and `>`", 1), - ("Press Ctrl.\n", "HTML tag", 1), - ("Text.\n\n\n", "HTML comment", 3), - ("Text.[^1]\n\n[^1]: Paragraph one.\n\n - A list.\n", "list, code block or other block in a footnote", 5), - ("Text.[^1]\n\n[^1]: Paragraph one.\n > A quote.\n", "list, code block or other block in a footnote", 4), -] + + [ + (M + markdown, construct, line + 2) + for markdown, construct, line in [ + # the class methods section (M is its heading): the markdown starts at line 3 + ("| a | b |\n|---|---|\n| x | y |\n", "table outside a method", 1), + ("Intro.\n\n| a | b |\n|---|---|\n| x | y |\n", "table outside a method", 3), + ("### *ar\n\n| a | b |\n|---|\n| x | y |\n", "delimiter row has another number of cells", 4), + ("### *ar\n\n| a | b |\n|---|---|---|\n| x | y |\n", "delimiter row has another number of cells", 4), + ("### *ar\n\n| a |\n|---|\n| x |\n", "argument table with one column", 3), + ("### *ar\n\n| a | | b |\n|---|---|---|\n| x | 1 | y |\n", "column without a heading", 3), + ("### *ar\n\n| a | b |\n|---|---|\n", "table without rows", 3), + ("### *ar\n\n| a | b |\n|---|---|\n\nText.\n", "table without rows", 3), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\nMore text.\n", "line without `|` after a table", 6), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y | z |\n", "more cells than the header", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n| w | v | u |\n", "more cells than the header", 6), + ("### *ar\n\n| a | b |\n|---|---|\n| two words | y |\n", "argument name `two words`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| *ar | y |\n", "argument name `*ar`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| 1x | y |\n", "argument name `1x`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| **x** | y |\n", "argument name `**x**`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| | y |\n", "argument name ``", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| `x | y |\n", "argument name", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n| `x` | z |\n", "argument `x` twice", 6), + ("### *ar\n\n| a | b |\n|---|---|\n| x | |\n", "argument `x` without text", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x |\n", "argument `x` without text", 5), + ("### *ar\n\n| a | r | b |\n|---|---|---|\n| x | 1 |\n", "argument `x` without text", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | Code `a|b`. |\n", "`|` in code in a table", 5), + ("### *ar\n\n| `a|b` | c |\n|---|---|\n| x | y |\n", "`|` in code in a table", 3), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y \\\\| z |\n", "`\\\\|` in a table row", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n| a | b |\n|---|---|\n| w | v |\n", "second table", 7), + ("### *ar\n\nReturns: x.\n\n| a | b |\n|---|---|\n| w | v |\n", "table after `Returns:`", 5), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\nMore text.\n", "text after the argument table", 7), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n- A list.\n", "text after the argument table", 6), + ("### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n```\nx = 1;\n```\n", "text after the argument table", 7), + ( + "### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\n> [!NOTE]\n> A note.\n", + "text after the argument table", + 7, + ), + ("### *ar\n\nReturns: x.\n\nMore text.\n", "text after the `Returns:` paragraph", 5), + ( + "### *ar\n\n| a | b |\n|---|---|\n| x | y |\n\nReturns: x.\n\nReturns: y.\n", + "text after the `Returns:`", + 9, + ), + ("### Arguments\n\nText.\n", "heading in a methods section that is not a method", 1), + ("### ar\n\nText.\n", "heading in a methods section that is not a method", 1), + ("### *ar *kr\n\nText.\n", "heading in a methods section that is not a method", 1), + ("### *ar\n\n#### Details\n\nText.\n", "heading in a methods section that is not a method", 3), + ("### -ar\n\nText.\n", "heading in a methods section that is not a method", 1), + ("#### Discussion\n\nText.\n", "heading in a methods section that is not a method", 1), + ("### *ar\n\n#### Discussion\n\nA.\n\n#### Discussion\n\nB.\n", "heading in a methods section", 7), + ("### *ar\n\n#### Discussion\n\n| a | b |\n|---|---|\n| x | y |\n", "table in the discussion", 5), + ("### *ar\n\n#### Discussion\n\nA.\n\n##### More\n\nB.\n", "heading in a methods section", 7), + ] + ] + + [ + # the instance methods section: the markdown starts at line 3 + ("## Instance methods\n\n" + markdown, construct, line + 2) + for markdown, construct, line in [ + ("### *ar\n\nText.\n", "a method heading is like `### -ar`", 1), + ("### -play\n\n| a | b |\n|---|---|\n| x | y |\n\nMore text.\n", "text after the argument table", 7), + ("### -play\n\nReturns: x.\n\nMore text.\n", "put a `#### Discussion` heading before it", 5), + ] + ] + + [ + ("See .\n", "link in `<` and `>`", 1), + ("Mail .\n", "link in `<` and `>`", 1), + ("Press Ctrl.\n", "HTML tag", 1), + ("Text.\n\n\n", "HTML comment", 3), + ("Text.[^1]\n\n[^1]: Paragraph one.\n\n - A list.\n", "list, code block or other block in a footnote", 5), + ("Text.[^1]\n\n[^1]: Paragraph one.\n > A quote.\n", "list, code block or other block in a footnote", 4), + ] +) # Markdown that only the writers of the backend stop at, thus the error has no line. WRITER_ONLY = [ @@ -183,7 +200,7 @@ "---\ntitle: A\nsummary: B\n---\n\n## Section\n\n> A quote.\n", "> [!NOTE]\n> An alert.\n\n> A quote.\n", "Text.\n\n```\n# Fine in code\n> Fine in code\n```\n\n> A quote.\n", - "> A quote with a < b, \"quotation marks\" and C#.\n", + '> A quote with a < b, "quotation marks" and C#.\n', ] # Markdown, and the parts of the HTML page that SCDoc must make from the schelp output. The cases of SUPPORTED are @@ -197,37 +214,63 @@ ("Math $a:$ here.\n", ["a: here."]), ("Text.[^1]\n\n[^1]: A note that ends with a colon:\n", ["A note that ends with a colon:"]), ("**Two colons::** here.\n", ["Two colons:: here."]), - ("Text.\n\n![A caption: with a colon](images/a.png)\n\nAfter.\n", - ["

A caption: with a colon
"]), + ( + "Text.\n\n![A caption: with a colon](images/a.png)\n\nAfter.\n", + ["

A caption: with a colon
"], + ), ("![](a.png)\n", ["
"]), ("Text.\n\n> A quote.\n\nAfter.\n", ['

"A quote."\n

After.']), - ("> One\n> line.\n>\n> Two.\n>\n> Three:\n\n- A list after it.\n", - ['

"One line.\n

Two.\n

Three:"']), + ( + "> One\n> line.\n>\n> Two.\n>\n> Three:\n\n- A list after it.\n", + ['

"One line.\n

Two.\n

Three:"'], + ), ("> [!NOTE]\n> One.\n>\n> Two.\n", ["One.\n

Two."]), # a tag directly after a letter: SCDoc needs a character between them that is not a letter - ("A word**bold**, a word*italic*, a word`code`, a word[link](https://example.com) and a word$x$.\n", - ["A word\u2060bold, a word\u2060italic, a word\u2060code, " - 'a word\u2060link and a word\u2060x.']), - ("Café**bold** and x_**bold** and 2**bold**.\n", - ["Café\u2060bold and x_bold and 2bold."]), - ("A word[^1] and a word [^2].\n\n[^1]: One.\n[^2]: Two.\n", - ["

A word[1] - Line one and line two."]), - ("Text.[^1] After.\n\n[^1]: Paragraph one,\n still one.\n\n Paragraph two.\n\n\tThree.\n\nNot in the note.\n", - ["] - Paragraph one, still one.\n

Paragraph two.\n

Three.", "

Not in the note."]), + ( + "A word**bold**, a word*italic*, a word`code`, a word[link](https://example.com) and a word$x$.\n", + [ + "A word\u2060bold, a word\u2060italic, a word\u2060code, " + "a word\u2060link and a word\u2060x." + ], + ), + ( + "Café**bold** and x_**bold** and 2**bold**.\n", + ["Café\u2060bold and x_bold and 2bold."], + ), + ( + "A word[^1] and a word [^2].\n\n[^1]: One.\n[^2]: Two.\n", + ["

A word[1] - Line one and line two."], + ), + ( + "Text.[^1] After.\n\n[^1]: Paragraph one,\n still one.\n\n Paragraph two.\n\n\tThree.\n\nNot in the note.\n", + ["] - Paragraph one, still one.\n

Paragraph two.\n

Three.", "

Not in the note."], + ), ("# A::B\n\nText.\n", ["

A::B"]), - ("> [!NOTE]\n> Try this:\n> ```\n> x = 1;\n> ```\n> And then this.\n", - ["", "And then this."]), + ( + "> [!NOTE]\n> Try this:\n> ```\n> x = 1;\n> ```\n> And then this.\n", + ["", "And then this."], + ), ("It costs $5 and $10, and \\$x\\$ is not math.\n", ["It costs $5 and $10, and $x$ is not math."]), ("#1 is text.\n", ["

#1 is text."]), ("Math $a::b$ in text.\n", ["a::b"]), ("Before.\n\n$$\nx\n::\ny\n$$\n\nAfter.\n", ["x\n::\ny"]), ("Use `a::b` and `x\\` here.\n", ["a::b", "x\\ here."]), ("## Section: with a colon\n\nText.\n", ["

Section: with a colon

"]), - ("Term:\n: A definition that ends with a colon:\n\nAfter.\n", ["
Term:
A definition that ends with a colon:"]), - ("| A | B |\n|---|---|\n| 1 | 2 |\n", ["\n
AB
12
"]), + ( + "Term:\n: A definition that ends with a colon:\n\nAfter.\n", + ["
Term:
A definition that ends with a colon:"], + ), + ( + "| A | B |\n|---|---|\n| 1 | 2 |\n", + ["\n
AB
12
"], + ), ("| | |\n|---|---|\n| 1 | 2 |\n", ["\n
12
"]), - ("| A | |\n|---|---|\n| a \\|\\| b | `x \\| y` |\n", - ["Aa || bx | y"]), + ( + "| A | |\n|---|---|\n| a \\|\\| b | `x \\| y` |\n", + ["Aa || bx | y"], + ), ] diff --git a/tests/schelp_fixtures.py b/tests/schelp_fixtures.py index 101d3d9..6c4de6d 100644 --- a/tests/schelp_fixtures.py +++ b/tests/schelp_fixtures.py @@ -19,6 +19,7 @@ python3 tests/schelp_fixtures.py update """ + import argparse import importlib import json @@ -153,7 +154,10 @@ def render_texts(sclang: str, texts: dict, timeout: int = 180, copied: list = No + "0.exit;\n" ) env = dict( - os.environ, HOME=str(tmp / "home"), XDG_DATA_HOME=str(data), XDG_CONFIG_HOME=str(data), + os.environ, + HOME=str(tmp / "home"), + XDG_DATA_HOME=str(data), + XDG_CONFIG_HOME=str(data), QT_QPA_PLATFORM="offscreen", ) done = subprocess.run([sclang, str(script)], env=env, capture_output=True, text=True, timeout=timeout) @@ -192,8 +196,11 @@ def render_all(sclang: str, timeout: int = 180) -> dict: fixtures with a bibliography are not rendered. """ with_pandoc = find_pandoc() is not None - results = render_texts(sclang, {md_path.stem: convert(md_path) for md_path in fixtures() - if with_pandoc or not needs_pandoc(md_path)}, timeout) + results = render_texts( + sclang, + {md_path.stem: convert(md_path) for md_path in fixtures() if with_pandoc or not needs_pandoc(md_path)}, + timeout, + ) errors = [f"{name}: {result}" for name, result in results.items() if isinstance(result, RenderError)] if errors: raise RenderError("\n".join(errors)) diff --git a/tests/test_schelp_behavior.py b/tests/test_schelp_behavior.py index 4fc6617..ad42a25 100644 --- a/tests/test_schelp_behavior.py +++ b/tests/test_schelp_behavior.py @@ -2,6 +2,7 @@ How the schelp output is made, for the cases that the fixtures do not show: header values, special sections, admonitions, math, code, insertion points and quotation marks. """ + import pytest from md2misc import convert_schelp @@ -61,7 +62,7 @@ def test_metadata_lists_are_a_string_with_commas_or_a_list(value): ('summary: "Quoted: with a colon"', "SUMMARY::Quoted: with a colon\n"), ("summary: 'Single quoted'", "SUMMARY::Single quoted\n"), ("summary: Unquoted: with a colon", "SUMMARY::Unquoted: with a colon\n"), - ('related: ["Classes/A", \'Classes/B\']', "RELATED::Classes/A, Classes/B\n"), + ("related: [\"Classes/A\", 'Classes/B']", "RELATED::Classes/A, Classes/B\n"), ("related: Classes/A, Classes/B", "RELATED::Classes/A, Classes/B\n"), ('categories:\n - "A"\n - B', "CATEGORIES::A, B\n"), ], @@ -109,16 +110,19 @@ def test_header_without_title_or_class_is_an_error(): # ------------------------------------------------------ special sections -@pytest.mark.parametrize("heading, expected", [ - ("## Description", "DESCRIPTION::"), - ("## description", "DESCRIPTION::"), - ("## Examples", "EXAMPLES::"), - ("## EXAMPLES", "EXAMPLES::"), - ("## Other", "SECTION::Other"), - ("### Description", "SUBSECTION::Description"), - ("#### Examples", "SUBSUBSECTION::Examples"), - ("##### Deeper", "SUBSUBSECTION::Deeper"), -]) +@pytest.mark.parametrize( + "heading, expected", + [ + ("## Description", "DESCRIPTION::"), + ("## description", "DESCRIPTION::"), + ("## Examples", "EXAMPLES::"), + ("## EXAMPLES", "EXAMPLES::"), + ("## Other", "SECTION::Other"), + ("### Description", "SUBSECTION::Description"), + ("#### Examples", "SUBSUBSECTION::Examples"), + ("##### Deeper", "SUBSUBSECTION::Deeper"), + ], +) def test_headings(heading, expected): assert convert_schelp(heading + "\n") == expected + "\n" @@ -126,10 +130,18 @@ def test_headings(heading, expected): # ------------------------------------------------------------ admonitions -@pytest.mark.parametrize("mark, tag", [ - ("NOTE", "note"), ("TIP", "note"), ("IMPORTANT", "note"), ("WARNING", "warning"), ("CAUTION", "warning"), - ("note", "note"), ("Warning", "warning"), -]) +@pytest.mark.parametrize( + "mark, tag", + [ + ("NOTE", "note"), + ("TIP", "note"), + ("IMPORTANT", "note"), + ("WARNING", "warning"), + ("CAUTION", "warning"), + ("note", "note"), + ("Warning", "warning"), + ], +) def test_admonition_tags(mark, tag): assert convert_schelp(f"> [!{mark}]\n> The text.\n") == f"{tag}::\nThe text.\n\n::\n" @@ -218,15 +230,18 @@ def test_insertion_point_inside_a_line_is_an_html_comment(): # ------------------------------------------------------------ inline tags -@pytest.mark.parametrize("markdown, expected", [ - ("**Note:** text.", "strong::Note: :: text."), - ("*Note:* text.", "emphasis::Note: :: text."), - ("Use `foo:` here.", "Use code::foo: :: here."), - ("Use `C:\\` here.", "Use code::C:\\ :: here."), - ("[Note:](https://example.com) text.", "link::https://example.com##Note: :: text."), - ("Math $a:$ here.", "Math math::a: :: here."), - ("Text.[^1]\n\n[^1]: Ends:", "Text.footnote::Ends: ::"), -]) +@pytest.mark.parametrize( + "markdown, expected", + [ + ("**Note:** text.", "strong::Note: :: text."), + ("*Note:* text.", "emphasis::Note: :: text."), + ("Use `foo:` here.", "Use code::foo: :: here."), + ("Use `C:\\` here.", "Use code::C:\\ :: here."), + ("[Note:](https://example.com) text.", "link::https://example.com##Note: :: text."), + ("Math $a:$ here.", "Math math::a: :: here."), + ("Text.[^1]\n\n[^1]: Ends:", "Text.footnote::Ends: ::"), + ], +) def test_inline_tag_with_a_colon_or_backslash_at_the_end_gets_a_space(markdown, expected): # SCDoc takes the character as part of the end-tag `::` assert convert_schelp(markdown + "\n") == expected + "\n" @@ -268,15 +283,19 @@ def test_quotation_marks_stay(): assert convert_schelp("He said \"it is 'fine' now\".\n") == "He said \"it is 'fine' now\".\n" -@pytest.mark.parametrize("markdown, schelp", [ - ("A word**bold**.\n", "A word\u2060strong::bold::.\n"), - ("A word*italic*.\n", "A word\u2060emphasis::italic::.\n"), - ("A word`code`.\n", "A word\u2060code::code::.\n"), - ("A word[link](https://example.com).\n", "A word\u2060link::https://example.com##link::.\n"), - ("A word$x$.\n", "A word\u2060math::x::.\n"), - ("A word[^1].\n\n[^1]: A note.\n", "A word footnote::A note.::.\n"), - ("A word **bold** and 2**bold**.\n", "A word strong::bold:: and 2strong::bold::.\n"), -], ids=["bold", "italic", "code", "link", "math", "footnote", "no letter before"]) +@pytest.mark.parametrize( + "markdown, schelp", + [ + ("A word**bold**.\n", "A word\u2060strong::bold::.\n"), + ("A word*italic*.\n", "A word\u2060emphasis::italic::.\n"), + ("A word`code`.\n", "A word\u2060code::code::.\n"), + ("A word[link](https://example.com).\n", "A word\u2060link::https://example.com##link::.\n"), + ("A word$x$.\n", "A word\u2060math::x::.\n"), + ("A word[^1].\n\n[^1]: A note.\n", "A word footnote::A note.::.\n"), + ("A word **bold** and 2**bold**.\n", "A word strong::bold:: and 2strong::bold::.\n"), + ], + ids=["bold", "italic", "code", "link", "math", "footnote", "no letter before"], +) def test_tag_directly_after_a_letter(markdown, schelp): # SCDoc takes letters directly before `::` as the name of a tag: a word joiner (U+2060), or a space before a # footnote, keeps the word and the tag apart diff --git a/tests/test_schelp_citations.py b/tests/test_schelp_citations.py index 8b1ce7b..e0a4020 100644 --- a/tests/test_schelp_citations.py +++ b/tests/test_schelp_citations.py @@ -3,6 +3,7 @@ becomes a footnote. The first citation of a source gives its reference entry, later citations the short form. A citation in a footnote gives the short form in parentheses. The tests that run pandoc are skipped without it. """ + from pathlib import Path import pytest @@ -11,45 +12,51 @@ BIBLIOGRAPHY = Path(__file__).parent / "schelp" / "citations.bib" DOE = "Doe, Jane. 1999. emphasis::Sound and Wood::. Acme" -SMITH = ("Smith, John, and Ann Lee. 2000. “Bars and Rods: A Study of Modes.” emphasis::Journal of Acoustics:: 3: " - "1–9. link::https://doi.org/10.1000/xyz::") +SMITH = ( + "Smith, John, and Ann Lee. 2000. “Bars and Rods: A Study of Modes.” emphasis::Journal of Acoustics:: 3: " + "1–9. link::https://doi.org/10.1000/xyz::" +) def schelp(markdown: str) -> str: return convert_schelp(markdown, bibliography=BIBLIOGRAPHY) -@pytest.mark.parametrize("citation, footnote", [ - ("[@doe1999]", DOE + "."), - ("[@doe1999, p. 30]", DOE + ", p. 30."), - ("[@doe1999, 30]", DOE + ", p. 30."), - ("[@doe1999, 30-35]", DOE + ", pp. 30–35."), - ("[@doe1999, chap. 2]", DOE + ", chap. 2."), - ("[-@doe1999]", DOE + "."), - ("[@doe1999; @smith2000]", DOE + "; " + SMITH + "."), -], ids=["key", "page", "page number", "pages", "other locator", "no author", "two sources"]) +@pytest.mark.parametrize( + "citation, footnote", + [ + ("[@doe1999]", DOE + "."), + ("[@doe1999, p. 30]", DOE + ", p. 30."), + ("[@doe1999, 30]", DOE + ", p. 30."), + ("[@doe1999, 30-35]", DOE + ", pp. 30–35."), + ("[@doe1999, chap. 2]", DOE + ", chap. 2."), + ("[-@doe1999]", DOE + "."), + ("[@doe1999; @smith2000]", DOE + "; " + SMITH + "."), + ], + ids=["key", "page", "page number", "pages", "other locator", "no author", "two sources"], +) def test_first_citation_gives_the_reference_entry(citation, footnote, pandoc): assert schelp(f"A text {citation}.\n") == f"A text footnote::{footnote}::.\n" def test_later_citation_gives_the_short_form(pandoc): out = schelp("One [@doe1999]. Two [@doe1999, 31]. Three [@smith2000; @doe1999].\n") - assert out == (f"One footnote::{DOE}.::. Two footnote::Doe 1999, 31.::. " - f"Three footnote::{SMITH}; Doe 1999.::.\n") + assert out == (f"One footnote::{DOE}.::. Two footnote::Doe 1999, 31.::. Three footnote::{SMITH}; Doe 1999.::.\n") def test_works_of_one_author_and_year_are_told_apart(pandoc): out = schelp("One [@doe1999]. Two [@doe1999b]. Again [@doe1999b].\n") - assert out == ("One footnote::Doe, Jane. 1999b. emphasis::Sound and Wood::. Acme.::. " - # the style writes `———` for the second work of an author in a list; a footnote names the - # author again - "Two footnote::Doe, Jane. 1999a. emphasis::More Wood::. Acme.::. Again footnote::Doe 1999a.::.\n") + assert out == ( + "One footnote::Doe, Jane. 1999b. emphasis::Sound and Wood::. Acme.::. " + # the style writes `———` for the second work of an author in a list; a footnote names the + # author again + "Two footnote::Doe, Jane. 1999a. emphasis::More Wood::. Acme.::. Again footnote::Doe 1999a.::.\n" + ) def test_citation_in_a_footnote_gives_the_short_form_in_parentheses(pandoc): out = schelp("Text.[^1] More [@smith2000].\n\n[^1]: As in [@doe1999, 30].\n\n And [@smith2000].\n") - assert out == ("Text.footnote::As in (Doe 1999, 30).\n\nAnd (Smith and Lee 2000).:: " - f"More footnote::{SMITH}.::.\n") + assert out == (f"Text.footnote::As in (Doe 1999, 30).\n\nAnd (Smith and Lee 2000).:: More footnote::{SMITH}.::.\n") def test_citation_directly_after_a_word(pandoc): @@ -98,8 +105,9 @@ def test_text_without_citations_does_not_need_the_bibliography(monkeypatch): def test_citation_without_a_bibliography_names_the_choices(): - with pytest.raises(UnsupportedConstruct, match="give a bibliography to the conversion, or write the citation " - "as text"): + with pytest.raises( + UnsupportedConstruct, match="give a bibliography to the conversion, or write the citation as text" + ): convert_schelp("A text [@doe1999].\n") diff --git a/tests/test_schelp_errors.py b/tests/test_schelp_errors.py index 9108ec4..5a2da0a 100644 --- a/tests/test_schelp_errors.py +++ b/tests/test_schelp_errors.py @@ -2,6 +2,7 @@ Markdown that has no schelp form stops the conversion: `convert_schelp` raises an error that holds the construct and its line, and `describe()` names the file too. Markdown that only looks like such a construct is accepted. """ + import re import pytest @@ -25,12 +26,15 @@ def test_error_names_the_file_and_the_line(): with pytest.raises(UnsupportedConstruct) as error: convert_schelp("Text.\n\n---\n") assert str(error.value) == "line 3: the schelp output cannot write this Markdown construct: horizontal rule" - assert error.value.describe("page.md") == \ - "page.md:3: the schelp output cannot write this Markdown construct: horizontal rule" + assert ( + error.value.describe("page.md") + == "page.md:3: the schelp output cannot write this Markdown construct: horizontal rule" + ) -@pytest.mark.parametrize("markdown, metadata, insertions, message", DOCUMENT_ERRORS, - ids=[m for *_, m in DOCUMENT_ERRORS]) +@pytest.mark.parametrize( + "markdown, metadata, insertions, message", DOCUMENT_ERRORS, ids=[m for *_, m in DOCUMENT_ERRORS] +) def test_document_error_stops_the_conversion(markdown, metadata, insertions, message): with pytest.raises((DocumentError, UnsupportedConstruct)) as error: convert_schelp(markdown, metadata, insertions) diff --git a/tests/test_schelp_golden.py b/tests/test_schelp_golden.py index f941cdc..d329ee6 100644 --- a/tests/test_schelp_golden.py +++ b/tests/test_schelp_golden.py @@ -2,6 +2,7 @@ The schelp output has not changed: every fixture in tests/schelp is converted and compared with the .schelp file next to it. """ + import pytest from schelp_fixtures import convert, fixtures, needs_pandoc diff --git a/tests/test_schelp_methods.py b/tests/test_schelp_methods.py index 3c1a01c..8ef9c3c 100644 --- a/tests/test_schelp_methods.py +++ b/tests/test_schelp_methods.py @@ -3,6 +3,7 @@ gives `METHOD::`, the rows of the argument table of a method give `ARGUMENT::` entries, and a `Returns:` paragraph gives `returns::`. The checks that stop the conversion are in schelp_cases.py. """ + import re import pytest @@ -28,15 +29,18 @@ def arguments(schelp: str) -> list: def test_method_with_an_argument_table_and_a_return_value(): out = methods("### *ar\n\n" + TABLE + "\nReturns: one channel.\n\n## Examples\n\nText.\n") - assert out == ("CLASSMETHODS::\n\nMETHOD::ar\n\n" - "ARGUMENT::freq\nThe frequency.\n\nARGUMENT::amp\nThe level.\n\n" - "returns::one channel.\n\nEXAMPLES::\n\nText.\n") + assert out == ( + "CLASSMETHODS::\n\nMETHOD::ar\n\n" + "ARGUMENT::freq\nThe frequency.\n\nARGUMENT::amp\nThe level.\n\n" + "returns::one channel.\n\nEXAMPLES::\n\nText.\n" + ) def test_methods_without_tables_and_text_before_the_first_method(): out = methods("Intro.\n\n### *ar, *kr\n\nText.\n\nReturns: two\nchannels.\n\n### *new\n\nMakes one.\n") - assert out == ("CLASSMETHODS::\n\nIntro.\n\nMETHOD::ar, kr\n\nText.\n\nreturns::two\nchannels.\n\n" - "METHOD::new\n\nMakes one.\n") + assert out == ( + "CLASSMETHODS::\n\nIntro.\n\nMETHOD::ar, kr\n\nText.\n\nreturns::two\nchannels.\n\nMETHOD::new\n\nMakes one.\n" + ) def test_text_of_a_method_comes_before_its_arguments(): @@ -47,8 +51,13 @@ def test_text_of_a_method_comes_before_its_arguments(): def test_two_methods_with_tables(): out = methods("### *ar\n\n" + TABLE + "\n### *kr\n\n" + TABLE.replace("freq", "rate")) assert re.findall(r"^(METHOD|ARGUMENT)::(.*)$", out, re.M) == [ - ("METHOD", "ar"), ("ARGUMENT", "freq"), ("ARGUMENT", "amp"), - ("METHOD", "kr"), ("ARGUMENT", "rate"), ("ARGUMENT", "amp")] + ("METHOD", "ar"), + ("ARGUMENT", "freq"), + ("ARGUMENT", "amp"), + ("METHOD", "kr"), + ("ARGUMENT", "rate"), + ("ARGUMENT", "amp"), + ] def test_section_heading_is_not_case_sensitive(): @@ -61,10 +70,18 @@ def test_next_level_2_heading_ends_the_section(): assert "SECTION::More\n\nReturns: text, as it is not in a method." in out -@pytest.mark.parametrize("heading, names", [ - ("### *ar", "ar"), ("### *ar, *kr", "ar, kr"), ("### *ar,*kr", "ar, kr"), ("### *ar , *kr ", "ar, kr"), - ("### *new_2", "new_2"), ("### *ar, *kr, *new", "ar, kr, new"), -], ids=["one name", "two names", "no space", "more spaces", "underscore and digit", "three names"]) +@pytest.mark.parametrize( + "heading, names", + [ + ("### *ar", "ar"), + ("### *ar, *kr", "ar, kr"), + ("### *ar,*kr", "ar, kr"), + ("### *ar , *kr ", "ar, kr"), + ("### *new_2", "new_2"), + ("### *ar, *kr, *new", "ar, kr, new"), + ], + ids=["one name", "two names", "no space", "more spaces", "underscore and digit", "three names"], +) def test_method_headings(heading, names): assert f"METHOD::{names}\n" in methods(heading + "\n\nText.\n") @@ -72,21 +89,35 @@ def test_method_headings(heading, names): # ---------------------------------------------------- forms of the argument table -@pytest.mark.parametrize("table", [ - TABLE, - "Argument | Text\n---|---\nfreq | The frequency.\namp | The level.\n", - "| Argument | Text\n|---|---\n| freq | The frequency.\n| amp | The level.\n", - "Argument | Text |\n---|---|\nfreq | The frequency. |\namp | The level. |\n", - "| Argument | Text |\n---|---\nfreq | The frequency. |\n| amp | The level.\n", - "|Argument|Text|\n|-|-|\n|freq|The frequency.|\n|amp|The level.|\n", - "| Argument | Text |\n|:---|---:|\n| freq | The frequency. |\n| amp | The level. |\n", - "| Argument | Text |\n| :---: | :-- |\n| freq | The frequency. |\n| amp | The level. |\n", - " | Argument | Text |\n |---|---|\n | freq | The frequency. |\n | amp | The level. |\n", - "| Argument | Text |\n|---|---|\n|\tfreq\t| The frequency. |\n| amp | The level. | \n", - "| `Argument` | **Text** |\n|---|---|\n| freq | The frequency. |\n| amp | The level. |\n", -], ids=["outer pipes", "no outer pipes", "leading pipes only", "trailing pipes only", "mixed pipes", - "no spaces", "alignment colons", "spaces in the delimiter row", "indent of 3", "spaces and tabs", - "markup in the header"]) +@pytest.mark.parametrize( + "table", + [ + TABLE, + "Argument | Text\n---|---\nfreq | The frequency.\namp | The level.\n", + "| Argument | Text\n|---|---\n| freq | The frequency.\n| amp | The level.\n", + "Argument | Text |\n---|---|\nfreq | The frequency. |\namp | The level. |\n", + "| Argument | Text |\n---|---\nfreq | The frequency. |\n| amp | The level.\n", + "|Argument|Text|\n|-|-|\n|freq|The frequency.|\n|amp|The level.|\n", + "| Argument | Text |\n|:---|---:|\n| freq | The frequency. |\n| amp | The level. |\n", + "| Argument | Text |\n| :---: | :-- |\n| freq | The frequency. |\n| amp | The level. |\n", + " | Argument | Text |\n |---|---|\n | freq | The frequency. |\n | amp | The level. |\n", + "| Argument | Text |\n|---|---|\n|\tfreq\t| The frequency. |\n| amp | The level. | \n", + "| `Argument` | **Text** |\n|---|---|\n| freq | The frequency. |\n| amp | The level. |\n", + ], + ids=[ + "outer pipes", + "no outer pipes", + "leading pipes only", + "trailing pipes only", + "mixed pipes", + "no spaces", + "alignment colons", + "spaces in the delimiter row", + "indent of 3", + "spaces and tabs", + "markup in the header", + ], +) def test_forms_of_the_table_give_the_same_arguments(table): assert arguments(methods("### *ar\n\n" + table)) == ARGUMENTS @@ -98,10 +129,17 @@ def test_table_directly_after_a_paragraph_line(): assert arguments(out) == ARGUMENTS -@pytest.mark.parametrize("after", ["\n## Examples\n", "## Examples\n", "\nReturns: x.\n", "\n### *kr\n", - "### *kr\n"], - ids=["section after an empty line", "section directly after", "return value", - "method after an empty line", "method directly after"]) +@pytest.mark.parametrize( + "after", + ["\n## Examples\n", "## Examples\n", "\nReturns: x.\n", "\n### *kr\n", "### *kr\n"], + ids=[ + "section after an empty line", + "section directly after", + "return value", + "method after an empty line", + "method directly after", + ], +) def test_what_can_follow_the_table(after): assert arguments(methods("### *ar\n\n" + TABLE + after)) == ARGUMENTS @@ -121,35 +159,55 @@ def test_argument_names_with_underscores_and_digits(name): assert arguments(out) == [(name, "A.")] -@pytest.mark.parametrize("cell, text", [ - ("Uses `In.ar`.", "Uses code::In.ar::."), - ("A **loud** sound.", "A strong::loud:: sound."), - ("An *odd* one.", "An emphasis::odd:: one."), - ("See [SinOsc](sc:Classes/SinOsc).", "See link::Classes/SinOsc::."), - ("See [the site](https://example.com).", "See link::https://example.com##the site::."), - ("One \\| two.", "One | two."), - ("Code `a \\| b`.", "Code code::a | b::."), - ("A \\|\\| B.", "A \\|| B."), - ("Tag:: and ## here.", "Tag\\:: and \\## here."), - ("> 0 is on.", "> 0 is on."), - ("- 1 is off.", "- 1 is off."), - ("1. is first.", "1. is first."), - ("# is a sign.", "# is a sign."), - ("−1 to 1, ≥ 0.5.", "−1 to 1, ≥ 0.5."), - ("Math $x^2$.", "Math math::x^2::."), -], ids=["code", "bold", "italic", "sc link", "web link", "escaped pipe", "escaped pipe in code", - "two escaped pipes", "schelp marks", "quote mark", "list mark", "number mark", "heading mark", - "not ASCII", "math"]) +@pytest.mark.parametrize( + "cell, text", + [ + ("Uses `In.ar`.", "Uses code::In.ar::."), + ("A **loud** sound.", "A strong::loud:: sound."), + ("An *odd* one.", "An emphasis::odd:: one."), + ("See [SinOsc](sc:Classes/SinOsc).", "See link::Classes/SinOsc::."), + ("See [the site](https://example.com).", "See link::https://example.com##the site::."), + ("One \\| two.", "One | two."), + ("Code `a \\| b`.", "Code code::a | b::."), + ("A \\|\\| B.", "A \\|| B."), + ("Tag:: and ## here.", "Tag\\:: and \\## here."), + ("> 0 is on.", "> 0 is on."), + ("- 1 is off.", "- 1 is off."), + ("1. is first.", "1. is first."), + ("# is a sign.", "# is a sign."), + ("−1 to 1, ≥ 0.5.", "−1 to 1, ≥ 0.5."), + ("Math $x^2$.", "Math math::x^2::."), + ], + ids=[ + "code", + "bold", + "italic", + "sc link", + "web link", + "escaped pipe", + "escaped pipe in code", + "two escaped pipes", + "schelp marks", + "quote mark", + "list mark", + "number mark", + "heading mark", + "not ASCII", + "math", + ], +) def test_text_of_an_argument(cell, text): out = methods(f"### *ar\n\n| Argument | Text |\n|---|---|\n| x | {cell} |\n") assert arguments(out) == [("x", text)] def test_columns_between_the_name_and_the_text(): - table = ("| Argument | Range | Unit | Text |\n|---|---|---|---|\n" - "| freq | 20 to 20000 | Hz | The frequency. |\n" - "| amp | | | The level. |\n" - "| pan | −1 to 1 | | The position. |\n") + table = ( + "| Argument | Range | Unit | Text |\n|---|---|---|---|\n" + "| freq | 20 to 20000 | Hz | The frequency. |\n" + "| amp | | | The level. |\n" + "| pan | −1 to 1 | | The position. |\n" + ) assert arguments(methods("### *ar\n\n" + table)) == [ ("freq", "The frequency.\nRange: 20 to 20000\nUnit: Hz"), ("amp", "The level."), @@ -165,21 +223,29 @@ def test_markup_in_the_other_columns(): # ------------------------------------------------------------- the return value -@pytest.mark.parametrize("paragraph, returns", [ - ("Returns: one channel.", "returns::one channel."), - ("Returns:one channel.", "returns::one channel."), - ("Returns: an `Array`, two\nchannels.", "returns::an code::Array::, two\nchannels."), -], ids=["one line", "no space", "markup and two lines"]) +@pytest.mark.parametrize( + "paragraph, returns", + [ + ("Returns: one channel.", "returns::one channel."), + ("Returns:one channel.", "returns::one channel."), + ("Returns: an `Array`, two\nchannels.", "returns::an code::Array::, two\nchannels."), + ], + ids=["one line", "no space", "markup and two lines"], +) def test_return_value(paragraph, returns): assert returns in methods("### *ar\n\n" + TABLE + "\n" + paragraph + "\n") -@pytest.mark.parametrize("markdown", [ - "## Class methods\n\nReturns: before a method.\n", - "## Description\n\nReturns: in another section.\n", - "## Class methods\n\n### *ar\n\nThe text. Returns: in a paragraph.\n", - "## Class methods\n\n### *ar\n\nThe text.\nReturns: on the second line of a paragraph.\n", -], ids=["before a method", "in another section", "in the text", "second line of a paragraph"]) +@pytest.mark.parametrize( + "markdown", + [ + "## Class methods\n\nReturns: before a method.\n", + "## Description\n\nReturns: in another section.\n", + "## Class methods\n\n### *ar\n\nThe text. Returns: in a paragraph.\n", + "## Class methods\n\n### *ar\n\nThe text.\nReturns: on the second line of a paragraph.\n", + ], + ids=["before a method", "in another section", "in the text", "second line of a paragraph"], +) def test_returns_that_is_text(markdown): out = convert_schelp(markdown) assert "returns::" not in out @@ -190,17 +256,18 @@ def test_returns_that_is_text(markdown): def test_instance_methods_section(): - out = convert_schelp("## Instance methods\n\n### -play, -stop\n\nPlays it.\n\n" + TABLE - + "\nReturns: this.\n") - assert out == ("INSTANCEMETHODS::\n\nMETHOD::play, stop\n\nPlays it.\n\n" - "ARGUMENT::freq\nThe frequency.\n\nARGUMENT::amp\nThe level.\n\nreturns::this.\n") + out = convert_schelp("## Instance methods\n\n### -play, -stop\n\nPlays it.\n\n" + TABLE + "\nReturns: this.\n") + assert out == ( + "INSTANCEMETHODS::\n\nMETHOD::play, stop\n\nPlays it.\n\n" + "ARGUMENT::freq\nThe frequency.\n\nARGUMENT::amp\nThe level.\n\nreturns::this.\n" + ) def test_both_methods_sections(): - out = convert_schelp("## Class methods\n\n### *new\n\nMakes one.\n\n" - "## Instance methods\n\n### -free\n\nFrees it.\n") - assert out == ("CLASSMETHODS::\n\nMETHOD::new\n\nMakes one.\n\n" - "INSTANCEMETHODS::\n\nMETHOD::free\n\nFrees it.\n") + out = convert_schelp( + "## Class methods\n\n### *new\n\nMakes one.\n\n## Instance methods\n\n### -free\n\nFrees it.\n" + ) + assert out == ("CLASSMETHODS::\n\nMETHOD::new\n\nMakes one.\n\nINSTANCEMETHODS::\n\nMETHOD::free\n\nFrees it.\n") def test_instance_method_heading_outside_a_methods_section_is_a_heading(): @@ -210,8 +277,11 @@ def test_instance_method_heading_outside_a_methods_section_is_a_heading(): # ------------------------------------------------------------------ the discussion -@pytest.mark.parametrize("before", ["", TABLE + "\n", "Returns: x.\n\n", TABLE + "\nReturns: x.\n\n"], - ids=["after the text", "after the table", "after the return value", "after both"]) +@pytest.mark.parametrize( + "before", + ["", TABLE + "\n", "Returns: x.\n\n", TABLE + "\nReturns: x.\n\n"], + ids=["after the text", "after the table", "after the return value", "after both"], +) def test_discussion(before): out = methods("### *ar\n\nText.\n\n" + before + "#### Discussion\n\nMore text.\n\n```\nx = 1;\n```\n") assert out.endswith("discussion::\n\nMore text.\n\ncode::\nx = 1;\n::\n") @@ -219,8 +289,10 @@ def test_discussion(before): def test_discussion_can_hold_any_text(): - out = methods("### *ar\n\n" + TABLE + "\n#### discussion\n\nReturns: text here.\n\n- A list.\n\n" - "> [!NOTE]\n> A note.\n\n### *kr\n\nText.\n") + out = methods( + "### *ar\n\n" + TABLE + "\n#### discussion\n\nReturns: text here.\n\n- A list.\n\n" + "> [!NOTE]\n> A note.\n\n### *kr\n\nText.\n" + ) assert "discussion::\n\nReturns: text here.\n\nLIST::\n## A list.\n::" in out assert out.count("returns::") == 0 assert "METHOD::kr" in out diff --git a/tests/test_schelp_render.py b/tests/test_schelp_render.py index 17d6b16..b234021 100644 --- a/tests/test_schelp_render.py +++ b/tests/test_schelp_render.py @@ -5,6 +5,7 @@ All versions of sclang must parse the output with no error and give the expected parts of the pages. Only the version that made the .html files must give the same whole pages. """ + import re import pytest diff --git a/tests/test_schelp_tables.py b/tests/test_schelp_tables.py index 98cd168..0c683ee 100644 --- a/tests/test_schelp_tables.py +++ b/tests/test_schelp_tables.py @@ -2,34 +2,51 @@ Tables outside the methods sections: a pipe table of GitHub Flavored Markdown gives `table::`. SCDoc has no header row, thus the header row is a first row in bold. The checks that stop the conversion are in schelp_cases.py. """ + import pytest from md2misc import convert, convert_schelp -@pytest.mark.parametrize("markdown, schelp", [ - ("| A | B |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n", - "table::\n## strong::A:: || strong::B::\n## 1 || 2\n## 3 || 4\n::\n"), - ("| | |\n|---|---|\n| 1 | 2 |\n", "table::\n## 1 || 2\n::\n"), - ("| A | |\n|---|---|\n| 1 | 2 |\n", "table::\n## strong::A:: ||\n## 1 || 2\n::\n"), - ("| A | B |\n|---|---|\n| 1 |\n", "table::\n## strong::A:: || strong::B::\n## 1 ||\n::\n"), - ("A | B\n:-:|--:\n1 | 2\n", "table::\n## strong::A:: || strong::B::\n## 1 || 2\n::\n"), - ("| A |\n|---|\n| 1 |\n", "table::\n## strong::A::\n## 1\n::\n"), -], ids=["header and rows", "empty header row", "empty header cell", "short row", "no outer pipes and alignment", - "one column"]) +@pytest.mark.parametrize( + "markdown, schelp", + [ + ( + "| A | B |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n", + "table::\n## strong::A:: || strong::B::\n## 1 || 2\n## 3 || 4\n::\n", + ), + ("| | |\n|---|---|\n| 1 | 2 |\n", "table::\n## 1 || 2\n::\n"), + ("| A | |\n|---|---|\n| 1 | 2 |\n", "table::\n## strong::A:: ||\n## 1 || 2\n::\n"), + ("| A | B |\n|---|---|\n| 1 |\n", "table::\n## strong::A:: || strong::B::\n## 1 ||\n::\n"), + ("A | B\n:-:|--:\n1 | 2\n", "table::\n## strong::A:: || strong::B::\n## 1 || 2\n::\n"), + ("| A |\n|---|\n| 1 |\n", "table::\n## strong::A::\n## 1\n::\n"), + ], + ids=[ + "header and rows", + "empty header row", + "empty header cell", + "short row", + "no outer pipes and alignment", + "one column", + ], +) def test_table(markdown, schelp): assert convert_schelp(markdown) == schelp -@pytest.mark.parametrize("cell, text", [ - ("Uses `In.ar`.", "Uses code::In.ar::."), - ("A **loud** sound.", "A strong::loud:: sound."), - ("See [SinOsc](sc:Classes/SinOsc).", "See link::Classes/SinOsc::."), - ("One \\| two.", "One | two."), - ("Code `a \\| b`.", "Code code::a | b::."), - ("A \\|\\| B and ## C.", "A \\|| B and \\## C."), - ("Math $x^2$.", "Math math::x^2::."), -], ids=["code", "bold", "link", "escaped pipe", "escaped pipe in code", "schelp marks", "math"]) +@pytest.mark.parametrize( + "cell, text", + [ + ("Uses `In.ar`.", "Uses code::In.ar::."), + ("A **loud** sound.", "A strong::loud:: sound."), + ("See [SinOsc](sc:Classes/SinOsc).", "See link::Classes/SinOsc::."), + ("One \\| two.", "One | two."), + ("Code `a \\| b`.", "Code code::a | b::."), + ("A \\|\\| B and ## C.", "A \\|| B and \\## C."), + ("Math $x^2$.", "Math math::x^2::."), + ], + ids=["code", "bold", "link", "escaped pipe", "escaped pipe in code", "schelp marks", "math"], +) def test_markup_in_a_cell(cell, text): assert convert_schelp(f"| A |\n|---|\n| {cell} |\n") == f"table::\n## strong::A::\n## {text}\n::\n" diff --git a/tests/test_schelp_writer.py b/tests/test_schelp_writer.py index a8fa76a..c10afff 100644 --- a/tests/test_schelp_writer.py +++ b/tests/test_schelp_writer.py @@ -2,6 +2,7 @@ The writers of the schelp backend stop at the constructs that have no schelp form, too, if the check of the Markdown source does not find them first. The error has no line then. """ + import pytest from md2misc import convert_schelp diff --git a/tests/test_tables.py b/tests/test_tables.py index 3a3af48..1dfa0b2 100644 --- a/tests/test_tables.py +++ b/tests/test_tables.py @@ -3,6 +3,7 @@ table ends. The expected values are those of cmark-gfm 0.29.0.gfm.13, the GitHub Flavored Markdown parser of GitHub, where the comments do not say otherwise (checked on 2026-11-17). """ + import pytest from md2misc import tables @@ -15,70 +16,112 @@ def table(markdown: str): if tables.starts_table(lines, number): header = tables.split_row(lines[number]) rows = [header] - for row in lines[number + 2:tables.table_end(lines, number)]: + for row in lines[number + 2 : tables.table_end(lines, number)]: cells = tables.split_row(row) rows.append(cells + [""] * (len(header) - len(cells))) return rows return None -@pytest.mark.parametrize("markdown, rows", [ - ("| a | b |\n|---|---|\n| 1 | 2 |\n", [["a", "b"], ["1", "2"]]), - ("a | b\n---|---\n1 | 2\n", [["a", "b"], ["1", "2"]]), - ("| a | b\n|--|--\n| 1 | 2\n", [["a", "b"], ["1", "2"]]), - ("a | b |\n--|--|\n1 | 2 |\n", [["a", "b"], ["1", "2"]]), - ("| abc | defghi |\n:-: | -----------:\nbar | baz\n", [["abc", "defghi"], ["bar", "baz"]]), - ("|a|b|\n|-|-|\n|1|2|\n", [["a", "b"], ["1", "2"]]), - ("|a|b|c|d|\n|:--|:-:|--:|---|\n|1|2|3|4|\n", [["a", "b", "c", "d"], ["1", "2", "3", "4"]]), - ("|a|b|\n| :---: | ---: |\n|1|2|\n", [["a", "b"], ["1", "2"]]), - ("|a|b| \n|-|-| \n|1|2| \n", [["a", "b"], ["1", "2"]]), - (" |a|b|\n |-|-|\n |1|2|\n", [["a", "b"], ["1", "2"]]), -], ids=["outer pipes", "no outer pipes", "leading pipes only", "trailing pipes only", "mixed outer pipes", - "one hyphen", "alignment", "spaces around delimiter cells", "trailing spaces", "indent of 3"]) +@pytest.mark.parametrize( + "markdown, rows", + [ + ("| a | b |\n|---|---|\n| 1 | 2 |\n", [["a", "b"], ["1", "2"]]), + ("a | b\n---|---\n1 | 2\n", [["a", "b"], ["1", "2"]]), + ("| a | b\n|--|--\n| 1 | 2\n", [["a", "b"], ["1", "2"]]), + ("a | b |\n--|--|\n1 | 2 |\n", [["a", "b"], ["1", "2"]]), + ("| abc | defghi |\n:-: | -----------:\nbar | baz\n", [["abc", "defghi"], ["bar", "baz"]]), + ("|a|b|\n|-|-|\n|1|2|\n", [["a", "b"], ["1", "2"]]), + ("|a|b|c|d|\n|:--|:-:|--:|---|\n|1|2|3|4|\n", [["a", "b", "c", "d"], ["1", "2", "3", "4"]]), + ("|a|b|\n| :---: | ---: |\n|1|2|\n", [["a", "b"], ["1", "2"]]), + ("|a|b| \n|-|-| \n|1|2| \n", [["a", "b"], ["1", "2"]]), + (" |a|b|\n |-|-|\n |1|2|\n", [["a", "b"], ["1", "2"]]), + ], + ids=[ + "outer pipes", + "no outer pipes", + "leading pipes only", + "trailing pipes only", + "mixed outer pipes", + "one hyphen", + "alignment", + "spaces around delimiter cells", + "trailing spaces", + "indent of 3", + ], +) def test_forms_of_a_table(markdown, rows): assert table(markdown) == rows -@pytest.mark.parametrize("markdown", [ - "|a|b|\n|- -|---|\n|1|2|\n", - "|a|b|\n|:|---|\n", - "|a|b|\n|=|=|\n", - "|a|b|\n|-||\n", - "|a|\n---\n|1|\n", - " |a|b|\n |-|-|\n |1|2|\n", - "|a|b|\n |-|-|\n|1|2|\n", - "|a|b|\n\n|-|-|\n|1|2|\n", - "| a | b |\n| --- \\|| --- |\n", - "- a | b\n- c | d\n", - "a | b\n--- ---\n", - "Text without a pipe.\n---|---\n", -], ids=["space in a delimiter cell", "colon only", "equals signs", "empty delimiter cell", - "delimiter row without a pipe (a heading)", "indent of 4 (code)", "delimiter row with an indent of 4", - "empty line after the header", "escaped pipe in the delimiter row", "list items with pipes", - "delimiter row without pipes", "header without a pipe"]) +@pytest.mark.parametrize( + "markdown", + [ + "|a|b|\n|- -|---|\n|1|2|\n", + "|a|b|\n|:|---|\n", + "|a|b|\n|=|=|\n", + "|a|b|\n|-||\n", + "|a|\n---\n|1|\n", + " |a|b|\n |-|-|\n |1|2|\n", + "|a|b|\n |-|-|\n|1|2|\n", + "|a|b|\n\n|-|-|\n|1|2|\n", + "| a | b |\n| --- \\|| --- |\n", + "- a | b\n- c | d\n", + "a | b\n--- ---\n", + "Text without a pipe.\n---|---\n", + ], + ids=[ + "space in a delimiter cell", + "colon only", + "equals signs", + "empty delimiter cell", + "delimiter row without a pipe (a heading)", + "indent of 4 (code)", + "delimiter row with an indent of 4", + "empty line after the header", + "escaped pipe in the delimiter row", + "list items with pipes", + "delimiter row without pipes", + "header without a pipe", + ], +) def test_not_a_table(markdown): assert table(markdown) is None -@pytest.mark.parametrize("markdown, rows", [ - ("|a|\n|---|\n|1|\n", [["a"], ["1"]]), - ("a |\n--|\n1 |\n", [["a"], ["1"]]), - ("| a\n|--\n| 1\n", [["a"], ["1"]]), - ("||\n|-|\n|1|\n", [[""], ["1"]]), -], ids=["outer pipes", "trailing pipes", "leading pipes", "empty header"]) +@pytest.mark.parametrize( + "markdown, rows", + [ + ("|a|\n|---|\n|1|\n", [["a"], ["1"]]), + ("a |\n--|\n1 |\n", [["a"], ["1"]]), + ("| a\n|--\n| 1\n", [["a"], ["1"]]), + ("||\n|-|\n|1|\n", [[""], ["1"]]), + ], + ids=["outer pipes", "trailing pipes", "leading pipes", "empty header"], +) def test_one_column(markdown, rows): assert table(markdown) == rows -@pytest.mark.parametrize("markdown, rows", [ - ("|a|b|\n|-|-|\n", [["a", "b"]]), - ("|a|b|\n|-|-|\n|1|\n", [["a", "b"], ["1", ""]]), - ("|a|b|\n|-|-|\n||2|\n|1||\n", [["a", "b"], ["", "2"], ["1", ""]]), - ("| a | b |\n|-|-|\n| 1 |\t2\t|\n", [["a", "b"], ["1", "2"]]), - ("| | |\n|-|-|\n|1|2|\n", [["", ""], ["1", "2"]]), - ("| name | range |\n|---|---|\n| pan | −1 to 1 |\n", [["name", "range"], ["pan", "−1 to 1"]]), -], ids=["header only", "short row padded", "empty cells", "spaces and tabs trimmed", "empty header cells", - "text that is not ASCII"]) +@pytest.mark.parametrize( + "markdown, rows", + [ + ("|a|b|\n|-|-|\n", [["a", "b"]]), + ("|a|b|\n|-|-|\n|1|\n", [["a", "b"], ["1", ""]]), + ("|a|b|\n|-|-|\n||2|\n|1||\n", [["a", "b"], ["", "2"], ["1", ""]]), + ("| a | b |\n|-|-|\n| 1 |\t2\t|\n", [["a", "b"], ["1", "2"]]), + ("| | |\n|-|-|\n|1|2|\n", [["", ""], ["1", "2"]]), + ("| name | range |\n|---|---|\n| pan | −1 to 1 |\n", [["name", "range"], ["pan", "−1 to 1"]]), + ], + ids=[ + "header only", + "short row padded", + "empty cells", + "spaces and tabs trimmed", + "empty header cells", + "text that is not ASCII", + ], +) def test_cells(markdown, rows): assert table(markdown) == rows @@ -99,12 +142,16 @@ def test_delimiter_row_with_another_number_of_cells_starts_a_table(): assert table("|a|b|\n|---|---|---|\n|1|2|\n") == [["a", "b"], ["1", "2"]] -@pytest.mark.parametrize("row, cells", [ - ("|x\\|y|2|", ["x\\|y", "2"]), - ("|`x\\|y`|2|", ["`x\\|y`", "2"]), - ("|1|2\\|", ["1", "2\\|"]), - ("|`x|y`|2|", ["`x", "y`", "2"]), -], ids=["escaped pipe", "escaped pipe in code", "escaped pipe at the end", "pipe in code splits the cell"]) +@pytest.mark.parametrize( + "row, cells", + [ + ("|x\\|y|2|", ["x\\|y", "2"]), + ("|`x\\|y`|2|", ["`x\\|y`", "2"]), + ("|1|2\\|", ["1", "2\\|"]), + ("|`x|y`|2|", ["`x", "y`", "2"]), + ], + ids=["escaped pipe", "escaped pipe in code", "escaped pipe at the end", "pipe in code splits the cell"], +) def test_split_row_with_pipes_in_cells(row, cells): assert tables.split_row(row) == cells @@ -114,9 +161,20 @@ def test_unescape_gives_the_pipe(): assert tables.unescape("`x\\|y`") == "`x|y`" -@pytest.mark.parametrize("after", ["", "\n\nnext", "\n# H", "\n> q", "\n```\nx\n```", "\n- x", "\n1. x", "\n***"], - ids=["end of the text", "empty line", "heading", "block quote", "code block", "list", - "numbered list", "horizontal rule"]) +@pytest.mark.parametrize( + "after", + ["", "\n\nnext", "\n# H", "\n> q", "\n```\nx\n```", "\n- x", "\n1. x", "\n***"], + ids=[ + "end of the text", + "empty line", + "heading", + "block quote", + "code block", + "list", + "numbered list", + "horizontal rule", + ], +) def test_end_of_a_table(after): lines = ("|a|b|\n|-|-|\n|1|2|" + after).split("\n") assert tables.table_end(lines, 0) == 3 @@ -132,11 +190,15 @@ def test_second_delimiter_row_is_a_row(): assert table("|a|b|\n|-|-|\n|1|2|\n|-|-|\n") == [["a", "b"], ["1", "2"], ["-", "-"]] -@pytest.mark.parametrize("markdown, header", [ - ("para\n|a|b|\n|-|-|\n|1|2|\n", 1), - ("p1\np2\n|a|b|\n|-|-|\n", 2), - ("|a|\n|b|\n|-|\n", 1), -], ids=["after a paragraph line", "after two paragraph lines", "only one header row"]) +@pytest.mark.parametrize( + "markdown, header", + [ + ("para\n|a|b|\n|-|-|\n|1|2|\n", 1), + ("p1\np2\n|a|b|\n|-|-|\n", 2), + ("|a|\n|b|\n|-|\n", 1), + ], + ids=["after a paragraph line", "after two paragraph lines", "only one header row"], +) def test_header_is_the_line_before_the_delimiter_row(markdown, header): lines = markdown.split("\n") assert [n for n in range(len(lines)) if tables.starts_table(lines, n)] == [header] diff --git a/tests/test_tex_battery.py b/tests/test_tex_battery.py index 2617c89..9e1db8a 100644 --- a/tests/test_tex_battery.py +++ b/tests/test_tex_battery.py @@ -3,6 +3,7 @@ .tex file that md2tex wrote for it. name@variant.tex is the Markdown of name.md with the convert() arguments from name@variant.args. See battery.py for how the fixtures are made. """ + import json import pytest diff --git a/tests/test_tex_library.py b/tests/test_tex_library.py index 6ef330a..8212d14 100644 --- a/tests/test_tex_library.py +++ b/tests/test_tex_library.py @@ -1,6 +1,7 @@ """ The TeX backend as a library: the arguments of `convert`, the default template, the warnings and the errors. """ + import subprocess import sys from pathlib import Path @@ -36,8 +37,9 @@ def test_unnumbered_headings(): def test_override_language_gives_every_code_block_the_language(): markdown = "```python\nx = 1\n```\n" assert "\\begin{minted}{python}" in convert(markdown) - assert "\\begin{minted}{supercollider}" in convert(markdown, minted_language="supercollider", - override_language=True) + assert "\\begin{minted}{supercollider}" in convert( + markdown, minted_language="supercollider", override_language=True + ) def test_default_template_has_the_tokens_for_the_body_and_the_document_class():