forked from Araq/nimedit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.nim
498 lines (458 loc) · 12.6 KB
/
console.nim
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# Some nice console support.
import buffertype, buffer, os, osproc, streams, strutils, browsers, tables
const
ExtensionsToIgnore* = [
".ppu", ".o", ".obj", ".dcu",
".map", ".tds", ".err", ".bak", ".pyc", ".exe", ".rod", ".pdb", ".idb",
".idx", ".ilk", ".dll", ".so", ".a"
]
proc ignoreFile*(f: string): bool =
let (_, name, ext) = f.splitFile
result = name[0] == '.' or ext in ExtensionsToIgnore or f == "nimcache"
type
CmdHistory* = object
cmds*: seq[string]
suggested*: int
proc addCmd*(h: var CmdHistory; cmd: string) =
var replaceWith = -1
for i in 0..high(h.cmds):
if h.cmds[i] == cmd:
# suggest it again:
swap(h.cmds[i], h.cmds[^1])
h.suggested = h.cmds.high
return
elif h.cmds[i] in cmd:
# correct previously wrong or shorter command:
if replaceWith < 0 or h.cmds[replaceWith] < h.cmds[i]: replaceWith = i
if replaceWith < 0:
h.cmds.add cmd
else:
h.cmds[replaceWith] = cmd
proc suggest*(h: var CmdHistory; up: bool): string =
if h.suggested < 0 or h.suggested >= h.cmds.len:
h.suggested = (if up: h.cmds.high else: 0)
if h.suggested >= 0 and h.suggested < h.cmds.len:
result = h.cmds[h.suggested]
h.suggested += (if up: -1 else: 1)
else:
result = ""
type
Console* = ref object
b: Buffer
hist*: Table[string, CmdHistory]
files: seq[string]
prefix: string
processRunning*: bool
beforeSuggestionPos: int
aliases*: seq[(string, string)]
process: string
proc insertReadonly*(c: Console; s: string) =
insertReadonly(c.b, s)
proc insertPrompt*(c: Console) =
c.insertReadOnly(os.getCurrentDir() & ">")
proc newConsole*(b: Buffer): Console =
result = Console(b: b, hist: initTable[string, CmdHistory](), files: @[],
prefix: "", aliases: @[], process: "")
result.hist[""] = CmdHistory(cmds: @[], suggested: -1)
proc getCommand(c: Console): string =
result = ""
let b = c.b
for i in b.readOnly+1 ..< c.b.len:
result.add c.b[i]
proc emptyCmd(c: Console) =
let b = c.b
while true:
if b.len-1 <= b.readOnly: break
backspace(b, false)
proc caretToEnd(c: Console) =
if c.b.numberOfLines > 1:
deselect(c.b)
c.b.gotoPos(c.b.len)
proc upPressed*(c: Console) =
c.caretToEnd
let sug = c.hist[c.process].suggest(up=true)
if sug.len > 0:
emptyCmd(c)
c.b.insert sug
proc downPressed*(c: Console) =
c.caretToEnd
let sug = c.hist[c.process].suggest(up=false)
if sug.len > 0:
emptyCmd(c)
c.b.insert sug
proc handleHexChar(s: string; pos: int; xi: var int): int =
case s[pos]
of '0'..'9':
xi = (xi shl 4) or (ord(s[pos]) - ord('0'))
result = pos+1
of 'a'..'f':
xi = (xi shl 4) or (ord(s[pos]) - ord('a') + 10)
result = pos+1
of 'A'..'F':
xi = (xi shl 4) or (ord(s[pos]) - ord('A') + 10)
result = pos+1
else: discard
proc parseEscape(s: string; w: var string; start=0): int =
var pos = start+1 # skip '\'
case s[pos]
of 'n', 'N':
w.add("\n")
inc(pos)
of 'r', 'R', 'c', 'C':
add(w, '\c')
inc(pos)
of 'l', 'L':
add(w, '\L')
inc(pos)
of 'f', 'F':
add(w, '\f')
inc(pos)
of 'e', 'E':
add(w, '\e')
inc(pos)
of 'a', 'A':
add(w, '\a')
inc(pos)
of 'b', 'B':
add(w, '\b')
inc(pos)
of 'v', 'V':
add(w, '\v')
inc(pos)
of 't', 'T':
add(w, '\t')
inc(pos)
of '\'', '\"':
add(w, s[pos])
inc(pos)
of '\\':
add(w, '\\')
inc(pos)
of 'x', 'X':
inc(pos)
var xi = 0
pos = handleHexChar(s, pos, xi)
pos = handleHexChar(s, pos, xi)
add(w, chr(xi))
of '0'..'9':
var xi = 0
while s[pos] in {'0'..'9'}:
xi = (xi * 10) + (ord(s[pos]) - ord('0'))
inc(pos)
if xi <= 255: add(w, chr(xi))
else:
w.add('\\')
result = pos
proc parseWord*(s: string; w: var string;
start=0; convToLower=false): int =
template conv(c): untyped = (if convToLower: c.toLowerAscii else: c)
w.setLen(0)
var i = start
while i < s.len and s[i] in {' ', '\t'}: inc i
if i >= s.len: return i
case s[i]
of '\'':
inc i
while i < s.len:
if s[i] == '\'':
if i+1 < s.len and s[i+1] == '\'':
w.add s[i]
inc i
else:
inc i
break
else:
w.add s[i].conv
inc i
of '"':
inc i
while i < s.len:
if s[i] == '"':
inc i
break
elif s[i] == '\\':
i = parseEscape(s, w, i)
else:
w.add s[i].conv
inc i
else:
while i < s.len and s[i] > ' ':
w.add s[i].conv
inc i
result = i
proc startsWithIgnoreCase(s, prefix: string): bool =
var i = 0
while true:
if i >= prefix.len: return true
if s[i].toLowerAscii != prefix[i].toLowerAscii: return false
inc(i)
proc suggestPath(c: Console; b: Buffer; prefix: string) =
# suggest the path with the matching prefix (ignoring case),
# but ultimately suggest every file:
var sug = -1
if prefix.len > 0:
for i, x in c.files:
if x.extractFilename.startsWithIgnoreCase(prefix) and not x.ignoreFile:
sug = i
break
if sug < 0 and prefix.len > 0:
# if we have no prefix, pick a file that contains the prefix somewhere
let p = prefix.toLowerAscii
for i, x in c.files:
if p in x.toLowerAscii and not x.ignoreFile:
sug = i
break
# no match, just suggest something, but ignore crap starting with a dot:
if sug < 0 and prefix.len == 0:
sug = 0
while sug < c.files.high:
if c.files[sug].ignoreFile: inc sug
else: break
if sug >=% c.files.len: return
# these inserts&deletes do not count as changed event:
let oldChanged = b.changed
for i in 0..<c.beforeSuggestionPos: backspace(b, false, overrideUtf8=true)
insert(b, c.files[sug])
c.beforeSuggestionPos = c.files[sug].len
delete(c.files, sug)
b.changed = oldChanged
proc addFile(c: Console; path: string) =
if find(path, {' ', '\t'}) >= 0:
c.files.add path.escape
else:
c.files.add path
proc tabPressed*(c: Console; basePath: string) =
let b = c.b
if b.changed:
let cmd = getCommand(c)
c.prefix.setLen 0
var prefixB = ""
var i = 0
while true:
i = parseWord(cmd, prefixB, i)
# if prefixB.len == 0 means at end:
if prefixB.len == 0:
# parseWord always skips initial whitespace, so we look at the passed
# character:
if i > 0 and cmd[i-1] == ' ':
# no prefix:
setLen c.prefix, 0
break
swap(c.prefix, prefixB)
c.beforeSuggestionPos = c.prefix.len
setLen c.files, 0
b.changed = false
if c.files.len == 0:
# prefix == "..\..\foo"
let (path, prefix) = c.prefix.splitPath
if path[0] == '~':
let expandedPath = getHomeDir() / path.substr(1)
for k, f in os.walkDir(expandedPath, relative=false):
c.addFile f
elif c.prefix.isAbsolute:
for k, f in os.walkDir(path, relative=false):
c.addFile f
else:
for k, f in os.walkDir(basePath / path, relative=true):
c.addFile path / f
c.prefix = prefix
suggestPath(c, b, c.prefix)
proc cmdToArgs(cmd: string): tuple[exe: string, args: seq[string]] =
result.exe = ""
result.args = @[]
var i = parseWord(cmd, result.exe, 0)
while true:
var x = ""
i = parseWord(cmd, x, i)
if x.len == 0: break
result.args.add x
proc dirContents(c: Console; ext: string) =
var i = 0
for k, f in os.walkDir(getCurrentDir(), relative=true):
if ext.len == 0 or cmpPaths(f.splitFile.ext, ext) == 0:
c.insertReadonly(f)
if i == 4:
c.insertReadonly("\L")
i = 0
else:
c.insertReadonly(" ")
inc i
c.insertReadonly("\L")
# Threading channels
var requests: Channel[string]
requests.open()
var responses: Channel[string]
responses.open()
# Threading channels END
const EndToken = "\e" # a single ESC
proc execThreadProc() {.thread.} =
template waitForExit() =
started = false
let exitCode = p.waitForExit()
p.close()
if exitCode != 0:
responses.send("Process terminated with exitcode: " & $exitCode & "\L")
responses.send EndToken
when defined(consoleapp):
template echod(msg) = echo msg
else:
template echod(msg) = discard
var p: Process
var o: Stream
var started = false
while true:
var tasks = requests.peek()
if tasks == 0 and not started: tasks = 1
if tasks > 0:
for i in 0..<tasks:
let task = requests.recv()
if task == EndToken:
echod("[Thread] Stopping process.")
p.terminate()
o.close()
waitForExit()
else:
if not started:
let (bin, args) = cmdToArgs(task)
try:
p = startProcess(bin, os.getCurrentDir(), args,
options = {poStdErrToStdOut, poUsePath, poInteractive,
poDaemon})
o = p.outputStream
started = true
except:
started = false
responses.send getCurrentExceptionMsg()
responses.send EndToken
echod "STARTED " & bin
else:
p.inputStream.writeline task
# Check if process exited.
if started:
if not p.running:
echod("[Thread] Process exited.")
while not o.atEnd:
let line = o.readAll()
responses.send(line)
# Process exited.
waitForExit()
elif osproc.hasData(p):
let line = o.readAll()
responses.send(line)
var backgroundThread: Thread[void]
createThread[void](backgroundThread, execThreadProc)
proc update*(c: Console) =
if c.processRunning:
if responses.peek > 0:
let resp = responses.recv()
if resp == EndToken:
c.processRunning = false
c.process.setLen 0
c.insertReadOnly "\L"
insertPrompt(c)
else:
insertReadOnly(c, resp)
proc sendBreak*(c: Console) =
if c.processRunning:
requests.send EndToken
proc extractFilePosition*(b: Buffer): (string, int, int) =
## Line is -1 if not an interpretable file position.
template parseNumber(line) =
while i < b.len and b[i] in Digits:
line = line * 10 + (b[i].ord - '0'.ord)
inc i
# assume the cursor is under 'Hint:', 'Error:' etc. This is how the message
# might look like: foo.nim(3, 4) Error: bla bla bla.
# As a nice benefit, the same parsing also detects Nim stack traces. :-)
var i = b.cursor
while i > 0 and b[i-1] != '\L': dec i
result = ("", -1, -1)
while i < b.len and b[i] == ' ': inc i
while i < b.len and b[i] != ' ':
if b[i] == '(': break
elif b[i] == ':' and i+1 < b.len and b[i+1] != '\\': break
result[0].add b[i]
inc i
var line, col: int
if i+1 < b.len and b[i] == '(' and b[i+1] in Digits:
inc i
parseNumber(line)
if i < b.len and b[i] == ',':
inc i
while b[i] == ' ': inc i
parseNumber(col)
else:
col = -1
if i < b.len and b[i] == ')':
result[1] = line
result[2] = col
elif i+1 < b.len and b[i] == ':' and b[i+1] in Digits:
inc i
parseNumber(line)
if i < b.len and b[i] == ':':
inc i
parseNumber(col)
if i < b.len and b[i] == ':':
result[1] = line
result[2] = col
proc runCommand*(c: Console; cmd: var string): string =
c.b.gotoPos(c.b.len)
c.files.setLen 0
addCmd(c.hist[c.process], cmd)
if c.processRunning:
requests.send cmd
return
var a = ""
var i = parseWord(cmd, a, 0, true)
c.insertReadOnly "\L"
for al in c.aliases:
if a == al[0]:
cmd = al[1] & cmd.substr(i)
i = parseWord(cmd, a, 0, true)
break
case a
of "":
insertPrompt c
of "o":
var b = ""
i = parseWord(cmd, b, i)
insertPrompt c
if b.len > 0:
if isAbsolute(b): result = b
else: result = os.getCurrentDir() / b
of "cls":
clear(c.b)
insertPrompt c
of "cd":
var b = ""
i = parseWord(cmd, b, i)
try:
os.setCurrentDir(b)
except OSError:
c.insertReadOnly(getCurrentExceptionMsg() & "\L")
insertPrompt c
of "save":
var filename = ""
i = parseWord(cmd, filename, i)
if filename.len > 0: c.b.saveAs(filename)
insertPrompt c
of "d":
var b = ""
i = parseWord(cmd, b, i)
c.dirContents(b)
insertPrompt c
else:
if i >= cmd.len-1 and (a.endsWith".html" or a.startsWith"http://" or
a.startsWith"https://"):
openDefaultBrowser(a)
#echo a
else:
requests.send cmd
c.processRunning = true
swap(c.process, cmd)
if c.process notin c.hist:
c.hist[c.process] = CmdHistory(cmds: @[], suggested: -1)
proc enterPressed*(c: Console): string =
c.b.gotoPos(c.b.len)
var cmd = getCommand(c)
result = runCommand(c, cmd)