netresearch/matrix-skill / skills/matrix-communication
matrix-communication
FlaggedUse when communicating via Matrix chat, notifying teams, or managing E2EE. Triggers on #room:server references, Matrix URLs, and chat requests.
scripts/_lib/formatting.py
View on GitHub# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Netresearch DTT GmbH
"""Message formatting for Matrix scripts.
All functions use ONLY stdlib.
"""
import html as _html
import re
# `[text](url)` where the URL may hold balanced parentheses one level deep,
# such as JQL's `currentUser()`; `[^)]+` would end the URL at the first `)`.
_MD_LINK_RE = re.compile(r"\[([^\]]+)\]\(((?:[^()]|\([^()]*\))+)\)")
def shorten_service_urls(text: str) -> str:
"""Convert service URLs to shorter linked text.
Supported services:
- Jira: https://jira.example.com/browse/PROJ-123 -> [PROJ-123](url)
- GitHub Issues/PRs: https://github.com/owner/repo/issues/123 -> [owner/repo#123](url)
- GitHub commits: https://github.com/owner/repo/commit/abc123 -> [owner/repo@abc123](url)
- GitLab Issues/MRs: https://gitlab.example.com/group/project/-/issues/123 -> [group/project#123](url)
URLs already inside `[text](url)` markdown links are left untouched so the
caller's chosen link text is preserved (and to avoid producing broken
nested `[text]([short](url))` shapes).
"""
# Protect existing markdown links from being re-wrapped.
protected: list[str] = []
def _protect(match: "re.Match[str]") -> str:
idx = len(protected)
protected.append(match.group(0))
return f"\x00MDLINK{idx}\x00"
text = _MD_LINK_RE.sub(_protect, text)
# Jira URLs: https://jira.*/browse/PROJ-123 or https://*.atlassian.net/browse/PROJ-123
text = re.sub(
r"https?://[^/]+/browse/([A-Z][A-Z0-9]+-\d+)", r"[\1](https://\g<0>)", text
)
# Fix double https
text = re.sub(r"\(https://https?://", r"(https://", text)
# GitHub Issues/PRs: https://github.com/owner/repo/issues/123 or /pull/123
text = re.sub(
r"https?://github\.com/([^/]+)/([^/]+)/(issues|pull)/(\d+)",
r"[\1/\2#\4](\g<0>)",
text,
)
# GitHub commits: https://github.com/owner/repo/commit/abc123...
text = re.sub(
r"https?://github\.com/([^/]+)/([^/]+)/commit/([a-f0-9]{7,40})",
r"[\1/\2@\3](\g<0>)",
text,
)
# GitLab Issues/MRs: https://gitlab.*/group/project/-/issues/123 or /-/merge_requests/123
text = re.sub(
r"https?://[^/]+/([^/]+/[^/]+)/-/(issues|merge_requests)/(\d+)",
r"[\1#\3](\g<0>)",
text,
)
# Restore protected markdown links. Bounds-check the index so a forged
# placeholder in user input can't raise IndexError — unknown placeholders
# are left as-is.
def _restore(match: "re.Match[str]") -> str:
idx = int(match.group(1))
if 0 <= idx < len(protected):
return protected[idx]
return match.group(0)
text = re.sub(r"\x00MDLINK(\d+)\x00", _restore, text)
return text
_LINK_SCHEMES = ("http://", "https://", "mailto:", "matrix:")
def _markdown_link(match: "re.Match[str]") -> str:
label, url = match.group(1), match.group(2)
if not _html.unescape(url).strip().lower().startswith(_LINK_SCHEMES):
return label
return f'<a href="{url}">{label}</a>'
def markdown_to_html(text: str) -> str:
"""Convert markdown to Matrix HTML with smart features.
Supports:
- ## headings (h1-h6)
- **bold**, *italic*, `code`, ~~strikethrough~~
- [text](url) links
- ||spoiler|| text (Discord-style)
- ```lang code blocks ```
- > blockquotes
- list items: `- item`, `* item`, `+ item`
- | table | rows |
- @user:server mentions (clickable pills)
- #room:server room links (clickable)
- Auto-shortens Jira, GitHub, GitLab URLs
"""
# First, shorten service URLs (before other processing)
html = shorten_service_urls(text)
# The input is text, not markup: escape it before any tag is generated, so
# HTML in the message (a forged link, a fake mention) is shown as typed.
html = _html.escape(html, quote=True)
# Extract and protect code blocks from other processing
code_blocks = []
def save_code_block(match):
lang = match.group(1) or ""
code = match.group(2)
idx = len(code_blocks)
if lang:
code_blocks.append(
f'<pre><code class="language-{lang}">{code}</code></pre>'
)
else:
code_blocks.append(f"<pre><code>{code}</code></pre>")
return f"{{{{CODEBLOCK_{idx}}}}}"
html = re.sub(r"```(\w*)\n(.*?)```", save_code_block, html, flags=re.DOTALL)
# Spoilers: ||text|| -> <span data-mx-spoiler>text</span>
# But not table separators - check for pipe at start/end of line
html = re.sub(
r"(?<!\|)\|\|(.+?)\|\|(?!\|)", r"<span data-mx-spoiler>\1</span>", html
)
# Markdown links: [text](url) -> <a href="url">text</a>, for web, mail and
# matrix URLs only; any other scheme keeps the link text without a link.
html = _MD_LINK_RE.sub(_markdown_link, html)
# Matrix user mentions: @user:server -> clickable pill
# Only match if not already inside a link
html = re.sub(
r'(?<!["\'/])(@[a-zA-Z0-9._=-]+:[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})',
r'<a href="https://matrix.to/#/\1">\1</a>',
html,
)
# Matrix room links: #room:server -> clickable link
# Only match if not already inside a link
html = re.sub(
r'(?<!["\'/])(#[a-zA-Z0-9._=-]+:[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})',
r'<a href="https://matrix.to/#/\1">\1</a>',
html,
)
# Emphasis runs follow CommonMark left/right-flanking: the opening
# delimiter must NOT be followed by whitespace, and the closing one
# must NOT be preceded by whitespace. Without that, `* item` (a bullet)
# would be parsed as an italic opener and chew up the line until the
# next stray `*`.
# Strikethrough: ~~text~~ -> <del>text</del>
html = re.sub(r"~~(?=\S)(.+?)(?<=\S)~~", r"<del>\1</del>", html)
# Bold: **text** -> <strong>text</strong>
html = re.sub(r"\*\*(?=\S)(.+?)(?<=\S)\*\*", r"<strong>\1</strong>", html)
# Italic: *text* -> <em>text</em>
html = re.sub(r"\*(?=\S)([^*\n]+?)(?<=\S)\*", r"<em>\1</em>", html)
# Inline code: `text` -> <code>text</code>
html = re.sub(r"`(.+?)`", r"<code>\1</code>", html)
# Normalize multiple newlines
html = re.sub(r"\n{2,}", "\n", html)
# Process line-based formatting (headings, lists, blockquotes, tables)
lines = html.split("\n")
in_list = False
in_quote = False
in_table = False
result = []
for line in lines:
stripped = line.strip()
# Headings: ## Heading -> <h2>
heading_match = re.match(r"^(#{1,6})\s+(.+)$", stripped)
if heading_match:
if in_quote:
result.append("</blockquote>")
in_quote = False
if in_list:
result.append("</ul>")
in_list = False
if in_table:
result.append("</table>")
in_table = False
level = len(heading_match.group(1))
heading_text = heading_match.group(2)
result.append(f"<h{level}>{heading_text}</h{level}>")
continue
# Tables: | col | col |
if stripped.startswith("|") and stripped.endswith("|"):
# Parse table cells
cells = [c.strip() for c in stripped.split("|")[1:-1]]
# Check if this is a separator line (|---|---|)
if all(re.match(r"^[-:]+$", c) for c in cells if c):
# Skip separator line, it's just formatting
continue
if in_quote:
result.append("</blockquote>")
in_quote = False
if in_list:
result.append("</ul>")
in_list = False
if not in_table:
result.append("<table>")
in_table = True
# First row is header
result.append(
"<tr>" + "".join(f"<th>{c}</th>" for c in cells) + "</tr>"
)
else:
result.append(
"<tr>" + "".join(f"<td>{c}</td>" for c in cells) + "</tr>"
)
continue
# Close table if we're leaving table context
if in_table and not (stripped.startswith("|") and stripped.endswith("|")):
result.append("</table>")
in_table = False
# Blockquotes: > text (escaped above)
if stripped.startswith("> "):
if not in_quote:
if in_list:
result.append("</ul>")
in_list = False
result.append("<blockquote>")
in_quote = True
result.append(stripped[5:])
# Lists: `- item`, `* item`, `+ item` (all valid CommonMark bullets)
elif stripped[:2] in ("- ", "* ", "+ "):
if in_quote:
result.append("</blockquote>")
in_quote = False
if not in_list:
result.append("<ul>")
in_list = True
result.append(f"<li>{stripped[2:]}</li>")
elif stripped == "":
# End blockquote on empty line
if in_quote:
result.append("</blockquote>")
in_quote = False
continue
else:
if in_quote:
result.append("</blockquote>")
in_quote = False
if in_list:
result.append("</ul>")
in_list = False
result.append(line)
# Close any open tags
if in_quote:
result.append("</blockquote>")
if in_list:
result.append("</ul>")
if in_table:
result.append("</table>")
# Join with special marker, then convert to <br> only outside block elements
html = "{{BR}}".join(result)
# Don't add <br> around block elements
html = re.sub(
r"\{\{BR\}\}(?=<ul>|<li>|</ul>|</li>|<blockquote>|</blockquote>|<pre>|<table>|<tr>|</table>|<h[1-6]>)",
"",
html,
)
html = re.sub(
r"(</ul>|</li>|</blockquote>|</pre>|</table>|</tr>|</h[1-6]>)\{\{BR\}\}",
r"\1",
html,
)
html = re.sub(r"(<blockquote>|<table>)\{\{BR\}\}", r"\1", html)
html = html.replace("{{BR}}", "<br>")
# Restore code blocks
for idx, block in enumerate(code_blocks):
html = html.replace(f"{{{{CODEBLOCK_{idx}}}}}", block)
return html
def add_bot_prefix(message: str, prefix: str) -> str:
"""Add bot prefix intelligently.
If message starts with a heading, insert prefix after the heading.
Otherwise, prepend prefix to the message. A message that already opens
with the prefix (an announcement written with the leading glyph
matrix-announcement recommends, or an edit of a prefixed message) is
returned unchanged, so the prefix appears once.
"""
# compare without surrounding whitespace on either side, so a configured
# prefix such as " 🤖" is recognised in the text it produced earlier
marker = prefix.strip()
if marker and message.lstrip().startswith(marker):
return message
lines = message.split("\n")
if not lines:
return f"{prefix} {message}"
first_line = lines[0].strip()
# Check if first line is a heading
if re.match(r"^#{1,6}\s+", first_line):
# the prefix this function inserts sits after a blank line
body = next((line for line in lines[1:] if line.strip()), "")
if marker and body.lstrip().startswith(marker):
return message
# Insert prefix after heading on same line or next line
lines[0] = first_line
if len(lines) > 1:
# Insert prefix at start of content after heading
lines.insert(1, f"\n{prefix}")
else:
# Add prefix after heading
lines.append(f"\n{prefix}")
return "\n".join(lines)
else:
# Prepend prefix to message
return f"{prefix} {message}"
def rich_text_fields(content) -> dict:
"""`format` and `formatted_body` of an event's content, when it carries them.
`body` is only the plain-text fallback. A sender may put something entirely
different there: matrix-hookshot, for one, writes `Received webhook data:`
plus the raw JSON into `body` when the webhook payload has no `text` key,
while `formatted_body` holds the HTML that Element actually renders. A
reader that returns `body` alone cannot tell the two apart. Non-string
values are dropped rather than passed on.
"""
if not isinstance(content, dict):
return {}
fields = {}
for key in ("format", "formatted_body"):
value = content.get(key)
if isinstance(value, str) and value:
fields[key] = value
return fields
MATRIX_TO = "https://matrix.to/#/"
def mention_pill(user_id: str, label: str | None = None) -> str:
"""Markdown link that a Matrix client renders as a mention pill."""
return f"[{label or user_id.split(':')[0].lstrip('@')}]({MATRIX_TO}{user_id})"
def build_mentions(user_ids, room: bool = False) -> dict:
"""The `m.mentions` block (MSC3952).
This is what actually fires a notification on a modern client. A plain
`@name` in the body does not: it only ever matched the legacy
`contains_user_name` push rule, and only when the text happened to contain
the exact localpart - `@bjoern` never notified `bjoern.marten`.
"""
mentions = {}
if user_ids:
mentions["user_ids"] = list(dict.fromkeys(user_ids))
if room:
mentions["room"] = True
return mentions
def inject_pills(markdown: str, user_ids) -> str:
"""Turn a plain `@localpart` into a pill link, for the HTML body only.
The plain-text body is left alone on purpose: it keeps the bare localpart,
which is what the legacy push rule reads, and it is what a client without
HTML shows. A name that does not appear in the text is not inserted -
`m.mentions` already carries the notification, and silently rewriting
someone's message is worse than a missing pill.
"""
for user_id in user_ids or []:
if f"{MATRIX_TO}{user_id}" in markdown:
# Already pilled by hand. Wrapping the link text again produces a
# link inside a link, which renders as neither.
continue
localpart = user_id.split(":")[0].lstrip("@")
pattern = re.compile(rf"(?<!\]\()@?{re.escape(localpart)}\b")
def replace(match, user_id=user_id, localpart=localpart):
return mention_pill(user_id, localpart)
markdown = pattern.sub(replace, markdown, count=1)
return markdown
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |