5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Pandoc】他の.mdファイルへのリンクを.htmlに書き換える

Last updated at Posted at 2017-02-13

PandocはMarkdownをHTMLやMS Wordに変換できるツールです。
http://pandoc.org/
http://sky-y.github.io/site-pandoc-jp/users-guide/

今回、Pandocを使って出力したHTMLファイルのリンク先のMarkdownもHTMLに変換したい場合、
リンクが.mdのままなのでリンクつながらないという問題があり、.mdのリンクを.htmlに変換する方法を調べたので投稿します。

参考
http://qiita.com/takada-at/items/187923e57071c0aa73a7
http://stackoverflow.com/questions/40993488/convert-markdown-links-to-html-with-pandoc

やりたいこと

Markdownで

[Document](./document.md)

などと書いた箇所のリンクが

<a href="./document.md">Document</a>

と変換されますが、これを

<a href="./document.html">Document</a>

という形にしたいです。

手順1. panfluteをインストール

Pythonのpanfluteというパッケージをインストールします。
http://scorreia.com/software/panflute/index.html

手順2. .pyファイルを作成する

こちらに書いてある通り、
下記のpyファイルを作成します。
(ファイル名は何でもいいですが、今回は「convertlink.py」とします)

convertlink.py
# coding:utf-8
import re
import panflute as pf

def action(elem, doc):
    if isinstance(elem, pf.Link):
        matches = list(re.finditer(r'(\.md)', elem.url))
        if matches:
            m = matches[-1]
            elem.url = elem.url[:m.start(1)] + '.html' + elem.url[m.end(1):]
            return elem

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

手順3. Pandoc実行時に引数--filterに、作った.pyファイルを指定する

こちらを参考にしました。

pandoc input.md --filter=./convertlink.py -t html5 -o output.html

結果

Markdownで

[Document](./document.md)

などと書いた箇所のリンクが

<a href="./document.html">Document</a>

に変換されていれば成功です。

5
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?