Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Link patterns - customizing link text #71

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 23 additions & 4 deletions lib/markdown2.py
Expand Up @@ -1755,21 +1755,40 @@ def _do_link_patterns(self, text):
lookbehind assertion to attempt to guard against this. lookbehind assertion to attempt to guard against this.
""" """
link_from_hash = {} link_from_hash = {}
for regex, repl in self.link_patterns: for pattern in self.link_patterns:
replacements = [] replacements = []

if len(pattern) == 3:
regex, repl, repl_title = pattern
else:
regex, repl = pattern
repl_title = link_text = None

for match in regex.finditer(text): for match in regex.finditer(text):

if hasattr(repl, "__call__"): if hasattr(repl, "__call__"):
href = repl(match) href = repl(match)
else: else:
href = match.expand(repl) href = match.expand(repl)
replacements.append((match.span(), href))
for (start, end), href in reversed(replacements): if repl_title != None:
if hasattr(repl_title, "__call__"):
link_text = repl_title(match)
else:
link_text = match.expand(repl_title)

replacements.append((match.span(), href, link_text))
for (start, end), href, new_text in reversed(replacements):
escaped_href = ( escaped_href = (
href.replace('"', '"') # b/c of attr quote href.replace('"', '"') # b/c of attr quote
# To avoid markdown <em> and <strong>: # To avoid markdown <em> and <strong>:
.replace('*', self._escape_table['*']) .replace('*', self._escape_table['*'])
.replace('_', self._escape_table['_'])) .replace('_', self._escape_table['_']))
link = '<a href="%s">%s</a>' % (escaped_href, text[start:end])
if new_text == None:
new_text = text[start:end]

link = '<a href="%s">%s</a>' % (escaped_href, new_text)
hash = _hash_text(link) hash = _hash_text(link)
link_from_hash[hash] = link link_from_hash[hash] = link
text = text[:start] + hash + text[end:] text = text[:start] + hash + text[end:]
Expand Down