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

JuliaLang / julia / #37828

03 Jul 2024 11:00PM UTC coverage: 85.714% (-1.8%) from 87.505%
#37828

push

local

web-flow
delete possibly stale reset_gc_stats (#55015)

See discussion in https://github.com/JuliaLang/julia/issues/55014.

Doesn't seem breaking, but I can close the PR if it is.

Closes https://github.com/JuliaLang/julia/issues/55014.

74029 of 86367 relevant lines covered (85.71%)

15597711.0 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 import `import .Foo`
×
289
                    push!(mods, arg1)
×
290
                end
291
            else # i.e. `Foo: bar`
292
                sym = first((arg1::Expr).args)::Symbol
×
293
                if sym != :. # don't include local import `import .Foo: a`
×
294
                    push!(mods, sym)
×
295
                end
296
            end
297
        end
×
298
    end
299
    if ast.head !== :thunk
×
300
        for arg in ast.args
×
301
            if isexpr(arg, (:block, :if, :using, :import))
×
302
                _modules_to_be_loaded!(arg, mods)
×
303
            end
304
        end
×
305
    else
306
        code = ast.args[1]
×
307
        for arg in code.code
×
308
            isa(arg, Expr) || continue
×
309
            _modules_to_be_loaded!(arg, mods)
×
310
        end
×
311
    end
312
end
313

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

320
"""
321
    start_repl_backend(repl_channel::Channel, response_channel::Channel)
322

323
    Starts loop for REPL backend
324
    Returns a REPLBackend with backend_task assigned
325

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

337
"""
338
    start_repl_backend(backend::REPLBackend)
339

340
    Call directly to run backend loop on current Task.
341
    Use @async for run backend on new Task.
342

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

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

368
struct REPLDisplay{Repl<:AbstractREPL} <: AbstractDisplay
369
    repl::Repl
370
end
371

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

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

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

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

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

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

482
"""
483
    run_repl(repl::AbstractREPL)
484
    run_repl(repl, consumer = backend->nothing; backend_on_current_task = true)
485

486
    Main function to start the REPL
487

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

514
## BasicREPL ##
515

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

523
outstream(r::BasicREPL) = r.terminal
×
524
hascolor(r::BasicREPL) = hascolor(r.terminal)
×
525

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

573
## LineEditREPL ##
574

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

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

623
mutable struct REPLCompletionProvider <: CompletionProvider
624
    modifiers::LineEdit.Modifiers
625
end
626
REPLCompletionProvider() = REPLCompletionProvider(LineEdit.Modifiers())
×
627

628
mutable struct ShellCompletionProvider <: CompletionProvider end
629
struct LatexCompletions <: CompletionProvider end
630

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

639
setmodifiers!(c::CompletionProvider, m::LineEdit.Modifiers) = nothing
×
640

641
setmodifiers!(c::REPLCompletionProvider, m::LineEdit.Modifiers) = c.modifiers = m
×
642

643
"""
644
    activate(mod::Module=Main)
645

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

832
    return :ok
×
833
end
834

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

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

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

886
history_first(s::LineEdit.MIState, hist::REPLHistoryProvider) =
×
887
    history_prev(s, hist, hist.cur_idx - 1 -
888
                 (hist.cur_idx > hist.start_idx+1 ? hist.start_idx : 0))
889

890
history_last(s::LineEdit.MIState, hist::REPLHistoryProvider) =
×
891
    history_next(s, hist, length(hist.history) - hist.cur_idx + 1)
892

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

934
function history_search(hist::REPLHistoryProvider, query_buffer::IOBuffer, response_buffer::IOBuffer,
×
935
                        backwards::Bool=false, skip_current::Bool=false)
936

937
    qpos = position(query_buffer)
×
938
    qpos > 0 || return true
×
939
    searchdata = beforecursor(query_buffer)
×
940
    response_str = String(take!(copy(response_buffer)))
×
941

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

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

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

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

984
    return false
×
985
end
986

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

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

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

1005
backend(r::AbstractREPL) = r.backendref
×
1006

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

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

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

1042
function prepare_next(repl::LineEditREPL)
×
1043
    println(terminal(repl))
×
1044
end
1045

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

1068
repl_filename(repl, hp::REPLHistoryProvider) = "REPL[$(max(length(hp.history)-hp.start_idx, 1))]"
×
1069
repl_filename(repl, hp) = "REPL"
×
1070

1071
const JL_PROMPT_PASTE = Ref(true)
1072
enable_promptpaste(v::Bool) = JL_PROMPT_PASTE[] = v
×
1073

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

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

1090

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

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

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

1122
    ############################### Stage I ################################
1123

1124
    # This will provide completions for REPL and help mode
1125
    replc = REPLCompletionProvider()
×
1126

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

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

1148

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

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

1194

1195
    ################################# Stage II #############################
1196

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

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

1229

1230
    search_prompt, skeymap = LineEdit.setup_search_keymap(hp)
×
1231
    search_prompt.complete = LatexCompletions()
×
1232

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

1238
    # Canonicalize user keymap input
1239
    if isa(extra_repl_keymap, Dict)
×
1240
        extra_repl_keymap = AnyDict[extra_repl_keymap]
×
1241
    end
1242

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

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

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

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

1466
    prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, julia_prompt)
×
1467

1468
    a = Dict{Any,Any}[skeymap, repl_keymap, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
×
1469
    prepend!(a, extra_repl_keymap)
×
1470

1471
    julia_prompt.keymap_dict = LineEdit.keymap(a)
×
1472

1473
    mk = mode_keymap(julia_prompt)
×
1474

1475
    b = Dict{Any,Any}[skeymap, mk, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
×
1476
    prepend!(b, extra_repl_keymap)
×
1477

1478
    shell_mode.keymap_dict = help_mode.keymap_dict = dummy_pkg_mode.keymap_dict = LineEdit.keymap(b)
×
1479

1480
    allprompts = LineEdit.TextInterface[julia_prompt, shell_mode, help_mode, dummy_pkg_mode, search_prompt, prefix_prompt]
×
1481
    return ModalInterface(allprompts)
×
1482
end
1483

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

1503
## StreamREPL ##
1504

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

1517
outstream(s::StreamREPL) = s.stream
×
1518
hascolor(s::StreamREPL) = get(s.stream, :color, false)::Bool
×
1519

1520
answer_color(r::LineEditREPL) = r.envcolors ? Base.answer_color() : r.answer_color
×
1521
answer_color(r::StreamREPL) = r.answer_color
×
1522
input_color(r::LineEditREPL) = r.envcolors ? Base.input_color() : r.input_color
×
1523
input_color(r::StreamREPL) = r.input_color
×
1524

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

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

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

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

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

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

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

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

1634
            """)
1635
        end
1636
    end
1637
end
1638

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

1670
module Numbered
1671

1672
using ..REPL
1673

1674
__current_ast_transforms() = isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1675

1676
function repl_eval_counter(hp)
×
1677
    return length(hp.history) - hp.start_idx
×
1678
end
1679

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

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

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

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

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

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

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

1750
"""
1751
    Out[n]
1752

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

1756
See also [`ans`](@ref).
1757
"""
1758
Base.MainInclude.Out
1759

1760
end
1761

1762
import .Numbered.numbered_prompt!
1763

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

1769
if Base.generating_output()
1770
    include("precompile.jl")
1771
end
1772

1773
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