I was asked to create a product manual with a mechanism similar to a simplified version of O'Reilly Atlas. I wanted to use Asciidoctor to create the manual, so I decided to write it in AsciiDoc format, but it was easier to get used to Markdown format, so I had to convert from Markdown format to AsciiDoc format. It was. I thought I could afford to use pandoc, but I couldn't convert as I intended.
If you use pandoc, you should study Haskell and fix it, but I don't have time, so I wondered if I could make a conversion program using Python's Markdown parser library.
The table is as follows.
Evaluation item | Python-Markdown | Misaka | Mistune |
---|---|---|---|
URL | https://github.com/waylan/Python-Markdown | https://github.com/FSX/misaka | https://github.com/lepture/mistune |
license | BSD | MIT | BSD |
Implementation | python | python + C | python |
Corresponding version | Python 2.7, 3.3+ and PyPy | Python 2.7, 3.2+ and PyPy 2.6 | Python 2.6+, Python 3.3+ and PyPy |
Output custom | × | ◯ | ◯ |
Remarks | Depends on Hoedown |
Python-Markdown is a path because you can't customize the output. Misaka seems to be dead, but it's a pass because it depends on Hoedown.
I decided to use Mistune by the elimination method, so I will implement it using this.
It seems to work with Python 2.6 or higher, so I confirmed the operation with 2.7.11.
pip install mistune
It's easy!
We have prepared the following Markdown format files and sources for HTML conversion. It is almost the same as what is written in the official Basic Usage.
test.md
#Sample documentation
##Chapter XX
###Section XXX
convert.py
import mistune
with open('test.md', 'r') as test_file:
markdown = mistune.Markdown()
print markdown(test_file.read())
And run it.
python convert.py
Then, the output result is as follows.
output
<h1>Sample documentation</h1>
<h2>Chapter XX</h2>
<h3>Section XXX</h3>
Since it is partially applied, it seems good to prepare a template separately from the HTML definition etc. and make it as if rewriting only the contents of the Body.
Now the main subject.
It seems that mistune should inherit the Renderer class and override the item (method) you want to output. This time, I want to replace the heading tag with section in AsciiDoc format, so I made it as follows.
custom_render.py
import mistune
class CustomRenderer(mistune.Renderer):
def header(self, text, level, raw=None):
section = '=' * level
return '{0} {1}\n'.format(section, text)
if __name__ == '__main__':
custom_renderer = CustomRenderer()
with open('test.md', 'r') as test_file:
markdown = mistune.Markdown(renderer=custom_renderer)
print markdown(test_file.read())
I will do it.
python custom_render.py
The result is as follows.
output
=Sample documentation
==Chapter XX
===Section XXX
I got the results I expected!
After that, if you override the method from the required syntax and arrange the output format, you can convert the format.
Recommended Posts