-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove_toc.py
54 lines (48 loc) · 2.06 KB
/
remove_toc.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
"""
This script removes TOC and Back-to-top links generated by the
generate_toc.py script.
author: Fabrizio Musacchio (https://www.fabriziomusacchio.com)
date: 19.02.2022
"""
# %% IMPORTS
import sys
import re
# %% MAIN ROUTINE
Current_Markdown_Text = sys.argv[1]
"""
The following text conversion and re-conversion has to be performed,
as the shell echo of multiline text within the Applescript introduces
a a type of linebreaks other than "\n", which is not interpretable by
Python. The following procedure re-introduces the "\n"-linebreaks:
"""
Current_Markdown_New_Text = Current_Markdown_Text.splitlines()
Current_Markdown_New_Text_tmp = [Current_Markdown_New_Text[0]]
#Current_Markdown_New_Text_tmp.append(Current_Markdown_New_Text[0])
# Scan the text for "#" and create the TOC:
for line_idx, line in enumerate(Current_Markdown_New_Text[1:]):
line_idx+=1
if line.startswith("#"):
# remove any id in headlines from a previous run:
line_cleaned = re.sub(r'\s*\[.*\]', '', line)
# update the current cleaned heading:
Current_Markdown_New_Text_tmp.append(line_cleaned)
elif line=="<div style='text-align: right;'><a href='#toc'>Toc ↑</a></div>":
# remove any previously place Back-to-top link and some whitespace:
if Current_Markdown_New_Text_tmp[-1] == '':
del Current_Markdown_New_Text_tmp[-1]
else:
Current_Markdown_New_Text_tmp.append(line)
# remove the TOC-section:
for line_idx, line in enumerate(Current_Markdown_New_Text_tmp):
if line == '<!-- TOC START -->':
toc_start_idx = line_idx
if line == '<!-- TOC END -->':
toc_end_idx = line_idx
if toc_start_idx!=0 and toc_end_idx!=0:
Current_Markdown_New_Text_tmp2 = []
Current_Markdown_New_Text_tmp2+=Current_Markdown_New_Text_tmp[0:toc_start_idx]
Current_Markdown_New_Text_tmp2+=Current_Markdown_New_Text_tmp[toc_end_idx+1:]
else:
Current_Markdown_New_Text_tmp2 = Current_Markdown_New_Text_tmp
Current_Markdown_New_Text = '\n'.join(Current_Markdown_New_Text_tmp2)
print(Current_Markdown_New_Text)