-
Notifications
You must be signed in to change notification settings - Fork 863
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
Option to convert .md links to .html #1094
Comments
You could certainly write an extension to handle this, but this is not standard Markdown behavior, so you are unlikely to see this integrated by default in Python Markdown. |
Not sure if you resolved this, @venthur, and I didn't see any extensions. I have similar need / desire and I think this does what we want: import os
from markdown import markdown
from markdown import Extension
from markdown.inlinepatterns import LinkInlineProcessor
from markdown.inlinepatterns import LINK_RE
class CustomLinkInlineProcessor(LinkInlineProcessor):
def getLink(self, *args, **kwargs):
(href, title, index, handled) = super().getLink(*args, **kwargs)
parts = os.path.splitext(href)
ext = '.html' if (parts[1] == '.md') else parts[1]
href = ''.join((parts[0], ext))
return (href, title, index, handled)
class CustomLinkExtension(Extension):
def extendMarkdown(self, md):
md.inlinePatterns.deregister('link')
pattern = CustomLinkInlineProcessor(LINK_RE, md)
md.inlinePatterns.register(pattern, 'link', 160)
data = 'Some text and a [link](path/to/a/document.md).\n'
data += 'And a [normal link](http://www.google.com/image.jpg).\n'
data += 'More text.'
html = markdown(data, extensions=[CustomLinkExtension()])
print(f'ORIGINAL:\n{data}\nCONVERTED:\n{html}') I'm brand new to Python-Markdown as of yesterday, and I haven't (yet) packaged / tested this well. EDIT: Created a repository for this. |
Interesting, i solved it slightly differently using a class MarkdownLinkTreeprocessor(Treeprocessor):
"""Converts relative links to .md files to .html
"""
def run(self, root):
for element in root.iter():
if element.tag == 'a':
url = element.get('href')
converted = self.convert(url)
element.set('href', converted)
return root
def convert(self, url):
scheme, netloc, path, query, fragment = urlsplit(url)
logger.debug(
f'{url}: {scheme=} {netloc=} {path=} {query=} {fragment=}'
)
if (scheme or netloc or not path):
return url
if path.endswith('.md'):
path = path[:-3] + '.html'
url = urlunsplit((scheme, netloc, path, query, fragment))
return |
Excellent. Thank you. |
Created a simple extension repository. |
Hi,
when converting a tree of markdown documents with internal links, it would be useful to convert the link targets from
.md
to.html
as well.E.g.:
should point to
link.html
. I understand that that might not be the desired default behavior but it would surely be a useful addition.The text was updated successfully, but these errors were encountered: