| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
# This script transforms markdown files into html and (optionally) nroff. The |
| 4 |
# output files are written into the current directory named for the input file |
| 5 |
# without the .md suffix and either the .html suffix or no suffix. |
| 6 |
# |
| 7 |
# If the input .md file has a section number at the end of the name (e.g., |
| 8 |
# rsync.1.md) a nroff file is also output (PROJ.NUM.md -> PROJ.NUM). |
| 9 |
# |
| 10 |
# The markdown input format has one extra extension: if a numbered list starts |
| 11 |
# at 0, it is turned into a description list. The dl's dt tag is taken from the |
| 12 |
# contents of the first tag inside the li, which is usually a p, code, or |
| 13 |
# strong tag. |
| 14 |
# |
| 15 |
# The cmarkgfm or commonmark lib is used to transforms the input file into |
| 16 |
# html. Then, the html.parser is used as a state machine that lets us tweak |
| 17 |
# the html and (optionally) output nroff data based on the html tags. |
| 18 |
# |
| 19 |
# If the string @USE_GFM_PARSER@ exists in the file, the string is removed and |
| 20 |
# a github-flavored-markup parser is used to parse the file. |
| 21 |
# |
| 22 |
# The man-page .md files also get the vars @VERSION@, @BINDIR@, and @LIBDIR@ |
| 23 |
# substituted. Some of these values depend on the Makefile $(prefix) (see the |
| 24 |
# generated Makefile). If the maintainer wants to build files for /usr/local |
| 25 |
# while creating release-ready man-page files for /usr, use the environment to |
| 26 |
# set RSYNC_OVERRIDE_PREFIX=/usr. |
| 27 |
|
| 28 |
# Copyright (C) 2020 - 2021 Wayne Davison |
| 29 |
# |
| 30 |
# This program is freely redistributable. |
| 31 |
|
| 32 |
import os, sys, re, argparse, subprocess, time |
| 33 |
from html.parser import HTMLParser |
| 34 |
|
| 35 |
VALID_PAGES = 'README INSTALL COPYING rsync.1 rrsync.1 rsync-ssl.1 rsyncd.conf.5'.split() |
| 36 |
|
| 37 |
CONSUMES_TXT = set('h1 h2 h3 p li pre'.split()) |
| 38 |
|
| 39 |
HTML_START = """\ |
| 40 |
<html><head> |
| 41 |
<title>%TITLE%</title> |
| 42 |
<meta charset="UTF-8"/> |
| 43 |
<link href="https://fonts.googleapis.com/css2?family=Roboto&family=Roboto+Mono&display=swap" rel="stylesheet"> |
| 44 |
<style> |
| 45 |
body { |
| 46 |
max-width: 50em; |
| 47 |
margin: auto; |
| 48 |
} |
| 49 |
body, b, strong, u { |
| 50 |
font-family: 'Roboto', sans-serif; |
| 51 |
} |
| 52 |
a.tgt { font-face: symbol; font-weight: 400; font-size: 70%; visibility: hidden; text-decoration: none; color: #ddd; padding: 0 4px; border: 0; } |
| 53 |
a.tgt:after { content: '🔗'; } |
| 54 |
a.tgt:hover { color: #444; background-color: #eaeaea; } |
| 55 |
h1:hover > a.tgt, h2:hover > a.tgt, h3:hover > a.tgt, dt:hover > a.tgt { visibility: visible; } |
| 56 |
code { |
| 57 |
font-family: 'Roboto Mono', monospace; |
| 58 |
font-weight: bold; |
| 59 |
white-space: pre; |
| 60 |
} |
| 61 |
pre code { |
| 62 |
display: block; |
| 63 |
font-weight: normal; |
| 64 |
} |
| 65 |
blockquote pre code { |
| 66 |
background: #f1f1f1; |
| 67 |
} |
| 68 |
dd p:first-of-type { |
| 69 |
margin-block-start: 0em; |
| 70 |
} |
| 71 |
</style> |
| 72 |
</head><body> |
| 73 |
""" |
| 74 |
|
| 75 |
TABLE_STYLE = """\ |
| 76 |
table { |
| 77 |
border-color: grey; |
| 78 |
border-spacing: 0; |
| 79 |
} |
| 80 |
tr { |
| 81 |
border-top: 1px solid grey; |
| 82 |
} |
| 83 |
tr:nth-child(2n) { |
| 84 |
background-color: #f6f8fa; |
| 85 |
} |
| 86 |
th, td { |
| 87 |
border: 1px solid #dfe2e5; |
| 88 |
text-align: center; |
| 89 |
padding-left: 1em; |
| 90 |
padding-right: 1em; |
| 91 |
} |
| 92 |
""" |
| 93 |
|
| 94 |
MAN_HTML_END = """\ |
| 95 |
<div style="float: right"><p><i>%s</i></p></div> |
| 96 |
""" |
| 97 |
|
| 98 |
HTML_END = """\ |
| 99 |
</body></html> |
| 100 |
""" |
| 101 |
|
| 102 |
MAN_START = r""" |
| 103 |
.TH "%s" "%s" "%s" "%s" "User Commands" |
| 104 |
.\" prefix=%s |
| 105 |
""".lstrip() |
| 106 |
|
| 107 |
MAN_END = """\ |
| 108 |
""" |
| 109 |
|
| 110 |
NORM_FONT = ('\1', r"\fP") |
| 111 |
BOLD_FONT = ('\2', r"\fB") |
| 112 |
UNDR_FONT = ('\3', r"\fI") |
| 113 |
NBR_DASH = ('\4', r"\-") |
| 114 |
NBR_SPACE = ('\xa0', r"\ ") |
| 115 |
|
| 116 |
FILENAME_RE = re.compile(r'^(?P<fn>(?P<srcdir>.+/)?(?P<name>(?P<prog>[^/]+?)(\.(?P<sect>\d+))?)\.md)$') |
| 117 |
ASSIGNMENT_RE = re.compile(r'^(\w+)=(.+)') |
| 118 |
VER_RE = re.compile(r'^#define\s+RSYNC_VERSION\s+"(\d.+?)"', re.M) |
| 119 |
TZ_RE = re.compile(r'^#define\s+MAINTAINER_TZ_OFFSET\s+(-?\d+(\.\d+)?)', re.M) |
| 120 |
VAR_REF_RE = re.compile(r'\$\{(\w+)\}') |
| 121 |
VERSION_RE = re.compile(r' (\d[.\d]+)[, ]') |
| 122 |
BIN_CHARS_RE = re.compile(r'[\1-\7]+') |
| 123 |
LONG_OPT_DASH_RE = re.compile(r'(--\w[-\w]+)') |
| 124 |
SPACE_DOUBLE_DASH_RE = re.compile(r'\s--(\s)') |
| 125 |
NON_SPACE_SINGLE_DASH_RE = re.compile(r'(^|\W)-') |
| 126 |
WHITESPACE_RE = re.compile(r'\s') |
| 127 |
CODE_BLOCK_RE = re.compile(r'[%s]([^=%s]+)[=%s]' % (BOLD_FONT[0], NORM_FONT[0], NORM_FONT[0])) |
| 128 |
NBR_DASH_RE = re.compile(r'[%s]' % NBR_DASH[0]) |
| 129 |
INVALID_TARGET_CHARS_RE = re.compile(r'[^-A-Za-z0-9._]') |
| 130 |
INVALID_START_CHAR_RE = re.compile(r'^([^A-Za-z0-9])') |
| 131 |
MANIFY_LINESTART_RE = re.compile(r"^(['.])", flags=re.M) |
| 132 |
|
| 133 |
md_parser = None |
| 134 |
env_subs = { } |
| 135 |
|
| 136 |
warning_count = 0 |
| 137 |
|
| 138 |
def main(): |
| 139 |
for mdfn in args.mdfiles: |
| 140 |
parse_md_file(mdfn) |
| 141 |
|
| 142 |
if args.test: |
| 143 |
print("The test was successful.") |
| 144 |
|
| 145 |
|
| 146 |
def parse_md_file(mdfn): |
| 147 |
fi = FILENAME_RE.match(mdfn) |
| 148 |
if not fi: |
| 149 |
die('Failed to parse a md input file name:', mdfn) |
| 150 |
fi = argparse.Namespace(**fi.groupdict()) |
| 151 |
fi.want_manpage = not not fi.sect |
| 152 |
if fi.want_manpage: |
| 153 |
fi.title = fi.prog + '(' + fi.sect + ') manpage' |
| 154 |
else: |
| 155 |
fi.title = fi.prog + ' for rsync' |
| 156 |
|
| 157 |
if fi.want_manpage: |
| 158 |
if not env_subs: |
| 159 |
find_man_substitutions() |
| 160 |
prog_ver = 'rsync ' + env_subs['VERSION'] |
| 161 |
if fi.prog != 'rsync': |
| 162 |
prog_ver = fi.prog + ' from ' + prog_ver |
| 163 |
fi.man_headings = (fi.prog, fi.sect, env_subs['date'], prog_ver, env_subs['prefix']) |
| 164 |
|
| 165 |
with open(mdfn, 'r', encoding='utf-8') as fh: |
| 166 |
txt = fh.read() |
| 167 |
|
| 168 |
use_gfm_parser = '@USE_GFM_PARSER@' in txt |
| 169 |
if use_gfm_parser: |
| 170 |
txt = txt.replace('@USE_GFM_PARSER@', '') |
| 171 |
|
| 172 |
if fi.want_manpage: |
| 173 |
txt = (txt.replace('@VERSION@', env_subs['VERSION']) |
| 174 |
.replace('@BINDIR@', env_subs['bindir']) |
| 175 |
.replace('@LIBDIR@', env_subs['libdir'])) |
| 176 |
|
| 177 |
if use_gfm_parser: |
| 178 |
if not gfm_parser: |
| 179 |
die('Input file requires cmarkgfm parser:', mdfn) |
| 180 |
fi.html_in = gfm_parser(txt) |
| 181 |
else: |
| 182 |
fi.html_in = md_parser(txt) |
| 183 |
txt = None |
| 184 |
|
| 185 |
TransformHtml(fi) |
| 186 |
|
| 187 |
if args.test: |
| 188 |
return |
| 189 |
|
| 190 |
output_list = [ (fi.name + '.html', fi.html_out) ] |
| 191 |
if fi.want_manpage: |
| 192 |
output_list += [ (fi.name, fi.man_out) ] |
| 193 |
for fn, txt in output_list: |
| 194 |
if args.dest and args.dest != '.': |
| 195 |
fn = os.path.join(args.dest, fn) |
| 196 |
if os.path.lexists(fn): |
| 197 |
os.unlink(fn) |
| 198 |
print("Wrote:", fn) |
| 199 |
with open(fn, 'w', encoding='utf-8') as fh: |
| 200 |
fh.write(txt) |
| 201 |
|
| 202 |
|
| 203 |
def find_man_substitutions(): |
| 204 |
srcdir = os.path.dirname(sys.argv[0]) + '/' |
| 205 |
mtime = 0 |
| 206 |
|
| 207 |
git_dir = srcdir + '.git' |
| 208 |
if os.path.lexists(git_dir): |
| 209 |
mtime = int(subprocess.check_output(['git', '--git-dir', git_dir, 'log', '-1', '--format=%at'])) |
| 210 |
|
| 211 |
# Allow "prefix" to be overridden via the environment: |
| 212 |
env_subs['prefix'] = os.environ.get('RSYNC_OVERRIDE_PREFIX', None) |
| 213 |
|
| 214 |
if args.test: |
| 215 |
env_subs['VERSION'] = '1.0.0' |
| 216 |
env_subs['bindir'] = '/usr/bin' |
| 217 |
env_subs['libdir'] = '/usr/lib/rsync' |
| 218 |
tz_offset = 0 |
| 219 |
else: |
| 220 |
for fn in (srcdir + 'version.h', 'Makefile'): |
| 221 |
try: |
| 222 |
st = os.lstat(fn) |
| 223 |
except OSError: |
| 224 |
die('Failed to find', srcdir + fn) |
| 225 |
if not mtime: |
| 226 |
mtime = st.st_mtime |
| 227 |
|
| 228 |
with open(srcdir + 'version.h', 'r', encoding='utf-8') as fh: |
| 229 |
txt = fh.read() |
| 230 |
m = VER_RE.search(txt) |
| 231 |
env_subs['VERSION'] = m.group(1) |
| 232 |
m = TZ_RE.search(txt) # the tzdata lib may not be installed, so we use a simple hour offset |
| 233 |
tz_offset = float(m.group(1)) * 60 * 60 |
| 234 |
|
| 235 |
with open('Makefile', 'r', encoding='utf-8') as fh: |
| 236 |
for line in fh: |
| 237 |
m = ASSIGNMENT_RE.match(line) |
| 238 |
if not m: |
| 239 |
continue |
| 240 |
var, val = (m.group(1), m.group(2)) |
| 241 |
if var == 'prefix' and env_subs[var] is not None: |
| 242 |
continue |
| 243 |
while VAR_REF_RE.search(val): |
| 244 |
val = VAR_REF_RE.sub(lambda m: env_subs[m.group(1)], val) |
| 245 |
env_subs[var] = val |
| 246 |
if var == 'srcdir': |
| 247 |
break |
| 248 |
|
| 249 |
env_subs['date'] = time.strftime('%d %b %Y', time.gmtime(mtime + tz_offset)).lstrip('0') |
| 250 |
|
| 251 |
if 'SOURCE_DATE_EPOCH' in os.environ: |
| 252 |
env_subs['date'] = time.strftime('%d %b %Y', time.gmtime(int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))) |
| 253 |
|
| 254 |
|
| 255 |
def html_via_commonmark(txt): |
| 256 |
return commonmark.HtmlRenderer().render(commonmark.Parser().parse(txt)) |
| 257 |
|
| 258 |
|
| 259 |
class TransformHtml(HTMLParser): |
| 260 |
def __init__(self, fi): |
| 261 |
HTMLParser.__init__(self, convert_charrefs=True) |
| 262 |
|
| 263 |
self.fn = fi.fn |
| 264 |
|
| 265 |
st = self.state = argparse.Namespace( |
| 266 |
list_state = [ ], |
| 267 |
p_macro = ".P\n", |
| 268 |
at_first_tag_in_li = False, |
| 269 |
at_first_tag_in_dd = False, |
| 270 |
dt_from = None, |
| 271 |
in_pre = False, |
| 272 |
in_code = False, |
| 273 |
html_out = [ HTML_START.replace('%TITLE%', fi.title) ], |
| 274 |
man_out = [ ], |
| 275 |
txt = '', |
| 276 |
want_manpage = fi.want_manpage, |
| 277 |
created_hashtags = set(), |
| 278 |
derived_hashtags = set(), |
| 279 |
referenced_hashtags = set(), |
| 280 |
bad_hashtags = set(), |
| 281 |
latest_targets = [ ], |
| 282 |
opt_prefix = 'opt', |
| 283 |
a_href = None, |
| 284 |
a_href_external = False, |
| 285 |
a_txt_start = None, |
| 286 |
after_a_tag = False, |
| 287 |
target_suf = '', |
| 288 |
) |
| 289 |
|
| 290 |
if st.want_manpage: |
| 291 |
st.man_out.append(MAN_START % fi.man_headings) |
| 292 |
|
| 293 |
if '</table>' in fi.html_in: |
| 294 |
st.html_out[0] = st.html_out[0].replace('</style>', TABLE_STYLE + '</style>') |
| 295 |
|
| 296 |
self.feed(fi.html_in) |
| 297 |
fi.html_in = None |
| 298 |
|
| 299 |
if st.want_manpage: |
| 300 |
st.html_out.append(MAN_HTML_END % env_subs['date']) |
| 301 |
st.html_out.append(HTML_END) |
| 302 |
st.man_out.append(MAN_END) |
| 303 |
|
| 304 |
fi.html_out = ''.join(st.html_out) |
| 305 |
st.html_out = None |
| 306 |
|
| 307 |
fi.man_out = ''.join(st.man_out) |
| 308 |
st.man_out = None |
| 309 |
|
| 310 |
for tgt, txt in st.derived_hashtags: |
| 311 |
derived = txt2target(txt, tgt) |
| 312 |
if derived not in st.created_hashtags: |
| 313 |
txt = BIN_CHARS_RE.sub('', txt.replace(NBR_DASH[0], '-').replace(NBR_SPACE[0], ' ')) |
| 314 |
warn('Unknown derived hashtag link in', self.fn, 'based on:', (tgt, txt)) |
| 315 |
|
| 316 |
for bad in st.bad_hashtags: |
| 317 |
if bad in st.created_hashtags: |
| 318 |
warn('Missing "#" in hashtag link in', self.fn + ':', bad) |
| 319 |
else: |
| 320 |
warn('Unknown non-hashtag link in', self.fn + ':', bad) |
| 321 |
|
| 322 |
for bad in st.referenced_hashtags - st.created_hashtags: |
| 323 |
warn('Unknown hashtag link in', self.fn + ':', '#' + bad) |
| 324 |
|
| 325 |
def handle_UE(self): |
| 326 |
st = self.state |
| 327 |
if st.txt.startswith(('.', ',', '!', '?', ';', ':')): |
| 328 |
st.man_out[-1] = ".UE " + st.txt[0] + "\n" |
| 329 |
st.txt = st.txt[1:] |
| 330 |
st.after_a_tag = False |
| 331 |
|
| 332 |
def handle_starttag(self, tag, attrs_list): |
| 333 |
st = self.state |
| 334 |
if args.debug: |
| 335 |
self.output_debug('START', (tag, attrs_list)) |
| 336 |
if st.at_first_tag_in_li: |
| 337 |
if st.list_state[-1] == 'dl': |
| 338 |
st.dt_from = tag |
| 339 |
if tag == 'p': |
| 340 |
tag = 'dt' |
| 341 |
else: |
| 342 |
st.html_out.append('<dt>') |
| 343 |
elif tag == 'p': |
| 344 |
st.at_first_tag_in_dd = True # Kluge to suppress a .P at the start of an li. |
| 345 |
st.at_first_tag_in_li = False |
| 346 |
if tag == 'p': |
| 347 |
if not st.at_first_tag_in_dd: |
| 348 |
st.man_out.append(st.p_macro) |
| 349 |
elif tag == 'li': |
| 350 |
st.at_first_tag_in_li = True |
| 351 |
lstate = st.list_state[-1] |
| 352 |
if lstate == 'dl': |
| 353 |
return |
| 354 |
if lstate == 'o': |
| 355 |
st.man_out.append(".IP o\n") |
| 356 |
else: |
| 357 |
st.man_out.append(".IP " + str(lstate) + ".\n") |
| 358 |
st.list_state[-1] += 1 |
| 359 |
elif tag == 'blockquote': |
| 360 |
st.man_out.append(".RS 4\n") |
| 361 |
elif tag == 'pre': |
| 362 |
st.in_pre = True |
| 363 |
st.man_out.append(st.p_macro + ".nf\n") |
| 364 |
elif tag == 'code' and not st.in_pre: |
| 365 |
st.in_code = True |
| 366 |
st.txt += BOLD_FONT[0] |
| 367 |
elif tag == 'strong' or tag == 'b': |
| 368 |
st.txt += BOLD_FONT[0] |
| 369 |
elif tag == 'em' or tag == 'i': |
| 370 |
if st.want_manpage: |
| 371 |
tag = 'u' # Change it into underline to be more like the manpage |
| 372 |
st.txt += UNDR_FONT[0] |
| 373 |
elif tag == 'ol': |
| 374 |
start = 1 |
| 375 |
for var, val in attrs_list: |
| 376 |
if var == 'start': |
| 377 |
start = int(val) # We only support integers. |
| 378 |
break |
| 379 |
if st.list_state: |
| 380 |
st.man_out.append(".RS\n") |
| 381 |
if start == 0: |
| 382 |
tag = 'dl' |
| 383 |
attrs_list = [ ] |
| 384 |
st.list_state.append('dl') |
| 385 |
else: |
| 386 |
st.list_state.append(start) |
| 387 |
st.man_out.append(st.p_macro) |
| 388 |
st.p_macro = ".IP\n" |
| 389 |
elif tag == 'ul': |
| 390 |
st.man_out.append(st.p_macro) |
| 391 |
if st.list_state: |
| 392 |
st.man_out.append(".RS\n") |
| 393 |
st.p_macro = ".IP\n" |
| 394 |
st.list_state.append('o') |
| 395 |
elif tag == 'hr': |
| 396 |
st.man_out.append(".l\n") |
| 397 |
st.html_out.append("<hr />") |
| 398 |
return |
| 399 |
elif tag == 'a': |
| 400 |
st.a_href = None |
| 401 |
for var, val in attrs_list: |
| 402 |
if var == 'href': |
| 403 |
if val.startswith(('https://', 'http://', 'mailto:', 'ftp:')): |
| 404 |
if st.after_a_tag: |
| 405 |
self.handle_UE() |
| 406 |
st.man_out.append(manify(st.txt.strip()) + "\n") |
| 407 |
st.man_out.append(".UR " + val + "\n") |
| 408 |
st.txt = '' |
| 409 |
st.a_href = val |
| 410 |
st.a_href_external = True |
| 411 |
elif '#' in val: |
| 412 |
pg, tgt = val.split('#', 1) |
| 413 |
if pg and pg not in VALID_PAGES or '#' in tgt: |
| 414 |
st.bad_hashtags.add(val) |
| 415 |
elif tgt in ('', 'opt', 'dopt'): |
| 416 |
st.a_href = val |
| 417 |
st.a_href_external = False |
| 418 |
elif pg == '': |
| 419 |
st.referenced_hashtags.add(tgt) |
| 420 |
if tgt in st.latest_targets: |
| 421 |
warn('Found link to the current section in', self.fn + ':', val) |
| 422 |
elif val not in VALID_PAGES: |
| 423 |
st.bad_hashtags.add(val) |
| 424 |
st.a_txt_start = len(st.txt) |
| 425 |
st.html_out.append('<' + tag + ''.join(' ' + var + '="' + htmlify(val) + '"' for var, val in attrs_list) + '>') |
| 426 |
st.at_first_tag_in_dd = False |
| 427 |
|
| 428 |
|
| 429 |
def handle_endtag(self, tag): |
| 430 |
st = self.state |
| 431 |
if args.debug: |
| 432 |
self.output_debug('END', (tag,)) |
| 433 |
if st.after_a_tag: |
| 434 |
self.handle_UE() |
| 435 |
if tag in CONSUMES_TXT or st.dt_from == tag: |
| 436 |
txt = st.txt.strip() |
| 437 |
st.txt = '' |
| 438 |
else: |
| 439 |
txt = None |
| 440 |
add_to_txt = None |
| 441 |
if tag == 'h1': |
| 442 |
tgt = txt |
| 443 |
target_suf = '' |
| 444 |
if tgt.startswith('NEWS for '): |
| 445 |
m = VERSION_RE.search(tgt) |
| 446 |
if m: |
| 447 |
tgt = m.group(1) |
| 448 |
st.target_suf = '-' + tgt |
| 449 |
self.add_targets(tag, tgt) |
| 450 |
elif tag == 'h2': |
| 451 |
st.man_out.append(st.p_macro + '.SH "' + manify(txt) + '"\n') |
| 452 |
self.add_targets(tag, txt, st.target_suf) |
| 453 |
st.opt_prefix = 'dopt' if txt == 'DAEMON OPTIONS' else 'opt' |
| 454 |
elif tag == 'h3': |
| 455 |
st.man_out.append(st.p_macro + '.SS "' + manify(txt) + '"\n') |
| 456 |
self.add_targets(tag, txt, st.target_suf) |
| 457 |
elif tag == 'p': |
| 458 |
if st.dt_from == 'p': |
| 459 |
tag = 'dt' |
| 460 |
st.man_out.append('.IP "' + manify(txt) + '"\n') |
| 461 |
if txt.startswith(BOLD_FONT[0]): |
| 462 |
self.add_targets(tag, txt) |
| 463 |
st.dt_from = None |
| 464 |
elif txt != '': |
| 465 |
st.man_out.append(manify(txt) + "\n") |
| 466 |
elif tag == 'li': |
| 467 |
if st.list_state[-1] == 'dl': |
| 468 |
if st.at_first_tag_in_li: |
| 469 |
die("Invalid 0. -> td translation") |
| 470 |
tag = 'dd' |
| 471 |
if txt != '': |
| 472 |
st.man_out.append(manify(txt) + "\n") |
| 473 |
st.at_first_tag_in_li = False |
| 474 |
elif tag == 'blockquote': |
| 475 |
st.man_out.append(".RE\n") |
| 476 |
elif tag == 'pre': |
| 477 |
st.in_pre = False |
| 478 |
st.man_out.append(manify(txt) + "\n.fi\n") |
| 479 |
elif (tag == 'code' and not st.in_pre): |
| 480 |
st.in_code = False |
| 481 |
add_to_txt = NORM_FONT[0] |
| 482 |
elif tag == 'strong' or tag == 'b': |
| 483 |
add_to_txt = NORM_FONT[0] |
| 484 |
elif tag == 'em' or tag == 'i': |
| 485 |
if st.want_manpage: |
| 486 |
tag = 'u' # Change it into underline to be more like the manpage |
| 487 |
add_to_txt = NORM_FONT[0] |
| 488 |
elif tag == 'ol' or tag == 'ul': |
| 489 |
if st.list_state.pop() == 'dl': |
| 490 |
tag = 'dl' |
| 491 |
if st.list_state: |
| 492 |
st.man_out.append(".RE\n") |
| 493 |
else: |
| 494 |
st.p_macro = ".P\n" |
| 495 |
st.at_first_tag_in_dd = False |
| 496 |
elif tag == 'hr': |
| 497 |
return |
| 498 |
elif tag == 'a': |
| 499 |
if st.a_href_external: |
| 500 |
st.txt = st.txt.strip() |
| 501 |
if args.force_link_text or st.a_href != st.txt: |
| 502 |
st.man_out.append(manify(st.txt) + "\n") |
| 503 |
st.man_out.append(".UE\n") # This might get replaced with a punctuation version in handle_UE() |
| 504 |
st.after_a_tag = True |
| 505 |
st.a_href_external = False |
| 506 |
st.txt = '' |
| 507 |
elif st.a_href: |
| 508 |
atxt = st.txt[st.a_txt_start:] |
| 509 |
find = 'href="' + st.a_href + '"' |
| 510 |
for j in range(len(st.html_out)-1, 0, -1): |
| 511 |
if find in st.html_out[j]: |
| 512 |
pg, tgt = st.a_href.split('#', 1) |
| 513 |
derived = txt2target(atxt, tgt) |
| 514 |
if pg == '': |
| 515 |
if derived in st.latest_targets: |
| 516 |
warn('Found link to the current section in', self.fn + ':', st.a_href) |
| 517 |
st.derived_hashtags.add((tgt, atxt)) |
| 518 |
st.html_out[j] = st.html_out[j].replace(find, 'href="' + pg + '#' + derived + '"') |
| 519 |
break |
| 520 |
else: |
| 521 |
die('INTERNAL ERROR: failed to find href in html data:', find) |
| 522 |
st.html_out.append('</' + tag + '>') |
| 523 |
if add_to_txt: |
| 524 |
if txt is None: |
| 525 |
st.txt += add_to_txt |
| 526 |
else: |
| 527 |
txt += add_to_txt |
| 528 |
if st.dt_from == tag: |
| 529 |
st.man_out.append('.IP "' + manify(txt) + '"\n') |
| 530 |
st.html_out.append('</dt><dd>') |
| 531 |
st.at_first_tag_in_dd = True |
| 532 |
st.dt_from = None |
| 533 |
elif tag == 'dt': |
| 534 |
st.html_out.append('<dd>') |
| 535 |
st.at_first_tag_in_dd = True |
| 536 |
|
| 537 |
|
| 538 |
def handle_data(self, txt): |
| 539 |
st = self.state |
| 540 |
if '](' in txt: |
| 541 |
warn('Malformed link in', self.fn + ':', txt) |
| 542 |
if args.debug: |
| 543 |
self.output_debug('DATA', (txt,)) |
| 544 |
if st.in_pre: |
| 545 |
html = htmlify(txt) |
| 546 |
else: |
| 547 |
txt = LONG_OPT_DASH_RE.sub(lambda x: x.group(1).replace('-', NBR_DASH[0]), txt) |
| 548 |
txt = SPACE_DOUBLE_DASH_RE.sub(NBR_SPACE[0] + r'--\1', txt).replace('--', NBR_DASH[0]*2) |
| 549 |
txt = NON_SPACE_SINGLE_DASH_RE.sub(r'\1' + NBR_DASH[0], txt) |
| 550 |
html = htmlify(txt) |
| 551 |
if st.in_code: |
| 552 |
txt = WHITESPACE_RE.sub(NBR_SPACE[0], txt) |
| 553 |
html = html.replace(NBR_DASH[0], '-').replace(NBR_SPACE[0], ' ') # <code> is non-breaking in CSS |
| 554 |
st.html_out.append(html.replace(NBR_SPACE[0], ' ').replace(NBR_DASH[0], '-⁠')) |
| 555 |
st.txt += txt |
| 556 |
|
| 557 |
|
| 558 |
def add_targets(self, tag, txt, suf=None): |
| 559 |
st = self.state |
| 560 |
tag = '<' + tag + '>' |
| 561 |
targets = CODE_BLOCK_RE.findall(txt) |
| 562 |
if not targets: |
| 563 |
targets = [ txt ] |
| 564 |
tag_pos = 0 |
| 565 |
for txt in targets: |
| 566 |
txt = txt2target(txt, st.opt_prefix) |
| 567 |
if not txt: |
| 568 |
continue |
| 569 |
if suf: |
| 570 |
txt += suf |
| 571 |
if txt in st.created_hashtags: |
| 572 |
for j in range(2, 1000): |
| 573 |
chk = txt + '-' + str(j) |
| 574 |
if chk not in st.created_hashtags: |
| 575 |
print('Made link target unique:', chk) |
| 576 |
txt = chk |
| 577 |
break |
| 578 |
if tag_pos == 0: |
| 579 |
tag_pos -= 1 |
| 580 |
while st.html_out[tag_pos] != tag: |
| 581 |
tag_pos -= 1 |
| 582 |
st.html_out[tag_pos] = tag[:-1] + ' id="' + txt + '">' |
| 583 |
st.html_out.append('<a href="#' + txt + '" class="tgt"></a>') |
| 584 |
tag_pos -= 1 # take into account the append |
| 585 |
else: |
| 586 |
st.html_out[tag_pos] = '<span id="' + txt + '"></span>' + st.html_out[tag_pos] |
| 587 |
st.created_hashtags.add(txt) |
| 588 |
st.latest_targets = targets |
| 589 |
|
| 590 |
|
| 591 |
def output_debug(self, event, extra): |
| 592 |
import pprint |
| 593 |
st = self.state |
| 594 |
if args.debug < 2: |
| 595 |
st = argparse.Namespace(**vars(st)) |
| 596 |
if len(st.html_out) > 2: |
| 597 |
st.html_out = ['...'] + st.html_out[-2:] |
| 598 |
if len(st.man_out) > 2: |
| 599 |
st.man_out = ['...'] + st.man_out[-2:] |
| 600 |
print(event, extra) |
| 601 |
pprint.PrettyPrinter(indent=2).pprint(vars(st)) |
| 602 |
|
| 603 |
|
| 604 |
def txt2target(txt, opt_prefix): |
| 605 |
txt = txt.strip().rstrip(':') |
| 606 |
m = CODE_BLOCK_RE.search(txt) |
| 607 |
if m: |
| 608 |
txt = m.group(1) |
| 609 |
txt = NBR_DASH_RE.sub('-', txt) |
| 610 |
txt = BIN_CHARS_RE.sub('', txt) |
| 611 |
txt = INVALID_TARGET_CHARS_RE.sub('_', txt) |
| 612 |
if opt_prefix and txt.startswith('-'): |
| 613 |
txt = opt_prefix + txt |
| 614 |
else: |
| 615 |
txt = INVALID_START_CHAR_RE.sub(r't\1', txt) |
| 616 |
return txt |
| 617 |
|
| 618 |
|
| 619 |
def manify(txt): |
| 620 |
return MANIFY_LINESTART_RE.sub(r'\&\1', txt.replace('\\', '\\\\') |
| 621 |
.replace(NBR_SPACE[0], NBR_SPACE[1]) |
| 622 |
.replace(NBR_DASH[0], NBR_DASH[1]) |
| 623 |
.replace(NORM_FONT[0], NORM_FONT[1]) |
| 624 |
.replace(BOLD_FONT[0], BOLD_FONT[1]) |
| 625 |
.replace(UNDR_FONT[0], UNDR_FONT[1])) |
| 626 |
|
| 627 |
|
| 628 |
def htmlify(txt): |
| 629 |
return txt.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"') |
| 630 |
|
| 631 |
|
| 632 |
def warn(*msg): |
| 633 |
print(*msg, file=sys.stderr) |
| 634 |
global warning_count |
| 635 |
warning_count += 1 |
| 636 |
|
| 637 |
|
| 638 |
def die(*msg): |
| 639 |
warn(*msg) |
| 640 |
sys.exit(1) |
| 641 |
|
| 642 |
|
| 643 |
if __name__ == '__main__': |
| 644 |
parser = argparse.ArgumentParser(description="Convert markdown into html and (optionally) nroff. Each input filename must have a .md suffix, which is changed to .html for the output filename. If the input filename ends with .num.md (e.g. foo.1.md) then a nroff file is also output with the input filename's .md suffix removed (e.g. foo.1).", add_help=False) |
| 645 |
parser.add_argument('--test', action='store_true', help="Just test the parsing without outputting any files.") |
| 646 |
parser.add_argument('--dest', metavar='DIR', help="Create files in DIR instead of the current directory.") |
| 647 |
parser.add_argument('--force-link-text', action='store_true', help="Don't remove the link text if it matches the link href. Useful when nroff doesn't understand .UR and .UE.") |
| 648 |
parser.add_argument('--debug', '-D', action='count', default=0, help='Output copious info on the html parsing. Repeat for even more.') |
| 649 |
parser.add_argument("--help", "-h", action="help", help="Output this help message and exit.") |
| 650 |
parser.add_argument("mdfiles", metavar='FILE.md', nargs='+', help="One or more .md files to convert.") |
| 651 |
args = parser.parse_args() |
| 652 |
|
| 653 |
try: |
| 654 |
import cmarkgfm |
| 655 |
md_parser = cmarkgfm.markdown_to_html |
| 656 |
gfm_parser = cmarkgfm.github_flavored_markdown_to_html |
| 657 |
except: |
| 658 |
try: |
| 659 |
import commonmark |
| 660 |
md_parser = html_via_commonmark |
| 661 |
except: |
| 662 |
die("Failed to find cmarkgfm or commonmark for python3.") |
| 663 |
gfm_parser = None |
| 664 |
|
| 665 |
main() |
| 666 |
if warning_count: |
| 667 |
sys.exit(1) |