3 # This script takes a manpage written in markdown and turns it into an html web
4 # page and a nroff man page. The input file must have the name of the program
5 # and the section in this format: NAME.NUM.md. The output files are written
6 # into the current directory named NAME.NUM.html and NAME.NUM. The input
7 # format has one extra extension: if a numbered list starts at 0, it is turned
8 # into a description list. The dl's dt tag is taken from the contents of the
9 # first tag inside the li, which is usually a p, code, or strong tag. The
10 # cmarkgfm or commonmark lib is used to transforms the input file into html.
11 # The html.parser is used as a state machine that both tweaks the html and
12 # outputs the nroff data based on the html tags.
14 # Copyright (C) 2020 Wayne Davison
16 # This program is freely redistributable.
18 import sys, os, re, argparse, subprocess, time
19 from html.parser import HTMLParser
21 CONSUMES_TXT = set('h1 h2 p li pre'.split())
26 <link href="https://fonts.googleapis.com/css2?family=Roboto&family=Roboto+Mono&display=swap" rel="stylesheet">
33 font-family: 'Roboto', sans-serif;
36 font-family: 'Roboto Mono', monospace;
47 margin-block-start: 0em;
54 <div style="float: right"><p><i>%s</i></p></div>
59 .TH "%s" "%s" "%s" "%s" "User Commands"
65 NORM_FONT = ('\1', r"\fP")
66 BOLD_FONT = ('\2', r"\fB")
67 ULIN_FONT = ('\3', r"\fI")
72 fi = re.match(r'^(?P<fn>(?P<srcdir>.+/)?(?P<name>(?P<prog>[^/]+)\.(?P<sect>\d+))\.md)$', args.mdfile)
74 die('Failed to parse NAME.NUM.md out of input file:', args.mdfile)
75 fi = argparse.Namespace(**fi.groupdict())
80 fi.title = fi.prog + '(' + fi.sect + ') man page'
83 if os.path.lexists(fi.srcdir + '.git'):
84 fi.mtime = int(subprocess.check_output('git log -1 --format=%at'.split()))
86 env_subs = { 'prefix': os.environ.get('RSYNC_OVERRIDE_PREFIX', None) }
89 env_subs['VERSION'] = '1.0.0'
90 env_subs['libdir'] = '/usr'
92 for fn in 'NEWS.md Makefile'.split():
94 st = os.lstat(fi.srcdir + fn)
96 die('Failed to find', fi.srcdir + fn)
98 fi.mtime = st.st_mtime
100 with open(fi.srcdir + 'Makefile', 'r', encoding='utf-8') as fh:
102 m = re.match(r'^(\w+)=(.+)', line)
105 var, val = (m.group(1), m.group(2))
106 if var == 'prefix' and env_subs[var] is not None:
108 while re.search(r'\$\{', val):
109 val = re.sub(r'\$\{(\w+)\}', lambda m: env_subs[m.group(1)], val)
114 with open(fi.fn, 'r', encoding='utf-8') as fh:
117 txt = re.sub(r'@VERSION@', env_subs['VERSION'], txt)
118 txt = re.sub(r'@LIBDIR@', env_subs['libdir'], txt)
120 fi.html_in = md_parser(txt)
123 fi.date = time.strftime('%d %b %Y', time.localtime(fi.mtime))
124 fi.man_headings = (fi.prog, fi.sect, fi.date, fi.prog + ' ' + env_subs['VERSION'])
129 print("The test was successful.")
132 for fn, txt in ((fi.name + '.html', fi.html_out), (fi.name, fi.man_out)):
134 with open(fn, 'w', encoding='utf-8') as fh:
138 def html_via_cmarkgfm(txt):
139 return cmarkgfm.markdown_to_html(txt)
142 def html_via_commonmark(txt):
143 return commonmark.HtmlRenderer().render(commonmark.Parser().parse(txt))
146 class HtmlToManPage(HTMLParser):
147 def __init__(self, fi):
148 HTMLParser.__init__(self, convert_charrefs=True)
150 st = self.state = argparse.Namespace(
153 at_first_tag_in_li = False,
154 at_first_tag_in_dd = False,
158 html_out = [ HTML_START % fi.title ],
159 man_out = [ MAN_START % fi.man_headings ],
163 self.feed(fi.html_in)
166 st.html_out.append(HTML_END % fi.date)
167 st.man_out.append(MAN_END)
169 fi.html_out = ''.join(st.html_out)
172 fi.man_out = ''.join(st.man_out)
176 def handle_starttag(self, tag, attrs_list):
179 self.output_debug('START', (tag, attrs_list))
180 if st.at_first_tag_in_li:
181 if st.list_state[-1] == 'dl':
186 st.html_out.append('<dt>')
188 st.at_first_tag_in_dd = True # Kluge to suppress a .P at the start of an li.
189 st.at_first_tag_in_li = False
191 if not st.at_first_tag_in_dd:
192 st.man_out.append(st.p_macro)
194 st.at_first_tag_in_li = True
195 lstate = st.list_state[-1]
199 st.man_out.append(".IP o\n")
201 st.man_out.append(".IP " + str(lstate) + ".\n")
202 st.list_state[-1] += 1
203 elif tag == 'blockquote':
204 st.man_out.append(".RS 4\n")
207 st.man_out.append(st.p_macro + ".nf\n")
208 elif tag == 'code' and not st.in_pre:
210 st.txt += BOLD_FONT[0]
211 elif tag == 'strong' or tag == 'b':
212 st.txt += BOLD_FONT[0]
213 elif tag == 'em' or tag == 'i':
214 tag = 'u' # Change it into underline to be more like the man page
215 st.txt += ULIN_FONT[0]
218 for var, val in attrs_list:
220 start = int(val) # We only support integers.
223 st.man_out.append(".RS\n")
227 st.list_state.append('dl')
229 st.list_state.append(start)
230 st.man_out.append(st.p_macro)
233 st.man_out.append(st.p_macro)
235 st.man_out.append(".RS\n")
237 st.list_state.append('o')
238 st.html_out.append('<' + tag + ''.join(' ' + var + '="' + htmlify(val) + '"' for var, val in attrs_list) + '>')
239 st.at_first_tag_in_dd = False
242 def handle_endtag(self, tag):
245 self.output_debug('END', (tag,))
246 if tag in CONSUMES_TXT or st.dt_from == tag:
253 st.man_out.append(st.p_macro + '.SH "' + manify(txt) + '"\n')
255 st.man_out.append(st.p_macro + '.SS "' + manify(txt) + '"\n')
257 if st.dt_from == 'p':
259 st.man_out.append('.IP "' + manify(txt) + '"\n')
262 st.man_out.append(manify(txt) + "\n")
264 if st.list_state[-1] == 'dl':
265 if st.at_first_tag_in_li:
266 die("Invalid 0. -> td translation")
269 st.man_out.append(manify(txt) + "\n")
270 st.at_first_tag_in_li = False
271 elif tag == 'blockquote':
272 st.man_out.append(".RE\n")
275 st.man_out.append(manify(txt) + "\n.fi\n")
276 elif (tag == 'code' and not st.in_pre):
278 add_to_txt = NORM_FONT[0]
279 elif tag == 'strong' or tag == 'b':
280 add_to_txt = NORM_FONT[0]
281 elif tag == 'em' or tag == 'i':
282 tag = 'u' # Change it into underline to be more like the man page
283 add_to_txt = NORM_FONT[0]
284 elif tag == 'ol' or tag == 'ul':
285 if st.list_state.pop() == 'dl':
288 st.man_out.append(".RE\n")
291 st.at_first_tag_in_dd = False
292 st.html_out.append('</' + tag + '>')
298 if st.dt_from == tag:
299 st.man_out.append('.IP "' + manify(txt) + '"\n')
300 st.html_out.append('</dt><dd>')
301 st.at_first_tag_in_dd = True
304 st.html_out.append('<dd>')
305 st.at_first_tag_in_dd = True
308 def handle_data(self, data):
311 self.output_debug('DATA', (data,))
313 data = re.sub(r'\s', '\xa0', data) # nbsp in non-pre code
314 data = re.sub(r'\s--\s', '\xa0-- ', data)
315 st.html_out.append(htmlify(data))
319 def output_debug(self, event, extra):
323 st = argparse.Namespace(**vars(st))
324 if len(st.html_out) > 2:
325 st.html_out = ['...'] + st.html_out[-2:]
326 if len(st.man_out) > 2:
327 st.man_out = ['...'] + st.man_out[-2:]
329 pprint.PrettyPrinter(indent=2).pprint(vars(st))
333 return re.sub(r"^(['.])", r'\&\1', txt.replace('\\', '\\\\')
334 .replace("\xa0", r'\ ') # non-breaking space
335 .replace('--', r'\-\-') # non-breaking double dash
336 .replace(NORM_FONT[0], NORM_FONT[1])
337 .replace(BOLD_FONT[0], BOLD_FONT[1])
338 .replace(ULIN_FONT[0], ULIN_FONT[1]), flags=re.M)
342 return re.sub(r'(\W)-', r'\1‑',
343 txt.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')
344 .replace('--', '‑‑').replace("\xa0-", ' ‑').replace("\xa0", ' '))
348 print(*msg, file=sys.stderr)
356 if __name__ == '__main__':
357 parser = argparse.ArgumentParser(description='Transform a NAME.NUM.md markdown file into a NAME.NUM.html web page & a NAME.NUM man page.', add_help=False)
358 parser.add_argument('--test', action='store_true', help='Test if we can parse the input w/o updating any files.')
359 parser.add_argument('--debug', '-D', action='count', default=0, help='Output copious info on the html parsing. Repeat for even more.')
360 parser.add_argument("--help", "-h", action="help", help="Output this help message and exit.")
361 parser.add_argument('mdfile', help="The NAME.NUM.md file to parse.")
362 args = parser.parse_args()
366 md_parser = html_via_cmarkgfm
370 md_parser = html_via_commonmark
372 die("Failed to find cmarkgfm or commonmark for python3.")