-
Notifications
You must be signed in to change notification settings - Fork 0
/
markdown_editor.py
148 lines (81 loc) · 2.26 KB
/
markdown_editor.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
result = []
help_message = """\nThis program helps user to format text using markdown language.
Supported formatters:
- plain
- bold
- italic
- link
- inline-code
- new-line
- header
- unordered-list
- ordered-list
Use command !done to finish formatting and save the result to a file output.md in the program directory.
Use command !help to print this message.\n"""
def get_text():
return input("Text: ")
def plain():
return get_text()
def bold():
return f"**{get_text()}**"
def italic():
return f"*{get_text()}*"
def link():
label = input("Label: ")
url = input("URL: ")
return f"[{label}]({url})"
def inline_code():
return f"`{get_text()}`"
def new_line():
return "\n"
def header():
lvl = 0
text = ""
while lvl < 1 or lvl > 6:
lvl = int(input("Level: "))
text = get_text()
return f"{'#' * lvl} {text}\n"
def create_list(ordered=False):
rows = 0
text = []
while rows < 1:
rows = int(input("Number of rows: "))
if rows < 1:
print("The number of rows should be greater than zero")
for i in range(1, rows + 1):
row = input(f"Row #{i}: ")
if ordered:
text.append(f"{i}. {row}\n")
else:
text.append(f"* {row}\n")
return "".join(text)
def ordered_list():
return create_list(ordered=True)
formatters = {"plain": plain,
"bold": bold,
"italic": italic,
"link": link,
"inline-code": inline_code,
"line-break": new_line,
"header": header,
"unordered-list": create_list,
"ordered-list": ordered_list}
print(help_message)
while True:
input_ = input("Choose a formatter: ")
if input_ == "!done":
try:
file = open("output.md", "w")
for item in result:
file.write(item)
file.close()
except FileExistsError:
print("Failed to save file.")
break
elif input_ == "!help":
print(help_message)
elif input_ not in formatters:
print("Unknown formatter or command. Please try again.")
else:
result.append(formatters[input_]())
print(*result, sep="")