Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get python-markdown to additionally "urlify" links when formatting plain text?

Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:

http://www.google.com/

How do I get markdown to add tags to URLs when I format a block of text?

like image 447
andrewrk Avatar asked Oct 15 '08 06:10

andrewrk


4 Answers

You could write an extension to markdown. Save this code as mdx_autolink.py

import markdown
from markdown.inlinepatterns import Pattern

EXTRA_AUTOLINK_RE = r'(?<!"|>)((https?://|www)[-\w./#?%=&]+)'

class AutoLinkPattern(Pattern):

    def handleMatch(self, m):
        el = markdown.etree.Element('a')
        if m.group(2).startswith('http'):
            href = m.group(2)
        else:
            href = 'http://%s' % m.group(2)
        el.set('href', href)
        el.text = m.group(2)
        return el

class AutoLinkExtension(markdown.Extension):
    """
    There's already an inline pattern called autolink which handles 
    <http://www.google.com> type links. So lets call this extra_autolink 
    """

    def extendMarkdown(self, md, md_globals):
        md.inlinePatterns.add('extra_autolink', 
            AutoLinkPattern(EXTRA_AUTOLINK_RE, self), '<automail')

def makeExtension(configs=[]):
    return AutoLinkExtension(configs=configs)

Then use it in your template like this:

{% load markdown %}

(( content|markdown:'autolink'))

Update:

I've found an issue with this solution: When markdown's standard link syntax is used and the displayed portion matches the regular expression, eg:

[www.google.com](http://www.yahoo.co.uk)

strangely becomes: www.google.com

But who'd want to do that anyway?!

like image 148
SamBarnes Avatar answered Nov 06 '22 19:11

SamBarnes


Best case scenario, edit the markdown and just put < > around the URLs. This will make the link clickable. Only problem is it requires educating your users, or whoever writes the markdown.

like image 45
andrewrk Avatar answered Nov 06 '22 19:11

andrewrk


There's an extra for this in python-markdown2:

http://code.google.com/p/python-markdown2/wiki/LinkPatterns

like image 3
Jonny Buchanan Avatar answered Nov 06 '22 19:11

Jonny Buchanan


I couldn't get superjoe30's regular expression to compile, so I adapted his solution to convert plain URLs (within Markdown text) to be Markdown compatible.

The modified filter:

urlfinder = re.compile('^(http:\/\/\S+)')
urlfinder2 = re.compile('\s(http:\/\/\S+)')
@register.filter('urlify_markdown')
def urlify_markdown(value):
    value = urlfinder.sub(r'<\1>', value)
    return urlfinder2.sub(r' <\1>', value)

Within the template:

<div>
    {{ content|urlify_markdown|markdown}}
</div>
like image 2
csytan Avatar answered Nov 06 '22 20:11

csytan