-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathLineEdit.jl
1370 lines (1230 loc) · 41.4 KB
/
LineEdit.jl
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module LineEdit
using ..Terminals
import ..Terminals: raw!, width, height, cmove, getX,
getY, clear_line, beep
import Base: ensureroom, peek, show
abstract TextInterface
export run_interface, Prompt, ModalInterface, transition, reset_state, edit_insert, keymap
immutable ModalInterface <: TextInterface
modes
end
type MIState
interface::ModalInterface
current_mode
aborted::Bool
mode_state
kill_buffer::ByteString
previous_key::Array{Char,1}
key_repeats::Int
end
MIState(i, c, a, m) = MIState(i, c, a, m, "", Char[], 0)
type Mode <: TextInterface
end
type Prompt <: TextInterface
prompt
first_prompt
# A string or function to be printed before the prompt. May not change the length of the prompt.
# This may be used for changing the color, issuing other terminal escape codes, etc.
prompt_prefix
# Same as prefix except after the prompt
prompt_suffix
keymap_func
keymap_func_data
complete
on_enter
on_done
hist
sticky::Bool
end
show(io::IO, x::Prompt) = show(io, string("Prompt(\"", x.prompt, "\",...)"))
immutable InputAreaState
num_rows::Int64
curs_row::Int64
end
type PromptState
terminal::TextTerminal
p::Prompt
input_buffer::IOBuffer
ias::InputAreaState
indent::Int
end
input_string(s::PromptState) = bytestring(pointer(s.input_buffer.data), s.input_buffer.size)
input_string_newlines(s::PromptState) = count(c->(c == '\n'), input_string(s))
function input_string_newlines_aftercursor(s::PromptState)
str = input_string(s)
length(str) == 0 && return 0
rest = str[nextind(str, position(s.input_buffer)):end]
return count(c->(c == '\n'), rest)
end
abstract HistoryProvider
abstract CompletionProvider
type EmptyCompletionProvider <: CompletionProvider
end
type EmptyHistoryProvider <: HistoryProvider
end
reset_state(::EmptyHistoryProvider) = nothing
complete_line(c::EmptyCompletionProvider, s) = [], true, true
terminal(s::IO) = s
terminal(s::PromptState) = s.terminal
for f in [:terminal, :edit_insert, :on_enter, :add_history, :buffer, :edit_backspace, :(Base.isempty),
:replace_line, :refresh_multi_line, :input_string, :edit_move_left, :edit_move_right,
:edit_move_word_left, :edit_move_word_right, :update_display_buffer]
@eval ($f)(s::MIState, args...) = $(f)(s.mode_state[s.current_mode], args...)
end
function common_prefix(completions)
ret = ""
c1 = completions[1]
isempty(c1) && return ret
i = 1
cc, nexti = next(c1, i)
while true
for c in completions
(i > endof(c) || c[i] != cc) && return ret
end
ret *= string(cc)
i >= endof(c1) && return ret
i = nexti
cc, nexti = next(c1, i)
end
end
# Show available completions
function show_completions(s::PromptState, completions)
colmax = maximum(map(length, completions))
num_cols = max(div(width(terminal(s)), colmax+2), 1)
entries_per_col, r = divrem(length(completions), num_cols)
entries_per_col += r != 0
# skip any lines of input after the cursor
cmove_down(terminal(s), input_string_newlines_aftercursor(s))
println(terminal(s))
for row = 1:entries_per_col
for col = 0:num_cols
idx = row + col*entries_per_col
if idx <= length(completions)
cmove_col(terminal(s), (colmax+2)*col)
print(terminal(s), completions[idx])
end
end
println(terminal(s))
end
# make space for the prompt
for i = 1:input_string_newlines(s)
println(terminal(s))
end
end
# Prompt Completions
complete_line(s::MIState) = complete_line(s.mode_state[s.current_mode], s.key_repeats)
function complete_line(s::PromptState, repeats)
completions, partial, should_complete = complete_line(s.p.complete, s)
if length(completions) == 0
beep(terminal(s))
elseif !should_complete
# should_complete is false for cases where we only want to show
# a list of possible completions but not complete, e.g. foo(\t
show_completions(s, completions)
elseif length(completions) == 1
# Replace word by completion
prev_pos = position(s.input_buffer)
seek(s.input_buffer, prev_pos-sizeof(partial))
edit_replace(s, position(s.input_buffer), prev_pos, completions[1])
else
p = common_prefix(completions)
if length(p) > 0 && p != partial
# All possible completions share the same prefix, so we might as
# well complete that
prev_pos = position(s.input_buffer)
seek(s.input_buffer, prev_pos-sizeof(partial))
edit_replace(s, position(s.input_buffer), prev_pos, p)
elseif repeats > 0
show_completions(s, completions)
end
end
end
clear_input_area(terminal, s) = (_clear_input_area(terminal, s.ias); s.ias = InputAreaState(0, 0))
clear_input_area(s) = clear_input_area(s.terminal, s)
function _clear_input_area(terminal, state::InputAreaState)
# Go to the last line
if state.curs_row < state.num_rows
cmove_down(terminal, state.num_rows-state.curs_row)
end
# Clear lines one by one going up
for j=0:(state.num_rows-2)
clear_line(terminal)
cmove_up(terminal)
end
# Clear top line
clear_line(terminal)
end
prompt_string(s::PromptState) = s.p.prompt
prompt_string(s::String) = s
refresh_multi_line(termbuf::TerminalBuffer, s::PromptState) = s.ias =
refresh_multi_line(termbuf, terminal(s), buffer(s), s.ias, s, indent = s.indent)
function refresh_multi_line(termbuf::TerminalBuffer, terminal::UnixTerminal, buf, state::InputAreaState, prompt = ""; indent = 0)
cols = width(terminal)
_clear_input_area(termbuf, state)
curs_row = -1 # relative to prompt
curs_col = -1 # absolute
curs_pos = -1 # 1-based column position of the cursor
cur_row = 0
buf_pos = position(buf)
line_pos = buf_pos
# Write out the prompt string
write_prompt(termbuf, prompt)
prompt = prompt_string(prompt)
seek(buf, 0)
llength = 0
l = ""
plength = strwidth(prompt)
pslength = length(prompt.data)
# Now go through the buffer line by line
while cur_row == 0 || (!isempty(l) && l[end] == '\n')
l = readline(buf)
hasnl = !isempty(l) && l[end] == '\n'
cur_row += 1
# We need to deal with UTF8 characters. Since the IOBuffer is a bytearray, we just count bytes
llength = strwidth(l)
slength = length(l.data)
if cur_row == 1 # First line
if line_pos < slength
num_chars = strwidth(l[1:line_pos])
curs_row = div(plength+num_chars-1, cols) + 1
curs_pos = (plength+num_chars-1) % cols + 1
end
# Substract -1 if there's a '\n' at the end of the line (since it doesn't take up a column)
# The other -1, since we want 10,20 for cols=10 to still not add a row (but we want 11,21 to)
cur_row += div(max(plength+(llength-hasnl)-1,0), cols)
line_pos -= slength
write(termbuf, l)
else
# We expect to be line after the last valid output line (due to
# the '\n' at the end of the previous line)
if curs_row == -1
if line_pos < slength
num_chars = strwidth(l[1:line_pos])
curs_row = cur_row + div(indent+num_chars-1, cols)
curs_pos = (indent+num_chars-1) % cols + 1
end
line_pos -= slength # '\n' gets an extra pos
cur_row += div(max(indent+(llength-hasnl)-1,0), cols)
cmove_col(termbuf, indent+1)
write(termbuf, l)
# There's an issue if the cursor is after the very right end of the screen. In that case we need to
# move the cursor to the next line, and emit a newline if needed
if curs_pos == cols
# only emit the newline if the cursor is at the end of the line we're writing
if line_pos == 0
write(termbuf, "\n")
cur_row += 1
end
curs_row += 1
curs_pos = 0
cmove_col(termbuf, 1)
end
else
cur_row += div(max(indent+(llength-hasnl)-1,0), cols)
cmove_col(termbuf, indent+1)
write(termbuf, l)
end
end
end
seek(buf, buf_pos)
# If we are at the end of the buffer, we need to put the cursor one past the
# last character we have written
if curs_row == -1
curs_pos = ((cur_row == 1 ? plength : indent)+llength-1) % cols + 1
curs_row = cur_row
end
# Same issue as above. TODO: We should figure out
# how to refactor this to avoid duplcating functionality.
if curs_pos == cols
if line_pos == 0
write(termbuf, "\n")
cur_row += 1
end
curs_row += 1
curs_pos = 0
cmove_col(termbuf, 1)
end
# Let's move the cursor to the right position
# The line first
n = cur_row - curs_row
if n > 0
cmove_up(termbuf, n)
end
#columns are 1 based
cmove_col(termbuf, curs_pos+1)
# Updated cur_row,curs_row
return InputAreaState(cur_row, curs_row)
end
# Edit functionality
is_non_word_char(c) = c in " \t\n\"\\'`@\$><=:;|&{}()[].,+-*/?%^~"
function reset_key_repeats(f::Function, s::MIState)
key_repeats_sav = s.key_repeats
try
s.key_repeats = 0
f()
finally
s.key_repeats = key_repeats_sav
end
end
char_move_left(s::PromptState) = char_move_left(s.input_buffer)
function char_move_left(buf::IOBuffer)
while position(buf) > 0
seek(buf, position(buf)-1)
c = peek(buf)
(((c & 0x80) == 0) || ((c & 0xc0) == 0xc0)) && break
end
pos = position(buf)
c = read(buf, Char)
seek(buf, pos)
c
end
function edit_move_left(buf::IOBuffer)
if position(buf) > 0
#move to the next base UTF8 character to the left
while true
c = char_move_left(buf)
if charwidth(c) != 0 || c == '\n' || position(buf) == 0
break
end
end
return true
end
return false
end
edit_move_left(s::PromptState) = edit_move_left(s.input_buffer) && refresh_line(s)
function edit_move_word_left(s)
if position(s.input_buffer) > 0
char_move_word_left(s.input_buffer)
refresh_line(s)
end
end
char_move_right(s) = char_move_right(buffer(s))
function char_move_right(buf::IOBuffer)
!eof(buf) && read(buf, Char)
end
function char_move_word_right(buf::IOBuffer, is_delimiter=is_non_word_char)
while !eof(buf) && is_delimiter(char_move_right(buf))
end
while !eof(buf)
pos = position(buf)
if is_delimiter(char_move_right(buf))
seek(buf, pos)
break
end
end
end
function char_move_word_left(buf::IOBuffer, is_delimiter=is_non_word_char)
while position(buf) > 0 && is_delimiter(char_move_left(buf))
end
while position(buf) > 0
pos = position(buf)
if is_delimiter(char_move_left(buf))
seek(buf, pos)
break
end
end
end
char_move_word_right(s) = char_move_word_right(buffer(s))
char_move_word_left(s) = char_move_word_left(buffer(s))
function edit_move_right(buf::IOBuffer)
if !eof(buf)
# move to the next base UTF8 character to the right
while true
c = char_move_right(buf)
eof(buf) && break
pos = position(buf)
nextc = read(buf,Char)
seek(buf,pos)
(charwidth(nextc) != 0 || nextc == '\n') && break
end
return true
end
return false
end
edit_move_right(s::PromptState) = edit_move_right(s.input_buffer) && refresh_line(s)
function edit_move_word_right(s)
if !eof(s.input_buffer)
char_move_word_right(s)
refresh_line(s)
end
end
## Move line up/down
# Querying the terminal is expensive, memory access is cheap
# so to find the current column, we find the offset for the start
# of the line.
function edit_move_up(buf::IOBuffer)
npos = rsearch(buf.data, '\n', position(buf))
npos == 0 && return false # we're in the first line
# We're interested in character count, not byte count
offset = length(bytestring(buf.data[(npos+1):(position(buf))]))
npos2 = rsearch(buf.data, '\n', npos-1)
seek(buf, npos2)
for _ = 1:offset
pos = position(buf)
if read(buf, Char) == '\n'
seek(buf, pos)
break
end
end
return true
end
function edit_move_up(s)
changed = edit_move_up(buffer(s))
changed && refresh_line(s)
changed
end
function edit_move_down(buf::IOBuffer)
npos = rsearch(buf.data[1:buf.size], '\n', position(buf))
# We're interested in character count, not byte count
offset = length(bytestring(buf.data[(npos+1):(position(buf))]))
npos2 = search(buf.data[1:buf.size], '\n', position(buf)+1)
if npos2 == 0 #we're in the last line
return false
end
seek(buf, npos2)
for _ = 1:offset
pos = position(buf)
if eof(buf) || read(buf, Char) == '\n'
seek(buf, pos)
break
end
end
return true
end
function edit_move_down(s)
changed = edit_move_down(buffer(s))
changed && refresh_line(s)
changed
end
# splice! for IOBuffer: convert from 0-indexed positions, update the size,
# and keep the cursor position stable with the text
function splice_buffer!{T<:Integer}(buf::IOBuffer, r::UnitRange{T}, ins::String = "")
pos = position(buf)
if !isempty(r) && pos in r
seek(buf, first(r))
elseif pos > last(r)
seek(buf, pos - length(r))
end
splice!(buf.data, r .+ 1, ins.data) # position(), etc, are 0-indexed
buf.size = buf.size + sizeof(ins) - length(r)
seek(buf, position(buf) + sizeof(ins))
end
function edit_replace(s, from, to, str)
splice_buffer!(buffer(s), from:to-1, str)
end
function edit_insert(s::PromptState, c)
str = string(c)
edit_insert(s.input_buffer, str)
if !('\n' in str) && eof(s.input_buffer) &&
((position(s.input_buffer) + length(s.p.prompt) + sizeof(str) - 1) < width(terminal(s)))
#Avoid full update
write(terminal(s), str)
else
refresh_line(s)
end
end
function edit_insert(buf::IOBuffer, c)
if eof(buf)
write(buf, c)
else
splice_buffer!(buf, position(buf):position(buf)-1, string(c))
end
end
function edit_backspace(s::PromptState)
if edit_backspace(s.input_buffer)
refresh_line(s)
else
beep(terminal(s))
end
end
function edit_backspace(buf::IOBuffer)
if position(buf) > 0
oldpos = position(buf)
char_move_left(buf)
splice_buffer!(buf, position(buf):oldpos-1)
return true
else
return false
end
end
edit_delete(s) = edit_delete(buffer(s)) ? refresh_line(s) : beep(terminal(s))
function edit_delete(buf::IOBuffer)
eof(buf) && return false
oldpos = position(buf)
char_move_right(buf)
splice_buffer!(buf, oldpos:position(buf)-1)
true
end
function edit_werase(buf::IOBuffer)
pos1 = position(buf)
char_move_word_left(buf, isspace)
pos0 = position(buf)
pos0 < pos1 || return false
splice_buffer!(buf, pos0:pos1-1)
true
end
function edit_werase(s)
edit_werase(buffer(s)) && refresh_line(s)
end
function edit_delete_prev_word(buf::IOBuffer)
pos1 = position(buf)
char_move_word_left(buf)
pos0 = position(buf)
pos0 < pos1 || return false
splice_buffer!(buf, pos0:pos1-1)
true
end
function edit_delete_prev_word(s)
edit_delete_prev_word(buffer(s)) && refresh_line(s)
end
function edit_delete_next_word(buf::IOBuffer)
pos0 = position(buf)
char_move_word_right(buf)
pos1 = position(buf)
pos0 < pos1 || return false
splice_buffer!(buf, pos0:pos1-1)
true
end
function edit_delete_next_word(s)
edit_delete_next_word(buffer(s)) && refresh_line(s)
end
function edit_yank(s::MIState)
edit_insert(buffer(s), s.kill_buffer)
refresh_line(s)
end
function edit_kill_line(s::MIState)
buf = buffer(s)
pos = position(buf)
killbuf = readline(buf)
if length(killbuf) > 1 && killbuf[end] == '\n'
killbuf = killbuf[1:end-1]
char_move_left(buf)
end
s.kill_buffer = s.key_repeats > 0 ? s.kill_buffer * killbuf : killbuf
splice_buffer!(buf, pos:position(buf)-1)
refresh_line(s)
end
edit_transpose(s) = edit_transpose(buffer(s)) && refresh_line(s)
function edit_transpose(buf::IOBuffer)
position(buf) == 0 && return false
eof(buf) && char_move_left(buf)
char_move_left(buf)
pos = position(buf)
a, b = read(buf, Char), read(buf, Char)
seek(buf, pos)
write(buf, b, a)
return true
end
edit_clear(buf::IOBuffer) = truncate(buf, 0)
function edit_clear(s::MIState)
edit_clear(buffer(s))
refresh_line(s)
end
function replace_line(s::PromptState, l::IOBuffer)
s.input_buffer = l
end
function replace_line(s::PromptState, l)
s.input_buffer.ptr = 1
s.input_buffer.size = 0
write(s.input_buffer, l)
end
history_prev(::EmptyHistoryProvider) = ("", false)
history_next(::EmptyHistoryProvider) = ("", false)
history_search(::EmptyHistoryProvider, args...) = false
add_history(::EmptyHistoryProvider, s) = nothing
add_history(s::PromptState) = add_history(mode(s).hist, s)
history_next_prefix(s, hist) = false
history_prev_prefix(s, hist) = false
function history_prev(s, hist)
l, ok = history_prev(mode(s).hist)
if ok
replace_line(s, l)
move_input_start(s)
refresh_line(s)
else
beep(terminal(s))
end
end
function history_next(s, hist)
l, ok = history_next(mode(s).hist)
if ok
replace_line(s, l)
move_input_end(s)
refresh_line(s)
else
beep(terminal(s))
end
end
refresh_line(s) = refresh_multi_line(s)
refresh_line(s, termbuf) = refresh_multi_line(termbuf, s)
default_completion_cb(::IOBuffer) = []
default_enter_cb(_) = true
write_prompt(terminal, s::PromptState) = write_prompt(terminal, s, s.p.prompt)
function write_prompt(terminal, s::PromptState, prompt)
prefix = isa(s.p.prompt_prefix,Function) ? s.p.prompt_prefix() : s.p.prompt_prefix
suffix = isa(s.p.prompt_suffix,Function) ? s.p.prompt_suffix() : s.p.prompt_suffix
write(terminal, prefix)
write(terminal, prompt)
write(terminal, Base.text_colors[:normal])
write(terminal, suffix)
end
write_prompt(terminal, s::ASCIIString) = write(terminal, s)
normalize_key(key::Char) = string(key)
normalize_key(key::Integer) = normalize_key(char(key))
function normalize_key(key::String)
'\0' in key && error("Matching \\0 not currently supported.")
buf = IOBuffer()
i = start(key)
while !done(key, i)
c, i = next(key, i)
if c == '*'
write(buf, '\0')
elseif c == '^'
c, i = next(key, i)
write(buf, uppercase(c)-64)
elseif c == '\\'
c, i == next(key, i)
if c == 'C'
c, i == next(key, i)
@assert c == '-'
c, i == next(key, i)
write(buf, uppercase(c)-64)
elseif c == 'M'
c, i == next(key, i)
@assert c == '-'
c, i == next(key, i)
write(buf, '\e')
write(buf, c)
end
else
write(buf, c)
end
end
return takebuf_string(buf)
end
function normalize_keys(keymap::Dict)
return [normalize_key(k) => v for (k,v) in keymap]
end
function add_nested_key!(keymap::Dict, key, value)
i = start(key)
while !done(key, i)
c, i = next(key, i)
if c in keys(keymap)
if !isa(keymap[c], Dict)
error("Conflicting Definitions for keyseq " * escape_string(key) * " within one keymap")
end
elseif done(key, i)
keymap[c] = value
break
else
keymap[c] = Dict{Char,Any}()
end
keymap = keymap[c]
end
end
# Turn a Dict{Any,Any} into a Dict{Char,Any}
# For now we use \0 to represent unknown chars so that they are sorted before everything else
# If we ever actually want to match \0 in input, this will have to be reworked
function normalize_keymap(keymap::Dict)
ret = Dict{Char,Any}()
direct_keys = filter((k,v) -> isa(v, Union(Function, Nothing)), keymap)
# first direct entries
for key in keys(direct_keys)
add_nested_key!(ret, key, keymap[key])
end
# then redirected entries
for key in setdiff(keys(keymap), keys(direct_keys))
value = normalize_key(keymap[key])
haskey(keymap, value) || error("Could not find redirected value " * escape_string(keymap[key]))
add_nested_key!(ret, key, keymap[value])
end
ret
end
match_input(k::Function, s, cs) = (update_key_repeats(s, cs); return keymap_fcn(k, s, last(cs)))
match_input(k::Nothing, s, cs) = (s,p) -> return :ok
function match_input(keymap::Dict, s, cs=Char[])
c = read(terminal(s), Char)
push!(cs, c)
k = haskey(keymap, c) ? c : '\0'
return match_input(keymap[k], s, cs)
# perhaps better would be: match_input(get(keymap, k, nothing), s, cs) ?
end
keymap_fcn(f::Nothing, s, c) = (s, p) -> return :ok
function keymap_fcn(f::Function, s, c::Char)
return (s, p) -> begin
r = f(s, p, c)
if isa(r, Symbol)
return r
else
return :ok
end
end
end
update_key_repeats(s, keystroke) = nothing
function update_key_repeats(s::MIState, keystroke)
s.key_repeats = s.previous_key == keystroke ? s.key_repeats + 1 : 0
s.previous_key = keystroke
return
end
# deep merge where target has higher precedence
function keymap_merge!(target::Dict, source::Dict)
for k in keys(source)
if !haskey(target, k)
target[k] = source[k]
elseif isa(target[k], Dict)
keymap_merge!(target[k], source[k])
else
# Ignore, target has higher precedence
end
end
end
fixup_keymaps!(d, l, s, sk) = nothing
function fixup_keymaps!(dict::Dict, level, s, subkeymap)
if level > 1
for d in values(dict)
fixup_keymaps!(d, level-1, s, subkeymap)
end
else
if haskey(dict, s)
if isa(dict[s], Dict) && isa(subkeymap, Dict)
keymap_merge!(dict[s], subkeymap)
end
else
dict[s] = deepcopy(subkeymap)
end
end
end
function add_specialisations(dict, subdict, level)
default_branch = subdict['\0']
if isa(default_branch, Dict)
for s in keys(default_branch)
s == '\0' && add_specialisations(dict, default_branch, level+1)
fixup_keymaps!(dict, level, s, default_branch[s])
end
end
end
fix_conflicts!(x) = fix_conflicts!(x, 1)
fix_conflicts!(others, level) = nothing
function fix_conflicts!(dict::Dict, level)
# needs to be done first for every branch
if haskey(dict, '\0')
add_specialisations(dict, dict, level)
end
for (k,v) in dict
k == '\0' && continue
fix_conflicts!(v, level+1)
end
end
function keymap_prepare(keymap::Dict)
if !haskey(keymap, "\0")
keymap["\0"] = (o...)->error("Unrecognized input")
end
keymap = normalize_keymap(keymap)
fix_conflicts!(keymap)
keymap
end
function keymap_unify(keymaps)
length(keymaps) == 1 && return keymaps[1]
ret = Dict{Char,Any}()
for keymap in keymaps
keymap_merge!(ret, keymap)
end
fix_conflicts!(ret)
return ret
end
function keymap{D<:Dict}(keymaps::Array{D})
# keymaps is a vector of prioritized keymaps, with highest priority first
dict = map(normalize_keys, keymaps)
dict = keymap_prepare(merge(reverse(dict)...))
return (s,p)->match_input(dict, s)(s,p)
end
const escape_defaults = merge!(
{char(i) => nothing for i=[1:26, 28:31]}, # Ignore control characters by default
{ # And ignore other escape sequences by default
"\e*" => nothing,
"\e[*" => nothing,
# Also ignore extended escape sequences
# TODO: Support ranges of characters
"\e[1**" => nothing,
"\e[2**" => nothing,
"\e[3**" => nothing,
"\e[4**" => nothing,
"\e[5**" => nothing,
"\e[6**" => nothing,
"\e[1~" => "\e[H",
"\e[4~" => "\e[F",
"\e[7~" => "\e[H",
"\e[8~" => "\e[F",
"\eOA" => "\e[A",
"\eOB" => "\e[B",
"\eOC" => "\e[C",
"\eOD" => "\e[D",
"\eOH" => "\e[H",
"\eOF" => "\e[F",
})
function write_response_buffer(s::PromptState, data)
offset = s.input_buffer.ptr
ptr = data.response_buffer.ptr
seek(data.response_buffer, 0)
write(s.input_buffer, readall(data.response_buffer))
s.input_buffer.ptr = offset + ptr - 2
data.response_buffer.ptr = ptr
refresh_line(s)
end
type SearchState
terminal
histprompt
#rsearch (true) or ssearch (false)
backward::Bool
query_buffer::IOBuffer
response_buffer::IOBuffer
ias::InputAreaState
#The prompt whose input will be replaced by the matched history
parent
SearchState(terminal, histprompt, backward, query_buffer, response_buffer) =
new(terminal, histprompt, backward, query_buffer, response_buffer, InputAreaState(0,0))
end
terminal(s::SearchState) = s.terminal
function update_display_buffer(s::SearchState, data)
history_search(data.histprompt.hp, data.query_buffer, data.response_buffer, data.backward, false) || beep(terminal(s))
refresh_line(s)
end
function history_next_result(s::MIState, data::SearchState)
history_search(data.histprompt.hp, data.query_buffer, data.response_buffer, data.backward, true) || beep(terminal(s))
refresh_line(data)
end
function history_set_backward(s::SearchState, backward)
s.backward = backward
end
input_string(s::SearchState) = bytestring(pointer(s.query_buffer.data), s.query_buffer.size)
refresh_multi_line(termbuf::TerminalBuffer, term, s::Union(SearchState,PromptState)) = (@assert term == terminal(s); refresh_multi_line(termbuf,s))
function refresh_multi_line(termbuf::TerminalBuffer, s::SearchState)
buf = IOBuffer()
write(buf, pointer(s.query_buffer.data), s.query_buffer.ptr-1)
write(buf, "': ")
offset = buf.ptr
ptr = s.response_buffer.ptr
seek(s.response_buffer, 0)
write(buf, readall(s.response_buffer))
buf.ptr = offset + ptr - 1
s.response_buffer.ptr = ptr
s.ias = refresh_multi_line(termbuf, s.terminal, buf, s.ias, s.backward ? "(reverse-i-search)`" : "(forward-i-search)`")
end
function refresh_multi_line(s::Union(SearchState,PromptState))
refresh_multi_line(terminal(s), s)
end
function refresh_multi_line(terminal::UnixTerminal, args...; kwargs...)
outbuf = IOBuffer()
termbuf = TerminalBuffer(outbuf)
ret = refresh_multi_line(termbuf, terminal, args...;kwargs...)
# Output the entire refresh at once
write(terminal, takebuf_array(outbuf))
flush(terminal)
return ret
end
function reset_state(s::SearchState)
if s.query_buffer.size != 0
s.query_buffer.size = 0
s.query_buffer.ptr = 1
end
if s.response_buffer.size != 0
s.response_buffer.size = 0
s.response_buffer.ptr = 1
end
reset_state(s.histprompt.hp)
end
type HistoryPrompt{T<:HistoryProvider} <: TextInterface
hp::T
complete
keymap_func::Function
HistoryPrompt(hp) = new(hp, EmptyCompletionProvider())
end
HistoryPrompt{T<:HistoryProvider}(hp::T) = HistoryPrompt{T}(hp)
init_state(terminal, p::HistoryPrompt) = SearchState(terminal, p, true, IOBuffer(), IOBuffer())
state(s::MIState, p) = s.mode_state[p]
state(s::PromptState, p) = (@assert s.p == p; s)
mode(s::MIState) = s.current_mode
mode(s::PromptState) = s.p
mode(s::SearchState) = @assert false
# Search Mode completions
function complete_line(s::SearchState, repeats)
completions, partial, should_complete = complete_line(s.histprompt.complete, s)
# For now only allow exact completions in search mode
if length(completions) == 1
prev_pos = position(s.query_buffer)
seek(s.query_buffer, prev_pos-sizeof(partial))
edit_replace(s, position(s.query_buffer), prev_pos, completions[1])
end
end
function accept_result(s, p)
parent = state(s, p).parent
replace_line(state(s, parent), state(s, p).response_buffer)
transition(s, parent)
end
function copybuf!(dst::IOBuffer, src::IOBuffer)
n = src.size
ensureroom(dst, n)
copy!(dst.data, 1, src.data, 1, n)
dst.size = src.size
dst.ptr = src.ptr
end
function enter_search(s::MIState, p::HistoryPrompt, backward::Bool)
# a bit of hack to help fix #6325
buf = buffer(s)
p.hp.last_mode = mode(s)
p.hp.last_buffer = copy(buf)
ss = state(s, p)
ss.parent = mode(s)
ss.backward = backward
truncate(ss.query_buffer, 0)
copybuf!(ss.response_buffer, buf)
transition(s, p)
end
function setup_search_keymap(hp)
p = HistoryPrompt(hp)
pkeymap = {