diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a8d414..e228dc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## Unreleased + +- Add the `fancy_list` plugin for alphabetic and Roman ordered lists, with optional ordinal indicators and multi-letter numbering. + ## 0.7.0 - 2026-11-10 A security and bug-fix release. diff --git a/docs/index.md b/docs/index.md index d3ad724..0f275d5 100644 --- a/docs/index.md +++ b/docs/index.md @@ -135,6 +135,29 @@ lines or indentation, and close the block with another `---` line. .. autofunction:: mdit_py_plugins.deflist.deflist_plugin ``` +## Fancy ordered lists + +`fancy_list_plugin` supports mixed numbering in nested lists, such as articles +with alphabetic paragraphs and Roman-numbered clauses. + +```markdown +1. Rights + a) Notice + i. Early + ii. Late + b) Consent +2. Duties +``` + +A change of case, numbering style or delimiter starts a new list. A single +capital followed by a period needs two spaces before the item text, so +`B. Russell` stays in a paragraph. Use `#)` or `#.` to continue a list +without spelling out the next number. + +```{eval-rst} +.. autofunction:: mdit_py_plugins.fancy_list.fancy_list_plugin +``` + ## Task lists ```{eval-rst} diff --git a/mdit_py_plugins/fancy_list/LICENSE b/mdit_py_plugins/fancy_list/LICENSE new file mode 100644 index 0000000..c4a6f22 --- /dev/null +++ b/mdit_py_plugins/fancy_list/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2020 Moxio +Copyright (c) 2020 ExecutableBookProject +Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/mdit_py_plugins/fancy_list/__init__.py b/mdit_py_plugins/fancy_list/__init__.py new file mode 100644 index 0000000..0e049f2 --- /dev/null +++ b/mdit_py_plugins/fancy_list/__init__.py @@ -0,0 +1,31 @@ +from functools import partial + +from markdown_it import MarkdownIt + +from .index import fancy_list + + +def fancy_list_plugin( + md: MarkdownIt, *, allow_ordinal: bool = False, allow_multi_letter: bool = False +) -> None: + """Parse ordered lists marked with letters, Roman numerals, decimals or a hash. + + Markers end in a period or a closing parenthesis. Use two spaces after a + single capital letter and a period to distinguish a list from an initial. + A hash can continue any ordered list with the same delimiter. + + :param allow_ordinal: Accept an ordinal indicator, as in "1º.". The list + receives the CSS class "ordinal". + :param allow_multi_letter: Accept up to three alphabetic letters, as in + "AA)" for 27. A valid Roman numeral takes precedence at the start of + a list unless it is a single letter other than i or I. + """ + md.block.ruler.at( + "list", + partial( + fancy_list, + allow_ordinal=allow_ordinal, + allow_multi_letter=allow_multi_letter, + ), + {"alt": ["paragraph", "reference", "blockquote"]}, + ) diff --git a/mdit_py_plugins/fancy_list/index.py b/mdit_py_plugins/fancy_list/index.py new file mode 100644 index 0000000..97ebd94 --- /dev/null +++ b/mdit_py_plugins/fancy_list/index.py @@ -0,0 +1,248 @@ +"""Ordered-list rule based on markdown-it-py's list rule and markdown-it-fancy-lists.""" + +from dataclasses import dataclass +import re + +from markdown_it.rules_block import StateBlock +from markdown_it.rules_block.list import list_block, markTightParagraphs + +_MARKER = re.compile( + r"([0-9]{1,9}|[a-z]{1,3}|[A-Z]{1,3}|[ivxlcdm]+|[IVXLCDM]+|#)([º°˚ᵒ]?)([.)])" +) +_ROMAN = re.compile(r"M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})") +_ROMAN_VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} + + +@dataclass(frozen=True) +class _Marker: + text: str + style: str + value: int + delimiter: str + ordinal: bool + end: int + + def continues(self, previous: "_Marker") -> bool: + return ( + (self.style == "#" or self.style == previous.style) + and self.delimiter == previous.delimiter + and self.ordinal == previous.ordinal + ) + + +def _number( + text: str, previous_style: str, multi_letter: bool +) -> tuple[str, int] | None: + if text == "#": + return "#", 1 + if text.isdecimal(): + return "1", int(text) + + upper = text.upper() + alphabetic = len(text) == 1 or (multi_letter and len(text) <= 3) + # A single C starts an alphabetic list, but the same C can continue a Roman + # list. Multi-letter Roman numerals take priority unless following letters. + prefer_roman = previous_style in ("i", "I") or ( + previous_style not in ("a", "A") and (upper == "I" or len(text) > 1) + ) + if (prefer_roman or not alphabetic) and _ROMAN.fullmatch(upper): + total = previous = 0 + for letter in reversed(upper): + value = _ROMAN_VALUES[letter] + total += -value if value < previous else value + previous = value + return ("I" if text.isupper() else "i"), total + + if alphabetic: + total = 0 + for letter in upper: + total = total * 26 + ord(letter) - ord("A") + 1 + return ("A" if text.isupper() else "a"), total + return None + + +def _marker( + state: StateBlock, + line: int, + previous_style: str, + allow_ordinal: bool, + multi_letter: bool, +) -> _Marker | None: + start = state.bMarks[line] + state.tShift[line] + limit = state.eMarks[line] + # Match at most nine characters plus the delimiter, as for a decimal list. + match = _MARKER.match(state.src, start, min(start + 10, limit)) + if not match: + return None + text, ordinal, delimiter = match.groups() + end = match.end() + if ordinal and not allow_ordinal: + return None + if end < limit and state.src[end] not in " \t": + return None + needs_two_spaces = ( + len(text) == 1 and text.isupper() and delimiter == "." and not ordinal + ) + if needs_two_spaces: + if end + 1 >= limit or state.src[end + 1] not in " \t": + return None + # The first space belongs to the marker. Only the remaining whitespace + # sets the content indentation and decides whether the item starts with code. + end += 1 + number = _number(text, previous_style, multi_letter) + if number is None: + return None + return _Marker(text, number[0], number[1], delimiter, bool(ordinal), end) + + +def _item( + state: StateBlock, line: int, end_line: int, marker: _Marker +) -> tuple[bool, bool]: + """Parse an item and return whether it is loose and whether it has a checkbox.""" + first = state.bMarks[line] + shift = state.tShift[line] + count = state.sCount[line] + pos = marker.end + limit = state.eMarks[line] + initial = offset = count + pos - first - shift + while pos < limit and state.src[pos] in " \t": + if state.src[pos] == "\t": + offset += 4 - (offset + state.bsCount[line]) % 4 + else: + offset += 1 + pos += 1 + + # Five spaces introduce an indented code block. Empty items also have a + # one-column content indent, irrespective of their trailing whitespace. + padding = offset - initial + if pos == limit or padding > 4: + padding = 1 + + item = state.push("list_item_open", "li", 1) + item.map = [line, 0] + item.markup = marker.delimiter + item.info = marker.text + + old_indent, old_list_indent, old_tight = ( + state.blkIndent, + state.listIndent, + state.tight, + ) + state.listIndent, state.blkIndent = old_indent, initial + padding + state.tight = True + state.tShift[line], state.sCount[line] = pos - first, offset + has_checkbox = False + try: + # Native GFM task items consume the checkbox before the nested block + # parser reads the item's contents, except in indented code blocks. + if ( + state.md.options.get("tasklists", False) + and not state.is_code_block(line) + and pos + 4 <= limit + and state.src[pos : pos + 3] in ("[ ]", "[x]", "[X]") + and state.src[pos + 3] in " \t" + ): + has_checkbox = True + item.meta["checked"] = state.src[pos + 1] != " " + item.attrJoin("class", "task-list-item") + state.bMarks[line], state.tShift[line] = pos + 4, 0 + + if pos == limit and state.isEmpty(line + 1): + state.line = min(line + 2, end_line) + else: + state.md.block.tokenize(state, line, end_line) + loose = not state.tight + finally: + state.blkIndent, state.listIndent, state.tight = ( + old_indent, + old_list_indent, + old_tight, + ) + state.bMarks[line], state.tShift[line], state.sCount[line] = first, shift, count + + item.map[1] = state.line + state.push("list_item_close", "li", -1).markup = marker.delimiter + return loose, has_checkbox + + +def fancy_list( + state: StateBlock, + start_line: int, + end_line: int, + silent: bool, + *, + allow_ordinal: bool, + allow_multi_letter: bool, +) -> bool: + first = state.bMarks[start_line] + state.tShift[start_line] + if state.src[first : first + 1] in ("*", "-", "+"): + return list_block(state, start_line, end_line, silent) + + if state.is_code_block(start_line) or ( + state.listIndent >= 0 + and state.sCount[start_line] - state.listIndent >= 4 + and state.sCount[start_line] < state.blkIndent + ): + return False + marker = _marker(state, start_line, "", allow_ordinal, allow_multi_letter) + if marker is None: + return False + if silent: + if ( + state.parentType == "paragraph" + and state.sCount[start_line] >= state.blkIndent + ): + if marker.value != 1 and state.listIndent < 0: + return False + return state.skipSpaces(marker.end) < state.eMarks[start_line] + return True + + token_index = len(state.tokens) + opening = state.push("ordered_list_open", "ol", 1) + opening.map = [start_line, 0] + opening.markup = marker.delimiter + if marker.style not in ("1", "#"): + opening.attrSet("type", marker.style) + if marker.value != 1: + opening.attrSet("start", marker.value) + if marker.ordinal: + opening.attrSet("class", "ordinal") + + previous_parent = state.parentType + state.parentType = "list" + terminators = state.md.block.ruler.getRules("list") + tight = True + previous_empty = False + contains_tasks = False + line = start_line + try: + while True: + loose, has_checkbox = _item(state, line, end_line, marker) + tight = tight and not loose and not previous_empty + contains_tasks = contains_tasks or has_checkbox + next_line = state.line + previous_empty = next_line - line > 1 and state.isEmpty(next_line - 1) + line = next_line + if ( + line >= end_line + or state.sCount[line] < state.blkIndent + or state.is_code_block(line) + or any(rule(state, line, end_line, True) for rule in terminators) + ): + break + following = _marker( + state, line, marker.style, allow_ordinal, allow_multi_letter + ) + if following is None or not following.continues(marker): + break + marker = following + finally: + state.parentType = previous_parent + + if contains_tasks: + opening.attrJoin("class", "contains-task-list") + state.push("ordered_list_close", "ol", -1).markup = opening.markup + opening.map[1] = line + if tight: + markTightParagraphs(state, token_index) + return True diff --git a/tests/fixtures/fancy_list.md b/tests/fixtures/fancy_list.md new file mode 100644 index 0000000..4470de2 --- /dev/null +++ b/tests/fixtures/fancy_list.md @@ -0,0 +1,146 @@ +Nested legal numbering +. +1. Rights + a) Notice + i. Early + ii. Late + b) Consent +2. Duties +. +
    +
  1. Rights +
      +
    1. Notice +
        +
      1. Early
      2. +
      3. Late
      4. +
      +
    2. +
    3. Consent
    4. +
    +
  2. +
  3. Duties
  4. +
+. + +Roman numeral offset +. +iv. foo +v. bar +vi. baz +. +
    +
  1. foo
  2. +
  3. bar
  4. +
  5. baz
  6. +
+. + +Hash with a Roman list inside an alphabetic list +. +a. Part + iv) Four + #) Five +#. Section +. +
    +
  1. Part +
      +
    1. Four
    2. +
    3. Five
    4. +
    +
  2. +
  3. Section
  4. +
+. + +A different delimiter starts another list +. +1. foo +2. bar +3) baz +. +
    +
  1. foo
  2. +
  3. bar
  4. +
+
    +
  1. baz
  2. +
+. + +Initials and uppercase period markers +. +B. Russell was an English philosopher. + +I. Elba is an English actor. + +I. foo +II. bar + +B. foo +C. bar +. +

B. Russell was an English philosopher.

+

I. Elba is an English actor.

+
    +
  1. foo
  2. +
  3. bar
  4. +
+
    +
  1. foo
  2. +
  3. bar
  4. +
+. + +List markers inside block quotes and code fences +. +> i. one +> ii. two + +``` +a. code +``` +. +
+
    +
  1. one
  2. +
  3. two
  4. +
+
+
a. code
+
+. + +An invalid Roman numeral stays in a paragraph +. +VV. foo +VVI. bar +VVII. baz +. +

VV. foo +VVI. bar +VVII. baz

+. + +Only a first number interrupts a top-level paragraph +. +I need to buy +b. new shoes +c. a coat +d. a plane ticket + +I also need to buy +ii. new shoes +iii. a coat +iv. a plane ticket +. +

I need to buy +b. new shoes +c. a coat +d. a plane ticket

+

I also need to buy +ii. new shoes +iii. a coat +iv. a plane ticket

+. diff --git a/tests/test_fancy_list.py b/tests/test_fancy_list.py new file mode 100644 index 0000000..3862693 --- /dev/null +++ b/tests/test_fancy_list.py @@ -0,0 +1,89 @@ +from pathlib import Path + +from markdown_it import MarkdownIt +from markdown_it.utils import read_fixture_file +import pytest + +from mdit_py_plugins.fancy_list import fancy_list_plugin + + +@pytest.mark.parametrize( + "line,title,markdown,expected", + read_fixture_file(Path(__file__).parent / "fixtures" / "fancy_list.md"), +) +def test_render(line, title, markdown, expected): + assert MarkdownIt().use(fancy_list_plugin).render(markdown) == expected + + +@pytest.mark.parametrize( + "markdown", + [ + "text\n1.", + "1. foo\n2.\n3. bar", + "1.\nfoo\n\n2.\nbar", + "0003) **one**\n\n4) two\n continued", + "> - one\n> 1. two\n\n 5. code", + "-\titem\n* code\n+ last", + ], +) +def test_commonmark_tokens(markdown): + expected = [token.as_dict() for token in MarkdownIt().parse(markdown)] + tokens = MarkdownIt().use(fancy_list_plugin).parse(markdown) + assert [token.as_dict() for token in tokens] == expected + + +@pytest.mark.parametrize("indicator", ["º", "°", "˚", "ᵒ"]) +def test_ordinal(indicator): + source = f"iv{indicator}) four\n#{indicator}) five" + assert MarkdownIt().use(fancy_list_plugin).parse(source)[0].type == "paragraph_open" + tokens = MarkdownIt().use(fancy_list_plugin, allow_ordinal=True).parse(source) + assert tokens[0].attrs == {"type": "i", "start": 4, "class": "ordinal"} + assert [t.markup for t in tokens if t.type == "list_item_open"] == [")", ")"] + + +@pytest.mark.parametrize( + "marker,start,style", + [("AA", 27, "A"), ("zzz", 18278, "a"), ("IV", 4, "I")], +) +def test_multi_letter(marker, start, style): + source = f"{marker}) item" + md = MarkdownIt().use(fancy_list_plugin, allow_multi_letter=True) + assert md.parse(source)[0].attrs == {"type": style, "start": start} + assert md.parse("Ab) text\nABCD) text")[0].type == "paragraph_open" + assert ( + MarkdownIt().use(fancy_list_plugin).parse("AA) text")[0].type + == "paragraph_open" + ) + + +def test_marker_at_eof_and_list_maps(): + md = MarkdownIt().use(fancy_list_plugin) + tokens = md.parse("C. first\nD. second\nE)") + assert [ + (t.markup, t.info, t.map) for t in tokens if t.type == "list_item_open" + ] == [(".", "C", [0, 1]), (".", "D", [1, 2]), (")", "E", [2, 3])] + assert [t.map for t in tokens if t.type == "ordered_list_open"] == [[0, 2], [2, 3]] + assert md.render("a)") == '
    \n
  1. \n
\n' + + +@pytest.mark.parametrize("padding", [" ", "\t ", "\t\t"]) +def test_capital_period_padding(padding): + md = MarkdownIt().use(fancy_list_plugin) + assert md.render(f"A.{padding}entry") == '
    \n
  1. entry
  2. \n
\n' + + +def test_disable_list_rule(): + md = MarkdownIt().use(fancy_list_plugin).disable("list") + assert md.render("1. one\na) two") == "

1. one\na) two

\n" + + +def test_gfm_task_list(): + pytest.importorskip("markdown_it", minversion="4.1.0") + md = MarkdownIt() + md.options["tasklists"] = True + plain = "1. [x] done\n2. [ ] pending\n3. [x] code" + expected = md.render(plain) + md.use(fancy_list_plugin) + assert md.render(plain) == expected + fancy = "a) [x] done\nb) [ ] pending\nc) [x] code" + assert md.render(fancy) == expected.replace("