/
REPL.jl
1723 lines (1555 loc) · 62.8 KB
/
REPL.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
"""
Run Evaluate Print Loop (REPL)
Example minimal code
```julia
import REPL
term = REPL.Terminals.TTYTerminal("dumb", stdin, stdout, stderr)
repl = REPL.LineEditREPL(term, true)
REPL.run_repl(repl)
```
"""
module REPL
Base.Experimental.@optlevel 1
Base.Experimental.@max_methods 1
function UndefVarError_hint(io::IO, ex::UndefVarError)
var = ex.var
if var === :or
print(io, "\nSuggestion: Use `||` for short-circuiting boolean OR.")
elseif var === :and
print(io, "\nSuggestion: Use `&&` for short-circuiting boolean AND.")
elseif var === :help
println(io)
# Show friendly help message when user types help or help() and help is undefined
show(io, MIME("text/plain"), Base.Docs.parsedoc(Base.Docs.keywords[:help]))
elseif var === :quit
print(io, "\nSuggestion: To exit Julia, use Ctrl-D, or type exit() and press enter.")
end
if isdefined(ex, :scope)
scope = ex.scope
if scope isa Module
bnd = ccall(:jl_get_module_binding, Any, (Any, Any, Cint), scope, var, true)::Core.Binding
if isdefined(bnd, :owner)
owner = bnd.owner
if owner === bnd
print(io, "\nSuggestion: add an appropriate import or assignment. This global was declared but not assigned.")
end
else
owner = ccall(:jl_binding_owner, Ptr{Cvoid}, (Any, Any), scope, var)
if C_NULL == owner
# No global of this name exists in this module.
# This is the common case, so do not print that information.
# It could be the binding was exported by two modules, which we can detect
# by the `usingfailed` flag in the binding:
if isdefined(bnd, :flags) && Bool(bnd.flags >> 4 & 1) # magic location of the `usingfailed` flag
print(io, "\nHint: It looks like two or more modules export different ",
"bindings with this name, resulting in ambiguity. Try explicitly ",
"importing it from a particular module, or qualifying the name ",
"with the module it should come from.")
else
print(io, "\nSuggestion: check for spelling errors or missing imports.")
end
owner = bnd
else
owner = unsafe_pointer_to_objref(owner)::Core.Binding
end
end
if owner !== bnd
# this could use jl_binding_dbgmodule for the exported location in the message too
print(io, "\nSuggestion: this global was defined as `$(owner.globalref)` but not assigned a value.")
end
elseif scope === :static_parameter
print(io, "\nSuggestion: run Test.detect_unbound_args to detect method arguments that do not fully constrain a type parameter.")
elseif scope === :local
print(io, "\nSuggestion: check for an assignment to a local variable that shadows a global of the same name.")
end
else
scope = undef
end
if scope !== Base && !_UndefVarError_warnfor(io, Base, var)
warned = false
for m in Base.loaded_modules_order
m === Core && continue
m === Base && continue
m === Main && continue
m === scope && continue
warned |= _UndefVarError_warnfor(io, m, var)
end
warned ||
_UndefVarError_warnfor(io, Core, var) ||
_UndefVarError_warnfor(io, Main, var)
end
return nothing
end
function _UndefVarError_warnfor(io::IO, m::Module, var::Symbol)
Base.isbindingresolved(m, var) || return false
(Base.isexported(m, var) || Base.ispublic(m, var)) || return false
print(io, "\nHint: a global variable of this name also exists in $m.")
return true
end
function __init__()
Base.REPL_MODULE_REF[] = REPL
Base.Experimental.register_error_hint(UndefVarError_hint, UndefVarError)
return nothing
end
using Base.Meta, Sockets, StyledStrings
import InteractiveUtils
export
AbstractREPL,
BasicREPL,
LineEditREPL,
StreamREPL
import Base:
AbstractDisplay,
display,
show,
AnyDict,
==
_displaysize(io::IO) = displaysize(io)::Tuple{Int,Int}
include("Terminals.jl")
using .Terminals
abstract type AbstractREPL end
include("options.jl")
include("LineEdit.jl")
using .LineEdit
import ..LineEdit:
CompletionProvider,
HistoryProvider,
add_history,
complete_line,
history_next,
history_next_prefix,
history_prev,
history_prev_prefix,
history_first,
history_last,
history_search,
setmodifiers!,
terminal,
MIState,
PromptState,
mode_idx
include("REPLCompletions.jl")
using .REPLCompletions
include("TerminalMenus/TerminalMenus.jl")
include("docview.jl")
@nospecialize # use only declared type signatures
answer_color(::AbstractREPL) = ""
const JULIA_PROMPT = "julia> "
const PKG_PROMPT = "pkg> "
const SHELL_PROMPT = "shell> "
const HELP_PROMPT = "help?> "
mutable struct REPLBackend
"channel for AST"
repl_channel::Channel{Any}
"channel for results: (value, iserror)"
response_channel::Channel{Any}
"flag indicating the state of this backend"
in_eval::Bool
"transformation functions to apply before evaluating expressions"
ast_transforms::Vector{Any}
"current backend task"
backend_task::Task
REPLBackend(repl_channel, response_channel, in_eval, ast_transforms=copy(repl_ast_transforms)) =
new(repl_channel, response_channel, in_eval, ast_transforms)
end
REPLBackend() = REPLBackend(Channel(1), Channel(1), false)
"""
softscope(ex)
Return a modified version of the parsed expression `ex` that uses
the REPL's "soft" scoping rules for global syntax blocks.
"""
function softscope(@nospecialize ex)
if ex isa Expr
h = ex.head
if h === :toplevel
ex′ = Expr(h)
map!(softscope, resize!(ex′.args, length(ex.args)), ex.args)
return ex′
elseif h in (:meta, :import, :using, :export, :module, :error, :incomplete, :thunk)
return ex
elseif h === :global && all(x->isa(x, Symbol), ex.args)
return ex
else
return Expr(:block, Expr(:softscope, true), ex)
end
end
return ex
end
# Temporary alias until Documenter updates
const softscope! = softscope
const repl_ast_transforms = Any[softscope] # defaults for new REPL backends
# Allows an external package to add hooks into the code loading.
# The hook should take a Vector{Symbol} of package names and
# return true if all packages could be installed, false if not
# to e.g. install packages on demand
const install_packages_hooks = Any[]
# N.B.: Any functions starting with __repl_entry cut off backtraces when printing in the REPL.
# We need to do this for both the actual eval and macroexpand, since the latter can cause custom macro
# code to run (and error).
__repl_entry_lower_with_loc(mod::Module, @nospecialize(ast), toplevel_file::Ref{Ptr{UInt8}}, toplevel_line::Ref{Cint}) =
ccall(:jl_expand_with_loc, Any, (Any, Any, Ptr{UInt8}, Cint), ast, mod, toplevel_file[], toplevel_line[])
__repl_entry_eval_expanded_with_loc(mod::Module, @nospecialize(ast), toplevel_file::Ref{Ptr{UInt8}}, toplevel_line::Ref{Cint}) =
ccall(:jl_toplevel_eval_flex, Any, (Any, Any, Cint, Cint, Ptr{Ptr{UInt8}}, Ptr{Cint}), mod, ast, 1, 1, toplevel_file, toplevel_line)
function toplevel_eval_with_hooks(mod::Module, @nospecialize(ast), toplevel_file=Ref{Ptr{UInt8}}(Base.unsafe_convert(Ptr{UInt8}, :REPL)), toplevel_line=Ref{Cint}(1))
if !isexpr(ast, :toplevel)
ast = __repl_entry_lower_with_loc(mod, ast, toplevel_file, toplevel_line)
check_for_missing_packages_and_run_hooks(ast)
return __repl_entry_eval_expanded_with_loc(mod, ast, toplevel_file, toplevel_line)
end
local value=nothing
for i = 1:length(ast.args)
value = toplevel_eval_with_hooks(mod, ast.args[i], toplevel_file, toplevel_line)
end
return value
end
function eval_user_input(@nospecialize(ast), backend::REPLBackend, mod::Module)
lasterr = nothing
Base.sigatomic_begin()
while true
try
Base.sigatomic_end()
if lasterr !== nothing
put!(backend.response_channel, Pair{Any, Bool}(lasterr, true))
else
backend.in_eval = true
for xf in backend.ast_transforms
ast = Base.invokelatest(xf, ast)
end
value = toplevel_eval_with_hooks(mod, ast)
backend.in_eval = false
setglobal!(Base.MainInclude, :ans, value)
put!(backend.response_channel, Pair{Any, Bool}(value, false))
end
break
catch err
if lasterr !== nothing
println("SYSTEM ERROR: Failed to report error to REPL frontend")
println(err)
end
lasterr = current_exceptions()
end
end
Base.sigatomic_end()
nothing
end
function check_for_missing_packages_and_run_hooks(ast)
isa(ast, Expr) || return
mods = modules_to_be_loaded(ast)
filter!(mod -> isnothing(Base.identify_package(String(mod))), mods) # keep missing modules
if !isempty(mods)
isempty(install_packages_hooks) && Base.require_stdlib(Base.PkgId(Base.UUID("44cfe95a-1eb2-52ea-b672-e2afdf69b78f"), "Pkg"))
for f in install_packages_hooks
Base.invokelatest(f, mods) && return
end
end
end
function _modules_to_be_loaded!(ast::Expr, mods::Vector{Symbol})
ast.head === :quote && return mods # don't search if it's not going to be run during this eval
if ast.head === :using || ast.head === :import
for arg in ast.args
arg = arg::Expr
arg1 = first(arg.args)
if arg1 isa Symbol # i.e. `Foo`
if arg1 != :. # don't include local imports
push!(mods, arg1)
end
else # i.e. `Foo: bar`
push!(mods, first((arg1::Expr).args))
end
end
end
if ast.head !== :thunk
for arg in ast.args
if isexpr(arg, (:block, :if, :using, :import))
_modules_to_be_loaded!(arg, mods)
end
end
else
code = ast.args[1]
for arg in code.code
isa(arg, Expr) || continue
_modules_to_be_loaded!(arg, mods)
end
end
end
function modules_to_be_loaded(ast::Expr, mods::Vector{Symbol} = Symbol[])
_modules_to_be_loaded!(ast, mods)
filter!(mod::Symbol -> !in(mod, (:Base, :Main, :Core)), mods) # Exclude special non-package modules
return unique(mods)
end
"""
start_repl_backend(repl_channel::Channel, response_channel::Channel)
Starts loop for REPL backend
Returns a REPLBackend with backend_task assigned
Deprecated since sync / async behavior cannot be selected
"""
function start_repl_backend(repl_channel::Channel{Any}, response_channel::Channel{Any}
; get_module::Function = ()->Main)
# Maintain legacy behavior of asynchronous backend
backend = REPLBackend(repl_channel, response_channel, false)
# Assignment will be made twice, but will be immediately available
backend.backend_task = @async start_repl_backend(backend; get_module)
return backend
end
"""
start_repl_backend(backend::REPLBackend)
Call directly to run backend loop on current Task.
Use @async for run backend on new Task.
Does not return backend until loop is finished.
"""
function start_repl_backend(backend::REPLBackend, @nospecialize(consumer = x -> nothing); get_module::Function = ()->Main)
backend.backend_task = Base.current_task()
consumer(backend)
repl_backend_loop(backend, get_module)
return backend
end
function repl_backend_loop(backend::REPLBackend, get_module::Function)
# include looks at this to determine the relative include path
# nothing means cwd
while true
tls = task_local_storage()
tls[:SOURCE_PATH] = nothing
ast, show_value = take!(backend.repl_channel)
if show_value == -1
# exit flag
break
end
eval_user_input(ast, backend, get_module())
end
return nothing
end
struct REPLDisplay{Repl<:AbstractREPL} <: AbstractDisplay
repl::Repl
end
function display(d::REPLDisplay, mime::MIME"text/plain", x)
x = Ref{Any}(x)
with_repl_linfo(d.repl) do io
io = IOContext(io, :limit => true, :module => active_module(d)::Module)
if d.repl isa LineEditREPL
mistate = d.repl.mistate
mode = LineEdit.mode(mistate)
if mode isa LineEdit.Prompt
LineEdit.write_output_prefix(io, mode, get(io, :color, false)::Bool)
end
end
get(io, :color, false)::Bool && write(io, answer_color(d.repl))
if isdefined(d.repl, :options) && isdefined(d.repl.options, :iocontext)
# this can override the :limit property set initially
io = foldl(IOContext, d.repl.options.iocontext, init=io)
end
show(io, mime, x[])
println(io)
end
return nothing
end
display(d::REPLDisplay, x) = display(d, MIME("text/plain"), x)
function print_response(repl::AbstractREPL, response, show_value::Bool, have_color::Bool)
repl.waserror = response[2]
with_repl_linfo(repl) do io
io = IOContext(io, :module => active_module(repl)::Module)
print_response(io, response, show_value, have_color, specialdisplay(repl))
end
return nothing
end
function repl_display_error(errio::IO, @nospecialize errval)
# this will be set to true if types in the stacktrace are truncated
limitflag = Ref(false)
errio = IOContext(errio, :stacktrace_types_limited => limitflag)
Base.invokelatest(Base.display_error, errio, errval)
if limitflag[]
print(errio, "Some type information was truncated. Use `show(err)` to see complete types.")
println(errio)
end
return nothing
end
function print_response(errio::IO, response, show_value::Bool, have_color::Bool, specialdisplay::Union{AbstractDisplay,Nothing}=nothing)
Base.sigatomic_begin()
val, iserr = response
while true
try
Base.sigatomic_end()
if iserr
val = Base.scrub_repl_backtrace(val)
Base.istrivialerror(val) || setglobal!(Base.MainInclude, :err, val)
repl_display_error(errio, val)
else
if val !== nothing && show_value
try
if specialdisplay === nothing
Base.invokelatest(display, val)
else
Base.invokelatest(display, specialdisplay, val)
end
catch
println(errio, "Error showing value of type ", typeof(val), ":")
rethrow()
end
end
end
break
catch ex
if iserr
println(errio) # an error during printing is likely to leave us mid-line
println(errio, "SYSTEM (REPL): showing an error caused an error")
try
excs = Base.scrub_repl_backtrace(current_exceptions())
setglobal!(Base.MainInclude, :err, excs)
repl_display_error(errio, excs)
catch e
# at this point, only print the name of the type as a Symbol to
# minimize the possibility of further errors.
println(errio)
println(errio, "SYSTEM (REPL): caught exception of type ", typeof(e).name.name,
" while trying to handle a nested exception; giving up")
end
break
end
val = current_exceptions()
iserr = true
end
end
Base.sigatomic_end()
nothing
end
# A reference to a backend that is not mutable
struct REPLBackendRef
repl_channel::Channel{Any}
response_channel::Channel{Any}
end
REPLBackendRef(backend::REPLBackend) = REPLBackendRef(backend.repl_channel, backend.response_channel)
function destroy(ref::REPLBackendRef, state::Task)
if istaskfailed(state)
close(ref.repl_channel, TaskFailedException(state))
close(ref.response_channel, TaskFailedException(state))
end
close(ref.repl_channel)
close(ref.response_channel)
end
"""
run_repl(repl::AbstractREPL)
run_repl(repl, consumer = backend->nothing; backend_on_current_task = true)
Main function to start the REPL
consumer is an optional function that takes a REPLBackend as an argument
"""
function run_repl(repl::AbstractREPL, @nospecialize(consumer = x -> nothing); backend_on_current_task::Bool = true, backend = REPLBackend())
backend_ref = REPLBackendRef(backend)
cleanup = @task try
destroy(backend_ref, t)
catch e
Core.print(Core.stderr, "\nINTERNAL ERROR: ")
Core.println(Core.stderr, e)
Core.println(Core.stderr, catch_backtrace())
end
get_module = () -> active_module(repl)
if backend_on_current_task
t = @async run_frontend(repl, backend_ref)
errormonitor(t)
Base._wait2(t, cleanup)
start_repl_backend(backend, consumer; get_module)
else
t = @async start_repl_backend(backend, consumer; get_module)
errormonitor(t)
Base._wait2(t, cleanup)
run_frontend(repl, backend_ref)
end
return backend
end
## BasicREPL ##
mutable struct BasicREPL <: AbstractREPL
terminal::TextTerminal
waserror::Bool
frontend_task::Task
BasicREPL(t) = new(t, false)
end
outstream(r::BasicREPL) = r.terminal
hascolor(r::BasicREPL) = hascolor(r.terminal)
function run_frontend(repl::BasicREPL, backend::REPLBackendRef)
repl.frontend_task = current_task()
d = REPLDisplay(repl)
dopushdisplay = !in(d,Base.Multimedia.displays)
dopushdisplay && pushdisplay(d)
hit_eof = false
while true
Base.reseteof(repl.terminal)
write(repl.terminal, JULIA_PROMPT)
line = ""
ast = nothing
interrupted = false
while true
try
line *= readline(repl.terminal, keep=true)
catch e
if isa(e,InterruptException)
try # raise the debugger if present
ccall(:jl_raise_debugger, Int, ())
catch
end
line = ""
interrupted = true
break
elseif isa(e,EOFError)
hit_eof = true
break
else
rethrow()
end
end
ast = Base.parse_input_line(line)
(isa(ast,Expr) && ast.head === :incomplete) || break
end
if !isempty(line)
response = eval_with_backend(ast, backend)
print_response(repl, response, !ends_with_semicolon(line), false)
end
write(repl.terminal, '\n')
((!interrupted && isempty(line)) || hit_eof) && break
end
# terminate backend
put!(backend.repl_channel, (nothing, -1))
dopushdisplay && popdisplay(d)
nothing
end
## LineEditREPL ##
mutable struct LineEditREPL <: AbstractREPL
t::TextTerminal
hascolor::Bool
prompt_color::String
input_color::String
answer_color::String
shell_color::String
help_color::String
history_file::Bool
in_shell::Bool
in_help::Bool
envcolors::Bool
waserror::Bool
specialdisplay::Union{Nothing,AbstractDisplay}
options::Options
mistate::Union{MIState,Nothing}
last_shown_line_infos::Vector{Tuple{String,Int}}
interface::ModalInterface
backendref::REPLBackendRef
frontend_task::Task
function LineEditREPL(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell,in_help,envcolors)
opts = Options()
opts.hascolor = hascolor
if !hascolor
opts.beep_colors = [""]
end
new(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell,
in_help,envcolors,false,nothing, opts, nothing, Tuple{String,Int}[])
end
end
outstream(r::LineEditREPL) = (t = r.t; t isa TTYTerminal ? t.out_stream : t)
specialdisplay(r::LineEditREPL) = r.specialdisplay
specialdisplay(r::AbstractREPL) = nothing
terminal(r::LineEditREPL) = r.t
hascolor(r::LineEditREPL) = r.hascolor
LineEditREPL(t::TextTerminal, hascolor::Bool, envcolors::Bool=false) =
LineEditREPL(t, hascolor,
hascolor ? Base.text_colors[:green] : "",
hascolor ? Base.input_color() : "",
hascolor ? Base.answer_color() : "",
hascolor ? Base.text_colors[:red] : "",
hascolor ? Base.text_colors[:yellow] : "",
false, false, false, envcolors
)
mutable struct REPLCompletionProvider <: CompletionProvider
modifiers::LineEdit.Modifiers
end
REPLCompletionProvider() = REPLCompletionProvider(LineEdit.Modifiers())
mutable struct ShellCompletionProvider <: CompletionProvider end
struct LatexCompletions <: CompletionProvider end
function active_module() # this method is also called from Base
isdefined(Base, :active_repl) || return Main
return active_module(Base.active_repl::AbstractREPL)
end
active_module((; mistate)::LineEditREPL) = mistate === nothing ? Main : mistate.active_module
active_module(::AbstractREPL) = Main
active_module(d::REPLDisplay) = active_module(d.repl)
setmodifiers!(c::CompletionProvider, m::LineEdit.Modifiers) = nothing
setmodifiers!(c::REPLCompletionProvider, m::LineEdit.Modifiers) = c.modifiers = m
"""
activate(mod::Module=Main)
Set `mod` as the default contextual module in the REPL,
both for evaluating expressions and printing them.
"""
function activate(mod::Module=Main)
mistate = (Base.active_repl::LineEditREPL).mistate
mistate === nothing && return nothing
mistate.active_module = mod
Base.load_InteractiveUtils(mod)
return nothing
end
beforecursor(buf::IOBuffer) = String(buf.data[1:buf.ptr-1])
function complete_line(c::REPLCompletionProvider, s::PromptState, mod::Module)
partial = beforecursor(s.input_buffer)
full = LineEdit.input_string(s)
ret, range, should_complete = completions(full, lastindex(partial), mod, c.modifiers.shift)
c.modifiers = LineEdit.Modifiers()
return unique!(map(completion_text, ret)), partial[range], should_complete
end
function complete_line(c::ShellCompletionProvider, s::PromptState)
# First parse everything up to the current position
partial = beforecursor(s.input_buffer)
full = LineEdit.input_string(s)
ret, range, should_complete = shell_completions(full, lastindex(partial))
return unique!(map(completion_text, ret)), partial[range], should_complete
end
function complete_line(c::LatexCompletions, s)
partial = beforecursor(LineEdit.buffer(s))
full = LineEdit.input_string(s)::String
ret, range, should_complete = bslash_completions(full, lastindex(partial))[2]
return unique!(map(completion_text, ret)), partial[range], should_complete
end
with_repl_linfo(f, repl) = f(outstream(repl))
function with_repl_linfo(f, repl::LineEditREPL)
linfos = Tuple{String,Int}[]
io = IOContext(outstream(repl), :last_shown_line_infos => linfos)
f(io)
if !isempty(linfos)
repl.last_shown_line_infos = linfos
end
nothing
end
mutable struct REPLHistoryProvider <: HistoryProvider
history::Vector{String}
file_path::String
history_file::Union{Nothing,IO}
start_idx::Int
cur_idx::Int
last_idx::Int
last_buffer::IOBuffer
last_mode::Union{Nothing,Prompt}
mode_mapping::Dict{Symbol,Prompt}
modes::Vector{Symbol}
end
REPLHistoryProvider(mode_mapping::Dict{Symbol}) =
REPLHistoryProvider(String[], "", nothing, 0, 0, -1, IOBuffer(),
nothing, mode_mapping, UInt8[])
invalid_history_message(path::String) = """
Invalid history file ($path) format:
If you have a history file left over from an older version of Julia,
try renaming or deleting it.
Invalid character: """
munged_history_message(path::String) = """
Invalid history file ($path) format:
An editor may have converted tabs to spaces at line """
function hist_open_file(hp::REPLHistoryProvider)
f = open(hp.file_path, read=true, write=true, create=true)
hp.history_file = f
seekend(f)
end
function hist_from_file(hp::REPLHistoryProvider, path::String)
getline(lines, i) = i > length(lines) ? "" : lines[i]
file_lines = readlines(path)
countlines = 0
while true
# First parse the metadata that starts with '#' in particular the REPL mode
countlines += 1
line = getline(file_lines, countlines)
mode = :julia
isempty(line) && break
line[1] != '#' &&
error(invalid_history_message(path), repr(line[1]), " at line ", countlines)
while !isempty(line)
startswith(line, '#') || break
if startswith(line, "# mode: ")
mode = Symbol(SubString(line, 9))
end
countlines += 1
line = getline(file_lines, countlines)
end
isempty(line) && break
# Now parse the code for the current REPL mode
line[1] == ' ' &&
error(munged_history_message(path), countlines)
line[1] != '\t' &&
error(invalid_history_message(path), repr(line[1]), " at line ", countlines)
lines = String[]
while !isempty(line)
push!(lines, chomp(SubString(line, 2)))
next_line = getline(file_lines, countlines+1)
isempty(next_line) && break
first(next_line) == ' ' && error(munged_history_message(path), countlines)
# A line not starting with a tab means we are done with code for this entry
first(next_line) != '\t' && break
countlines += 1
line = getline(file_lines, countlines)
end
push!(hp.modes, mode)
push!(hp.history, join(lines, '\n'))
end
hp.start_idx = length(hp.history)
return hp
end
function add_history(hist::REPLHistoryProvider, s::PromptState)
str = rstrip(String(take!(copy(s.input_buffer))))
isempty(strip(str)) && return
mode = mode_idx(hist, LineEdit.mode(s))
!isempty(hist.history) &&
isequal(mode, hist.modes[end]) && str == hist.history[end] && return
push!(hist.modes, mode)
push!(hist.history, str)
hist.history_file === nothing && return
entry = """
# time: $(Libc.strftime("%Y-%m-%d %H:%M:%S %Z", time()))
# mode: $mode
$(replace(str, r"^"ms => "\t"))
"""
# TODO: write-lock history file
try
seekend(hist.history_file)
catch err
(err isa SystemError) || rethrow()
# File handle might get stale after a while, especially under network file systems
# If this doesn't fix it (e.g. when file is deleted), we'll end up rethrowing anyway
hist_open_file(hist)
end
print(hist.history_file, entry)
flush(hist.history_file)
nothing
end
function history_move(s::Union{LineEdit.MIState,LineEdit.PrefixSearchState}, hist::REPLHistoryProvider, idx::Int, save_idx::Int = hist.cur_idx)
max_idx = length(hist.history) + 1
@assert 1 <= hist.cur_idx <= max_idx
(1 <= idx <= max_idx) || return :none
idx != hist.cur_idx || return :none
# save the current line
if save_idx == max_idx
hist.last_mode = LineEdit.mode(s)
hist.last_buffer = copy(LineEdit.buffer(s))
else
hist.history[save_idx] = LineEdit.input_string(s)
hist.modes[save_idx] = mode_idx(hist, LineEdit.mode(s))
end
# load the saved line
if idx == max_idx
last_buffer = hist.last_buffer
LineEdit.transition(s, hist.last_mode) do
LineEdit.replace_line(s, last_buffer)
end
hist.last_mode = nothing
hist.last_buffer = IOBuffer()
else
if haskey(hist.mode_mapping, hist.modes[idx])
LineEdit.transition(s, hist.mode_mapping[hist.modes[idx]]) do
LineEdit.replace_line(s, hist.history[idx])
end
else
return :skip
end
end
hist.cur_idx = idx
return :ok
end
# REPL History can also transitions modes
function LineEdit.accept_result_newmode(hist::REPLHistoryProvider)
if 1 <= hist.cur_idx <= length(hist.modes)
return hist.mode_mapping[hist.modes[hist.cur_idx]]
end
return nothing
end
function history_prev(s::LineEdit.MIState, hist::REPLHistoryProvider,
num::Int=1, save_idx::Int = hist.cur_idx)
num <= 0 && return history_next(s, hist, -num, save_idx)
hist.last_idx = -1
m = history_move(s, hist, hist.cur_idx-num, save_idx)
if m === :ok
LineEdit.move_input_start(s)
LineEdit.reset_key_repeats(s) do
LineEdit.move_line_end(s)
end
return LineEdit.refresh_line(s)
elseif m === :skip
return history_prev(s, hist, num+1, save_idx)
else
return Terminals.beep(s)
end
end
function history_next(s::LineEdit.MIState, hist::REPLHistoryProvider,
num::Int=1, save_idx::Int = hist.cur_idx)
if num == 0
Terminals.beep(s)
return
end
num < 0 && return history_prev(s, hist, -num, save_idx)
cur_idx = hist.cur_idx
max_idx = length(hist.history) + 1
if cur_idx == max_idx && 0 < hist.last_idx
# issue #6312
cur_idx = hist.last_idx
hist.last_idx = -1
end
m = history_move(s, hist, cur_idx+num, save_idx)
if m === :ok
LineEdit.move_input_end(s)
return LineEdit.refresh_line(s)
elseif m === :skip
return history_next(s, hist, num+1, save_idx)
else
return Terminals.beep(s)
end
end
history_first(s::LineEdit.MIState, hist::REPLHistoryProvider) =
history_prev(s, hist, hist.cur_idx - 1 -
(hist.cur_idx > hist.start_idx+1 ? hist.start_idx : 0))
history_last(s::LineEdit.MIState, hist::REPLHistoryProvider) =
history_next(s, hist, length(hist.history) - hist.cur_idx + 1)
function history_move_prefix(s::LineEdit.PrefixSearchState,
hist::REPLHistoryProvider,
prefix::AbstractString,
backwards::Bool,
cur_idx::Int = hist.cur_idx)
cur_response = String(take!(copy(LineEdit.buffer(s))))
# when searching forward, start at last_idx
if !backwards && hist.last_idx > 0
cur_idx = hist.last_idx
end
hist.last_idx = -1
max_idx = length(hist.history)+1
idxs = backwards ? ((cur_idx-1):-1:1) : ((cur_idx+1):1:max_idx)
for idx in idxs
if (idx == max_idx) || (startswith(hist.history[idx], prefix) && (hist.history[idx] != cur_response || get(hist.mode_mapping, hist.modes[idx], nothing) !== LineEdit.mode(s)))
m = history_move(s, hist, idx)
if m === :ok
if idx == max_idx
# on resuming the in-progress edit, leave the cursor where the user last had it
elseif isempty(prefix)
# on empty prefix search, move cursor to the end
LineEdit.move_input_end(s)
else
# otherwise, keep cursor at the prefix position as a visual cue
seek(LineEdit.buffer(s), sizeof(prefix))
end
LineEdit.refresh_line(s)
return :ok
elseif m === :skip
return history_move_prefix(s,hist,prefix,backwards,idx)
end
end
end
Terminals.beep(s)
nothing
end
history_next_prefix(s::LineEdit.PrefixSearchState, hist::REPLHistoryProvider, prefix::AbstractString) =
history_move_prefix(s, hist, prefix, false)
history_prev_prefix(s::LineEdit.PrefixSearchState, hist::REPLHistoryProvider, prefix::AbstractString) =
history_move_prefix(s, hist, prefix, true)
function history_search(hist::REPLHistoryProvider, query_buffer::IOBuffer, response_buffer::IOBuffer,
backwards::Bool=false, skip_current::Bool=false)
qpos = position(query_buffer)
qpos > 0 || return true
searchdata = beforecursor(query_buffer)
response_str = String(take!(copy(response_buffer)))
# Alright, first try to see if the current match still works
a = position(response_buffer) + 1 # position is zero-indexed
# FIXME: I'm pretty sure this is broken since it uses an index
# into the search data to index into the response string
b = a + sizeof(searchdata)
b = b ≤ ncodeunits(response_str) ? prevind(response_str, b) : b-1
b = min(lastindex(response_str), b) # ensure that b is valid
searchstart = backwards ? b : a
if searchdata == response_str[a:b]
if skip_current
searchstart = backwards ? prevind(response_str, b) : nextind(response_str, a)
else
return true
end
end
# Start searching
# First the current response buffer
if 1 <= searchstart <= lastindex(response_str)
match = backwards ? findprev(searchdata, response_str, searchstart) :
findnext(searchdata, response_str, searchstart)
if match !== nothing
seek(response_buffer, first(match) - 1)
return true
end
end
# Now search all the other buffers
idxs = backwards ? ((hist.cur_idx-1):-1:1) : ((hist.cur_idx+1):1:length(hist.history))
for idx in idxs
h = hist.history[idx]
match = backwards ? findlast(searchdata, h) : findfirst(searchdata, h)
if match !== nothing && h != response_str && haskey(hist.mode_mapping, hist.modes[idx])
truncate(response_buffer, 0)
write(response_buffer, h)
seek(response_buffer, first(match) - 1)
hist.cur_idx = idx
return true
end
end
return false
end
function history_reset_state(hist::REPLHistoryProvider)
if hist.cur_idx != length(hist.history) + 1
hist.last_idx = hist.cur_idx
hist.cur_idx = length(hist.history) + 1
end
nothing
end
LineEdit.reset_state(hist::REPLHistoryProvider) = history_reset_state(hist)
function return_callback(s)
ast = Base.parse_input_line(String(take!(copy(LineEdit.buffer(s)))), depwarn=false)
return !(isa(ast, Expr) && ast.head === :incomplete)
end
find_hist_file() = get(ENV, "JULIA_HISTORY",
!isempty(DEPOT_PATH) ? joinpath(DEPOT_PATH[1], "logs", "repl_history.jl") :
error("DEPOT_PATH is empty and ENV[\"JULIA_HISTORY\"] not set."))
backend(r::AbstractREPL) = r.backendref
function eval_with_backend(ast, backend::REPLBackendRef)