]> git.madduck.net Git - etc/mutt.git/blob - .mutt/markdown2html

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

e0a2b19677adb121ba4dabf01df2afb8dcfce281
[etc/mutt.git] / .mutt / markdown2html
1 #!/usr/bin/python3
2 #
3 # markdown2html.py — simple Markdown-to-HTML converter for use with Mutt
4 #
5 # Mutt recently learnt [how to compose `multipart/alternative`
6 # emails][1]. This script assumes a message has been composed using Markdown
7 # (with a lot of pandoc extensions enabled), and translates it to `text/html`
8 # for Mutt to tie into such a `multipart/alternative` message.
9 #
10 # [1]: https://gitlab.com/muttmua/mutt/commit/0e566a03725b4ad789aa6ac1d17cdf7bf4e7e354)
11 #
12 # Configuration:
13 #   muttrc:
14 #     set send_multipart_alternative=yes
15 #     set send_multipart_alternative_filter=/path/to/markdown2html.py
16 #
17 # Optionally, Custom CSS styles will be read from `~/.mutt/markdown2html.css`,
18 # if present.
19 #
20 # Requirements:
21 #   - python3
22 #   - PyPandoc (and pandoc installed, or downloaded)
23 #   - Pynliner
24 #
25 # Optional:
26 #   - Pygments, if installed, then syntax highlighting is enabled
27 #
28 # Latest version:
29 #   https://git.madduck.net/etc/mutt.git/blob_plain/HEAD:/.mutt/markdown2html
30 #
31 # Copyright © 2019 martin f. krafft <madduck@madduck.net>
32 # Released under the GPL-2+ licence, just like Mutt itself.
33 #
34
35 import pypandoc
36 import pynliner
37 import re
38 import os
39 import sys
40
41 try:
42     from pygments.formatters import get_formatter_by_name
43     formatter = get_formatter_by_name('html', style='default')
44     DEFAULT_CSS = formatter.get_style_defs('.sourceCode')
45
46 except ImportError:
47     DEFAULT_CSS = ""
48
49
50 DEFAULT_CSS += '''
51 .block {
52     padding: 0 0.5em;
53     margin: 0;
54     border-left: 2px solid #eee;
55 }
56 .quote, blockquote {
57     padding: 0 0.5em;
58     margin: 0;
59     font-style: italic;
60     border-left: 2px solid #666;
61     color: #666;
62     font-size: 80%;
63 }
64 .quotelead {
65     margin-bottom: -1em;
66     font-size: 80%;
67 }
68 .quotechar { display: none; }
69 .footnote-ref, .footnote-back { text-decoration: none;}
70 .signature {
71     color: #999;
72     font-family: monospace;
73     white-space: pre;
74     margin: 1em 0 0 0;
75     font-size: 80%;
76 }
77 table, th, td {
78     border-collapse: collapse;
79     border: 1px solid #999;
80 }
81 th, td { padding: 0.5em; }
82 .header {
83     background: #eee;
84 }
85 .even { background: #eee; }
86 h1, h2, h3, h4, h5, h6 {
87     color: #666;
88     background-color: #eee;
89     padding-left: 0.5em
90 }
91 h1 { font-size: 130%; }
92 h2 { font-size: 120%; }
93 h3 { font-size: 110%; }
94 h4 { font-size: 107%; }
95 h5 { font-size: 103%; }
96 h6 { font-size: 100%; }
97 p { padding: 0 0.5em; }
98 '''
99
100 STYLESHEET = os.path.join(os.path.expanduser('~/.mutt'),
101                           'markdown2html.css')
102 if os.path.exists(STYLESHEET):
103     DEFAULT_CSS += open(STYLESHEET).read()
104
105 HTML_DOCUMENT = '''<!DOCTYPE html>
106 <html><head>
107 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
108 <meta charset="utf-8"/>
109 <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes"/>
110 </head><body class="email">
111 {htmlbody}
112 </body></html>'''
113
114
115 SIGNATURE_HTML = \
116         '<div class="signature"><span class="leader">-- </span>{sig}</div>'
117
118
119 def _preprocess_markdown(mdwn):
120     '''
121     Preprocess Markdown for handling by the converter.
122     '''
123     # convert hard line breaks within paragraphs to 2 trailing spaces, which
124     # is the markdown way of representing hard line breaks. Note how the
125     # regexp will not match between paragraphs.
126     ret = re.sub(r'(\S)\n(\s*\S)', r'\g<1>  \n\g<2>', mdwn, flags=re.MULTILINE)
127
128     # Clients like Thunderbird need the leading '>' to be able to properly
129     # create nested quotes, so we duplicate the symbol, the first instance
130     # will tell pandoc to create a blockquote, while the second instance will
131     # be a <span> containing the character, along with a class that causes CSS
132     # to actually hide it from display. However, this does not work with the
133     # text-mode HTML2text converters, and so it's left commented for now.
134     #ret = re.sub(r'\n>', r'  \n>[>]{.quotechar}', ret, flags=re.MULTILINE)
135
136     return ret
137
138
139 def _identify_quotes_for_later(mdwn):
140     '''
141     Email quoting such as:
142
143     ```
144     On 1970-01-01, you said:
145     > The Flat Earth Society has members all around the globe.
146     ```
147
148     isn't really properly handled by Markdown, so let's do our best to
149     identify the individual elements, and mark them, using a syntax similar to
150     what pandoc uses already in some cases. As pandoc won't actually use these
151     data (yet?), we call `self._reformat_quotes` later to use these markers
152     to slap the appropriate classes on the HTML tags.
153     '''
154
155     def generate_lines_with_context(mdwn):
156         '''
157         Iterates the input string line-wise, returning a triplet of
158         previous, current, and next line, the first and last of which
159         will be None on the first and last line of the input data
160         respectively.
161         '''
162         prev = cur = nxt = None
163         lines = iter(mdwn.splitlines())
164         cur = next(lines)
165         for nxt in lines:
166             yield prev, cur, nxt
167             prev = cur
168             cur = nxt
169         yield prev, cur, None
170
171     ret = []
172     for prev, cur, nxt in generate_lines_with_context(mdwn):
173
174         # The lead-in to a quote is a single line immediately preceding the
175         # quote, and ending with ':'. Note that there could be multiple of
176         # these:
177         if re.match(r'^.+:\s*$', cur) and nxt.startswith('>'):
178             ret.append(f'{{.quotelead}}{cur.strip()}')
179             # pandoc needs an empty line before the blockquote, so
180             # we enter one for the purpose of HTML rendition:
181             ret.append('')
182             continue
183
184         # The first blockquote after such a lead-in gets marked as the
185         # "initial" quote:
186         elif prev and re.match(r'^.+:\s*$', prev) and cur.startswith('>'):
187             ret.append(re.sub(r'^(\s*>\s*)+(.+)',
188                               r'\g<1>{.quoteinitial}\g<2>',
189                               cur, flags=re.MULTILINE))
190
191         # All other occurrences of blockquotes get the "subsequent" marker:
192         elif cur.startswith('>') and prev and not prev.startswith('>'):
193             ret.append(re.sub(r'^((?:\s*>\s*)+)(.+)',
194                               r'\g<1>{.quotesubsequent}\g<2>',
195                               cur, flags=re.MULTILINE))
196
197         else: # pass through everything else.
198             ret.append(cur)
199
200     return '\n'.join(ret)
201
202
203 def _reformat_quotes(html):
204     '''
205     Earlier in the pipeline, we marked email quoting, using markers, which we
206     now need to turn into HTML classes, so that we can use CSS to style them.
207     '''
208     ret = html.replace('<p>{.quotelead}', '<p class="quotelead">')
209     ret = re.sub(r'<blockquote>\n((?:<blockquote>\n)*)<p>(?:\{\.quote(\w+)\})',
210                  r'<blockquote class="quote \g<2>">\n\g<1><p>', ret, flags=re.MULTILINE)
211     return ret
212
213
214
215 def _convert_with_pandoc(mdwn, inputfmt='markdown', outputfmt='html5',
216                          ext_enabled=None, ext_disabled=None,
217                          standalone=True, selfcontained=True, title=None):
218     '''
219     Invoke pandoc to do the actual conversion of Markdown to HTML5.
220     '''
221     if not ext_enabled:
222         ext_enabled = [ 'backtick_code_blocks',
223                        'line_blocks',
224                        'fancy_lists',
225                        'startnum',
226                        'definition_lists',
227                        'example_lists',
228                        'table_captions',
229                        'simple_tables',
230                        'multiline_tables',
231                        'grid_tables',
232                        'pipe_tables',
233                        'all_symbols_escapable',
234                        'intraword_underscores',
235                        'strikeout',
236                        'superscript',
237                        'subscript',
238                        'fenced_divs',
239                        'bracketed_spans',
240                        'footnotes',
241                        'inline_notes',
242                        'emoji',
243                        'tex_math_double_backslash',
244                        'autolink_bare_uris'
245                       ]
246     if not ext_disabled:
247         ext_disabled = [ 'tex_math_single_backslash',
248                          'tex_math_dollars',
249                          'smart',
250                          'raw_html'
251                        ]
252
253     enabled = '+'.join(ext_enabled)
254     disabled = '-'.join(ext_disabled)
255     inputfmt = f'{inputfmt}+{enabled}-{disabled}'
256
257     args = []
258     if standalone:
259         args.append('--standalone')
260     if selfcontained:
261         args.append('--self-contained')
262     if title:
263         args.append(f'--metadata=pagetitle:"{title}"')
264
265     return pypandoc.convert_text(mdwn, format=inputfmt, to=outputfmt,
266                                  extra_args=args)
267
268
269 def _apply_styling(html):
270     '''
271     Inline all styles defined and used into the individual HTML tags.
272     '''
273     return pynliner.Pynliner().from_string(html).with_cssString(DEFAULT_CSS).run()
274
275
276 def _postprocess_html(html):
277     '''
278     Postprocess the generated and styled HTML.
279     '''
280     return html
281
282
283 def convert_markdown_to_html(mdwn):
284     '''
285     Converts the input Markdown to HTML, handling separately the body, as well
286     as an optional signature.
287     '''
288     parts = re.split(r'^-- $', mdwn, 1, flags=re.MULTILINE)
289     body = parts[0]
290     if len(parts) == 2:
291         sig = parts[1]
292     else:
293         sig = None
294
295     html=''
296     if body:
297         body = _preprocess_markdown(body)
298         body = _identify_quotes_for_later(body)
299         html = _convert_with_pandoc(body, standalone=True, selfcontained=True)
300         html = _reformat_quotes(html)
301
302     if sig:
303         sig = _preprocess_markdown(sig)
304         html += SIGNATURE_HTML.format(sig='<br/>'.join(sig.splitlines()))
305
306     html = HTML_DOCUMENT.format(htmlbody=html)
307     html = _apply_styling(html)
308     html = _postprocess_html(html)
309
310     return html
311
312
313 def main():
314     '''
315     Convert text on stdin to HTML, and print it to stdout, like mutt would
316     expect.
317     '''
318     html = convert_markdown_to_html(sys.stdin.read())
319     if html:
320         # mutt expects the content type in the first line, so:
321         print(f'text/html\n\n{html}')
322
323
324 if __name__ == '__main__':
325     main()