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

2024/9/20 0:26:51

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?

Answer

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

import markdown
from markdown.inlinepatterns import PatternEXTRA_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 elclass 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?!

https://en.xdnf.cn/q/72753.html

Related Q&A

Best way to read aws credentials file

In my python code I need to extract AWS credentials AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID which are stored in the plain text file as described here: https://docs.aws.amazon.com/sdkref/latest/guid…

Profiling on live Django server?

Ive never done code coverage in Python, but Im looking for something like GCCs gcov, which tells me how many times each line executes, or Apples Shark which gives a hierarchial breakdown of how long ea…

Inset axes anchored to specific points in data coordinates?

Id like to be able to overlay multiple inset axes on top of a set of parent axes, something like this:Ideally, Id like the anchor point of each set of inset axes to be fixed in data coordinates, but fo…

No module named folium.plugins, Python 3.6

I am trying to import folium into a Jupyter notebook Im working on and I cannot seem to solve the import issues with the Folium library. Has anyone else solved this problem?After encountering an error…

How you enable CBC to return best solution when timelimit? (Pyomo)

I am trying to use CBC(v2.10.3) on Pyomo to solve for a integer linear problem.When executing the solver, I am currently setting a timelimit of 600s.opt = SolverFactory ("cbc")opt.options[sec…

SSL cert issue with Python Requests

Im making a request to a site which requires SSL cert to access. When I tried to access the URL, I get SSL Certificate errorimport requests proxies = {"https":"https://user:pwd@host:port…

MatplotLib get all annotation by axes

im doing a project with Python and Tkinter. I can plot an array of data and i also implemented a function to add annotation on plot when i click with the mouse, but now i need a list of all annotation…

Using Pandas to applymap with access to index/column?

Whats the most effective way to solve the following pandas problem? Heres a simplified example with some data in a data frame: import pandas as pd import numpy as np df = pd.DataFrame(np.random.randin…

Multiple URL segment in Flask and other Python frameowrks

Im building an application in both Bottle and Flask to see which I am more comfortable with as Django is too much batteries included.I have read through the routing documentation of both, which is very…

installing python modules that require gcc on shared hosting with no gcc or root access

Im using Hostgator shared as a production environment and I had a problem installing some python modules, after using:pip install MySQL-pythonpip install pillowresults in:unable to execute gcc: Permiss…