-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathLineEdit.jl
2993 lines (2700 loc) · 99.9 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
import ..REPL
using ..REPL: AbstractREPL, Options
using ..Terminals
import ..Terminals: raw!, width, height, clear_line, beep
import Base: ensureroom, show, AnyDict, position
using Base: something
using InteractiveUtils: InteractiveUtils
abstract type TextInterface end # see interface immediately below
abstract type ModeState end # see interface below
abstract type HistoryProvider end
abstract type CompletionProvider end
export run_interface, Prompt, ModalInterface, transition, reset_state, edit_insert, keymap
@nospecialize # use only declared type signatures
const StringLike = Union{Char,String,SubString{String}}
# interface for TextInterface
function Base.getproperty(ti::TextInterface, name::Symbol)
if name === :hp
return getfield(ti, :hp)::HistoryProvider
elseif name === :complete
return getfield(ti, :complete)::CompletionProvider
elseif name === :keymap_dict
return getfield(ti, :keymap_dict)::Dict{Char,Any}
end
return getfield(ti, name)
end
struct ModalInterface <: TextInterface
modes::Vector{TextInterface}
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}
output_prefix::Union{String,Function}
output_prefix_prefix::Union{String,Function}
output_prefix_suffix::Union{String,Function}
keymap_dict::Dict{Char,Any}
repl::Union{AbstractREPL,Nothing}
complete::CompletionProvider
on_enter::Function
on_done::Function
hist::HistoryProvider # TODO?: rename this `hp` (consistency with other TextInterfaces), or is the type-assert useful for mode(s)?
sticky::Bool
end
show(io::IO, x::Prompt) = show(io, string("Prompt(\"", prompt_string(x.prompt), "\",...)"))
mutable struct MIState
interface::ModalInterface
active_module::Module
previous_active_module::Module
current_mode::TextInterface
aborted::Bool
mode_state::IdDict{TextInterface,ModeState}
kill_ring::Vector{String}
kill_idx::Int
previous_key::Vector{Char}
key_repeats::Int
last_action::Symbol
current_action::Symbol
async_channel::Channel{Function}
line_modify_lock::Base.ReentrantLock
hint_generation_lock::Base.ReentrantLock
n_keys_pressed::Int
end
MIState(i, mod, c, a, m) = MIState(i, mod, mod, c, a, m, String[], 0, Char[], 0, :none, :none, Channel{Function}(), Base.ReentrantLock(), Base.ReentrantLock(), 0)
const BufferLike = Union{MIState,ModeState,IOBuffer}
const State = Union{MIState,ModeState}
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
region_active::Symbol # :shift or :mark or :off
hint::Union{String,Nothing}
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.SpinLock
# this would better be Threads.Atomic{Float64}, but not supported on some platforms
beeping::Float64
# this option is to detect when code is pasted in non-"bracketed paste mode" :
last_newline::Float64 # register when last newline was entered
# this option is to speed up output
refresh_wait::Union{Timer,Nothing}
end
struct Modifiers
shift::Bool
end
Modifiers() = Modifiers(false)
options(s::PromptState) =
if isdefined(s.p, :repl) && isdefined(s.p.repl, :options)
# we can't test isa(s.p.repl, LineEditREPL) as LineEditREPL is defined
# in the REPL module
s.p.repl.options::Options
else
REPL.GlobalOptions::Options
end
function setmark(s::MIState, guess_region_active::Bool=true)
refresh = set_action!(s, :setmark)
s.current_action === :setmark && s.key_repeats > 0 && activate_region(s, :mark)
mark(buffer(s))
refresh && refresh_line(s)
nothing
end
# the default mark is 0
getmark(s::BufferLike) = max(0, buffer(s).mark)
const Region = Pair{Int,Int}
_region(s::BufferLike) = getmark(s) => position(s)
region(s::BufferLike) = Pair(extrema(_region(s))...)
bufend(s::BufferLike) = buffer(s).size
axes(reg::Region) = first(reg)+1:last(reg)
content(s::BufferLike, reg::Region = 0=>bufend(s)) = String(buffer(s).data[axes(reg)])
function activate_region(s::PromptState, state::Symbol)
@assert state in (:mark, :shift, :off)
s.region_active = state
nothing
end
activate_region(s::ModeState, state::Symbol) = false
deactivate_region(s::ModeState) = activate_region(s, :off)
is_region_active(s::PromptState) = s.region_active in (:shift, :mark)
is_region_active(s::ModeState) = false
region_active(s::PromptState) = s.region_active
region_active(s::ModeState) = :off
input_string(s::PromptState) = String(take!(copy(s.input_buffer)))::String
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
struct EmptyCompletionProvider <: CompletionProvider end
struct EmptyHistoryProvider <: HistoryProvider end
reset_state(::EmptyHistoryProvider) = nothing
# Before, completions were always given as strings. But at least for backslash
# completions, it's nice to see what glyphs are available in the completion preview.
# To separate between what's shown in the preview list of possible matches, and what's
# actually completed, we introduce this struct.
struct NamedCompletion
completion::String # what is actually completed, for example "\trianglecdot"
name::String # what is displayed in lists of possible completions, for example "◬ \trianglecdot"
end
NamedCompletion(completion::String) = NamedCompletion(completion, completion)
complete_line(c::EmptyCompletionProvider, s; hint::Bool=false) = NamedCompletion[], "", true
# complete_line can be specialized for only two arguments, when the active module
# doesn't matter (e.g. Pkg does this)
complete_line(c::CompletionProvider, s, ::Module; hint::Bool=false) = complete_line(c, s; hint)
terminal(s::IO) = s
terminal(s::PromptState) = s.terminal
function beep(s::PromptState, duration::Real=options(s).beep_duration,
blink::Real=options(s).beep_blink,
maxduration::Real=options(s).beep_maxduration;
colors=options(s).beep_colors,
use_current::Bool=options(s).beep_use_current)
isinteractive() || return # some tests fail on some platforms
s.beeping = min(s.beeping + duration, maxduration)
let colors = Base.copymutable(colors)
errormonitor(@async begin
trylock(s.refresh_lock) || return
try
orig_prefix = s.p.prompt_prefix
use_current && push!(colors, prompt_string(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
finally
unlock(s.refresh_lock)
end
end)
end
nothing
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)
nothing
end
beep(::ModeState) = nothing
cancel_beep(::ModeState) = nothing
for f in Union{Symbol,Expr}[
: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,
:deactivate_region, :activate_region, :is_region_active, :region_active]
@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...)
set_action!(s, $(Expr(:quote, f)))
$(f)(state(s), args...)
end
end
const COMMAND_GROUPS =
Dict(:movement => [:edit_move_left, :edit_move_right, :edit_move_word_left, :edit_move_word_right,
:edit_move_up, :edit_move_down, :edit_exchange_point_and_mark],
:deletion => [:edit_clear, :edit_backspace, :edit_delete, :edit_werase,
:edit_delete_prev_word,
:edit_delete_next_word,
:edit_kill_line_forwards, :edit_kill_line_backwards, :edit_kill_region],
:insertion => [:edit_insert, :edit_insert_newline, :edit_yank],
:replacement => [:edit_yank_pop, :edit_transpose_chars, :edit_transpose_words,
:edit_upper_case, :edit_lower_case, :edit_title_case, :edit_indent,
:edit_transpose_lines_up!, :edit_transpose_lines_down!],
:copy => [:edit_copy_region],
:misc => [:complete_line, :setmark, :edit_undo!, :edit_redo!])
const COMMAND_GROUP = Dict{Symbol,Symbol}(command=>group for (group, commands) in COMMAND_GROUPS for command in commands)
command_group(command::Symbol) = get(COMMAND_GROUP, command, :nogroup)
command_group(command::Function) = command_group(nameof(command))
# return true if command should keep active a region
function preserve_active(command::Symbol)
command ∈ [:edit_indent, :edit_transpose_lines_down!, :edit_transpose_lines_up!]
end
# returns whether the "active region" status changed visibly,
# i.e. whether there should be a visual refresh
function set_action!(s::MIState, command::Symbol)
# if a command is already running, don't update the current_action field,
# as the caller is used as a helper function
s.current_action === :unknown || return false
active = region_active(s)
## record current action
s.current_action = command
## handle activeness of the region
if startswith(String(command), "shift_") # shift-move command
if active !== :shift
setmark(s) # s.current_action must already have been set
activate_region(s, :shift)
# NOTE: if the region was already active from a non-shift
# move (e.g. ^Space^Space), the region is visibly changed
return active !== :off # active status is reset
end
elseif !(preserve_active(command) ||
command_group(command) === :movement && region_active(s) === :mark)
# if we move after a shift-move, the region is de-activated
# (e.g. like emacs behavior)
deactivate_region(s)
return active !== :off
end
false
end
set_action!(s, command::Symbol) = nothing
common_prefix(completions::Vector{NamedCompletion}) = common_prefix(map(x -> x.completion, completions))
function common_prefix(completions::Vector{String})
ret = ""
c1 = completions[1]
isempty(c1) && return ret
i = 1
cc, nexti = iterate(c1, i)
while true
for c in completions
(i > lastindex(c) || c[i] != cc) && return ret
end
ret = string(ret, cc)
i >= lastindex(c1) && return ret
i = nexti
cc, nexti = iterate(c1, i)
end
end
# This is the maximum number of completions that will be displayed in a single
# column, anything above that and multiple columns will be used. Note that this
# does not restrict column length when multiple columns are used.
const MULTICOLUMN_THRESHOLD = 5
show_completions(s::PromptState, completions::Vector{NamedCompletion}) = show_completions(s, map(x -> x.name, completions))
# Show available completions
function show_completions(s::PromptState, completions::Vector{String})
# skip any lines of input after the cursor
cmove_down(terminal(s), input_string_newlines_aftercursor(s))
println(terminal(s))
if any(Base.Fix1(occursin, '\n'), completions)
foreach(Base.Fix1(println, terminal(s)), completions)
else
n = length(completions)
colmax = 2 + maximum(length, completions; init=1) # n.b. length >= textwidth
num_cols = min(cld(n, MULTICOLUMN_THRESHOLD),
max(div(width(terminal(s)), colmax), 1))
entries_per_col = cld(n, num_cols)
idx = 0
for _ in 1:entries_per_col
for col = 0:(num_cols-1)
idx += 1
idx > n && break
cmove_col(terminal(s), colmax*col+1)
print(terminal(s), completions[idx])
end
println(terminal(s))
end
end
# make space for the prompt
for i = 1:input_string_newlines(s)
println(terminal(s))
end
end
# Prompt Completions & Hints
function complete_line(s::MIState)
set_action!(s, :complete_line)
if complete_line(state(s), s.key_repeats, s.active_module)
return refresh_line(s)
else
beep(s)
return :ignore
end
end
# Old complete_line return type: Vector{String}, String, Bool
# New complete_line return type: NamedCompletion{String}, String, Bool
# OR NamedCompletion{String}, Region, Bool
#
# due to close coupling of the Pkg ReplExt `complete_line` can still return a vector of strings,
# so we convert those in this helper
function complete_line_named(c, s, args...; kwargs...)::Tuple{Vector{NamedCompletion},Region,Bool}
r1, r2, should_complete = complete_line(c, s, args...; kwargs...)::Union{
Tuple{Vector{String}, String, Bool},
Tuple{Vector{NamedCompletion}, String, Bool},
Tuple{Vector{NamedCompletion}, Region, Bool},
}
completions = (r1 isa Vector{String} ? map(NamedCompletion, r1) : r1)
r = (r2 isa String ? (position(s)-sizeof(r2) => position(s)) : r2)
completions, r, should_complete
end
# checks for a hint and shows it if appropriate.
# to allow the user to type even if hint generation is slow, the
# hint is generated on a worker thread, and only shown if the user hasn't
# pressed a key since the hint generation was requested
function check_show_hint(s::MIState)
st = state(s)
this_key_i = s.n_keys_pressed
next_key_pressed() = @lock s.line_modify_lock s.n_keys_pressed > this_key_i
function lock_clear_hint()
@lock s.line_modify_lock begin
next_key_pressed() || s.aborted || clear_hint(st) && refresh_line(s)
end
end
if !options(st).hint_tab_completes || !eof(buffer(st))
# only generate hints if enabled and at the end of the line
# TODO: maybe show hints for insertions at other positions
# Requires making space for them earlier in refresh_multi_line
lock_clear_hint()
return
end
t_completion = Threads.@spawn :default begin
named_completions, reg, should_complete = nothing, nothing, nothing
# only allow one task to generate hints at a time and check around lock
# if the user has pressed a key since the hint was requested, to skip old completions
next_key_pressed() && return
@lock s.hint_generation_lock begin
next_key_pressed() && return
named_completions, reg, should_complete = try
complete_line_named(st.p.complete, st, s.active_module; hint = true)
catch
lock_clear_hint()
return
end
end
next_key_pressed() && return
completions = map(x -> x.completion, named_completions)
if isempty(completions)
lock_clear_hint()
return
end
# Don't complete for single chars, given e.g. `x` completes to `xor`
if reg.second - reg.first > 1 && should_complete
singlecompletion = length(completions) == 1
p = singlecompletion ? completions[1] : common_prefix(completions)
if singlecompletion || p in completions # i.e. complete `@time` even though `@time_imports` etc. exists
# The completion `p` and the region `reg` may not share the same initial
# characters, for instance when completing to subscripts or superscripts.
# So, in general, make sure that the hint starts at the correct position by
# incrementing its starting position by as many characters as the input.
maxind = lastindex(p)
startind = sizeof(content(s, reg))
if startind ≤ maxind # completion on a complete name returns itself so check that there's something to hint
# index of p from which to start providing the hint
startind = nextind(p, startind)
hint = p[startind:end]
next_key_pressed() && return
@lock s.line_modify_lock begin
if !s.aborted
state(s).hint = hint
refresh_line(s)
end
end
return
end
end
end
lock_clear_hint()
end
Base.errormonitor(t_completion)
return
end
function clear_hint(s::ModeState)
if !isnothing(s.hint)
s.hint = "" # don't set to nothing here. That will be done in `maybe_show_hint`
return true # indicate maybe_show_hint has work to do
else
return false
end
end
function complete_line(s::PromptState, repeats::Int, mod::Module; hint::Bool=false)
completions, reg, should_complete = complete_line_named(s.p.complete, s, mod; hint)
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
push_undo(s)
edit_splice!(s, reg, completions[1].completion)
else
p = common_prefix(completions)
partial = content(s, reg.first => min(bufend(s), reg.first + sizeof(p)))
if !isempty(p) && p != partial
# All possible completions share the same prefix, so we might as
# well complete that.
push_undo(s)
edit_splice!(s, reg, p)
elseif repeats > 0
show_completions(s, completions)
end
end
return true
end
function clear_input_area(terminal::AbstractTerminal, s::PromptState)
if s.refresh_wait !== nothing
close(s.refresh_wait)
s.refresh_wait = nothing
end
_clear_input_area(terminal, s.ias)
s.ias = InputAreaState(0, 0)
end
clear_input_area(terminal::AbstractTerminal, s::ModeState) = (_clear_input_area(terminal, s.ias); s.ias = InputAreaState(0, 0))
clear_input_area(s::ModeState) = clear_input_area(s.terminal, s)
function _clear_input_area(terminal::AbstractTerminal, 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)
nothing
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)
function maybe_show_hint(s::PromptState)
isa(s.hint, String) || return nothing
# The hint being "" then nothing is used to first clear a previous hint, then skip printing the hint
if isempty(s.hint)
s.hint = nothing
else
Base.printstyled(terminal(s), s.hint, color=:light_black)
cmove_left(terminal(s), textwidth(s.hint))
s.hint = "" # being "" signals to do one clear line remainder to clear the hint next time the screen is refreshed
end
return nothing
end
function refresh_multi_line(s::PromptState; kw...)
if s.refresh_wait !== nothing
close(s.refresh_wait)
s.refresh_wait = nothing
end
if s.hint isa String
# clear remainder of line which is unknown here if it had a hint before unbeknownst to refresh_multi_line
# the clear line cannot be printed each time because it would break column movement
print(terminal(s), "\e[0K")
end
r = refresh_multi_line(terminal(s), s; kw...)
maybe_show_hint(s) # now maybe write the hint back to the screen
return r
end
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::IOBuffer,
state::InputAreaState, prompt = "";
indent::Int = 0, region_active::Bool = false)
_clear_input_area(termbuf, state)
cols = width(terminal)
rows = height(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
regstart, regstop = region(buf)
written = 0
@static if Sys.iswindows()
writer = Terminals.pipe_writer(terminal)
if writer isa Base.TTY && !Base.ispty(writer)::Bool
_reset_console_mode(writer.handle)
end
end
# Write out the prompt string
lindent = write_prompt(termbuf, prompt, hascolor(terminal))::Int
# Count the '\n' at the end of the line if the terminal emulator does (specific to DOS cmd prompt)
miscountnl = @static if Sys.iswindows()
reader = Terminals.pipe_reader(terminal)
reader isa Base.TTY && !Base.ispty(reader)::Bool
else false end
# 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
lastline = false # indicates when to stop printing lines, even when there are potentially
# more (for the case where rows is too small to print everything)
# Note: when there are too many lines for rows, we still print the first lines
# even if they are going to not be visible in the end: for simplicity, but
# also because it does the 'right thing' when the window is resized
while moreinput
line = readline(buf, keep=true)
moreinput = endswith(line, "\n")
if rows == 1 && line_pos <= sizeof(line) - moreinput
# we special case rows == 1, as otherwise by the time the cursor is seen to
# be in the current line, it's too late to chop the '\n' away
lastline = true
curs_row = 1
curs_pos = lindent + line_pos
end
if moreinput && lastline # we want to print only one "visual" line, so
line = chomp(line) # don't include the trailing "\n"
end
# We need to deal with on-screen characters, so use textwidth to compute occupied columns
llength = textwidth(line)
slength = sizeof(line)
cur_row += 1
# lwrite: what will be written to termbuf
lwrite = region_active ? highlight_region(line, regstart, regstop, written, slength) :
line
written += slength
cmove_col(termbuf, lindent + 1)
write(termbuf, lwrite)
# 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
line_pos -= slength # '\n' gets an extra pos
# in this case, we haven't yet written the cursor position
if line_pos < 0 || !moreinput
num_chars = line_pos >= 0 ?
llength :
textwidth(line[1:prevind(line, 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
lastline && break
if curs_row >= 0 && cur_row + 1 >= rows && # when too many lines,
cur_row - curs_row + 1 >= rows ÷ 2 # center the cursor
lastline = true
end
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 highlight_region(lwrite::Union{String,SubString{String}}, regstart::Int, regstop::Int, written::Int, slength::Int)
if written <= regstop <= written+slength
i = thisind(lwrite, regstop-written)
lwrite = lwrite[1:i] * Base.disable_text_style[:reverse] * lwrite[nextind(lwrite, i):end]
end
if written <= regstart <= written+slength
i = thisind(lwrite, regstart-written)
lwrite = lwrite[1:i] * Base.text_colors[:reverse] * lwrite[nextind(lwrite, i):end]
end
return lwrite
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::Char) = c in """ \t\n\"\\'`@\$><=:;|&{}()[].,+-*/?%^~"""
function reset_key_repeats(f::Function, s::MIState)
key_repeats_sav = s.key_repeats
try
s.key_repeats = 0
return f()
finally
s.key_repeats = key_repeats_sav
end
end
function edit_exchange_point_and_mark(s::MIState)
set_action!(s, :edit_exchange_point_and_mark)
return edit_exchange_point_and_mark(buffer(s)) ? refresh_line(s) : false
end
function edit_exchange_point_and_mark(buf::IOBuffer)
m = getmark(buf)
m == position(buf) && return false
mark(buf)
seek(buf, m)
return 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)
return 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 textwidth(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) : false
function edit_move_word_left(s::PromptState)
if position(s) > 0
char_move_word_left(s.input_buffer)
return refresh_line(s)
end
return nothing
end
char_move_right(s::MIState) = char_move_right(buffer(s))
function char_move_right(buf::IOBuffer)
return !eof(buf) && read(buf, Char)
end
function char_move_word_right(buf::IOBuffer, is_delimiter::Function=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::Function=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::Union{MIState,ModeState}) = char_move_word_right(buffer(s))
char_move_word_left(s::Union{MIState,ModeState}) = 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)
(textwidth(nextc) != 0 || nextc == '\n') && break
end
return true
end
return false
end
function edit_move_right(m::MIState)
s = state(m)
buf = s.input_buffer
if edit_move_right(s.input_buffer)
refresh_line(s)
return true
else
completions, reg, should_complete = complete_line(s.p.complete, s, m.active_module)
if should_complete && eof(buf) && length(completions) == 1 && reg.second - reg.first > 1
# Replace word by completion
prev_pos = position(s)
push_undo(s)
edit_splice!(s, (prev_pos - reg.second + reg.first) => prev_pos, completions[1].completion)
refresh_line(state(s))
return true
else
return false
end
end
end
function edit_move_word_right(s::PromptState)
if !eof(s.input_buffer)
char_move_word_right(s)
return refresh_line(s)
end
return nothing
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 = findprev(isequal(UInt8('\n')), buf.data, position(buf))
npos === nothing && 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 = something(findprev(isequal(UInt8('\n')), buf.data, npos-1), 0)
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::MIState)
set_action!(s, :edit_move_up)
changed = edit_move_up(buffer(s))
changed && refresh_line(s)
return changed
end
function edit_move_down(buf::IOBuffer)
npos = something(findprev(isequal(UInt8('\n')), buf.data[1:buf.size], position(buf)), 0)
# We're interested in character count, not byte count
offset = length(String(buf.data[(npos+1):(position(buf))]))
npos2 = findnext(isequal(UInt8('\n')), buf.data[1:buf.size], position(buf)+1)
if npos2 === nothing #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::MIState)
set_action!(s, :edit_move_down)
changed = edit_move_down(buffer(s))
changed && refresh_line(s)
return changed
end
function edit_shift_move(s::MIState, move_function::Function)
@assert command_group(move_function) === :movement
set_action!(s, Symbol(:shift_, move_function))
return move_function(s)
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::BufferLike, r::Region=region(s), ins::String = ""; rigid_mark::Bool=true)
A, B = first(r), last(r)
A >= B && isempty(ins) && return ins
buf = buffer(s)
pos = position(buf) # n.b. position(), etc, are 0-indexed
adjust_pos = true
if A <= pos < B
seek(buf, A)
elseif B <= pos
seek(buf, pos - B + A)
else
adjust_pos = false
end
mark = buf.mark
if mark != -1
if A < mark < B || A == mark == B
# rigid_mark is used only if the mark is strictly "inside"
# the region, or the region is empty and the mark is at the boundary
mark = rigid_mark ? A : A + sizeof(ins)
elseif mark >= B
mark += sizeof(ins) - B + A
end
buf.mark = -1
end
# Implement ret = splice!(buf.data, A+1:B, codeunits(ins)) for a stream
pos = position(buf)
seek(buf, A)
ret = read(buf, A >= B ? 0 : B - A)
trail = read(buf)
seek(buf, A)
write(buf, ins)
write(buf, trail)
truncate(buf, position(buf))
seek(buf, pos + (adjust_pos ? sizeof(ins) : 0))
buf.mark = mark
return String(ret)
end
edit_splice!(s::MIState, ins::AbstractString) = edit_splice!(s, region(s), ins)
function edit_insert(s::PromptState, c::StringLike)
push_undo(s)
buf = s.input_buffer
if ! options(s).auto_indent_bracketed_paste
pos = position(buf)
if pos > 0
if buf.data[pos] != _space && string(c) != " "
options(s).auto_indent_tmp_off = false
end
if buf.data[pos] == _space
#tabulators are already expanded to space
#this expansion may take longer than auto_indent_time_threshold which breaks the timing
s.last_newline = time()
else
#if characters after new line are coming in very fast
#its probably copy&paste => switch auto-indent off for the next coming new line
if ! options(s).auto_indent_tmp_off && time() - s.last_newline < options(s).auto_indent_time_threshold
options(s).auto_indent_tmp_off = true
end
end
end
end
old_wait = s.refresh_wait !== nothing
if old_wait
close(s.refresh_wait)
s.refresh_wait = nothing
end
str = string(c)
edit_insert(buf, str)
if '\n' in str
refresh_line(s)
else
after = options(s).auto_refresh_time_delay
termbuf = terminal(s)
w = width(termbuf)
offset = s.ias.curs_row == 1 || s.indent < 0 ?
sizeof(prompt_string(s.p.prompt)::String) : s.indent
offset += position(buf) - beginofline(buf) # size of current line
spinner = '\0'