-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextensions.py
41 lines (33 loc) · 1.45 KB
/
extensions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""
Based on https://github.com/kriwil/markdown-newtab
New Tab Extension for Python-Markdown
=====================================
Modify the behavior of specially-formatted links in Python-Markdown to open a in a new
window if and only if the 'href' attribute of these links begins with 'newtab+'
This changes the HTML output to add target="_blank" to such elements.
Example:
[www.example.com](newtab+https://www.example.com)
"""
from markdown import Extension
from markdown.inlinepatterns import \
LinkInlineProcessor, ReferenceInlineProcessor, AutolinkInlineProcessor, AutomailInlineProcessor, \
ShortReferenceInlineProcessor, \
LINK_RE, REFERENCE_RE, AUTOLINK_RE, AUTOMAIL_RE
class NewTabMixin(object):
def handleMatch(self, m, data):
el, start, end = super(NewTabMixin, self).handleMatch(m, data)
if el is not None:
current_href = el.get('href','')
if current_href.startswith('newtab+'):
new_href = current_href.replace('newtab+', '')
el.set('href', new_href)
el.set('target', '_blank')
return el, start, end
class NewTabLinkProcessor(NewTabMixin, LinkInlineProcessor):
pass
class NewTabExtension(Extension):
"""Modifies HTML output to open links in a new tab."""
def extendMarkdown(self, md):
md.inlinePatterns.register(NewTabLinkProcessor(LINK_RE, md), 'link', 160)
def makeExtension(**kwargs):
return NewTabExtension(**kwargs)