-
Notifications
You must be signed in to change notification settings - Fork 0
/
gfm-to-commonmark.py
executable file
·56 lines (47 loc) · 1.58 KB
/
gfm-to-commonmark.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# Author: Manuel Bucher <dev@manuelbucher.com>
# Date: 2023-01-09
# This file fixes new line management from github flavored markdown to commonmark
import sys
def rewrite_newlines(inp):
out = ""
num_empty = 0 # max 2 newlines
code = False
for line in inp:
start = line.strip()
if start == "":
if num_empty == 0:
out += "\n"
num_empty += 1
continue
else:
num_empty = 0
if start.startswith('```'):
code = not code
if len(start) > 2 and (start[0] == '*' or start[0] == '-') and start[1] != ' ' and start[1] != '*' and start[1] != '-':
star = line.find('*')
dash = line.find('-')
elems = []
if star != -1:
elems.append(star)
if dash != -1:
elems.append(dash)
star = min(elems)
line = line[:star+1] + " " + line[star+1:]
start = start[0]
out += line.rstrip() + '\n'
if start != '-' and start != '*' and not line[0].isspace() and not code:
out += '\n'
num_empty = 1
return out
def main():
for file in sys.argv[1:]:
inp = open(file).readlines()
out = rewrite_newlines(inp)
with open(file, 'w') as f:
f.write(out)
if __name__ == '__main__':
main()