-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
224 lines (185 loc) · 7.39 KB
/
main.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import sys
import os
import utils.CursorLibs as Curs
import colorama
colorama.init()
def create_fill_char():
return "=" * os.get_terminal_size().columns
def printAll(fileLine, currentLns, sectionColA: int, sectionColB: int, hint=None):
fill_char = create_fill_char()
if hint:
print(hint)
print(fill_char)
width = len(str(len(fileLine)))
for i, line in enumerate(fileLine):
if not sectionColA is None:
line = line[:sectionColA] + colorama.Back.WHITE + line[sectionColA:sectionColB] + colorama.Back.RESET + line[sectionColB:]
currentSign = f'{colorama.Style.BRIGHT}|{colorama.Style.RESET_ALL}' if i == currentLns else '|'
print(f"{i + 1:>{width}} {currentSign} {line}")
print(fill_char)
def write(filename, fileLine):
try:
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(fileLine))
except Exception as e:
print(f"Error writing to file: {e}")
def handle_resize(signum, frame):
global fill_char
fill_char = create_fill_char()
def ed_mode(filename):
global use_autoresize, cursor_mode
print("HINT: type .help to open the help menu")
print(" You can exit the editor with .quit/.q command.")
currentLns = 0
toggleDisplay = True
toggleClean = True
toggleAppend = True
history = []
selection = None
clipboard = None
customHint = None
sectionColA = None
sectionColB = None
if not os.path.exists(filename):
try:
open(filename, 'w', encoding='utf-8').close()
except Exception as e:
print(f"Error creating file: {e}")
return
while True:
try:
with open(filename, 'r', encoding='utf-8') as f:
fileLine = f.read().split('\n')
except Exception as e:
print(f"Error reading file: {e}")
break
if toggleDisplay:
print(f"Editing {filename}")
printAll(fileLine, currentLns, sectionColA, sectionColB, customHint)
customHint = None
try:
shinput = input(f'I {currentLns + 1} > ')
except KeyboardInterrupt:
print("\nExiting... Goodbye!")
break
except EOFError:
print("\nInput error detected. Exiting...")
break
if shinput in ('.nextline', '.n'):
currentLns += 1
if currentLns == len(fileLine):
fileLine.append('')
elif shinput.startswith(('.goto', '.g')):
try:
gotoLns = int(shinput.split(' ')[-1]) - 1
if 0 <= gotoLns < len(fileLine):
currentLns = gotoLns
else:
print("Line number out of range.")
except ValueError:
print("Invalid line number.")
elif shinput in ('.append', '.ta'):
toggleAppend = not toggleAppend
elif shinput in ('.display', '.td'):
toggleDisplay = not toggleDisplay
elif shinput in ('.prevline', '.p'):
if currentLns > 0:
currentLns -= 1
if fileLine[currentLns] == '' and currentLns + 2 == len(fileLine):
fileLine.pop()
elif shinput in ('.cleanall', '.ca'):
if input('Really clean all lines? [Y/N] ').lower() == 'y':
history.append((fileLine[:], currentLns))
fileLine = ['']
currentLns = 0
elif shinput in ('.cleanline', '.cl'):
if input(f'Really clean line {currentLns + 1}? [Y/N] ').lower() == 'y':
history.append((fileLine[:], currentLns))
fileLine[currentLns] = ''
elif shinput in ('.quit', '.q'):
write(filename, fileLine)
break
elif shinput in ('.autoclean', '.tc'):
toggleClean = not toggleClean
elif shinput in ('.help', '.h'):
input("""
.help (.h) - Show this help menu
.quit (.q) - Quit the editor
.goto (.g) - Go to a specific line
.nextline (.n) - Move to the next line
.prevline (.p) - Move to the previous line
.replace (.r) - Replace text on the current line
.insert (.i) - Insert text at a specific column in the current line
.duplicate (.d) - Duplicate the current line
.undo (.u) - Undo the last action
.cleanall (.ca) - Clear all lines
.cleanline (.cl) - Clear the current line
.display (.td) - Toggle file display
.append (.ta) - Toggle append mode
.autoclean (.tc) - Toggle auto clean screen
.select (.sel) - Select texts
""")
elif shinput.startswith('.sel '):
args = shinput.split(' ')
sectionColA = int(args[-2])
sectionColB = int(args[-1])
elif shinput.startswith('.unsel'):
sectionColA = None
sectionColB = None
elif shinput.startswith('.insert '):
try:
parts = shinput.split(' ', 2) # Split into 3 parts: command, column, text
if len(parts) < 3:
raise ValueError("Missing arguments.")
_, insCol, insText = parts
insCol = int(insCol)
if insCol < 0 or insCol > len(fileLine[currentLns]):
raise IndexError("Column out of bounds.")
fileLine[currentLns] = fileLine[currentLns][:insCol] + insText + fileLine[currentLns][insCol:]
print("Text inserted successfully.")
except ValueError as e:
print(f"Invalid syntax or input: {e}. Use: .insert <column> <text>")
except IndexError as e:
print(f"Error: {e}")
elif shinput in ('.duplicate', '.d'):
history.append((fileLine[:], currentLns))
fileLine.insert(currentLns + 1, fileLine[currentLns])
currentLns += 1
elif shinput.startswith('.replace '):
try:
_, target, replace = shinput.split(' ', 2)
history.append((fileLine[:], currentLns))
fileLine[currentLns] = fileLine[currentLns].replace(target, replace)
except ValueError:
print("Invalid syntax. Use: .replace <target> <replacement>")
elif shinput in ('.undo', '.u'):
if history:
fileLine, currentLns = history.pop()
else:
print("No actions to undo.")
elif shinput in ('.info', '.i'):
print(f'Current line: {currentLns + 1}')
print(f'Current file: {filename}')
print(f'Current lines: {len(fileLine)}')
print(f'Append mode: {toggleAppend}')
elif shinput in ('.cursor', '.cur'):
if cursor_mode:
cursor_mode = False
customHint = "Disabled cursor mode"
else:
cursor_mode = True
customHint = "Disabled cursor mode"
else:
history.append((fileLine[:], currentLns))
fileLine[currentLns] = fileLine[currentLns] + shinput if toggleAppend else shinput
if toggleClean:
Curs.clear_screen()
write(filename, fileLine)
if __name__ == "__main__":
print("\nOmegaEdit 0.1")
if len(sys.argv) < 2:
print("Usage: python3 script.py <filename>")
else:
use_autoresize = True
cursor_mode = False
ed_mode(sys.argv[-1])