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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
23 changes: 23 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
23 changes: 23 additions & 0 deletions mdit_py_plugins/fancy_list/LICENSE
Original file line number Diff line number Diff line change
@@ -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.
31 changes: 31 additions & 0 deletions mdit_py_plugins/fancy_list/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]},
)
248 changes: 248 additions & 0 deletions mdit_py_plugins/fancy_list/index.py
Original file line number Diff line number Diff line change
@@ -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
Loading