• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

JuliaLang / julia / #37814

21 Jun 2024 02:07AM UTC coverage: 85.685% (-1.4%) from 87.073%
#37814

push

local

web-flow
REPL.prompt!: don't use Char peek (#54865)

73939 of 86292 relevant lines covered (85.68%)

15599027.75 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.64
/stdlib/REPL/src/REPL.jl
1
# This file is a part of Julia. License is MIT: https://julialang.org/license
2

3
"""
4
Run Evaluate Print Loop (REPL)
5

6
Example minimal code
7

8
```julia
9
import REPL
10
term = REPL.Terminals.TTYTerminal("dumb", stdin, stdout, stderr)
11
repl = REPL.LineEditREPL(term, true)
12
REPL.run_repl(repl)
13
```
14
"""
15
module REPL
16

17
Base.Experimental.@optlevel 1
18
Base.Experimental.@max_methods 1
19

20
function UndefVarError_hint(io::IO, ex::UndefVarError)
×
21
    var = ex.var
×
22
    if var === :or
×
23
        print(io, "\nSuggestion: Use `||` for short-circuiting boolean OR.")
×
24
    elseif var === :and
×
25
        print(io, "\nSuggestion: Use `&&` for short-circuiting boolean AND.")
×
26
    elseif var === :help
×
27
        println(io)
×
28
        # Show friendly help message when user types help or help() and help is undefined
29
        show(io, MIME("text/plain"), Base.Docs.parsedoc(Base.Docs.keywords[:help]))
×
30
    elseif var === :quit
×
31
        print(io, "\nSuggestion: To exit Julia, use Ctrl-D, or type exit() and press enter.")
×
32
    end
33
    if isdefined(ex, :scope)
×
34
        scope = ex.scope
×
35
        if scope isa Module
×
36
            bnd = ccall(:jl_get_module_binding, Any, (Any, Any, Cint), scope, var, true)::Core.Binding
×
37
            if isdefined(bnd, :owner)
×
38
                owner = bnd.owner
×
39
                if owner === bnd
×
40
                    print(io, "\nSuggestion: add an appropriate import or assignment. This global was declared but not assigned.")
×
41
                end
42
            else
43
                owner = ccall(:jl_binding_owner, Ptr{Cvoid}, (Any, Any), scope, var)
×
44
                if C_NULL == owner
×
45
                    # No global of this name exists in this module.
46
                    # This is the common case, so do not print that information.
47
                    # It could be the binding was exported by two modules, which we can detect
48
                    # by the `usingfailed` flag in the binding:
49
                    if isdefined(bnd, :flags) && Bool(bnd.flags >> 4 & 1) # magic location of the `usingfailed` flag
×
50
                        print(io, "\nHint: It looks like two or more modules export different ",
×
51
                              "bindings with this name, resulting in ambiguity. Try explicitly ",
52
                              "importing it from a particular module, or qualifying the name ",
53
                              "with the module it should come from.")
54
                    else
55
                        print(io, "\nSuggestion: check for spelling errors or missing imports.")
×
56
                    end
57
                    owner = bnd
×
58
                else
59
                    owner = unsafe_pointer_to_objref(owner)::Core.Binding
×
60
                end
61
            end
62
            if owner !== bnd
×
63
                # this could use jl_binding_dbgmodule for the exported location in the message too
64
                print(io, "\nSuggestion: this global was defined as `$(owner.globalref)` but not assigned a value.")
×
65
            end
66
        elseif scope === :static_parameter
×
67
            print(io, "\nSuggestion: run Test.detect_unbound_args to detect method arguments that do not fully constrain a type parameter.")
×
68
        elseif scope === :local
×
69
            print(io, "\nSuggestion: check for an assignment to a local variable that shadows a global of the same name.")
×
70
        end
71
    else
72
        scope = undef
×
73
    end
74
    if scope !== Base && !_UndefVarError_warnfor(io, Base, var)
×
75
        warned = false
×
76
        for m in Base.loaded_modules_order
×
77
            m === Core && continue
×
78
            m === Base && continue
×
79
            m === Main && continue
×
80
            m === scope && continue
×
81
            warned |= _UndefVarError_warnfor(io, m, var)
×
82
        end
×
83
        warned ||
×
84
            _UndefVarError_warnfor(io, Core, var) ||
85
            _UndefVarError_warnfor(io, Main, var)
86
    end
87
    return nothing
×
88
end
89

90
function _UndefVarError_warnfor(io::IO, m::Module, var::Symbol)
×
91
    Base.isbindingresolved(m, var) || return false
×
92
    (Base.isexported(m, var) || Base.ispublic(m, var)) || return false
×
93
    print(io, "\nHint: a global variable of this name also exists in $m.")
×
94
    return true
×
95
end
96

97
function __init__()
2✔
98
    Base.REPL_MODULE_REF[] = REPL
2✔
99
    Base.Experimental.register_error_hint(UndefVarError_hint, UndefVarError)
2✔
100
    return nothing
2✔
101
end
102

103
using Base.Meta, Sockets, StyledStrings
104
import InteractiveUtils
105

106
export
107
    AbstractREPL,
108
    BasicREPL,
109
    LineEditREPL,
110
    StreamREPL
111

112
import Base:
113
    AbstractDisplay,
114
    display,
115
    show,
116
    AnyDict,
117
    ==
118

119
_displaysize(io::IO) = displaysize(io)::Tuple{Int,Int}
×
120

121
include("Terminals.jl")
122
using .Terminals
123

124
abstract type AbstractREPL end
125

126
include("options.jl")
127

128
include("LineEdit.jl")
129
using .LineEdit
130
import ..LineEdit:
131
    CompletionProvider,
132
    HistoryProvider,
133
    add_history,
134
    complete_line,
135
    history_next,
136
    history_next_prefix,
137
    history_prev,
138
    history_prev_prefix,
139
    history_first,
140
    history_last,
141
    history_search,
142
    setmodifiers!,
143
    terminal,
144
    MIState,
145
    PromptState,
146
    mode_idx
147

148
include("REPLCompletions.jl")
149
using .REPLCompletions
150

151
include("TerminalMenus/TerminalMenus.jl")
152
include("docview.jl")
153

154
include("Pkg_beforeload.jl")
155

156
@nospecialize # use only declared type signatures
157

158
answer_color(::AbstractREPL) = ""
×
159

160
const JULIA_PROMPT = "julia> "
161
const PKG_PROMPT = "pkg> "
162
const SHELL_PROMPT = "shell> "
163
const HELP_PROMPT = "help?> "
164

165
mutable struct REPLBackend
166
    "channel for AST"
167
    repl_channel::Channel{Any}
168
    "channel for results: (value, iserror)"
169
    response_channel::Channel{Any}
170
    "flag indicating the state of this backend"
171
    in_eval::Bool
172
    "transformation functions to apply before evaluating expressions"
173
    ast_transforms::Vector{Any}
174
    "current backend task"
175
    backend_task::Task
176

177
    REPLBackend(repl_channel, response_channel, in_eval, ast_transforms=copy(repl_ast_transforms)) =
×
178
        new(repl_channel, response_channel, in_eval, ast_transforms)
179
end
180
REPLBackend() = REPLBackend(Channel(1), Channel(1), false)
×
181

182
"""
183
    softscope(ex)
184

185
Return a modified version of the parsed expression `ex` that uses
186
the REPL's "soft" scoping rules for global syntax blocks.
187
"""
188
function softscope(@nospecialize ex)
×
189
    if ex isa Expr
×
190
        h = ex.head
×
191
        if h === :toplevel
×
192
            ex′ = Expr(h)
×
193
            map!(softscope, resize!(ex′.args, length(ex.args)), ex.args)
×
194
            return ex′
×
195
        elseif h in (:meta, :import, :using, :export, :module, :error, :incomplete, :thunk)
×
196
            return ex
×
197
        elseif h === :global && all(x->isa(x, Symbol), ex.args)
×
198
            return ex
×
199
        else
200
            return Expr(:block, Expr(:softscope, true), ex)
×
201
        end
202
    end
203
    return ex
×
204
end
205

206
# Temporary alias until Documenter updates
207
const softscope! = softscope
208

209
const repl_ast_transforms = Any[softscope] # defaults for new REPL backends
210

211
# Allows an external package to add hooks into the code loading.
212
# The hook should take a Vector{Symbol} of package names and
213
# return true if all packages could be installed, false if not
214
# to e.g. install packages on demand
215
const install_packages_hooks = Any[]
216

217
# N.B.: Any functions starting with __repl_entry cut off backtraces when printing in the REPL.
218
# We need to do this for both the actual eval and macroexpand, since the latter can cause custom macro
219
# code to run (and error).
220
__repl_entry_lower_with_loc(mod::Module, @nospecialize(ast), toplevel_file::Ref{Ptr{UInt8}}, toplevel_line::Ref{Cint}) =
×
221
    ccall(:jl_expand_with_loc, Any, (Any, Any, Ptr{UInt8}, Cint), ast, mod, toplevel_file[], toplevel_line[])
222
__repl_entry_eval_expanded_with_loc(mod::Module, @nospecialize(ast), toplevel_file::Ref{Ptr{UInt8}}, toplevel_line::Ref{Cint}) =
×
223
    ccall(:jl_toplevel_eval_flex, Any, (Any, Any, Cint, Cint, Ptr{Ptr{UInt8}}, Ptr{Cint}), mod, ast, 1, 1, toplevel_file, toplevel_line)
224

225
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))
×
226
    if !isexpr(ast, :toplevel)
×
227
        ast = __repl_entry_lower_with_loc(mod, ast, toplevel_file, toplevel_line)
×
228
        check_for_missing_packages_and_run_hooks(ast)
×
229
        return __repl_entry_eval_expanded_with_loc(mod, ast, toplevel_file, toplevel_line)
×
230
    end
231
    local value=nothing
×
232
    for i = 1:length(ast.args)
×
233
        value = toplevel_eval_with_hooks(mod, ast.args[i], toplevel_file, toplevel_line)
×
234
    end
×
235
    return value
×
236
end
237

238
function eval_user_input(@nospecialize(ast), backend::REPLBackend, mod::Module)
×
239
    lasterr = nothing
×
240
    Base.sigatomic_begin()
×
241
    while true
×
242
        try
×
243
            Base.sigatomic_end()
×
244
            if lasterr !== nothing
×
245
                put!(backend.response_channel, Pair{Any, Bool}(lasterr, true))
×
246
            else
247
                backend.in_eval = true
×
248
                for xf in backend.ast_transforms
×
249
                    ast = Base.invokelatest(xf, ast)
×
250
                end
×
251
                value = toplevel_eval_with_hooks(mod, ast)
×
252
                backend.in_eval = false
×
253
                setglobal!(Base.MainInclude, :ans, value)
×
254
                put!(backend.response_channel, Pair{Any, Bool}(value, false))
×
255
            end
256
            break
×
257
        catch err
258
            if lasterr !== nothing
×
259
                println("SYSTEM ERROR: Failed to report error to REPL frontend")
×
260
                println(err)
×
261
            end
262
            lasterr = current_exceptions()
×
263
        end
264
    end
×
265
    Base.sigatomic_end()
×
266
    nothing
×
267
end
268

269
function check_for_missing_packages_and_run_hooks(ast)
×
270
    isa(ast, Expr) || return
×
271
    mods = modules_to_be_loaded(ast)
×
272
    filter!(mod -> isnothing(Base.identify_package(String(mod))), mods) # keep missing modules
×
273
    if !isempty(mods)
×
274
        isempty(install_packages_hooks) && load_pkg()
×
275
        for f in install_packages_hooks
×
276
            Base.invokelatest(f, mods) && return
×
277
        end
×
278
    end
279
end
280

281
function _modules_to_be_loaded!(ast::Expr, mods::Vector{Symbol})
×
282
    ast.head === :quote && return mods # don't search if it's not going to be run during this eval
×
283
    if ast.head === :using || ast.head === :import
×
284
        for arg in ast.args
×
285
            arg = arg::Expr
×
286
            arg1 = first(arg.args)
×
287
            if arg1 isa Symbol # i.e. `Foo`
×
288
                if arg1 != :. # don't include local imports
×
289
                    push!(mods, arg1)
×
290
                end
291
            else # i.e. `Foo: bar`
292
                push!(mods, first((arg1::Expr).args))
×
293
            end
294
        end
×
295
    end
296
    if ast.head !== :thunk
×
297
        for arg in ast.args
×
298
            if isexpr(arg, (:block, :if, :using, :import))
×
299
                _modules_to_be_loaded!(arg, mods)
×
300
            end
301
        end
×
302
    else
303
        code = ast.args[1]
×
304
        for arg in code.code
×
305
            isa(arg, Expr) || continue
×
306
            _modules_to_be_loaded!(arg, mods)
×
307
        end
×
308
    end
309
end
310

311
function modules_to_be_loaded(ast::Expr, mods::Vector{Symbol} = Symbol[])
×
312
    _modules_to_be_loaded!(ast, mods)
×
313
    filter!(mod::Symbol -> !in(mod, (:Base, :Main, :Core)), mods) # Exclude special non-package modules
×
314
    return unique(mods)
×
315
end
316

317
"""
318
    start_repl_backend(repl_channel::Channel, response_channel::Channel)
319

320
    Starts loop for REPL backend
321
    Returns a REPLBackend with backend_task assigned
322

323
    Deprecated since sync / async behavior cannot be selected
324
"""
325
function start_repl_backend(repl_channel::Channel{Any}, response_channel::Channel{Any}
×
326
                            ; get_module::Function = ()->Main)
327
    # Maintain legacy behavior of asynchronous backend
328
    backend = REPLBackend(repl_channel, response_channel, false)
×
329
    # Assignment will be made twice, but will be immediately available
330
    backend.backend_task = @async start_repl_backend(backend; get_module)
×
331
    return backend
×
332
end
333

334
"""
335
    start_repl_backend(backend::REPLBackend)
336

337
    Call directly to run backend loop on current Task.
338
    Use @async for run backend on new Task.
339

340
    Does not return backend until loop is finished.
341
"""
342
function start_repl_backend(backend::REPLBackend,  @nospecialize(consumer = x -> nothing); get_module::Function = ()->Main)
×
343
    backend.backend_task = Base.current_task()
×
344
    consumer(backend)
×
345
    repl_backend_loop(backend, get_module)
×
346
    return backend
×
347
end
348

349
function repl_backend_loop(backend::REPLBackend, get_module::Function)
×
350
    # include looks at this to determine the relative include path
351
    # nothing means cwd
352
    while true
×
353
        tls = task_local_storage()
×
354
        tls[:SOURCE_PATH] = nothing
×
355
        ast, show_value = take!(backend.repl_channel)
×
356
        if show_value == -1
×
357
            # exit flag
358
            break
×
359
        end
360
        eval_user_input(ast, backend, get_module())
×
361
    end
×
362
    return nothing
×
363
end
364

365
struct REPLDisplay{Repl<:AbstractREPL} <: AbstractDisplay
366
    repl::Repl
367
end
368

369
function display(d::REPLDisplay, mime::MIME"text/plain", x)
×
370
    x = Ref{Any}(x)
×
371
    with_repl_linfo(d.repl) do io
×
372
        io = IOContext(io, :limit => true, :module => active_module(d)::Module)
×
373
        if d.repl isa LineEditREPL
×
374
            mistate = d.repl.mistate
×
375
            mode = LineEdit.mode(mistate)
×
376
            if mode isa LineEdit.Prompt
×
377
                LineEdit.write_output_prefix(io, mode, get(io, :color, false)::Bool)
×
378
            end
379
        end
380
        get(io, :color, false)::Bool && write(io, answer_color(d.repl))
×
381
        if isdefined(d.repl, :options) && isdefined(d.repl.options, :iocontext)
×
382
            # this can override the :limit property set initially
383
            io = foldl(IOContext, d.repl.options.iocontext, init=io)
×
384
        end
385
        show(io, mime, x[])
×
386
        println(io)
×
387
    end
388
    return nothing
×
389
end
390
display(d::REPLDisplay, x) = display(d, MIME("text/plain"), x)
×
391

392
function print_response(repl::AbstractREPL, response, show_value::Bool, have_color::Bool)
×
393
    repl.waserror = response[2]
×
394
    with_repl_linfo(repl) do io
×
395
        io = IOContext(io, :module => active_module(repl)::Module)
×
396
        print_response(io, response, show_value, have_color, specialdisplay(repl))
×
397
    end
398
    return nothing
×
399
end
400

401
function repl_display_error(errio::IO, @nospecialize errval)
×
402
    # this will be set to true if types in the stacktrace are truncated
403
    limitflag = Ref(false)
×
404
    errio = IOContext(errio, :stacktrace_types_limited => limitflag)
×
405
    Base.invokelatest(Base.display_error, errio, errval)
×
406
    if limitflag[]
×
407
        print(errio, "Some type information was truncated. Use `show(err)` to see complete types.")
×
408
        println(errio)
×
409
    end
410
    return nothing
×
411
end
412

413
function print_response(errio::IO, response, show_value::Bool, have_color::Bool, specialdisplay::Union{AbstractDisplay,Nothing}=nothing)
×
414
    Base.sigatomic_begin()
×
415
    val, iserr = response
×
416
    while true
×
417
        try
×
418
            Base.sigatomic_end()
×
419
            if iserr
×
420
                val = Base.scrub_repl_backtrace(val)
×
421
                Base.istrivialerror(val) || setglobal!(Base.MainInclude, :err, val)
×
422
                repl_display_error(errio, val)
×
423
            else
424
                if val !== nothing && show_value
×
425
                    try
×
426
                        if specialdisplay === nothing
×
427
                            Base.invokelatest(display, val)
×
428
                        else
429
                            Base.invokelatest(display, specialdisplay, val)
×
430
                        end
431
                    catch
432
                        println(errio, "Error showing value of type ", typeof(val), ":")
×
433
                        rethrow()
×
434
                    end
435
                end
436
            end
437
            break
×
438
        catch ex
439
            if iserr
×
440
                println(errio) # an error during printing is likely to leave us mid-line
×
441
                println(errio, "SYSTEM (REPL): showing an error caused an error")
×
442
                try
×
443
                    excs = Base.scrub_repl_backtrace(current_exceptions())
×
444
                    setglobal!(Base.MainInclude, :err, excs)
×
445
                    repl_display_error(errio, excs)
×
446
                catch e
447
                    # at this point, only print the name of the type as a Symbol to
448
                    # minimize the possibility of further errors.
449
                    println(errio)
×
450
                    println(errio, "SYSTEM (REPL): caught exception of type ", typeof(e).name.name,
×
451
                            " while trying to handle a nested exception; giving up")
452
                end
453
                break
×
454
            end
455
            val = current_exceptions()
×
456
            iserr = true
×
457
        end
458
    end
×
459
    Base.sigatomic_end()
×
460
    nothing
×
461
end
462

463
# A reference to a backend that is not mutable
464
struct REPLBackendRef
465
    repl_channel::Channel{Any}
466
    response_channel::Channel{Any}
467
end
468
REPLBackendRef(backend::REPLBackend) = REPLBackendRef(backend.repl_channel, backend.response_channel)
×
469

470
function destroy(ref::REPLBackendRef, state::Task)
×
471
    if istaskfailed(state)
×
472
        close(ref.repl_channel, TaskFailedException(state))
×
473
        close(ref.response_channel, TaskFailedException(state))
×
474
    end
475
    close(ref.repl_channel)
×
476
    close(ref.response_channel)
×
477
end
478

479
"""
480
    run_repl(repl::AbstractREPL)
481
    run_repl(repl, consumer = backend->nothing; backend_on_current_task = true)
482

483
    Main function to start the REPL
484

485
    consumer is an optional function that takes a REPLBackend as an argument
486
"""
487
function run_repl(repl::AbstractREPL, @nospecialize(consumer = x -> nothing); backend_on_current_task::Bool = true, backend = REPLBackend())
×
488
    backend_ref = REPLBackendRef(backend)
×
489
    cleanup = @task try
×
490
            destroy(backend_ref, t)
×
491
        catch e
492
            Core.print(Core.stderr, "\nINTERNAL ERROR: ")
×
493
            Core.println(Core.stderr, e)
×
494
            Core.println(Core.stderr, catch_backtrace())
×
495
        end
496
    get_module = () -> active_module(repl)
×
497
    if backend_on_current_task
×
498
        t = @async run_frontend(repl, backend_ref)
×
499
        errormonitor(t)
×
500
        Base._wait2(t, cleanup)
×
501
        start_repl_backend(backend, consumer; get_module)
×
502
    else
503
        t = @async start_repl_backend(backend, consumer; get_module)
×
504
        errormonitor(t)
×
505
        Base._wait2(t, cleanup)
×
506
        run_frontend(repl, backend_ref)
×
507
    end
508
    return backend
×
509
end
510

511
## BasicREPL ##
512

513
mutable struct BasicREPL <: AbstractREPL
514
    terminal::TextTerminal
515
    waserror::Bool
516
    frontend_task::Task
517
    BasicREPL(t) = new(t, false)
×
518
end
519

520
outstream(r::BasicREPL) = r.terminal
×
521
hascolor(r::BasicREPL) = hascolor(r.terminal)
×
522

523
function run_frontend(repl::BasicREPL, backend::REPLBackendRef)
×
524
    repl.frontend_task = current_task()
×
525
    d = REPLDisplay(repl)
×
526
    dopushdisplay = !in(d,Base.Multimedia.displays)
×
527
    dopushdisplay && pushdisplay(d)
×
528
    hit_eof = false
×
529
    while true
×
530
        Base.reseteof(repl.terminal)
×
531
        write(repl.terminal, JULIA_PROMPT)
×
532
        line = ""
×
533
        ast = nothing
×
534
        interrupted = false
×
535
        while true
×
536
            try
×
537
                line *= readline(repl.terminal, keep=true)
×
538
            catch e
539
                if isa(e,InterruptException)
×
540
                    try # raise the debugger if present
×
541
                        ccall(:jl_raise_debugger, Int, ())
×
542
                    catch
×
543
                    end
544
                    line = ""
×
545
                    interrupted = true
×
546
                    break
×
547
                elseif isa(e,EOFError)
×
548
                    hit_eof = true
×
549
                    break
×
550
                else
551
                    rethrow()
×
552
                end
553
            end
554
            ast = Base.parse_input_line(line)
×
555
            (isa(ast,Expr) && ast.head === :incomplete) || break
×
556
        end
×
557
        if !isempty(line)
×
558
            response = eval_with_backend(ast, backend)
×
559
            print_response(repl, response, !ends_with_semicolon(line), false)
×
560
        end
561
        write(repl.terminal, '\n')
×
562
        ((!interrupted && isempty(line)) || hit_eof) && break
×
563
    end
×
564
    # terminate backend
565
    put!(backend.repl_channel, (nothing, -1))
×
566
    dopushdisplay && popdisplay(d)
×
567
    nothing
×
568
end
569

570
## LineEditREPL ##
571

572
mutable struct LineEditREPL <: AbstractREPL
573
    t::TextTerminal
574
    hascolor::Bool
575
    prompt_color::String
576
    input_color::String
577
    answer_color::String
578
    shell_color::String
579
    help_color::String
580
    pkg_color::String
581
    history_file::Bool
582
    in_shell::Bool
583
    in_help::Bool
584
    envcolors::Bool
585
    waserror::Bool
586
    specialdisplay::Union{Nothing,AbstractDisplay}
587
    options::Options
588
    mistate::Union{MIState,Nothing}
589
    last_shown_line_infos::Vector{Tuple{String,Int}}
590
    interface::ModalInterface
591
    backendref::REPLBackendRef
592
    frontend_task::Task
593
    function LineEditREPL(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,pkg_color,history_file,in_shell,in_help,envcolors)
×
594
        opts = Options()
×
595
        opts.hascolor = hascolor
×
596
        if !hascolor
×
597
            opts.beep_colors = [""]
×
598
        end
599
        new(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,pkg_color,history_file,in_shell,
×
600
            in_help,envcolors,false,nothing, opts, nothing, Tuple{String,Int}[])
601
    end
602
end
603
outstream(r::LineEditREPL) = (t = r.t; t isa TTYTerminal ? t.out_stream : t)
×
604
specialdisplay(r::LineEditREPL) = r.specialdisplay
×
605
specialdisplay(r::AbstractREPL) = nothing
×
606
terminal(r::LineEditREPL) = r.t
×
607
hascolor(r::LineEditREPL) = r.hascolor
×
608

609
LineEditREPL(t::TextTerminal, hascolor::Bool, envcolors::Bool=false) =
×
610
    LineEditREPL(t, hascolor,
611
        hascolor ? Base.text_colors[:green] : "",
612
        hascolor ? Base.input_color() : "",
613
        hascolor ? Base.answer_color() : "",
614
        hascolor ? Base.text_colors[:red] : "",
615
        hascolor ? Base.text_colors[:yellow] : "",
616
        hascolor ? Base.text_colors[:blue] : "",
617
        false, false, false, envcolors
618
    )
619

620
mutable struct REPLCompletionProvider <: CompletionProvider
621
    modifiers::LineEdit.Modifiers
622
end
623
REPLCompletionProvider() = REPLCompletionProvider(LineEdit.Modifiers())
×
624

625
mutable struct ShellCompletionProvider <: CompletionProvider end
626
struct LatexCompletions <: CompletionProvider end
627

628
function active_module() # this method is also called from Base
9,844✔
629
    isdefined(Base, :active_repl) || return Main
19,688✔
630
    return active_module(Base.active_repl::AbstractREPL)
×
631
end
632
active_module((; mistate)::LineEditREPL) = mistate === nothing ? Main : mistate.active_module
×
633
active_module(::AbstractREPL) = Main
×
634
active_module(d::REPLDisplay) = active_module(d.repl)
×
635

636
setmodifiers!(c::CompletionProvider, m::LineEdit.Modifiers) = nothing
×
637

638
setmodifiers!(c::REPLCompletionProvider, m::LineEdit.Modifiers) = c.modifiers = m
×
639

640
"""
641
    activate(mod::Module=Main)
642

643
Set `mod` as the default contextual module in the REPL,
644
both for evaluating expressions and printing them.
645
"""
646
function activate(mod::Module=Main)
×
647
    mistate = (Base.active_repl::LineEditREPL).mistate
×
648
    mistate === nothing && return nothing
×
649
    mistate.active_module = mod
×
650
    Base.load_InteractiveUtils(mod)
×
651
    return nothing
×
652
end
653

654
beforecursor(buf::IOBuffer) = String(buf.data[1:buf.ptr-1])
×
655

656
function complete_line(c::REPLCompletionProvider, s::PromptState, mod::Module; hint::Bool=false)
×
657
    partial = beforecursor(s.input_buffer)
×
658
    full = LineEdit.input_string(s)
×
659
    ret, range, should_complete = completions(full, lastindex(partial), mod, c.modifiers.shift, hint)
×
660
    c.modifiers = LineEdit.Modifiers()
×
661
    return unique!(map(completion_text, ret)), partial[range], should_complete
×
662
end
663

664
function complete_line(c::ShellCompletionProvider, s::PromptState; hint::Bool=false)
×
665
    # First parse everything up to the current position
666
    partial = beforecursor(s.input_buffer)
×
667
    full = LineEdit.input_string(s)
×
668
    ret, range, should_complete = shell_completions(full, lastindex(partial), hint)
×
669
    return unique!(map(completion_text, ret)), partial[range], should_complete
×
670
end
671

672
function complete_line(c::LatexCompletions, s; hint::Bool=false)
×
673
    partial = beforecursor(LineEdit.buffer(s))
×
674
    full = LineEdit.input_string(s)::String
×
675
    ret, range, should_complete = bslash_completions(full, lastindex(partial), hint)[2]
×
676
    return unique!(map(completion_text, ret)), partial[range], should_complete
×
677
end
678

679
with_repl_linfo(f, repl) = f(outstream(repl))
×
680
function with_repl_linfo(f, repl::LineEditREPL)
×
681
    linfos = Tuple{String,Int}[]
×
682
    io = IOContext(outstream(repl), :last_shown_line_infos => linfos)
×
683
    f(io)
×
684
    if !isempty(linfos)
×
685
        repl.last_shown_line_infos = linfos
×
686
    end
687
    nothing
×
688
end
689

690
mutable struct REPLHistoryProvider <: HistoryProvider
691
    history::Vector{String}
692
    file_path::String
693
    history_file::Union{Nothing,IO}
694
    start_idx::Int
695
    cur_idx::Int
696
    last_idx::Int
697
    last_buffer::IOBuffer
698
    last_mode::Union{Nothing,Prompt}
699
    mode_mapping::Dict{Symbol,Prompt}
700
    modes::Vector{Symbol}
701
end
702
REPLHistoryProvider(mode_mapping::Dict{Symbol}) =
×
703
    REPLHistoryProvider(String[], "", nothing, 0, 0, -1, IOBuffer(),
704
                        nothing, mode_mapping, UInt8[])
705

706
invalid_history_message(path::String) = """
×
707
Invalid history file ($path) format:
708
If you have a history file left over from an older version of Julia,
709
try renaming or deleting it.
710
Invalid character: """
711

712
munged_history_message(path::String) = """
×
713
Invalid history file ($path) format:
714
An editor may have converted tabs to spaces at line """
715

716
function hist_open_file(hp::REPLHistoryProvider)
×
717
    f = open(hp.file_path, read=true, write=true, create=true)
×
718
    hp.history_file = f
×
719
    seekend(f)
×
720
end
721

722
function hist_from_file(hp::REPLHistoryProvider, path::String)
×
723
    getline(lines, i) = i > length(lines) ? "" : lines[i]
×
724
    file_lines = readlines(path)
×
725
    countlines = 0
×
726
    while true
×
727
        # First parse the metadata that starts with '#' in particular the REPL mode
728
        countlines += 1
×
729
        line = getline(file_lines, countlines)
×
730
        mode = :julia
×
731
        isempty(line) && break
×
732
        line[1] != '#' &&
×
733
            error(invalid_history_message(path), repr(line[1]), " at line ", countlines)
734
        while !isempty(line)
×
735
            startswith(line, '#') || break
×
736
            if startswith(line, "# mode: ")
×
737
                mode = Symbol(SubString(line, 9))
×
738
            end
739
            countlines += 1
×
740
            line = getline(file_lines, countlines)
×
741
        end
×
742
        isempty(line) && break
×
743

744
        # Now parse the code for the current REPL mode
745
        line[1] == ' '  &&
×
746
            error(munged_history_message(path), countlines)
747
        line[1] != '\t' &&
×
748
            error(invalid_history_message(path), repr(line[1]), " at line ", countlines)
749
        lines = String[]
×
750
        while !isempty(line)
×
751
            push!(lines, chomp(SubString(line, 2)))
×
752
            next_line = getline(file_lines, countlines+1)
×
753
            isempty(next_line) && break
×
754
            first(next_line) == ' '  && error(munged_history_message(path), countlines)
×
755
            # A line not starting with a tab means we are done with code for this entry
756
            first(next_line) != '\t' && break
×
757
            countlines += 1
×
758
            line = getline(file_lines, countlines)
×
759
        end
×
760
        push!(hp.modes, mode)
×
761
        push!(hp.history, join(lines, '\n'))
×
762
    end
×
763
    hp.start_idx = length(hp.history)
×
764
    return hp
×
765
end
766

767
function add_history(hist::REPLHistoryProvider, s::PromptState)
×
768
    str = rstrip(String(take!(copy(s.input_buffer))))
×
769
    isempty(strip(str)) && return
×
770
    mode = mode_idx(hist, LineEdit.mode(s))
×
771
    !isempty(hist.history) &&
×
772
        isequal(mode, hist.modes[end]) && str == hist.history[end] && return
773
    push!(hist.modes, mode)
×
774
    push!(hist.history, str)
×
775
    hist.history_file === nothing && return
×
776
    entry = """
×
777
    # time: $(Libc.strftime("%Y-%m-%d %H:%M:%S %Z", time()))
778
    # mode: $mode
779
    $(replace(str, r"^"ms => "\t"))
×
780
    """
781
    # TODO: write-lock history file
782
    try
×
783
        seekend(hist.history_file)
×
784
    catch err
785
        (err isa SystemError) || rethrow()
×
786
        # File handle might get stale after a while, especially under network file systems
787
        # If this doesn't fix it (e.g. when file is deleted), we'll end up rethrowing anyway
788
        hist_open_file(hist)
×
789
    end
790
    print(hist.history_file, entry)
×
791
    flush(hist.history_file)
×
792
    nothing
×
793
end
794

795
function history_move(s::Union{LineEdit.MIState,LineEdit.PrefixSearchState}, hist::REPLHistoryProvider, idx::Int, save_idx::Int = hist.cur_idx)
×
796
    max_idx = length(hist.history) + 1
×
797
    @assert 1 <= hist.cur_idx <= max_idx
×
798
    (1 <= idx <= max_idx) || return :none
×
799
    idx != hist.cur_idx || return :none
×
800

801
    # save the current line
802
    if save_idx == max_idx
×
803
        hist.last_mode = LineEdit.mode(s)
×
804
        hist.last_buffer = copy(LineEdit.buffer(s))
×
805
    else
806
        hist.history[save_idx] = LineEdit.input_string(s)
×
807
        hist.modes[save_idx] = mode_idx(hist, LineEdit.mode(s))
×
808
    end
809

810
    # load the saved line
811
    if idx == max_idx
×
812
        last_buffer = hist.last_buffer
×
813
        LineEdit.transition(s, hist.last_mode) do
×
814
            LineEdit.replace_line(s, last_buffer)
×
815
        end
816
        hist.last_mode = nothing
×
817
        hist.last_buffer = IOBuffer()
×
818
    else
819
        if haskey(hist.mode_mapping, hist.modes[idx])
×
820
            LineEdit.transition(s, hist.mode_mapping[hist.modes[idx]]) do
×
821
                LineEdit.replace_line(s, hist.history[idx])
×
822
            end
823
        else
824
            return :skip
×
825
        end
826
    end
827
    hist.cur_idx = idx
×
828

829
    return :ok
×
830
end
831

832
# REPL History can also transitions modes
833
function LineEdit.accept_result_newmode(hist::REPLHistoryProvider)
×
834
    if 1 <= hist.cur_idx <= length(hist.modes)
×
835
        return hist.mode_mapping[hist.modes[hist.cur_idx]]
×
836
    end
837
    return nothing
×
838
end
839

840
function history_prev(s::LineEdit.MIState, hist::REPLHistoryProvider,
×
841
                      num::Int=1, save_idx::Int = hist.cur_idx)
842
    num <= 0 && return history_next(s, hist, -num, save_idx)
×
843
    hist.last_idx = -1
×
844
    m = history_move(s, hist, hist.cur_idx-num, save_idx)
×
845
    if m === :ok
×
846
        LineEdit.move_input_start(s)
×
847
        LineEdit.reset_key_repeats(s) do
×
848
            LineEdit.move_line_end(s)
×
849
        end
850
        return LineEdit.refresh_line(s)
×
851
    elseif m === :skip
×
852
        return history_prev(s, hist, num+1, save_idx)
×
853
    else
854
        return Terminals.beep(s)
×
855
    end
856
end
857

858
function history_next(s::LineEdit.MIState, hist::REPLHistoryProvider,
×
859
                      num::Int=1, save_idx::Int = hist.cur_idx)
860
    if num == 0
×
861
        Terminals.beep(s)
×
862
        return
×
863
    end
864
    num < 0 && return history_prev(s, hist, -num, save_idx)
×
865
    cur_idx = hist.cur_idx
×
866
    max_idx = length(hist.history) + 1
×
867
    if cur_idx == max_idx && 0 < hist.last_idx
×
868
        # issue #6312
869
        cur_idx = hist.last_idx
×
870
        hist.last_idx = -1
×
871
    end
872
    m = history_move(s, hist, cur_idx+num, save_idx)
×
873
    if m === :ok
×
874
        LineEdit.move_input_end(s)
×
875
        return LineEdit.refresh_line(s)
×
876
    elseif m === :skip
×
877
        return history_next(s, hist, num+1, save_idx)
×
878
    else
879
        return Terminals.beep(s)
×
880
    end
881
end
882

883
history_first(s::LineEdit.MIState, hist::REPLHistoryProvider) =
×
884
    history_prev(s, hist, hist.cur_idx - 1 -
885
                 (hist.cur_idx > hist.start_idx+1 ? hist.start_idx : 0))
886

887
history_last(s::LineEdit.MIState, hist::REPLHistoryProvider) =
×
888
    history_next(s, hist, length(hist.history) - hist.cur_idx + 1)
889

890
function history_move_prefix(s::LineEdit.PrefixSearchState,
×
891
                             hist::REPLHistoryProvider,
892
                             prefix::AbstractString,
893
                             backwards::Bool,
894
                             cur_idx::Int = hist.cur_idx)
895
    cur_response = String(take!(copy(LineEdit.buffer(s))))
×
896
    # when searching forward, start at last_idx
897
    if !backwards && hist.last_idx > 0
×
898
        cur_idx = hist.last_idx
×
899
    end
900
    hist.last_idx = -1
×
901
    max_idx = length(hist.history)+1
×
902
    idxs = backwards ? ((cur_idx-1):-1:1) : ((cur_idx+1):1:max_idx)
×
903
    for idx in idxs
×
904
        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)))
×
905
            m = history_move(s, hist, idx)
×
906
            if m === :ok
×
907
                if idx == max_idx
×
908
                    # on resuming the in-progress edit, leave the cursor where the user last had it
909
                elseif isempty(prefix)
×
910
                    # on empty prefix search, move cursor to the end
911
                    LineEdit.move_input_end(s)
×
912
                else
913
                    # otherwise, keep cursor at the prefix position as a visual cue
914
                    seek(LineEdit.buffer(s), sizeof(prefix))
×
915
                end
916
                LineEdit.refresh_line(s)
×
917
                return :ok
×
918
            elseif m === :skip
×
919
                return history_move_prefix(s,hist,prefix,backwards,idx)
×
920
            end
921
        end
922
    end
×
923
    Terminals.beep(s)
×
924
    nothing
×
925
end
926
history_next_prefix(s::LineEdit.PrefixSearchState, hist::REPLHistoryProvider, prefix::AbstractString) =
×
927
    history_move_prefix(s, hist, prefix, false)
928
history_prev_prefix(s::LineEdit.PrefixSearchState, hist::REPLHistoryProvider, prefix::AbstractString) =
×
929
    history_move_prefix(s, hist, prefix, true)
930

931
function history_search(hist::REPLHistoryProvider, query_buffer::IOBuffer, response_buffer::IOBuffer,
×
932
                        backwards::Bool=false, skip_current::Bool=false)
933

934
    qpos = position(query_buffer)
×
935
    qpos > 0 || return true
×
936
    searchdata = beforecursor(query_buffer)
×
937
    response_str = String(take!(copy(response_buffer)))
×
938

939
    # Alright, first try to see if the current match still works
940
    a = position(response_buffer) + 1 # position is zero-indexed
×
941
    # FIXME: I'm pretty sure this is broken since it uses an index
942
    # into the search data to index into the response string
943
    b = a + sizeof(searchdata)
×
944
    b = b ≤ ncodeunits(response_str) ? prevind(response_str, b) : b-1
×
945
    b = min(lastindex(response_str), b) # ensure that b is valid
×
946

947
    searchstart = backwards ? b : a
×
948
    if searchdata == response_str[a:b]
×
949
        if skip_current
×
950
            searchstart = backwards ? prevind(response_str, b) : nextind(response_str, a)
×
951
        else
952
            return true
×
953
        end
954
    end
955

956
    # Start searching
957
    # First the current response buffer
958
    if 1 <= searchstart <= lastindex(response_str)
×
959
        match = backwards ? findprev(searchdata, response_str, searchstart) :
×
960
                            findnext(searchdata, response_str, searchstart)
961
        if match !== nothing
×
962
            seek(response_buffer, first(match) - 1)
×
963
            return true
×
964
        end
965
    end
966

967
    # Now search all the other buffers
968
    idxs = backwards ? ((hist.cur_idx-1):-1:1) : ((hist.cur_idx+1):1:length(hist.history))
×
969
    for idx in idxs
×
970
        h = hist.history[idx]
×
971
        match = backwards ? findlast(searchdata, h) : findfirst(searchdata, h)
×
972
        if match !== nothing && h != response_str && haskey(hist.mode_mapping, hist.modes[idx])
×
973
            truncate(response_buffer, 0)
×
974
            write(response_buffer, h)
×
975
            seek(response_buffer, first(match) - 1)
×
976
            hist.cur_idx = idx
×
977
            return true
×
978
        end
979
    end
×
980

981
    return false
×
982
end
983

984
function history_reset_state(hist::REPLHistoryProvider)
×
985
    if hist.cur_idx != length(hist.history) + 1
×
986
        hist.last_idx = hist.cur_idx
×
987
        hist.cur_idx = length(hist.history) + 1
×
988
    end
989
    nothing
×
990
end
991
LineEdit.reset_state(hist::REPLHistoryProvider) = history_reset_state(hist)
×
992

993
function return_callback(s)
×
994
    ast = Base.parse_input_line(String(take!(copy(LineEdit.buffer(s)))), depwarn=false)
×
995
    return !(isa(ast, Expr) && ast.head === :incomplete)
×
996
end
997

998
find_hist_file() = get(ENV, "JULIA_HISTORY",
×
999
                       !isempty(DEPOT_PATH) ? joinpath(DEPOT_PATH[1], "logs", "repl_history.jl") :
1000
                       error("DEPOT_PATH is empty and ENV[\"JULIA_HISTORY\"] not set."))
1001

1002
backend(r::AbstractREPL) = r.backendref
×
1003

1004
function eval_with_backend(ast, backend::REPLBackendRef)
×
1005
    put!(backend.repl_channel, (ast, 1))
×
1006
    return take!(backend.response_channel) # (val, iserr)
×
1007
end
1008

1009
function respond(f, repl, main; pass_empty::Bool = false, suppress_on_semicolon::Bool = true)
×
1010
    return function do_respond(s::MIState, buf, ok::Bool)
×
1011
        if !ok
×
1012
            return transition(s, :abort)
×
1013
        end
1014
        line = String(take!(buf)::Vector{UInt8})
×
1015
        if !isempty(line) || pass_empty
×
1016
            reset(repl)
×
1017
            local response
×
1018
            try
×
1019
                ast = Base.invokelatest(f, line)
×
1020
                response = eval_with_backend(ast, backend(repl))
×
1021
            catch
1022
                response = Pair{Any, Bool}(current_exceptions(), true)
×
1023
            end
1024
            hide_output = suppress_on_semicolon && ends_with_semicolon(line)
×
1025
            print_response(repl, response, !hide_output, hascolor(repl))
×
1026
        end
1027
        prepare_next(repl)
×
1028
        reset_state(s)
×
1029
        return s.current_mode.sticky ? true : transition(s, main)
×
1030
    end
1031
end
1032

1033
function reset(repl::LineEditREPL)
×
1034
    raw!(repl.t, false)
×
1035
    hascolor(repl) && print(repl.t, Base.text_colors[:normal])
×
1036
    nothing
×
1037
end
1038

1039
function prepare_next(repl::LineEditREPL)
×
1040
    println(terminal(repl))
×
1041
end
1042

1043
function mode_keymap(julia_prompt::Prompt)
×
1044
    AnyDict(
×
1045
    '\b' => function (s::MIState,o...)
×
1046
        if isempty(s) || position(LineEdit.buffer(s)) == 0
×
1047
            buf = copy(LineEdit.buffer(s))
×
1048
            transition(s, julia_prompt) do
×
1049
                LineEdit.state(s, julia_prompt).input_buffer = buf
×
1050
            end
1051
        else
1052
            LineEdit.edit_backspace(s)
×
1053
        end
1054
    end,
1055
    "^C" => function (s::MIState,o...)
×
1056
        LineEdit.move_input_end(s)
×
1057
        LineEdit.refresh_line(s)
×
1058
        print(LineEdit.terminal(s), "^C\n\n")
×
1059
        transition(s, julia_prompt)
×
1060
        transition(s, :reset)
×
1061
        LineEdit.refresh_line(s)
×
1062
    end)
1063
end
1064

1065
repl_filename(repl, hp::REPLHistoryProvider) = "REPL[$(max(length(hp.history)-hp.start_idx, 1))]"
×
1066
repl_filename(repl, hp) = "REPL"
×
1067

1068
const JL_PROMPT_PASTE = Ref(true)
1069
enable_promptpaste(v::Bool) = JL_PROMPT_PASTE[] = v
×
1070

1071
function contextual_prompt(repl::LineEditREPL, prompt::Union{String,Function})
×
1072
    function ()
×
1073
        mod = active_module(repl)
×
1074
        prefix = mod == Main ? "" : string('(', mod, ") ")
×
1075
        pr = prompt isa String ? prompt : prompt()
×
1076
        prefix * pr
×
1077
    end
1078
end
1079

1080
setup_interface(
×
1081
    repl::LineEditREPL;
1082
    # those keyword arguments may be deprecated eventually in favor of the Options mechanism
1083
    hascolor::Bool = repl.options.hascolor,
1084
    extra_repl_keymap::Any = repl.options.extra_keymap
1085
) = setup_interface(repl, hascolor, extra_repl_keymap)
1086

1087

1088
# This non keyword method can be precompiled which is important
1089
function setup_interface(
×
1090
    repl::LineEditREPL,
1091
    hascolor::Bool,
1092
    extra_repl_keymap::Any, # Union{Dict,Vector{<:Dict}},
1093
)
1094
    # The precompile statement emitter has problem outputting valid syntax for the
1095
    # type of `Union{Dict,Vector{<:Dict}}` (see #28808).
1096
    # This function is however important to precompile for REPL startup time, therefore,
1097
    # make the type Any and just assert that we have the correct type below.
1098
    @assert extra_repl_keymap isa Union{Dict,Vector{<:Dict}}
×
1099

1100
    ###
1101
    #
1102
    # This function returns the main interface that describes the REPL
1103
    # functionality, it is called internally by functions that setup a
1104
    # Terminal-based REPL frontend.
1105
    #
1106
    # See run_frontend(repl::LineEditREPL, backend::REPLBackendRef)
1107
    # for usage
1108
    #
1109
    ###
1110

1111
    ###
1112
    # We setup the interface in two stages.
1113
    # First, we set up all components (prompt,rsearch,shell,help)
1114
    # Second, we create keymaps with appropriate transitions between them
1115
    #   and assign them to the components
1116
    #
1117
    ###
1118

1119
    ############################### Stage I ################################
1120

1121
    # This will provide completions for REPL and help mode
1122
    replc = REPLCompletionProvider()
×
1123

1124
    # Set up the main Julia prompt
1125
    julia_prompt = Prompt(contextual_prompt(repl, JULIA_PROMPT);
×
1126
        # Copy colors from the prompt object
1127
        prompt_prefix = hascolor ? repl.prompt_color : "",
1128
        prompt_suffix = hascolor ?
1129
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
1130
        repl = repl,
1131
        complete = replc,
1132
        on_enter = return_callback)
1133

1134
    # Setup help mode
1135
    help_mode = Prompt(contextual_prompt(repl, "help?> "),
×
1136
        prompt_prefix = hascolor ? repl.help_color : "",
1137
        prompt_suffix = hascolor ?
1138
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
1139
        repl = repl,
1140
        complete = replc,
1141
        # When we're done transform the entered line into a call to helpmode function
1142
        on_done = respond(line::String->helpmode(outstream(repl), line, repl.mistate.active_module),
×
1143
                          repl, julia_prompt, pass_empty=true, suppress_on_semicolon=false))
1144

1145

1146
    # Set up shell mode
1147
    shell_mode = Prompt(SHELL_PROMPT;
×
1148
        prompt_prefix = hascolor ? repl.shell_color : "",
1149
        prompt_suffix = hascolor ?
1150
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
1151
        repl = repl,
1152
        complete = ShellCompletionProvider(),
1153
        # Transform "foo bar baz" into `foo bar baz` (shell quoting)
1154
        # and pass into Base.repl_cmd for processing (handles `ls` and `cd`
1155
        # special)
1156
        on_done = respond(repl, julia_prompt) do line
1157
            Expr(:call, :(Base.repl_cmd),
×
1158
                :(Base.cmd_gen($(Base.shell_parse(line::String)[1]))),
1159
                outstream(repl))
1160
        end,
1161
        sticky = true)
1162

1163
    # Set up dummy Pkg mode that will be replaced once Pkg is loaded
1164
    # use 6 dots to occupy the same space as the most likely "@v1.xx" env name
1165
    dummy_pkg_mode = Prompt(Pkg_promptf,
×
1166
        prompt_prefix = hascolor ? repl.pkg_color : "",
1167
        prompt_suffix = hascolor ?
1168
        (repl.envcolors ? Base.input_color : repl.input_color) : "",
1169
        repl = repl,
1170
        complete = LineEdit.EmptyCompletionProvider(),
1171
        on_done = respond(line->nothing, repl, julia_prompt),
×
1172
        on_enter = function (s::MIState)
×
1173
                # This is hit when the user tries to execute a command before the real Pkg mode has been
1174
                # switched to. Ok to do this even if Pkg is loading on the other task because of the loading lock.
1175
                REPLExt = load_pkg()
×
1176
                if REPLExt isa Module && isdefined(REPLExt, :PkgCompletionProvider)
×
1177
                    for mode in repl.interface.modes
×
1178
                        if mode isa LineEdit.Prompt && mode.complete isa REPLExt.PkgCompletionProvider
×
1179
                            # pkg mode
1180
                            buf = copy(LineEdit.buffer(s))
×
1181
                            transition(s, mode) do
×
1182
                                LineEdit.state(s, mode).input_buffer = buf
×
1183
                            end
1184
                        end
1185
                    end
×
1186
                end
1187
                return true
×
1188
            end,
1189
        sticky = true)
1190

1191

1192
    ################################# Stage II #############################
1193

1194
    # Setup history
1195
    # We will have a unified history for all REPL modes
1196
    hp = REPLHistoryProvider(Dict{Symbol,Prompt}(:julia => julia_prompt,
×
1197
                                                 :shell => shell_mode,
1198
                                                 :help  => help_mode,
1199
                                                 :pkg  => dummy_pkg_mode))
1200
    if repl.history_file
×
1201
        try
×
1202
            hist_path = find_hist_file()
×
1203
            mkpath(dirname(hist_path))
×
1204
            hp.file_path = hist_path
×
1205
            hist_open_file(hp)
×
1206
            finalizer(replc) do replc
×
1207
                close(hp.history_file)
×
1208
            end
1209
            hist_from_file(hp, hist_path)
×
1210
        catch
1211
            # use REPL.hascolor to avoid using the local variable with the same name
1212
            print_response(repl, Pair{Any, Bool}(current_exceptions(), true), true, REPL.hascolor(repl))
×
1213
            println(outstream(repl))
×
1214
            @info "Disabling history file for this session"
×
1215
            repl.history_file = false
×
1216
        end
1217
    end
1218
    history_reset_state(hp)
×
1219
    julia_prompt.hist = hp
×
1220
    shell_mode.hist = hp
×
1221
    help_mode.hist = hp
×
1222
    dummy_pkg_mode.hist = hp
×
1223

1224
    julia_prompt.on_done = respond(x->Base.parse_input_line(x,filename=repl_filename(repl,hp)), repl, julia_prompt)
×
1225

1226

1227
    search_prompt, skeymap = LineEdit.setup_search_keymap(hp)
×
1228
    search_prompt.complete = LatexCompletions()
×
1229

1230
    shell_prompt_len = length(SHELL_PROMPT)
×
1231
    help_prompt_len = length(HELP_PROMPT)
×
1232
    jl_prompt_regex = r"^In \[[0-9]+\]: |^(?:\(.+\) )?julia> "
×
1233
    pkg_prompt_regex = r"^(?:\(.+\) )?pkg> "
×
1234

1235
    # Canonicalize user keymap input
1236
    if isa(extra_repl_keymap, Dict)
×
1237
        extra_repl_keymap = AnyDict[extra_repl_keymap]
×
1238
    end
1239

1240
    repl_keymap = AnyDict(
×
1241
        ';' => function (s::MIState,o...)
×
1242
            if isempty(s) || position(LineEdit.buffer(s)) == 0
×
1243
                buf = copy(LineEdit.buffer(s))
×
1244
                transition(s, shell_mode) do
×
1245
                    LineEdit.state(s, shell_mode).input_buffer = buf
×
1246
                end
1247
            else
1248
                edit_insert(s, ';')
×
1249
            end
1250
        end,
1251
        '?' => function (s::MIState,o...)
×
1252
            if isempty(s) || position(LineEdit.buffer(s)) == 0
×
1253
                buf = copy(LineEdit.buffer(s))
×
1254
                transition(s, help_mode) do
×
1255
                    LineEdit.state(s, help_mode).input_buffer = buf
×
1256
                end
1257
            else
1258
                edit_insert(s, '?')
×
1259
            end
1260
        end,
1261
        ']' => function (s::MIState,o...)
×
1262
            if isempty(s) || position(LineEdit.buffer(s)) == 0
×
1263
                buf = copy(LineEdit.buffer(s))
×
1264
                transition(s, dummy_pkg_mode) do
×
1265
                    LineEdit.state(s, dummy_pkg_mode).input_buffer = buf
×
1266
                end
1267
                # load Pkg on another thread if available so that typing in the dummy Pkg prompt
1268
                # isn't blocked, but instruct the main REPL task to do the transition via s.async_channel
1269
                t_replswitch = Threads.@spawn begin
×
1270
                    REPLExt = load_pkg()
×
1271
                    if REPLExt isa Module && isdefined(REPLExt, :PkgCompletionProvider)
×
1272
                        put!(s.async_channel,
×
1273
                            function (s::MIState)
×
1274
                                LineEdit.mode(s) === dummy_pkg_mode || return :ok
×
1275
                                for mode in repl.interface.modes
×
1276
                                    if mode isa LineEdit.Prompt && mode.complete isa REPLExt.PkgCompletionProvider
×
1277
                                        buf = copy(LineEdit.buffer(s))
×
1278
                                        transition(s, mode) do
×
1279
                                            LineEdit.state(s, mode).input_buffer = buf
×
1280
                                        end
1281
                                        if !isempty(s) && @invokelatest(LineEdit.check_for_hint(s))
×
1282
                                            @invokelatest(LineEdit.refresh_line(s))
×
1283
                                        end
1284
                                        break
×
1285
                                    end
1286
                                end
×
1287
                                return :ok
×
1288
                            end
1289
                        )
1290
                    end
1291
                end
1292
                Base.errormonitor(t_replswitch)
×
1293
            else
1294
                edit_insert(s, ']')
×
1295
            end
1296
        end,
1297

1298
        # Bracketed Paste Mode
1299
        "\e[200~" => (s::MIState,o...)->begin
×
1300
            input = LineEdit.bracketed_paste(s) # read directly from s until reaching the end-bracketed-paste marker
×
1301
            sbuffer = LineEdit.buffer(s)
×
1302
            curspos = position(sbuffer)
×
1303
            seek(sbuffer, 0)
×
1304
            shouldeval = (bytesavailable(sbuffer) == curspos && !occursin(UInt8('\n'), sbuffer))
×
1305
            seek(sbuffer, curspos)
×
1306
            if curspos == 0
×
1307
                # if pasting at the beginning, strip leading whitespace
1308
                input = lstrip(input)
×
1309
            end
1310
            if !shouldeval
×
1311
                # when pasting in the middle of input, just paste in place
1312
                # don't try to execute all the WIP, since that's rather confusing
1313
                # and is often ill-defined how it should behave
1314
                edit_insert(s, input)
×
1315
                return
×
1316
            end
1317
            LineEdit.push_undo(s)
×
1318
            edit_insert(sbuffer, input)
×
1319
            input = String(take!(sbuffer))
×
1320
            oldpos = firstindex(input)
×
1321
            firstline = true
×
1322
            isprompt_paste = false
×
1323
            curr_prompt_len = 0
×
1324
            pasting_help = false
×
1325

1326
            while oldpos <= lastindex(input) # loop until all lines have been executed
×
1327
                if JL_PROMPT_PASTE[]
×
1328
                    # Check if the next statement starts with a prompt i.e. "julia> ", in that case
1329
                    # skip it. But first skip whitespace unless pasting in a docstring which may have
1330
                    # indented prompt examples that we don't want to execute
1331
                    while input[oldpos] in (pasting_help ? ('\n') : ('\n', ' ', '\t'))
×
1332
                        oldpos = nextind(input, oldpos)
×
1333
                        oldpos >= sizeof(input) && return
×
1334
                    end
×
1335
                    substr = SubString(input, oldpos)
×
1336
                    # Check if input line starts with "julia> ", remove it if we are in prompt paste mode
1337
                    if (firstline || isprompt_paste) && startswith(substr, jl_prompt_regex)
×
1338
                        detected_jl_prompt = match(jl_prompt_regex, substr).match
×
1339
                        isprompt_paste = true
×
1340
                        curr_prompt_len = sizeof(detected_jl_prompt)
×
1341
                        oldpos += curr_prompt_len
×
1342
                        transition(s, julia_prompt)
×
1343
                        pasting_help = false
×
1344
                    # Check if input line starts with "pkg> " or "(...) pkg> ", remove it if we are in prompt paste mode and switch mode
1345
                    elseif (firstline || isprompt_paste) && startswith(substr, pkg_prompt_regex)
×
1346
                        detected_pkg_prompt = match(pkg_prompt_regex, substr).match
×
1347
                        isprompt_paste = true
×
1348
                        curr_prompt_len = sizeof(detected_pkg_prompt)
×
1349
                        oldpos += curr_prompt_len
×
1350
                        Base.active_repl.interface.modes[1].keymap_dict[']'](s, o...)
×
1351
                        pasting_help = false
×
1352
                    # Check if input line starts with "shell> ", remove it if we are in prompt paste mode and switch mode
1353
                    elseif (firstline || isprompt_paste) && startswith(substr, SHELL_PROMPT)
×
1354
                        isprompt_paste = true
×
1355
                        oldpos += shell_prompt_len
×
1356
                        curr_prompt_len = shell_prompt_len
×
1357
                        transition(s, shell_mode)
×
1358
                        pasting_help = false
×
1359
                    # Check if input line starts with "help?> ", remove it if we are in prompt paste mode and switch mode
1360
                    elseif (firstline || isprompt_paste) && startswith(substr, HELP_PROMPT)
×
1361
                        isprompt_paste = true
×
1362
                        oldpos += help_prompt_len
×
1363
                        curr_prompt_len = help_prompt_len
×
1364
                        transition(s, help_mode)
×
1365
                        pasting_help = true
×
1366
                    # If we are prompt pasting and current statement does not begin with a mode prefix, skip to next line
1367
                    elseif isprompt_paste
×
1368
                        while input[oldpos] != '\n'
×
1369
                            oldpos = nextind(input, oldpos)
×
1370
                            oldpos >= sizeof(input) && return
×
1371
                        end
×
1372
                        continue
×
1373
                    end
1374
                end
1375
                dump_tail = false
×
1376
                nl_pos = findfirst('\n', input[oldpos:end])
×
1377
                if s.current_mode == julia_prompt
×
1378
                    ast, pos = Meta.parse(input, oldpos, raise=false, depwarn=false)
×
1379
                    if (isa(ast, Expr) && (ast.head === :error || ast.head === :incomplete)) ||
×
1380
                            (pos > ncodeunits(input) && !endswith(input, '\n'))
1381
                        # remaining text is incomplete (an error, or parser ran to the end but didn't stop with a newline):
1382
                        # Insert all the remaining text as one line (might be empty)
1383
                        dump_tail = true
×
1384
                    end
1385
                elseif isnothing(nl_pos) # no newline at end, so just dump the tail into the prompt and don't execute
×
1386
                    dump_tail = true
×
1387
                elseif s.current_mode == shell_mode # handle multiline shell commands
×
1388
                    lines = split(input[oldpos:end], '\n')
×
1389
                    pos = oldpos + sizeof(lines[1]) + 1
×
1390
                    if length(lines) > 1
×
1391
                        for line in lines[2:end]
×
1392
                            # to be recognized as a multiline shell command, the lines must be indented to the
1393
                            # same prompt position
1394
                            if !startswith(line, ' '^curr_prompt_len)
×
1395
                                break
×
1396
                            end
1397
                            pos += sizeof(line) + 1
×
1398
                        end
×
1399
                    end
1400
                else
1401
                    pos = oldpos + nl_pos
×
1402
                end
1403
                if dump_tail
×
1404
                    tail = input[oldpos:end]
×
1405
                    if !firstline
×
1406
                        # strip leading whitespace, but only if it was the result of executing something
1407
                        # (avoids modifying the user's current leading wip line)
1408
                        tail = lstrip(tail)
×
1409
                    end
1410
                    if isprompt_paste # remove indentation spaces corresponding to the prompt
×
1411
                        tail = replace(tail, r"^"m * ' '^curr_prompt_len => "")
×
1412
                    end
1413
                    LineEdit.replace_line(s, tail, true)
×
1414
                    LineEdit.refresh_line(s)
×
1415
                    break
×
1416
                end
1417
                # get the line and strip leading and trailing whitespace
1418
                line = strip(input[oldpos:prevind(input, pos)])
×
1419
                if !isempty(line)
×
1420
                    if isprompt_paste # remove indentation spaces corresponding to the prompt
×
1421
                        line = replace(line, r"^"m * ' '^curr_prompt_len => "")
×
1422
                    end
1423
                    # put the line on the screen and history
1424
                    LineEdit.replace_line(s, line)
×
1425
                    LineEdit.commit_line(s)
×
1426
                    # execute the statement
1427
                    terminal = LineEdit.terminal(s) # This is slightly ugly but ok for now
×
1428
                    raw!(terminal, false) && disable_bracketed_paste(terminal)
×
1429
                    @invokelatest LineEdit.mode(s).on_done(s, LineEdit.buffer(s), true)
×
1430
                    raw!(terminal, true) && enable_bracketed_paste(terminal)
×
1431
                    LineEdit.push_undo(s) # when the last line is incomplete
×
1432
                end
1433
                oldpos = pos
×
1434
                firstline = false
×
1435
            end
×
1436
        end,
1437

1438
        # Open the editor at the location of a stackframe or method
1439
        # This is accessing a contextual variable that gets set in
1440
        # the show_backtrace and show_method_table functions.
1441
        "^Q" => (s::MIState, o...) -> begin
×
1442
            linfos = repl.last_shown_line_infos
×
1443
            str = String(take!(LineEdit.buffer(s)))
×
1444
            n = tryparse(Int, str)
×
1445
            n === nothing && @goto writeback
×
1446
            if n <= 0 || n > length(linfos) || startswith(linfos[n][1], "REPL[")
×
1447
                @goto writeback
×
1448
            end
1449
            try
×
1450
                InteractiveUtils.edit(Base.fixup_stdlib_path(linfos[n][1]), linfos[n][2])
×
1451
            catch ex
1452
                ex isa ProcessFailedException || ex isa Base.IOError || ex isa SystemError || rethrow()
×
1453
                @info "edit failed" _exception=ex
×
1454
            end
1455
            LineEdit.refresh_line(s)
×
1456
            return
×
1457
            @label writeback
×
1458
            write(LineEdit.buffer(s), str)
×
1459
            return
×
1460
        end,
1461
    )
1462

1463
    prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, julia_prompt)
×
1464

1465
    a = Dict{Any,Any}[skeymap, repl_keymap, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
×
1466
    prepend!(a, extra_repl_keymap)
×
1467

1468
    julia_prompt.keymap_dict = LineEdit.keymap(a)
×
1469

1470
    mk = mode_keymap(julia_prompt)
×
1471

1472
    b = Dict{Any,Any}[skeymap, mk, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
×
1473
    prepend!(b, extra_repl_keymap)
×
1474

1475
    shell_mode.keymap_dict = help_mode.keymap_dict = dummy_pkg_mode.keymap_dict = LineEdit.keymap(b)
×
1476

1477
    allprompts = LineEdit.TextInterface[julia_prompt, shell_mode, help_mode, dummy_pkg_mode, search_prompt, prefix_prompt]
×
1478
    return ModalInterface(allprompts)
×
1479
end
1480

1481
function run_frontend(repl::LineEditREPL, backend::REPLBackendRef)
×
1482
    repl.frontend_task = current_task()
×
1483
    d = REPLDisplay(repl)
×
1484
    dopushdisplay = repl.specialdisplay === nothing && !in(d,Base.Multimedia.displays)
×
1485
    dopushdisplay && pushdisplay(d)
×
1486
    if !isdefined(repl,:interface)
×
1487
        interface = repl.interface = setup_interface(repl)
×
1488
    else
1489
        interface = repl.interface
×
1490
    end
1491
    repl.backendref = backend
×
1492
    repl.mistate = LineEdit.init_state(terminal(repl), interface)
×
1493
    run_interface(terminal(repl), interface, repl.mistate)
×
1494
    # Terminate Backend
1495
    put!(backend.repl_channel, (nothing, -1))
×
1496
    dopushdisplay && popdisplay(d)
×
1497
    nothing
×
1498
end
1499

1500
## StreamREPL ##
1501

1502
mutable struct StreamREPL <: AbstractREPL
1503
    stream::IO
1504
    prompt_color::String
1505
    input_color::String
1506
    answer_color::String
1507
    waserror::Bool
1508
    frontend_task::Task
1509
    StreamREPL(stream,pc,ic,ac) = new(stream,pc,ic,ac,false)
×
1510
end
1511
StreamREPL(stream::IO) = StreamREPL(stream, Base.text_colors[:green], Base.input_color(), Base.answer_color())
×
1512
run_repl(stream::IO) = run_repl(StreamREPL(stream))
×
1513

1514
outstream(s::StreamREPL) = s.stream
×
1515
hascolor(s::StreamREPL) = get(s.stream, :color, false)::Bool
×
1516

1517
answer_color(r::LineEditREPL) = r.envcolors ? Base.answer_color() : r.answer_color
×
1518
answer_color(r::StreamREPL) = r.answer_color
×
1519
input_color(r::LineEditREPL) = r.envcolors ? Base.input_color() : r.input_color
×
1520
input_color(r::StreamREPL) = r.input_color
×
1521

1522
let matchend = Dict("\"" => r"\"", "\"\"\"" => r"\"\"\"", "'" => r"'",
1523
    "`" => r"`", "```" => r"```", "#" => r"$"m, "#=" => r"=#|#=")
1524
    global _rm_strings_and_comments
1525
    function _rm_strings_and_comments(code::Union{String,SubString{String}})
×
1526
        buf = IOBuffer(sizehint = sizeof(code))
×
1527
        pos = 1
×
1528
        while true
×
1529
            i = findnext(r"\"(?!\"\")|\"\"\"|'|`(?!``)|```|#(?!=)|#=", code, pos)
×
1530
            isnothing(i) && break
×
1531
            match = SubString(code, i)
×
1532
            j = findnext(matchend[match]::Regex, code, nextind(code, last(i)))
×
1533
            if match == "#=" # possibly nested
×
1534
                nested = 1
×
1535
                while j !== nothing
×
1536
                    nested += SubString(code, j) == "#=" ? +1 : -1
×
1537
                    iszero(nested) && break
×
1538
                    j = findnext(r"=#|#=", code, nextind(code, last(j)))
×
1539
                end
×
1540
            elseif match[1] != '#' # quote match: check non-escaped
×
1541
                while j !== nothing
×
1542
                    notbackslash = findprev(!=('\\'), code, prevind(code, first(j)))::Int
×
1543
                    isodd(first(j) - notbackslash) && break # not escaped
×
1544
                    j = findnext(matchend[match]::Regex, code, nextind(code, first(j)))
×
1545
                end
×
1546
            end
1547
            isnothing(j) && break
×
1548
            if match[1] == '#'
×
1549
                print(buf, SubString(code, pos, prevind(code, first(i))))
×
1550
            else
1551
                print(buf, SubString(code, pos, last(i)), ' ', SubString(code, j))
×
1552
            end
1553
            pos = nextind(code, last(j))
×
1554
        end
×
1555
        print(buf, SubString(code, pos, lastindex(code)))
×
1556
        return String(take!(buf))
×
1557
    end
1558
end
1559

1560
# heuristic function to decide if the presence of a semicolon
1561
# at the end of the expression was intended for suppressing output
1562
ends_with_semicolon(code::AbstractString) = ends_with_semicolon(String(code))
×
1563
ends_with_semicolon(code::Union{String,SubString{String}}) =
×
1564
    contains(_rm_strings_and_comments(code), r";\s*$")
×
1565

1566
function banner(io::IO = stdout; short = false)
×
1567
    if Base.GIT_VERSION_INFO.tagged_commit
×
1568
        commit_string = Base.TAGGED_RELEASE_BANNER
×
1569
    elseif isempty(Base.GIT_VERSION_INFO.commit)
×
1570
        commit_string = ""
×
1571
    else
1572
        days = Int(floor((ccall(:jl_clock_now, Float64, ()) - Base.GIT_VERSION_INFO.fork_master_timestamp) / (60 * 60 * 24)))
×
1573
        days = max(0, days)
×
1574
        unit = days == 1 ? "day" : "days"
×
1575
        distance = Base.GIT_VERSION_INFO.fork_master_distance
×
1576
        commit = Base.GIT_VERSION_INFO.commit_short
×
1577

1578
        if distance == 0
×
1579
            commit_string = "Commit $(commit) ($(days) $(unit) old master)"
×
1580
        else
1581
            branch = Base.GIT_VERSION_INFO.branch
×
1582
            commit_string = "$(branch)/$(commit) (fork: $(distance) commits, $(days) $(unit))"
×
1583
        end
1584
    end
1585

1586
    commit_date = isempty(Base.GIT_VERSION_INFO.date_string) ? "" : " ($(split(Base.GIT_VERSION_INFO.date_string)[1]))"
×
1587

1588
    if get(io, :color, false)::Bool
×
1589
        c = Base.text_colors
×
1590
        tx = c[:normal] # text
×
1591
        jl = c[:normal] # julia
×
1592
        d1 = c[:bold] * c[:blue]    # first dot
×
1593
        d2 = c[:bold] * c[:red]     # second dot
×
1594
        d3 = c[:bold] * c[:green]   # third dot
×
1595
        d4 = c[:bold] * c[:magenta] # fourth dot
×
1596

1597
        if short
×
1598
            print(io,"""
×
1599
              $(d3)o$(tx)  | Version $(VERSION)$(commit_date)
1600
             $(d2)o$(tx) $(d4)o$(tx) | $(commit_string)
1601
            """)
1602
        else
1603
            print(io,"""               $(d3)_$(tx)
×
1604
               $(d1)_$(tx)       $(jl)_$(tx) $(d2)_$(d3)(_)$(d4)_$(tx)     |  Documentation: https://docs.julialang.org
1605
              $(d1)(_)$(jl)     | $(d2)(_)$(tx) $(d4)(_)$(tx)    |
1606
               $(jl)_ _   _| |_  __ _$(tx)   |  Type \"?\" for help, \"]?\" for Pkg help.
1607
              $(jl)| | | | | | |/ _` |$(tx)  |
1608
              $(jl)| | |_| | | | (_| |$(tx)  |  Version $(VERSION)$(commit_date)
1609
             $(jl)_/ |\\__'_|_|_|\\__'_|$(tx)  |  $(commit_string)
1610
            $(jl)|__/$(tx)                   |
1611

1612
            """)
1613
        end
1614
    else
1615
        if short
×
1616
            print(io,"""
×
1617
              o  |  Version $(VERSION)$(commit_date)
1618
             o o |  $(commit_string)
1619
            """)
1620
        else
1621
            print(io,"""
×
1622
                           _
1623
               _       _ _(_)_     |  Documentation: https://docs.julialang.org
1624
              (_)     | (_) (_)    |
1625
               _ _   _| |_  __ _   |  Type \"?\" for help, \"]?\" for Pkg help.
1626
              | | | | | | |/ _` |  |
1627
              | | |_| | | | (_| |  |  Version $(VERSION)$(commit_date)
1628
             _/ |\\__'_|_|_|\\__'_|  |  $(commit_string)
1629
            |__/                   |
1630

1631
            """)
1632
        end
1633
    end
1634
end
1635

1636
function run_frontend(repl::StreamREPL, backend::REPLBackendRef)
×
1637
    repl.frontend_task = current_task()
×
1638
    have_color = hascolor(repl)
×
1639
    banner(repl.stream)
×
1640
    d = REPLDisplay(repl)
×
1641
    dopushdisplay = !in(d,Base.Multimedia.displays)
×
1642
    dopushdisplay && pushdisplay(d)
×
1643
    while !eof(repl.stream)::Bool
×
1644
        if have_color
×
1645
            print(repl.stream,repl.prompt_color)
×
1646
        end
1647
        print(repl.stream, "julia> ")
×
1648
        if have_color
×
1649
            print(repl.stream, input_color(repl))
×
1650
        end
1651
        line = readline(repl.stream, keep=true)
×
1652
        if !isempty(line)
×
1653
            ast = Base.parse_input_line(line)
×
1654
            if have_color
×
1655
                print(repl.stream, Base.color_normal)
×
1656
            end
1657
            response = eval_with_backend(ast, backend)
×
1658
            print_response(repl, response, !ends_with_semicolon(line), have_color)
×
1659
        end
1660
    end
×
1661
    # Terminate Backend
1662
    put!(backend.repl_channel, (nothing, -1))
×
1663
    dopushdisplay && popdisplay(d)
×
1664
    nothing
×
1665
end
1666

1667
module Numbered
1668

1669
using ..REPL
1670

1671
__current_ast_transforms() = isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1672

1673
function repl_eval_counter(hp)
×
1674
    return length(hp.history) - hp.start_idx
×
1675
end
1676

1677
function out_transform(@nospecialize(x), n::Ref{Int})
×
1678
    return Expr(:toplevel, get_usings!([], x)..., quote
×
1679
        let __temp_val_a72df459 = $x
×
1680
            $capture_result($n, __temp_val_a72df459)
×
1681
            __temp_val_a72df459
×
1682
        end
1683
    end)
1684
end
1685

1686
function get_usings!(usings, ex)
×
1687
    ex isa Expr || return usings
×
1688
    # get all `using` and `import` statements which are at the top level
1689
    for (i, arg) in enumerate(ex.args)
×
1690
        if Base.isexpr(arg, :toplevel)
×
1691
            get_usings!(usings, arg)
×
1692
        elseif Base.isexpr(arg, [:using, :import])
×
1693
            push!(usings, popat!(ex.args, i))
×
1694
        end
1695
    end
×
1696
    return usings
×
1697
end
1698

1699
function capture_result(n::Ref{Int}, @nospecialize(x))
×
1700
    n = n[]
×
1701
    mod = Base.MainInclude
×
1702
    if !isdefined(mod, :Out)
×
1703
        @eval mod global Out
×
1704
        @eval mod export Out
×
1705
        setglobal!(mod, :Out, Dict{Int, Any}())
×
1706
    end
1707
    if x !== getglobal(mod, :Out) && x !== nothing # remove this?
×
1708
        getglobal(mod, :Out)[n] = x
×
1709
    end
1710
    nothing
×
1711
end
1712

1713
function set_prompt(repl::LineEditREPL, n::Ref{Int})
×
1714
    julia_prompt = repl.interface.modes[1]
×
1715
    julia_prompt.prompt = function()
×
1716
        n[] = repl_eval_counter(julia_prompt.hist)+1
×
1717
        string("In [", n[], "]: ")
×
1718
    end
1719
    nothing
×
1720
end
1721

1722
function set_output_prefix(repl::LineEditREPL, n::Ref{Int})
×
1723
    julia_prompt = repl.interface.modes[1]
×
1724
    if REPL.hascolor(repl)
×
1725
        julia_prompt.output_prefix_prefix = Base.text_colors[:red]
×
1726
    end
1727
    julia_prompt.output_prefix = () -> string("Out[", n[], "]: ")
×
1728
    nothing
×
1729
end
1730

1731
function __current_ast_transforms(backend)
×
1732
    if backend === nothing
×
1733
        isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1734
    else
1735
        backend.ast_transforms
×
1736
    end
1737
end
1738

1739
function numbered_prompt!(repl::LineEditREPL=Base.active_repl, backend=nothing)
×
1740
    n = Ref{Int}(0)
×
1741
    set_prompt(repl, n)
×
1742
    set_output_prefix(repl, n)
×
1743
    push!(__current_ast_transforms(backend), @nospecialize(ast) -> out_transform(ast, n))
×
1744
    return
×
1745
end
1746

1747
"""
1748
    Out[n]
1749

1750
A variable referring to all previously computed values, automatically imported to the interactive prompt.
1751
Only defined and exists while using [Numbered prompt](@ref Numbered-prompt).
1752

1753
See also [`ans`](@ref).
1754
"""
1755
Base.MainInclude.Out
1756

1757
end
1758

1759
import .Numbered.numbered_prompt!
1760

1761
# this assignment won't survive precompilation,
1762
# but will stick if REPL is baked into a sysimg.
1763
# Needs to occur after this module is finished.
1764
Base.REPL_MODULE_REF[] = REPL
1765

1766
if Base.generating_output()
1767
    include("precompile.jl")
1768
end
1769

1770
end # module
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc