69 lines
2.0 KiB
Python
69 lines
2.0 KiB
Python
|
"""
|
||
|
Guild Journal Extension for Python-Markdown
|
||
|
======================================
|
||
|
|
||
|
Converts [[NPC/Frankie]] to links.
|
||
|
|
||
|
Original code Copyright [Waylan Limberg](http://achinghead.com/).
|
||
|
|
||
|
All changes Copyright The Python Markdown Project
|
||
|
|
||
|
License: [BSD](https://opensource.org/licenses/bsd-license.php)
|
||
|
|
||
|
"""
|
||
|
|
||
|
from markdown.extensions import Extension
|
||
|
from markdown.inlinepatterns import InlineProcessor
|
||
|
from guild.models import NPC, Character
|
||
|
import xml.etree.ElementTree as etree
|
||
|
|
||
|
|
||
|
def build_url(category: str, name):
|
||
|
"""Build a URL from the label, a base, and an end."""
|
||
|
if category.lower() == "char":
|
||
|
try:
|
||
|
return Character.get_by_name(name).get_absolute_url()
|
||
|
except Character.DoesNotExist:
|
||
|
return ""
|
||
|
elif category.lower() == "npc":
|
||
|
try:
|
||
|
return NPC.get_by_name(name).get_absolute_url()
|
||
|
except NPC.DoesNotExist:
|
||
|
return ""
|
||
|
return ""
|
||
|
|
||
|
|
||
|
class GuildLinkExtension(Extension):
|
||
|
def extendMarkdown(self, md):
|
||
|
self.md = md
|
||
|
|
||
|
# append to end of inline patterns
|
||
|
GUILD_RE = r"\[\[([\w0-9_ -]+)\/([\w0-9_ -]+)\]\]"
|
||
|
wikilinkPattern = GuildLinksInlineProcessor(GUILD_RE, self.getConfigs())
|
||
|
wikilinkPattern.md = md
|
||
|
md.inlinePatterns.register(wikilinkPattern, "guildlinks", 75)
|
||
|
|
||
|
|
||
|
class GuildLinksInlineProcessor(InlineProcessor):
|
||
|
def __init__(self, pattern, config):
|
||
|
super().__init__(pattern)
|
||
|
self.config = config
|
||
|
|
||
|
def handleMatch(self, m, data):
|
||
|
if m.group(1).strip() and m.group(2).strip():
|
||
|
category = m.group(1).strip()
|
||
|
name = m.group(2).strip()
|
||
|
url = build_url(category, name)
|
||
|
a = etree.Element("a")
|
||
|
a.text = name
|
||
|
a.set("href", url)
|
||
|
if url == "":
|
||
|
a.set("class", "invalid-url")
|
||
|
else:
|
||
|
a = ""
|
||
|
return a, m.start(0), m.end(0)
|
||
|
|
||
|
|
||
|
def makeExtension(**kwargs): # pragma: no cover
|
||
|
return GuildLinkExtension(**kwargs)
|