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;
48 margin-block-start: 0em;
55 <div style="float: right"><p><i>%s</i></p></div>
60 .TH "%s" "%s" "%s" "%s" "User Commands"
66 NORM_FONT = ('\1', r"\fP")
67 BOLD_FONT = ('\2', r"\fB")
68 UNDR_FONT = ('\3', r"\fI")
69 NBR_DASH = ('\4', r"\-")
70 NBR_SPACE = ('\xa0', r"\ ")
75 fi = re.match(r'^(?P<fn>(?P<srcdir>.+/)?(?P<name>(?P<prog>[^/]+)\.(?P<sect>\d+))\.md)$', args.mdfile)
77 die('Failed to parse NAME.NUM.md out of input file:', args.mdfile)
78 fi = argparse.Namespace(**fi.groupdict())
83 fi.title = fi.prog + '(' + fi.sect + ') man page'
86 git_dir = fi.srcdir + '.git'
87 if os.path.lexists(git_dir):
88 fi.mtime = int(subprocess.check_output(['git', '--git-dir', git_dir, 'log', '-1', '--format=%at']))
90 env_subs = { 'prefix': os.environ.get('RSYNC_OVERRIDE_PREFIX', None) }
93 env_subs['VERSION'] = '1.0.0'
94 env_subs['libdir'] = '/usr'
96 for fn in (fi.srcdir + 'NEWS.md', 'Makefile'):
100 die('Failed to find', fi.srcdir + fn)
102 fi.mtime = st.st_mtime
104 with open('Makefile', 'r', encoding='utf-8') as fh:
106 m = re.match(r'^(\w+)=(.+)', line)
109 var, val = (m.group(1), m.group(2))
110 if var == 'prefix' and env_subs[var] is not None:
112 while re.search(r'\$\{', val):
113 val = re.sub(r'\$\{(\w+)\}', lambda m: env_subs[m.group(1)], val)
118 with open(fi.fn, 'r', encoding='utf-8') as fh:
121 txt = re.sub(r'@VERSION@', env_subs['VERSION'], txt)
122 txt = re.sub(r'@LIBDIR@', env_subs['libdir'], txt)
124 fi.html_in = md_parser(txt)
127 fi.date = time.strftime('%d %b %Y', time.localtime(fi.mtime))
128 fi.man_headings = (fi.prog, fi.sect, fi.date, fi.prog + ' ' + env_subs['VERSION'])
133 print("The test was successful.")
136 for fn, txt in ((fi.name + '.html', fi.html_out), (fi.name, fi.man_out)):
138 with open(fn, 'w', encoding='utf-8') as fh:
142 def html_via_cmarkgfm(txt):
143 return cmarkgfm.markdown_to_html(txt)
146 def html_via_commonmark(txt):
147 return commonmark.HtmlRenderer().render(commonmark.Parser().parse(txt))
150 class HtmlToManPage(HTMLParser):
151 def __init__(self, fi):
152 HTMLParser.__init__(self, convert_charrefs=True)
154 st = self.state = argparse.Namespace(
157 at_first_tag_in_li = False,
158 at_first_tag_in_dd = False,
162 html_out = [ HTML_START % fi.title ],
163 man_out = [ MAN_START % fi.man_headings ],
167 self.feed(fi.html_in)
170 st.html_out.append(HTML_END % fi.date)
171 st.man_out.append(MAN_END)
173 fi.html_out = ''.join(st.html_out)
176 fi.man_out = ''.join(st.man_out)
180 def handle_starttag(self, tag, attrs_list):
183 self.output_debug('START', (tag, attrs_list))
184 if st.at_first_tag_in_li:
185 if st.list_state[-1] == 'dl':
190 st.html_out.append('<dt>')
192 st.at_first_tag_in_dd = True # Kluge to suppress a .P at the start of an li.
193 st.at_first_tag_in_li = False
195 if not st.at_first_tag_in_dd:
196 st.man_out.append(st.p_macro)
198 st.at_first_tag_in_li = True
199 lstate = st.list_state[-1]
203 st.man_out.append(".IP o\n")
205 st.man_out.append(".IP " + str(lstate) + ".\n")
206 st.list_state[-1] += 1
207 elif tag == 'blockquote':
208 st.man_out.append(".RS 4\n")
211 st.man_out.append(st.p_macro + ".nf\n")
212 elif tag == 'code' and not st.in_pre:
214 st.txt += BOLD_FONT[0]
215 elif tag == 'strong' or tag == 'b':
216 st.txt += BOLD_FONT[0]
217 elif tag == 'em' or tag == 'i':
218 tag = 'u' # Change it into underline to be more like the man page
219 st.txt += UNDR_FONT[0]
222 for var, val in attrs_list:
224 start = int(val) # We only support integers.
227 st.man_out.append(".RS\n")
231 st.list_state.append('dl')
233 st.list_state.append(start)
234 st.man_out.append(st.p_macro)
237 st.man_out.append(st.p_macro)
239 st.man_out.append(".RS\n")
241 st.list_state.append('o')
242 st.html_out.append('<' + tag + ''.join(' ' + var + '="' + htmlify(val) + '"' for var, val in attrs_list) + '>')
243 st.at_first_tag_in_dd = False
246 def handle_endtag(self, tag):
249 self.output_debug('END', (tag,))
250 if tag in CONSUMES_TXT or st.dt_from == tag:
257 st.man_out.append(st.p_macro + '.SH "' + manify(txt) + '"\n')
259 st.man_out.append(st.p_macro + '.SS "' + manify(txt) + '"\n')
261 if st.dt_from == 'p':
263 st.man_out.append('.IP "' + manify(txt) + '"\n')
266 st.man_out.append(manify(txt) + "\n")
268 if st.list_state[-1] == 'dl':
269 if st.at_first_tag_in_li:
270 die("Invalid 0. -> td translation")
273 st.man_out.append(manify(txt) + "\n")
274 st.at_first_tag_in_li = False
275 elif tag == 'blockquote':
276 st.man_out.append(".RE\n")
279 st.man_out.append(manify(txt) + "\n.fi\n")
280 elif (tag == 'code' and not st.in_pre):
282 add_to_txt = NORM_FONT[0]
283 elif tag == 'strong' or tag == 'b':
284 add_to_txt = NORM_FONT[0]
285 elif tag == 'em' or tag == 'i':
286 tag = 'u' # Change it into underline to be more like the man page
287 add_to_txt = NORM_FONT[0]
288 elif tag == 'ol' or tag == 'ul':
289 if st.list_state.pop() == 'dl':
292 st.man_out.append(".RE\n")
295 st.at_first_tag_in_dd = False
296 st.html_out.append('</' + tag + '>')
302 if st.dt_from == tag:
303 st.man_out.append('.IP "' + manify(txt) + '"\n')
304 st.html_out.append('</dt><dd>')
305 st.at_first_tag_in_dd = True
308 st.html_out.append('<dd>')
309 st.at_first_tag_in_dd = True
312 def handle_data(self, txt):
315 self.output_debug('DATA', (txt,))
319 txt = re.sub(r'\s--(\s)', NBR_SPACE[0] + r'--\1', txt).replace('--', NBR_DASH[0]*2)
320 txt = re.sub(r'(^|\W)-', r'\1' + NBR_DASH[0], txt)
323 txt = re.sub(r'\s', NBR_SPACE[0], txt)
324 html = html.replace(NBR_DASH[0], '-').replace(NBR_SPACE[0], ' ') # <code> is non-breaking in CSS
325 st.html_out.append(html.replace(NBR_SPACE[0], ' ').replace(NBR_DASH[0], '-⁠'))
329 def output_debug(self, event, extra):
333 st = argparse.Namespace(**vars(st))
334 if len(st.html_out) > 2:
335 st.html_out = ['...'] + st.html_out[-2:]
336 if len(st.man_out) > 2:
337 st.man_out = ['...'] + st.man_out[-2:]
339 pprint.PrettyPrinter(indent=2).pprint(vars(st))
343 return re.sub(r"^(['.])", r'\&\1', txt.replace('\\', '\\\\')
344 .replace(NBR_SPACE[0], NBR_SPACE[1])
345 .replace(NBR_DASH[0], NBR_DASH[1])
346 .replace(NORM_FONT[0], NORM_FONT[1])
347 .replace(BOLD_FONT[0], BOLD_FONT[1])
348 .replace(UNDR_FONT[0], UNDR_FONT[1]), flags=re.M)
352 return txt.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"')
356 print(*msg, file=sys.stderr)
364 if __name__ == '__main__':
365 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)
366 parser.add_argument('--test', action='store_true', help='Test if we can parse the input w/o updating any files.')
367 parser.add_argument('--debug', '-D', action='count', default=0, help='Output copious info on the html parsing. Repeat for even more.')
368 parser.add_argument("--help", "-h", action="help", help="Output this help message and exit.")
369 parser.add_argument('mdfile', help="The NAME.NUM.md file to parse.")
370 args = parser.parse_args()
374 md_parser = html_via_cmarkgfm
378 md_parser = html_via_commonmark
380 die("Failed to find cmarkgfm or commonmark for python3.")