Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions DEVELOPING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 5 additions & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<br>` 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 `<br>` 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

Expand Down
26 changes: 24 additions & 2 deletions docs/tex.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|---|---|
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions md2misc/backends/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
36 changes: 33 additions & 3 deletions md2misc/backends/base.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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")

Expand Down
41 changes: 33 additions & 8 deletions md2misc/backends/tex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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"\&")
Expand Down Expand Up @@ -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 + "\\)"
Expand Down
80 changes: 48 additions & 32 deletions md2misc/converters.py
Original file line number Diff line number Diff line change
@@ -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

# ---------------------------------------------------------------
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"""
Expand All @@ -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
Expand All @@ -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)

Expand Down
1 change: 1 addition & 0 deletions md2misc/errors_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading
Loading