-
Notifications
You must be signed in to change notification settings - Fork 1
/
gitoc.py
75 lines (59 loc) · 2.1 KB
/
gitoc.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import sys
headline_dic={'#':0,'##':1,'###':2,'####':3,'#####':4,'######':5}
suojin={0:-1,1:-1,2:-1,3:-1,4:-1,5:-1,6:-1}
def writefile(fp, str=None):
with open(fp,'w') as f:
f.write(str)
def detectHeadLines(f):
'''detact headline and return inserted string.
params:
f: Markdown file
'''
f.seek(0)
insert_str=""
org_str=""
last_status = -1
c_status=-1
headline_counter=0
iscode=False
for line in f.readlines():
if(line[:3]=='```'):
iscode= not iscode
# fix code indent bug.
if not iscode:
line=line.strip(' ')
ls=line.split(' ')
if len(ls)>1 and ls[0] in headline_dic.keys() and not iscode:
headline_counter+=1
c_status=headline_dic[ls[0]]
# find first rank headline
if last_status==-1 or c_status==0 or suojin[c_status]==0:
# init suojin
for key in suojin.keys():
suojin[key]=-1
suojin[c_status]=0
elif c_status>last_status:
suojin[c_status]=suojin[last_status]+1
# update headline text
headtext=' '.join(ls[1:-1])
if ls[-1][-1]=='\n':
headtext+=(' '+ls[-1][:-1])
else:
headtext+=(' '+ls[-1])
headid = '{}{}'.format('head',headline_counter)
headline=ls[0]+' <span id=\"{}\"'.format(headid)+'>'+ headtext+'</span>'+'\n'
org_str+=headline
jump_str='- [{}](#{}{})'.format(headtext,'head',headline_counter)
insert_str+=('\t'*suojin[c_status]+jump_str+'\n')
last_status=c_status
else:
org_str+=line
return insert_str+"\n"+org_str
if __name__=='__main__':
filename = sys.argv[1]
#print(filename)
f = open(filename,'r',encoding='utf-8')
insert_str=detectHeadLines(f)
f.close()
with open('{}.md'.format(filename[:filename.find('_')]),'w',encoding='utf-8') as f:
f.write(insert_str)