-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
LineEdit.jl
2085 lines (1870 loc) · 63.2 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
# This file is a part of Julia. License is MIT: https://julialang.org/license
module LineEdit
using ..Terminals
import ..Terminals: raw!, width, height, cmove, getX,
getY, clear_line, beep
import Base: ensureroom, peek, show, AnyDict, position
abstract type TextInterface end
abstract type ModeState end
export run_interface, Prompt, ModalInterface, transition, reset_state, edit_insert, keymap
struct ModalInterface <: TextInterface
modes::Array{Base.LineEdit.TextInterface,1}
end
mutable struct Prompt <: TextInterface
# A string or function to be printed as the prompt.
prompt::Union{String,Function}
# 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::Union{String,Function}
# Same as prefix except after the prompt
prompt_suffix::Union{String,Function}
keymap_dict::Dict{Char}
repl # ::AbstractREPL
complete # ::REPLCompletionProvider
on_enter::Function
on_done::Function
hist # ::REPLHistoryProvider
sticky::Bool
end
show(io::IO, x::Prompt) = show(io, string("Prompt(\"", prompt_string(x.prompt), "\",...)"))
"Maximum number of entries in the kill ring queue.
Beyond this number, oldest entries are discarded first."
const KILL_RING_MAX = Ref(100)
mutable struct MIState
interface::ModalInterface
current_mode::TextInterface
aborted::Bool
mode_state::Dict
kill_ring::Vector{String}
kill_idx::Int
previous_key::Vector{Char}
key_repeats::Int
last_action::Symbol
end
MIState(i, c, a, m) = MIState(i, c, a, m, String[], 0, Char[], 0, :begin)
function show(io::IO, s::MIState)
print(io, "MI State (", mode(s), " active)")
end
struct InputAreaState
num_rows::Int64
curs_row::Int64
end
mutable struct PromptState <: ModeState
terminal::AbstractTerminal
p::Prompt
input_buffer::IOBuffer
undo_buffers::Vector{IOBuffer}
undo_idx::Int
ias::InputAreaState
# indentation of lines which do not include the prompt
# if negative, the width of the prompt is used
indent::Int
refresh_lock::Threads.AbstractLock
# this would better be Threads.Atomic{Float64}, but not supported on some platforms
beeping::Float64
end
options(s::PromptState) = isdefined(s.p, :repl) ? s.p.repl.options : Base.REPL.Options()
setmark(s) = mark(buffer(s))
# the default mark is 0
getmark(s) = max(0, buffer(s).mark)
const Region = Pair{<:Integer,<:Integer}
_region(s) = getmark(s) => position(s)
region(s) = Pair(extrema(_region(s))...)
bufend(s) = buffer(s).size
indexes(reg::Region) = first(reg)+1:last(reg)
content(s, reg::Region = 0=>bufend(s)) = String(buffer(s).data[indexes(reg)])
const REGION_ANIMATION_DURATION = Ref(0.2)
input_string(s::PromptState) = String(take!(copy(s.input_buffer)))
input_string_newlines(s::PromptState) = count(c->(c == '\n'), input_string(s))
function input_string_newlines_aftercursor(s::PromptState)
str = input_string(s)
isempty(str) && return 0
rest = str[nextind(str, position(s)):end]
return count(c->(c == '\n'), rest)
end
abstract type HistoryProvider end
abstract type CompletionProvider end
struct EmptyCompletionProvider <: CompletionProvider end
struct EmptyHistoryProvider <: HistoryProvider end
reset_state(::EmptyHistoryProvider) = nothing
complete_line(c::EmptyCompletionProvider, s) = [], true, true
terminal(s::IO) = s
terminal(s::PromptState) = s.terminal
# these may be better stored in Prompt or LineEditREPL
const BEEP_DURATION = Ref(0.2)
const BEEP_BLINK = Ref(0.2)
const BEEP_MAXDURATION = Ref(1.0)
const BEEP_COLORS = ["\e[90m"] # gray (text_colors not yet available)
const BEEP_USE_CURRENT = Ref(true)
function beep(s::PromptState, duration::Real=BEEP_DURATION[], blink::Real=BEEP_BLINK[],
maxduration::Real=BEEP_MAXDURATION[];
colors=BEEP_COLORS, use_current::Bool=BEEP_USE_CURRENT[])
isinteractive() || return # some tests fail on some platforms
s.beeping = min(s.beeping + duration, maxduration)
@async begin
trylock(s.refresh_lock) || return
orig_prefix = s.p.prompt_prefix
colors = Base.copymutable(colors)
use_current && push!(colors, orig_prefix)
i = 0
while s.beeping > 0.0
prefix = colors[mod1(i+=1, end)]
s.p.prompt_prefix = prefix
refresh_multi_line(s, beeping=true)
sleep(blink)
s.beeping -= blink
end
s.p.prompt_prefix = orig_prefix
refresh_multi_line(s, beeping=true)
s.beeping = 0.0
unlock(s.refresh_lock)
end
end
function cancel_beep(s::PromptState)
# wait till beeping finishes
while !trylock(s.refresh_lock)
s.beeping = 0.0
sleep(.05)
end
unlock(s.refresh_lock)
end
beep(::ModeState) = nothing
cancel_beep(::ModeState) = nothing
for f in [:terminal, :on_enter, :add_history, :buffer, :(Base.isempty),
:replace_line, :refresh_multi_line, :input_string, :update_display_buffer,
:empty_undo, :push_undo, :pop_undo, :options, :cancel_beep, :beep]
@eval ($f)(s::MIState, args...) = $(f)(state(s), args...)
end
for f in [:edit_insert, :edit_insert_newline, :edit_backspace, :edit_move_left,
:edit_move_right, :edit_move_word_left, :edit_move_word_right]
@eval function ($f)(s::MIState, args...)
$(f)(state(s), args...)
return $(Expr(:quote, f))
end
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(ret, 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
function complete_line(s::MIState)
if complete_line(state(s), s.key_repeats)
refresh_line(s)
:complete_line
else
beep(s)
:ignore
end
end
function complete_line(s::PromptState, repeats)
completions, partial, should_complete = complete_line(s.p.complete, s)
isempty(completions) && return false
if !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)
push_undo(s)
edit_splice!(s, prev_pos-sizeof(partial) => prev_pos, completions[1])
else
p = common_prefix(completions)
if !isempty(p) && p != partial
# All possible completions share the same prefix, so we might as
# well complete that
prev_pos = position(s)
push_undo(s)
edit_splice!(s, prev_pos-sizeof(partial) => prev_pos, p)
elseif repeats > 0
show_completions(s, completions)
end
end
true
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 = 2:state.num_rows
clear_line(terminal)
cmove_up(terminal)
end
# Clear top line
clear_line(terminal)
end
prompt_string(s::PromptState) = prompt_string(s.p)
prompt_string(p::Prompt) = prompt_string(p.prompt)
prompt_string(s::AbstractString) = s
prompt_string(f::Function) = Base.invokelatest(f)
refresh_multi_line(s::ModeState; kw...) = refresh_multi_line(terminal(s), s; kw...)
refresh_multi_line(termbuf::TerminalBuffer, s::ModeState; kw...) = refresh_multi_line(termbuf, terminal(s), s; kw...)
refresh_multi_line(termbuf::TerminalBuffer, term, s::ModeState; kw...) = (@assert term == terminal(s); refresh_multi_line(termbuf,s; kw...))
function refresh_multi_line(termbuf::TerminalBuffer, terminal::UnixTerminal, buf, state::InputAreaState, prompt = ""; indent = 0)
_clear_input_area(termbuf, state)
cols = width(terminal)
curs_row = -1 # relative to prompt (1-based)
curs_pos = -1 # 1-based column position of the cursor
cur_row = 0 # count of the number of rows
buf_pos = position(buf)
line_pos = buf_pos
# Write out the prompt string
lindent = write_prompt(termbuf, prompt)
# Count the '\n' at the end of the line if the terminal emulator does (specific to DOS cmd prompt)
miscountnl = @static Sys.iswindows() ? (isa(Terminals.pipe_reader(terminal), Base.TTY) && !Base.ispty(Terminals.pipe_reader(terminal))) : false
# Now go through the buffer line by line
seek(buf, 0)
moreinput = true # add a blank line if there is a trailing newline on the last line
while moreinput
l = readline(buf, chomp=false)
moreinput = endswith(l, "\n")
# We need to deal with on-screen characters, so use strwidth to compute occupied columns
llength = strwidth(l)
slength = sizeof(l)
cur_row += 1
cmove_col(termbuf, lindent + 1)
write(termbuf, l)
# 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
# in this case, we haven't yet written the cursor position
line_pos -= slength # '\n' gets an extra pos
if line_pos < 0 || !moreinput
num_chars = (line_pos >= 0 ? llength : strwidth(l[1:prevind(l, line_pos + slength + 1)]))
curs_row, curs_pos = divrem(lindent + num_chars - 1, cols)
curs_row += cur_row
curs_pos += 1
# 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
end
end
cur_row += div(max(lindent + llength + miscountnl - 1, 0), cols)
lindent = indent < 0 ? lindent : indent
end
seek(buf, buf_pos)
# 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
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, take!(outbuf))
flush(terminal)
return ret
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
edit_exchange_point_and_mark(s::MIState) =
edit_exchange_point_and_mark(buffer(s)) && (refresh_line(s); true)
function edit_exchange_point_and_mark(buf::IOBuffer)
m = getmark(buf)
m == position(buf) && return false
mark(buf)
seek(buf, m)
true
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) > 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(content(buf, npos => 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(String(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 close-open region to index, update the size,
# and keep the cursor position and mark stable with the text
# returns the removed portion as a String
function edit_splice!(s, r::Region=region(s), ins::AbstractString = "")
A, B = first(r), last(r)
A >= B && isempty(ins) && return String(ins)
buf = buffer(s)
pos = position(buf)
if A <= pos < B
seek(buf, A)
elseif B <= pos
seek(buf, pos - B + A)
end
if A < buf.mark < B
buf.mark = A
elseif A < B <= buf.mark
buf.mark += sizeof(ins) - B + A
end
ret = splice!(buf.data, A+1:B, Vector{UInt8}(ins)) # position(), etc, are 0-indexed
buf.size = buf.size + sizeof(ins) - B + A
seek(buf, position(buf) + sizeof(ins))
String(ret)
end
edit_splice!(s, ins::AbstractString) = edit_splice!(s, region(s), ins)
function edit_insert(s::PromptState, c)
push_undo(s)
buf = s.input_buffer
str = string(c)
edit_insert(buf, str)
offset = s.ias.curs_row == 1 || s.indent < 0 ?
sizeof(prompt_string(s.p.prompt)) : s.indent
if !('\n' in str) && eof(buf) &&
((position(buf) - beginofline(buf) + # size of current line
offset + sizeof(str) - 1) < width(terminal(s)))
# Avoid full update when appending characters to the end
# and an update of curs_row isn't necessary (conservatively estimated)
write(terminal(s), str)
else
refresh_line(s)
end
end
function edit_insert(buf::IOBuffer, c)
if eof(buf)
return write(buf, c)
else
s = string(c)
edit_splice!(buf, position(buf) => position(buf), s)
return sizeof(s)
end
end
# align: number of ' ' to insert after '\n'
# if align < 0: align like line above
function edit_insert_newline(s::PromptState, align=-1)
push_undo(s)
buf = buffer(s)
if align < 0
beg = beginofline(buf)
align = min(findnext(_notspace, buf.data[beg+1:buf.size], 1) - 1,
position(buf) - beg) # indentation must not increase
align < 0 && (align = buf.size-beg)
end
edit_insert(buf, '\n' * ' '^align)
refresh_line(s)
end
# align: delete up to 4 spaces to align to a multiple of 4 chars
# adjust: also delete spaces on the right of the cursor to try to keep aligned what is
# on the right
function edit_backspace(s::PromptState, align::Bool=options(s).backspace_align,
adjust=options(s).backspace_adjust)
push_undo(s)
if edit_backspace(buffer(s), align, adjust)
refresh_line(s)
else
pop_undo(s)
beep(s)
end
end
const _newline = UInt8('\n')
const _space = UInt8(' ')
_notspace(c) = c != _space
beginofline(buf, pos=position(buf)) = findprev(buf.data, _newline, pos)
function endofline(buf, pos=position(buf))
eol = findnext(buf.data[pos+1:buf.size], _newline, 1)
eol == 0 ? buf.size : pos + eol - 1
end
function edit_backspace(buf::IOBuffer, align::Bool=false, adjust::Bool=false)
!align && adjust &&
throw(DomainError((align, adjust),
"if `adjust` is `true`, `align` must be `true`"))
oldpos = position(buf)
oldpos == 0 && return false
c = char_move_left(buf)
newpos = position(buf)
if align && c == ' ' # maybe delete multiple spaces
beg = beginofline(buf, newpos)
align = strwidth(String(buf.data[1+beg:newpos])) % 4
nonspace = findprev(_notspace, buf.data, newpos)
if newpos - align >= nonspace
newpos -= align
seek(buf, newpos)
if adjust
spaces = findnext(_notspace, buf.data[newpos+2:buf.size], 1)
oldpos = spaces == 0 ? buf.size :
buf.data[newpos+1+spaces] == _newline ? newpos+spaces :
newpos + min(spaces, 4)
end
end
end
edit_splice!(buf, newpos => oldpos)
return true
end
function edit_delete(s)
push_undo(s)
if edit_delete(buffer(s))
refresh_line(s)
else
pop_undo(s)
beep(s)
end
:edit_delete
end
function edit_delete(buf::IOBuffer)
eof(buf) && return false
oldpos = position(buf)
char_move_right(buf)
edit_splice!(buf, oldpos => position(buf))
true
end
function edit_werase(buf::IOBuffer)
pos1 = position(buf)
char_move_word_left(buf, isspace)
pos0 = position(buf)
edit_splice!(buf, pos0 => pos1)
end
function edit_werase(s::MIState)
push_undo(s)
if push_kill!(s, edit_werase(buffer(s)), rev=true)
refresh_line(s)
:edit_werase
else
pop_undo(s)
:ignore
end
end
function edit_delete_prev_word(buf::IOBuffer)
pos1 = position(buf)
char_move_word_left(buf)
pos0 = position(buf)
edit_splice!(buf, pos0 => pos1)
end
function edit_delete_prev_word(s::MIState)
push_undo(s)
if push_kill!(s, edit_delete_prev_word(buffer(s)), rev=true)
refresh_line(s)
:edit_delete_prev_word
else
pop_undo(s)
:ignore
end
end
function edit_delete_next_word(buf::IOBuffer)
pos0 = position(buf)
char_move_word_right(buf)
pos1 = position(buf)
edit_splice!(buf, pos0 => pos1)
end
function edit_delete_next_word(s)
push_undo(s)
if push_kill!(s, edit_delete_next_word(buffer(s)))
refresh_line(s)
:edit_delete_next_word
else
pop_undo(s)
:ignore
end
end
function edit_yank(s::MIState)
if isempty(s.kill_ring)
beep(s)
return :ignore
end
setmark(s) # necessary for edit_yank_pop
push_undo(s)
edit_insert(buffer(s), s.kill_ring[mod1(s.kill_idx, end)])
refresh_line(s)
:edit_yank
end
function edit_yank_pop(s::MIState, require_previous_yank=true)
repeat = s.last_action ∈ (:edit_yank, :edit_yank_pop)
if require_previous_yank && !repeat || isempty(s.kill_ring)
beep(s)
:ignore
else
require_previous_yank || repeat || setmark(s)
push_undo(s)
edit_splice!(s, s.kill_ring[mod1(s.kill_idx-=1, end)])
refresh_line(s)
:edit_yank_pop
end
end
function push_kill!(s::MIState, killed::String, concat = s.key_repeats > 0; rev=false)
isempty(killed) && return false
if concat && !isempty(s.kill_ring)
s.kill_ring[end] = rev ?
killed * s.kill_ring[end] : # keep expected order for backward deletion
s.kill_ring[end] * killed
else
push!(s.kill_ring, killed)
length(s.kill_ring) > KILL_RING_MAX[] && shift!(s.kill_ring)
end
s.kill_idx = endof(s.kill_ring)
true
end
function edit_kill_line(s::MIState)
push_undo(s)
buf = buffer(s)
pos = position(buf)
endpos = endofline(buf)
endpos == pos && buf.size > pos && (endpos += 1)
if push_kill!(s, edit_splice!(s, pos => endpos))
refresh_line(s)
:edit_kill_line
else
pop_undo(s)
:ignore
end
end
function edit_copy_region(s::MIState)
buf = buffer(s)
push_kill!(s, content(buf, region(buf)), false) || return :ignore
if REGION_ANIMATION_DURATION[] > 0.0
edit_exchange_point_and_mark(s)
sleep(REGION_ANIMATION_DURATION[])
edit_exchange_point_and_mark(s)
end
:edit_copy_region
end
function edit_kill_region(s::MIState)
push_undo(s)
if push_kill!(s, edit_splice!(s), false)
refresh_line(s)
:edit_kill_region
else
pop_undo(s)
:ignore
end
end
function edit_transpose_chars(s::MIState)
push_undo(s)
edit_transpose_chars(buffer(s)) ? refresh_line(s) : pop_undo(s)
:edit_transpose
end
function edit_transpose_chars(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
function edit_transpose_words(s)
push_undo(s)
edit_transpose_words(buffer(s)) ? refresh_line(s) : pop_undo(s)
:edit_transpose_words
end
function edit_transpose_words(buf::IOBuffer, mode=:emacs)
mode in [:readline, :emacs] ||
throw(ArgumentError("`mode` must be `:readline` or `:emacs`"))
pos = position(buf)
if mode == :emacs
char_move_word_left(buf)
char_move_word_right(buf)
end
char_move_word_right(buf)
e2 = position(buf)
char_move_word_left(buf)
b2 = position(buf)
char_move_word_left(buf)
b1 = position(buf)
char_move_word_right(buf)
e1 = position(buf)
e1 >= b2 && (seek(buf, pos); return false)
word2 = edit_splice!(buf, b2 => e2, content(buf, b1 => e1))
edit_splice!(buf, b1 => e1, word2)
seek(buf, e2)
true
end
edit_upper_case(s) = (edit_replace_word_right(s, uppercase); :edit_upper_case)
edit_lower_case(s) = (edit_replace_word_right(s, lowercase); :edit_lower_case)
edit_title_case(s) = (edit_replace_word_right(s, ucfirst); :edit_title_case)
function edit_replace_word_right(s, replace::Function)
push_undo(s)
edit_replace_word_right(buffer(s), replace) ? refresh_line(s) : pop_undo(s)
end
function edit_replace_word_right(buf::IOBuffer, replace::Function)
# put the cursor at the beginning of the next word
skipchars(buf, is_non_word_char)
b = position(buf)
char_move_word_right(buf)
e = position(buf)
e == b && return false
edit_splice!(buf, b => e, replace(content(buf, b => e)))
true
end
edit_clear(buf::IOBuffer) = truncate(buf, 0)
function edit_clear(s::MIState)
push_undo(s)
if push_kill!(s, edit_splice!(s, 0 => bufend(s)), false)
refresh_line(s)
:edit_clear
else
pop_undo(s)
:ignore
end
end
function replace_line(s::PromptState, l::IOBuffer)
empty_undo(s)
s.input_buffer = copy(l)
end
function replace_line(s::PromptState, l, keep_undo=false)
keep_undo || empty_undo(s)
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_first(::EmptyHistoryProvider) = ("", false)
history_last(::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, prefix) = false
history_prev_prefix(s, hist, prefix) = 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(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(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.p)
function write_prompt(terminal, p::Prompt)
prefix = prompt_string(p.prompt_prefix)
suffix = prompt_string(p.prompt_suffix)
write(terminal, prefix)
write(terminal, Base.text_colors[:bold])
width = write_prompt(terminal, p.prompt)
write(terminal, Base.text_colors[:normal])
write(terminal, suffix)
width
end
# returns the width of the written prompt
function write_prompt(terminal, s::Union{AbstractString,Function})
promptstr = prompt_string(s)
write(terminal, promptstr)
strwidth(promptstr)
end
### Keymap Support
const wildcard = Char(0x0010f7ff) # "Private Use" Char
normalize_key(key::Char) = string(key)
normalize_key(key::Integer) = normalize_key(Char(key))
function normalize_key(key::AbstractString)
wildcard in key && error("Matching Char(0x0010f7ff) not supported.")
buf = IOBuffer()
i = start(key)
while !done(key, i)
c, i = next(key, i)
if c == '*'
write(buf, wildcard)
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 String(take!(buf))
end
function normalize_keys(keymap::Dict)
ret = Dict{Any,Any}()
for (k,v) in keymap
normalized = normalize_key(k)
if haskey(ret,normalized)
error("""Multiple spellings of a key in a single keymap
(\"$k\" conflicts with existing mapping)""")