diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cec8c0..50a6c45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,22 @@ All important changes to md2misc are in this file. The format is from [Keep a Ch ## [Unreleased] +## [0.5.0] - 2026-11-30 + ### Changed - md2misc needs Python 3.12 or later. - The build backend is `uv_build` in place of setuptools. A build from source needs it. +- TeX: a badly formed citation, such as `[@doe1999 p. 3]`, stops the conversion with `ParsingException`. Before, `md2misc` dropped the rest of the citation or wrote it as a key. + +### Fixed + +- TeX: a citation no longer loses its locator without a message, for example `p.106`, `p. 121-122`, a range with an en dash, `chap. 2` or text after the page number. +- TeX: in a citation of more than one source, each locator goes with its source (`\parencites[p. 3]{a}{b}`). A `-` before a key gives a warning and is ignored there. +- TeX: `[@ doe]` and `[@,]` stop with a message in place of a `TypeError`. +- TeX: a citation key with `_`, `&` or `$` is written as it is. Before, it had a TeX escape, and `biblatex` did not find it. +- TeX: a `$` that is not part of math is written as `\$`. Before, it gave a line break and an `&`. +- TeX and schelp: in a text with no final newline, an unordered list at the end kept only a part of its lines. ## [0.4.0] - 2026-11-18 @@ -64,7 +76,8 @@ The first release of md2misc, which is derived from [md2tex](https://github.com/ - The package and the command have the name md2misc. The function `convert` writes the same TeX as md2tex, with one difference: a `#` followed at once by an escaped character is a heading. -[Unreleased]: https://github.com/aeskildsen/md2misc/compare/v0.4.0...HEAD +[Unreleased]: https://github.com/aeskildsen/md2misc/compare/v0.5.0...HEAD +[0.5.0]: https://github.com/aeskildsen/md2misc/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/aeskildsen/md2misc/compare/v0.3.0...v0.4.0 [0.3.0]: https://github.com/aeskildsen/md2misc/compare/v0.2.0...v0.3.0 [0.2.0]: https://github.com/aeskildsen/md2misc/compare/v0.1.0...v0.2.0 diff --git a/DEVELOPING.md b/DEVELOPING.md index 2bb596a..1d7d4a8 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -74,6 +74,9 @@ The tests of the citations run `pandoc`. They are skipped if `pandoc` is not on - `tests/test_schelp_tables.py`: the tables outside the methods sections. - `tests/test_schelp_citations.py`: the citations, with the bibliography `tests/schelp/citations.bib`. - `tests/test_tables.py`: the rows of a pipe table (`md2misc/tables.py`): which lines are a table, the cells and the end of the table. The expected values are those of cmark-gfm, the GFM parser of GitHub, where a comment does not say otherwise. +- `tests/test_tex_citations.py`: the citations in the TeX output: the locators, more than one source, the keys and the badly formed citations. +- `tests/test_tex_escapes.py`: the characters of the text that have a special meaning in TeX. +- `tests/test_lists.py`: the lists at the end of a text, in both outputs. - `tests/test_tex_library.py`: the arguments of `convert`, the default template, the warnings and the errors of the TeX backend, and that the package needs only the standard library. ### Fixture tools diff --git a/README.md b/README.md index 50c86bf..765c972 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ Warnings have the category `md2misc.Md2miscWarning`. Use the `warnings` module t ## Origin -`md2misc` is derived from [`md2tex`](https://github.com/paulhectork/md2tex) by Paul Kervegan. The full history of `md2tex`, with the commits of both authors, is part of the git history of this repository. The TeX output is meant to stay identical to the output of `md2tex`. See `NOTICE`. +`md2misc` is derived from [`md2tex`](https://github.com/paulhectork/md2tex) by Paul Kervegan. The full history of `md2tex`, with the commits of both authors, is part of the git history of this repository. The TeX output is meant to stay identical to the output of `md2tex`, except where `md2tex` is wrong (see [docs/design.md](docs/design.md#behaviour-kept-from-md2tex)). See `NOTICE`. ## Documentation diff --git a/docs/design.md b/docs/design.md index 877de3c..485670a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -7,7 +7,11 @@ ## Behaviour kept from md2tex -The TeX output stays the same as the output of md2tex. Thus `TeXBackend.remove_quote_marks()` turns every `>` into a space, so a `
` tag is never found. One known difference exists: a `#` followed at once by an escaped character (`#_x`) is a heading in md2misc, and text in md2tex. +The TeX output stays the same as the output of md2tex. Thus `TeXBackend.remove_quote_marks()` turns every `>` into a space, so a `
` tag is never found. The known differences are: + +- A `#` followed at once by an escaped character (`#_x`) is a heading in md2misc, and text in md2tex. +- Citations: md2tex drops the parts of a citation that it does not read, and writes a locator in a citation of more than one source as a key. md2misc writes these parts, or stops the conversion (see [tex.md](tex.md#citations)). +- md2tex writes a `$` that is not part of math as `\\\&`, writes a citation key with `_`, `&` or `$` with a TeX escape, and needs a final newline to find the last lines of an unordered list. ## Constructs without a schelp form diff --git a/docs/tex.md b/docs/tex.md index 7f6cee7..ddbbb5e 100644 --- a/docs/tex.md +++ b/docs/tex.md @@ -7,7 +7,7 @@ tex = convert(markdown, unnumbered=False, document_class="article", minted_language="text", override_language=False) ``` -`convert` returns the body of a TeX document. The output is the same as the output of `md2tex`. +`convert` returns the body of a TeX document. The output is the same as the output of `md2tex`, except for some [citations](#citations) and for headings such as `#_x` (see [design.md](design.md#behaviour-kept-from-md2tex)). | Argument | Meaning | |---|---| @@ -45,10 +45,32 @@ Code blocks use the [`minted`](http://tug.ctan.org/macros/latex/contrib/minted/m - Inline quotes - Footnotes. A reference with no note, and a note with no reference, are deleted. - Math, with `$x$` and `$$` blocks -- Citations in the style of Pandoc. The support is basic. +- Citations in the style of Pandoc (see [Citations](#citations)) Not supported: tables, strikethrough, emojis, task lists. A text block inside a list item is taken as a continuation of the item. +## Citations + +A citation becomes a `\parencite` command of `biblatex`. + +| Markdown | TeX | +|---|---| +| `[@doe1999]` | `\parencite{doe1999}` | +| `[-@doe1999]` (without the author name) | `\parencite*{doe1999}` | +| `[@doe1999, 30]`, `[@doe1999, p. 30]` | `\parencite[p. 30]{doe1999}` | +| `[@doe1999, 30-35]`, `[@doe1999, pp. 30-35]` | `\parencite[pp. 30-35]{doe1999}` | +| `[@doe1999, p. 30, emphasis added]` | `\parencite[p. 30, emphasis added]{doe1999}` | +| `[@doe1999, chap. 2]` | `\parencite[chap. 2]{doe1999}` | +| `[@doe1999; @smith2000]` | `\parencites{doe1999, smith2000}` | +| `[@doe1999, 30; @smith2000]` | `\parencites[p. 30]{doe1999}{smith2000}` | + +- A locator of pages is a number or a range (with `-`, `--` or an en dash), with or without `p.` or `pp.`. `md2misc` writes `p.` for one page and `pp.` for a range. +- All other locators are written as they are. +- A key can have `_`, `&` and `$`. `biblatex` does not accept `#` or `%` in a key. +- In a citation of more than one source, the author name cannot be omitted. `md2misc` ignores the `-` and gives a warning. +- A prefix is not supported. `[see @doe1999]` stays as text. +- A badly formed citation, such as `[@ doe1999]`, `[@doe1999 p. 3]` or `[@doe1999; see @smith2000]`, stops the conversion with `ParsingException`. + ## What gives a bad output - Badly formed Markdown. A badly formed list stops the conversion. diff --git a/md2misc/backends/__init__.py b/md2misc/backends/__init__.py index ccc4bd6..190aa37 100644 --- a/md2misc/backends/__init__.py +++ b/md2misc/backends/__init__.py @@ -1,5 +1,5 @@ -from .base import Backend +from .base import Backend, CitationSource from .schelp import SchelpBackend from .tex import TeXBackend -__all__ = ["Backend", "SchelpBackend", "TeXBackend"] +__all__ = ["Backend", "CitationSource", "SchelpBackend", "TeXBackend"] diff --git a/md2misc/backends/base.py b/md2misc/backends/base.py index d6e9762..1dd5f3d 100644 --- a/md2misc/backends/base.py +++ b/md2misc/backends/base.py @@ -1,7 +1,21 @@ +from typing import NamedTuple + from .. import syntax from ..errors_warnings import UnsupportedConstruct +class CitationSource(NamedTuple): + """ + one source of a citation, as the arguments of `Backend.citation()`. + """ + + key: str + locator: str | None + is_range: bool + omit_author: bool + suffix: str + + class Backend: """ an output format. the converters find the Markdown elements and call the @@ -198,16 +212,32 @@ def footnote(self, text: str) -> str: """ self.unsupported("footnote") - def citation(self, key: str, locator: str | None = None, is_range: bool = False, omit_author: bool = False) -> str: + def citation( + self, + key: str, + locator: str | None = None, + is_range: bool = False, + omit_author: bool = False, + suffix: str = "", + ) -> str: """ write a citation of one source. `locator` is a page number, or a range of pages if - `is_range` is true. `omit_author` is true if the author must not be named. + `is_range` is true. `omit_author` is true if the author must not be named. `suffix` is + text that follows the pages (it then starts with a comma), or the whole locator if it is + not of pages (`locator` is then `None`). it is escaped. """ self.unsupported("citation") def citations(self, keys: str) -> str: """ - write a citation of several sources. `keys` is the keys of the sources, separated by commas. + write a citation of several sources with no locators. `keys` is the keys of the sources, separated by commas. + """ + self.unsupported("citation") + + def qualified_citations(self, sources: list[CitationSource]) -> str: + """ + write a citation of several sources of which one or more have a locator or a suffix. a format that + cannot omit an author here ignores `omit_author`. """ self.unsupported("citation") diff --git a/md2misc/backends/tex.py b/md2misc/backends/tex.py index ac4be59..5e3b20c 100644 --- a/md2misc/backends/tex.py +++ b/md2misc/backends/tex.py @@ -2,7 +2,7 @@ from ..errors_warnings import Warnings from ..helpers import get_matching_brackets -from .base import Backend +from .base import Backend, CitationSource from .minted import languages @@ -52,7 +52,6 @@ def escape(self, string: str) -> str: string = string.replace(r"#", r"\#") 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"\_") string = string.replace("&", r"\&") @@ -161,15 +160,41 @@ def link(self, url: str, text: str) -> str: def footnote(self, text: str) -> str: return "\\footnote{" + text + "}" - def citation(self, key: str, locator: str | None = None, is_range: bool = False, omit_author: bool = False) -> str: - tex_locator = "" - if locator: - tex_locator = f"[pp. {locator}]" if is_range else f"[p. {locator}]" + def citation( + self, + key: str, + locator: str | None = None, + is_range: bool = False, + omit_author: bool = False, + suffix: str = "", + ) -> str: command = "\\parencite*" if omit_author else "\\parencite" - return command + tex_locator + "{" + key + "}" + return command + self._postnote(locator, is_range, suffix) + "{" + self._key(key) + "}" def citations(self, keys: str) -> str: - return "\\parencites{" + keys + "}" + return "\\parencites{" + self._key(keys) + "}" + + def qualified_citations(self, sources: list[CitationSource]) -> str: + return "\\parencites" + "".join( + self._postnote(source.locator, source.is_range, source.suffix) + "{" + self._key(source.key) + "}" + for source in sources + ) + + @staticmethod + def _key(key: str) -> str: + """ + a citation key as `biblatex` reads it: without the escapes that `escape()` put in the text. + """ + return key.replace("\\_", "_").replace("\\&", "&").replace("\\$", "$") + + @staticmethod + def _postnote(locator: str | None, is_range: bool, suffix: str) -> str: + """ + the optional argument of a citation command: the pages with their label, and the text after them. + """ + if locator: + suffix = ("pp. " if is_range else "p. ") + locator + suffix + return f"[{suffix}]" if suffix else "" def inline_math(self, expression: str) -> str: return "\\(" + expression + "\\)" diff --git a/md2misc/converters.py b/md2misc/converters.py index 66275c1..61d1179 100644 --- a/md2misc/converters.py +++ b/md2misc/converters.py @@ -1,9 +1,8 @@ import re -from typing import cast from . import syntax, tables -from .backends import Backend -from .errors_warnings import Warnings +from .backends import Backend, CitationSource +from .errors_warnings import ParsingException, Warnings from .helpers import process_list_indentation # --------------------------------------------------------------- @@ -152,7 +151,8 @@ def unordered_l(string: str, backend: Backend): :param backend: the output format :return: the updated string representation of a markdown file """ - lists = re.finditer(r"((^[ \t]*?-(?!-{2,}).*?\n)+(.+\n)*)+", string, flags=re.MULTILINE) + # the last line of the text can be a line of the list, with or without a newline + lists = re.finditer(r"((^[ \t]*?-(?!-{2,}).*?(?:\n|\Z))+(.+(?:\n|\Z))*)+", string, flags=re.MULTILINE) for ls in lists: # prepare list building lstext = ls[0] # extract list text @@ -412,6 +412,30 @@ def hyperlink(string: str, backend: Backend): return string + # a source in a citation: `@key`, with an optional locator after a comma. `-@key` omits the author name + source_regex = r"\s*(-?)@([^\s,;@\]]+)\s*(?:,(.*))?" + + # a locator that is a page or a range of pages, with or without `p.` or `pp.`, and optional text after a + # comma. a comma and a number make a list of pages, which is not of this form + page_locator_regex = r"(?:pp?\.\s*)?(\d+(?:\s*(?:-+|\u2013)\s*\d+)?)(\s*,\s*[^\d\s].*)?" + + @staticmethod + def _source(item: str, citation: str) -> CitationSource: + """ + read one source of a citation. `citation` is the whole citation, for the error message. + """ + parts = re.fullmatch(MDReference.source_regex, item, flags=re.S) + if not parts: + raise ParsingException( + f"badly formed citation `{citation}` (the forms are `[@key]`, `[@key, p. 30]` and `[@key; @other]`)" + ) + locator = " ".join((parts[3] or "").split()) + pages = re.fullmatch(MDReference.page_locator_regex, locator) + if not pages: + return CitationSource(parts[2], None, False, parts[1] == "-", locator) + numbers = re.sub(r"\s+", "", pages[1]) + return CitationSource(parts[2], numbers, not numbers.isdigit(), parts[1] == "-", pages[2] or "") + @staticmethod def citation(string: str, backend: Backend): r""" @@ -423,22 +447,24 @@ def citation(string: str, backend: Backend): 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 + - Citation form: `[@key, locator]`, or more sources separated by `;` + - Citation key: `@doe1999` (`-@doe1999` omits the author name with the \parencite* command) + - Locator: pages (see `page_locator_regex`), or any other text, which is written as it is Conversion examples: - [@doe1999] -> \parencite{doe1999} - [-@doe1999] -> \parencite*{doe1999} - [@doe1999, 30] -> \parencite[p. 30]{doe1999} - - [@doe1999, p. 30] -> \parencite[p. 30]{doe1999} - - [@doe1999, 30-35] -> \parencite[pp. 30-35]{doe1999} - - [@doe1999, pp. 30-35] -> \parencite[pp. 30-35]{doe1999} + - [@doe1999, p.30-35] -> \parencite[pp. 30-35]{doe1999} + - [@doe1999, p. 30, emphasis added] -> \parencite[p. 30, emphasis added]{doe1999} + - [@doe1999, chap. 2] -> \parencite[chap. 2]{doe1999} - [@doe1999; @smith] -> \parencites{doe1999, smith} + - [@doe1999, 30; @smith] -> \parencites[p. 30]{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 + - A prefix (`[see @doe1999]`) is not supported: before the first key, the text stays as it is; before a + later key, the conversion stops. + - The author name cannot be omitted in a citation of more than one source: `-` is ignored, with a warning. :param string: the string representation of a markdown file :param backend: the output format @@ -453,27 +479,17 @@ 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]: - # multiple references in one citation - # -> simple mode - keys = ref_string[1].replace(";", ",").replace("@", "") - citation_text = backend.citations(keys) + sources = [MDReference._source(item, ref_string[0]) for item in ref_string[1].split(";")] + if len(sources) == 1: + citation_text = backend.citation(*sources[0]) else: - # only one citation, so we split into citation key and locator - # a citation of another form, such as `[@ doe]`, has no match and stops with a TypeError - ref_components = cast( - "re.Match[str]", - 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("-") - 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, - ) + if any(source.omit_author for source in sources): + Warnings("citation_author_not_omitted", ref_string[0]) + if any(source.locator or source.suffix for source in sources): + citation_text = backend.qualified_citations(sources) + else: + # sources without locators: the form of md2tex + citation_text = backend.citations(re.sub(r"-?@", "", ref_string[1].replace(";", ","))) string = string.replace(ref_string[0], citation_text) diff --git a/md2misc/errors_warnings.py b/md2misc/errors_warnings.py index e42b60f..9dcea95 100644 --- a/md2misc/errors_warnings.py +++ b/md2misc/errors_warnings.py @@ -100,6 +100,7 @@ class to give custom warnings, with the category `Md2miscWarning`. the warnings "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.", "link_type_not_supported": "type of link `@@TOKEN@@` is not supported. leaving as is...", + "citation_author_not_omitted": "`@@TOKEN@@`: the author cannot be omitted in a citation of more than one source", } def __init__(self, key, val=None): diff --git a/pyproject.toml b/pyproject.toml index 6a2c729..2b66483 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "uv_build" [project] name = "md2misc" -version = "0.4.0" +version = "0.5.0" description = "A Python library that converts Markdown to TeX and to SuperCollider help (schelp)" readme = "README.md" license = "GPL-3.0-only" diff --git a/tests/test_lists.py b/tests/test_lists.py new file mode 100644 index 0000000..aa21747 --- /dev/null +++ b/tests/test_lists.py @@ -0,0 +1,28 @@ +""" +Lists at the end of a text: the final newline of the text does not change which lines are in the list. +""" + +import pytest + +from md2misc import convert, convert_schelp + +LISTS = { + "one item": "- only", + "two items": "- one\n- two", + "after text": "text\n\n- one\n- two", + "nested": "- a\n - b", + "continuation line": "- a\n- b\n more", + "lazy continuation line": "- a\nmore", + "numbered": "1. one\n2. two", +} + + +@pytest.mark.parametrize("function", [convert, convert_schelp]) +@pytest.mark.parametrize("markdown", LISTS.values(), ids=LISTS.keys()) +def test_a_list_at_the_end_needs_no_final_newline(function, markdown): + # the amount of white space can differ + assert function(markdown).split() == function(markdown + "\n").split() + + +def test_all_items_are_in_the_list(): + assert convert("- one\n- two").split() == [r"\begin{itemize}", r"\item", "one", r"\item", "two", r"\end{itemize}"] diff --git a/tests/test_tex_citations.py b/tests/test_tex_citations.py new file mode 100644 index 0000000..58673b1 --- /dev/null +++ b/tests/test_tex_citations.py @@ -0,0 +1,110 @@ +""" +Citations in the TeX output: `[@key]` becomes `\\parencite` (biblatex). No text of a citation is lost: the +converter writes it, or stops the conversion. +""" + +import warnings + +import pytest + +from md2misc import Md2miscWarning, ParsingException, convert + + +def tex(markdown): + return convert(markdown).strip() + + +@pytest.mark.parametrize( + "markdown, expected", + [ + # the forms of md2tex + ("[@a]", r"\parencite{a}"), + ("[-@a]", r"\parencite*{a}"), + ("[@a, 3]", r"\parencite[p. 3]{a}"), + ("[@a, p. 3]", r"\parencite[p. 3]{a}"), + ("[@a, 3-5]", r"\parencite[pp. 3-5]{a}"), + ("[@a, pp. 3-5]", r"\parencite[pp. 3-5]{a}"), + # other ways to write pages: the label follows the numbers + ("[@a, p.106]", r"\parencite[p. 106]{a}"), + ("[@a, p. 121-122]", r"\parencite[pp. 121-122]{a}"), + ("[@a, pp. 3]", r"\parencite[p. 3]{a}"), + ("[@a, p. 3–5]", r"\parencite[pp. 3–5]{a}"), + ("[@a, 30–35]", r"\parencite[pp. 30–35]{a}"), + ("[@a, 3--5]", r"\parencite[pp. 3--5]{a}"), + ("[@a, 3 - 5]", r"\parencite[pp. 3-5]{a}"), + ("[@a, p.\n3]", r"\parencite[p. 3]{a}"), + ("[@a , 3]", r"\parencite[p. 3]{a}"), + ("[-@a, p. 3]", r"\parencite*[p. 3]{a}"), + # text after the pages + ("[@a, p. 3, emphasis added]", r"\parencite[p. 3, emphasis added]{a}"), + # other locators are written as they are + ("[@a, chap. 2]", r"\parencite[chap. 2]{a}"), + ("[@a, p. 3 f.]", r"\parencite[p. 3 f.]{a}"), + ("[@a, 3, 5]", r"\parencite[3, 5]{a}"), + ("[@a, Steady-state waves | The human voice]", r"\parencite[Steady-state waves | The human voice]{a}"), + ("[@a, Drum &\nBass, 50%]", r"\parencite[Drum \& Bass, 50\%]{a}"), + # an empty locator + ("[@a,]", r"\parencite{a}"), + ], +) +def test_one_source(markdown, expected): + assert tex(markdown) == expected + + +@pytest.mark.parametrize( + "markdown, expected", + [ + # the form of md2tex + ("[@a; @b]", r"\parencites{a, b}"), + # a locator belongs to its source + ("[@a, p. 3; @b]", r"\parencites[p. 3]{a}{b}"), + ("[@a; @b, chap. 2]", r"\parencites{a}[chap. 2]{b}"), + ("[@a, 3-5;\n@b, p.7]", r"\parencites[pp. 3-5]{a}[p. 7]{b}"), + ], +) +def test_several_sources(markdown, expected): + assert tex(markdown) == expected + + +@pytest.mark.parametrize( + "markdown, expected", + [ + ("[-@a; @b]", r"\parencites{a, b}"), + ("[@a, 3; -@b]", r"\parencites[p. 3]{a}{b}"), + ], +) +def test_several_sources_cannot_omit_an_author(markdown, expected): + with pytest.warns(Md2miscWarning, match="author"): + assert tex(markdown) == expected + + +@pytest.mark.parametrize( + "citation", + ["[@ a]", "[@,]", "[@a b]", "[@a;]", "[@a; see @b]", "[@a @b]", "[@a, 3; b]"], +) +def test_a_badly_formed_citation_stops_with_its_text(citation): + with pytest.raises(ParsingException) as error: + convert(f"Text {citation}.\n") + assert citation in str(error.value) + + +@pytest.mark.parametrize("text", ["[see @a]", "[@]", "[-@]", "`[@a b]`", "[@a b](https://example.com)"]) +def test_text_that_is_not_a_citation(text): + with warnings.catch_warnings(): + warnings.simplefilter("error") + assert r"\parencite" not in tex(text) + + +@pytest.mark.parametrize( + "markdown, expected", + [ + ("[@doe_1999]", r"\parencite{doe_1999}"), + ("[-@doe_1999, 3]", r"\parencite*[p. 3]{doe_1999}"), + ("[@a_1; @b&c]", r"\parencites{a_1, b&c}"), + ("[@a$1, 3]", r"\parencite[p. 3]{a$1}"), + ("[@a_1, chap_2; @b&c]", r"\parencites[chap\_2]{a_1}{b&c}"), + ], +) +def test_a_key_is_written_as_it_is(markdown, expected): + # biblatex does not find a key with a TeX escape. a locator is text, thus it is escaped + assert tex(markdown) == expected diff --git a/tests/test_tex_escapes.py b/tests/test_tex_escapes.py new file mode 100644 index 0000000..bf20a31 --- /dev/null +++ b/tests/test_tex_escapes.py @@ -0,0 +1,26 @@ +""" +Characters of the text that have a special meaning in TeX. +""" + +import pytest + +from md2misc import convert + + +@pytest.mark.parametrize( + "markdown, expected", + [ + ("a $ b", r"a \$ b"), + ("It costs 5 $.", r"It costs 5 \$."), + ("$HOME", r"\$HOME"), + ("a $ b & c % d # e _ f", r"a \$ b \& c \% d \# e \_ f"), + ("- a $", "\\begin{itemize}\n\\item a \\$ \n\\end{itemize}"), + ], +) +def test_a_dollar_sign_in_text_stays_a_dollar_sign(markdown, expected): + assert convert(markdown + "\n").strip() == expected + + +def test_a_dollar_sign_in_math_and_code_is_not_escaped(): + assert convert("$x$\n").strip() == r"\(x\)" + assert r"\$" not in convert("`$HOME`\n")