Browse Source

Parse `==foo==` as `<mark>foo</mark>` in Mistune

Inspired by the syntax proposed by iaWriter.
master
David Larlet 4 years ago
parent
commit
9bb4c063d3
1 changed files with 37 additions and 6 deletions
  1. 37
    6
      site.py

+ 37
- 6
site.py View File

@@ -30,7 +30,33 @@ NORMALIZED_STRFTIME = "%Y-%m-%dT12:00:00+01:00"
TODAY = datetime.today() + timedelta(hours=6)


class ImgsWithSizesRenderer(mistune.HTMLRenderer):
class MarkParser(mistune.InlineParser):
"""Parses `==foo==` as `<mark>foo</mark>`."""

MARK = (
r"(\={2})(?=[^\s*])("
r"(?:\\[\\*]|[^*])*"
r"(?:" + mistune.InlineParser.ESCAPE + r"|[^\s*]))\1"
)

RULE_NAMES = mistune.InlineParser.RULE_NAMES + ("mark",)

def parse_mark(self, m, state):
marker = m.group(1)
text = m.group(2)
return "mark", self.render(text, state)


class MarkRenderer(mistune.HTMLRenderer):
"""To use in conjunction with `MarkParser`."""

def mark(self, text):
return "<mark>" + text + "</mark>"


class ImgsWithSizesRenderer(MarkRenderer):
"""Renders images as <figure>s and add sizes (useful for lazy loading)."""

def paragraph(self, text):
# In case of a figure, we do not want the (non-standard) paragraph.
if text.strip().startswith("<figure>"):
@@ -54,8 +80,9 @@ class ImgsWithSizesRenderer(mistune.HTMLRenderer):


class H2AnchorsRenderer(ImgsWithSizesRenderer):
"""Custom renderer for H2 titles with anchors."""

def heading(self, text, level):
# Set an anchor to h2 headings.
if level == 2:
slug = slugify(text)
return (
@@ -70,13 +97,17 @@ class H2AnchorsRenderer(ImgsWithSizesRenderer):


# We want a custom renderer to create a hash/link for each H2 headings.
markdown_with_h2_anchors = mistune.create_markdown(
renderer=H2AnchorsRenderer(escape=False), plugins=[DirectiveInclude()]
markdown_with_h2_anchors = mistune.Markdown(
renderer=H2AnchorsRenderer(escape=False),
inline=MarkParser(H2AnchorsRenderer(escape=False)),
plugins=[DirectiveInclude()],
)
# The second markdown is pertinent to generate articles for the feed,
# we do not need anchors in that case.
markdown_with_img_sizes = mistune.create_markdown(
renderer=ImgsWithSizesRenderer(escape=False), plugins=[DirectiveInclude()]
markdown_with_img_sizes = mistune.Markdown(
renderer=ImgsWithSizesRenderer(escape=False),
inline=MarkParser(ImgsWithSizesRenderer(escape=False)),
plugins=[DirectiveInclude()],
)

# This is the jinja2 configuration to locate templates.

Loading…
Cancel
Save