简体   繁体   中英

Convert Markdown links to HTML with Pandoc

In my new project I have multiple Markdown files which are linked to each other. These links refer to the original .md files.

Example:

File README.md

...
1. [Development documentation](Development.md)
1. [User documentation](Usage.md)
...

If I convert these files with Pandoc, eg, to HTML files, all links are still pointing to the original .md file. I'm looking for a way to also convert the link type, which means that output files should refer to the output file type such as HTML, PDF, TeX , etc. Is there a way to convert the internal link type with Pandoc?

I use this to convert the files:

pandoc -f markdown -t html5 input.md -o output.html

Example with the built-in Lua filters :

# links-to-html.lua
function Link(el)
  el.target = string.gsub(el.target, "%.md", ".html")
  return el
end

Then:

pandoc -f markdown -t html5 input.md -o output.html --lua-filter=links-to-html.lua

You can create a filter that checks every link element and—if the URL ends with .md —replaces it with .html .

Example with Python, using the panflute package:

import panflute as pf

def action(elem, doc):
    if isinstance(elem, pf.Link) and elem.url.endswith('.md'):
        elem.url = elem.url[:-3] + '.html'
        return elem

if __name__ == '__main__':
    pf.run_filter(action)

Assuming you are going to serve you HTML pages via a web server, it is relatively simple to resolve all *.md URLs as *.html ones instead of rewriting them via Pandoc, eg, using NGinx :

location ~ \.md$ {
  if (!-f $request_filename) {
    rewrite ^(.*)\.md$ $1 permanent;
  }
}

location / {
  try_files /$uri /$uri.html;
}

Alternatively, you can replace all md links with html using sed (taken from here ):

Change all internal file URLs from pointing to *.md links and instead point to the local *.html file

  1. recursively run this sed command (programmatically replace FILENAME)

     sed -n -i.bak '/href="\./s/\.md/\.html/' FILENAME.html
  2. alternatively, run the following command instead (programmatically replace FILENAME)

     sed -e '/href="\./s/\.md/\.html/' FILENAME.html > FILENAME.html.tmp && mv FILENAME.html.tmp FILENAME.html`

I had a similar problem, so I made md_htmldoc .

It finds all of the .md files in a directory and then makes a separate directory where all the Markdown files has been converted to HTML.

It fixes hyperlinks (thanks to Sergio Correia's answer ).

It also gathers up any local file references so that links to images and such still work.

For anyone using a Makefile to drive conversion, here is a Makefile fragment that provides a rule transforming a .md into a .html with link adjusted:

SHELL=/bin/bash

%.html: %.md
    ( set -eu -o pipefail ; \
    pandoc -i $< -t html | \
    sed -E 's/<a href="([^"]*).md/<a href="\1.html/g' > $@.tmp && mv -vf $@.tmp $@ ; )

If test.md exists in current directory, make test.html will do it.

The rule also takes care of not clobbering an existing HTML file (whatever the reason) until the conversion actually succeeds.

A slight modification to Sergio Correia's answer also catches anchor links in documents. Take care; in some rare cases this might garble links...

import panflute as pf

def action(elem, doc):
    if isinstance(elem, pf.Link):
        if elem.url.endswith('.md'):
            elem.url = elem.url[:-3] + '.html'
            return elem
        elif elem.url.find('.md#'):
            elem.url = elem.url.replace('.md#', '.html#')
            return elem

if __name__ == '__main__':
    pf.run_filter(action)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM