-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmd_fixer_v3.py
64 lines (58 loc) · 1.78 KB
/
md_fixer_v3.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
from tkinter.filedialog import askopenfilenames
from os import chdir, path, getcwd
chdir(path.dirname(path.abspath(__file__)))
def main():
files = None
while not files:
try:
input("Press Enter to select the file or folder.")
files = askopenfilenames(initialdir = getcwd(), title = "Select a file", filetypes = (("Markdown files", "*.md"), ("all files", "*.*")))
if any(files):
chdir(path.dirname(path.abspath(files[0])))
else:
raise AssertionError("No file(s) selected.")
except AssertionError as e:
return print(f"An error occurred: {e}")
assert files, "No file(s) selected."
def fix_content(file_dir:str):
with open(file_dir, encoding="utf-8") as file:
text = file.readlines()
def replace_space_tab(line:str) -> str:
if " " in line:
line = line.replace(" ", "\t")
first_char = -1
for i in range(len(line)):
if line[i] not in (" ", "\t"):
first_char = i
break
if " " in line[:first_char]:
line = line.replace(" ", "\t", line.count(" ", 0, first_char))
for i in range(len(line)):
if line[i] not in (" ", "\t"):
first_char = i
break
if " " in line[:first_char]:
line = line.replace(" ", "\t", line.count(" ", 0, first_char))
return line.removesuffix("\n").removesuffix("\r\n").removesuffix("\t")
new_content = ""
for line in text:
if line in ("\n", "\r\n"):
new_content += line
continue
line = replace_space_tab(line)
while line[-2:] != " ":
line += " "
new_content += line + "\n"
with open(file_dir, "w", encoding="utf-8") as file:
file.write(new_content)
print("Finished.")
print(f"{", ".join(files)} selected.")
for file in files:
fix_content(file)
if __name__ == "__main__":
while True:
try:
main()
except KeyboardInterrupt:
print("Exiting...")
break