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

JuliaLang / julia / #37629

23 Sep 2023 01:56AM UTC coverage: 86.504% (+0.5%) from 85.993%
#37629

push

local

web-flow
a bunch of minor fixes and improvements (#51421)

- fixed the docstring of `ir_inline_unionsplit!`
- simplify `show` for `SlotNumber`
- tweak bootstrap.jl (it slightly improves bootstrapping time)

2 of 2 new or added lines in 1 file covered. (100.0%)

72965 of 84349 relevant lines covered (86.5%)

11467543.33 hits per line

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

80.58
/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
function __init__()
10✔
18
    Base.REPL_MODULE_REF[] = REPL
10✔
19
end
20

21
Base.Experimental.@optlevel 1
22
Base.Experimental.@max_methods 1
23

24
using Base.Meta, Sockets
25
import InteractiveUtils
26

27
export
28
    AbstractREPL,
29
    BasicREPL,
30
    LineEditREPL,
31
    StreamREPL
32

33
import Base:
34
    AbstractDisplay,
35
    display,
36
    show,
37
    AnyDict,
38
    ==
39

40
_displaysize(io::IO) = displaysize(io)::Tuple{Int,Int}
29✔
41

42
include("Terminals.jl")
43
using .Terminals
44

45
abstract type AbstractREPL end
46

47
include("options.jl")
48

49
include("LineEdit.jl")
50
using .LineEdit
51
import ..LineEdit:
52
    CompletionProvider,
53
    HistoryProvider,
54
    add_history,
55
    complete_line,
56
    history_next,
57
    history_next_prefix,
58
    history_prev,
59
    history_prev_prefix,
60
    history_first,
61
    history_last,
62
    history_search,
63
    accept_result,
64
    setmodifiers!,
65
    terminal,
66
    MIState,
67
    PromptState,
68
    TextInterface,
69
    mode_idx
70

71
include("REPLCompletions.jl")
72
using .REPLCompletions
73

74
include("TerminalMenus/TerminalMenus.jl")
75
include("docview.jl")
76

77
@nospecialize # use only declared type signatures
78

79
answer_color(::AbstractREPL) = ""
×
80

81
const JULIA_PROMPT = "julia> "
82
const PKG_PROMPT = "pkg> "
83
const SHELL_PROMPT = "shell> "
84
const HELP_PROMPT = "help?> "
85

86
mutable struct REPLBackend
87
    "channel for AST"
88
    repl_channel::Channel{Any}
89
    "channel for results: (value, iserror)"
90
    response_channel::Channel{Any}
91
    "flag indicating the state of this backend"
92
    in_eval::Bool
93
    "transformation functions to apply before evaluating expressions"
94
    ast_transforms::Vector{Any}
95
    "current backend task"
96
    backend_task::Task
97

98
    REPLBackend(repl_channel, response_channel, in_eval, ast_transforms=copy(repl_ast_transforms)) =
48✔
99
        new(repl_channel, response_channel, in_eval, ast_transforms)
100
end
101
REPLBackend() = REPLBackend(Channel(1), Channel(1), false)
24✔
102

103
"""
104
    softscope(ex)
105

106
Return a modified version of the parsed expression `ex` that uses
107
the REPL's "soft" scoping rules for global syntax blocks.
108
"""
109
function softscope(@nospecialize ex)
364✔
110
    if ex isa Expr
364✔
111
        h = ex.head
235✔
112
        if h === :toplevel
235✔
113
            ex′ = Expr(h)
133✔
114
            map!(softscope, resize!(ex′.args, length(ex.args)), ex.args)
133✔
115
            return ex′
133✔
116
        elseif h in (:meta, :import, :using, :export, :module, :error, :incomplete, :thunk)
102✔
117
            return ex
2✔
118
        elseif h === :global && all(x->isa(x, Symbol), ex.args)
102✔
119
            return ex
1✔
120
        else
121
            return Expr(:block, Expr(:softscope, true), ex)
99✔
122
        end
123
    end
124
    return ex
129✔
125
end
126

127
# Temporary alias until Documenter updates
128
const softscope! = softscope
129

130
const repl_ast_transforms = Any[softscope] # defaults for new REPL backends
131

132
# Allows an external package to add hooks into the code loading.
133
# The hook should take a Vector{Symbol} of package names and
134
# return true if all packages could be installed, false if not
135
# to e.g. install packages on demand
136
const install_packages_hooks = Any[]
137

138
function eval_user_input(@nospecialize(ast), backend::REPLBackend, mod::Module)
104✔
139
    lasterr = nothing
×
140
    Base.sigatomic_begin()
104✔
141
    while true
107✔
142
        try
107✔
143
            Base.sigatomic_end()
107✔
144
            if lasterr !== nothing
107✔
145
                put!(backend.response_channel, Pair{Any, Bool}(lasterr, true))
3✔
146
            else
147
                backend.in_eval = true
104✔
148
                if !isempty(install_packages_hooks)
104✔
149
                    check_for_missing_packages_and_run_hooks(ast)
×
150
                end
151
                for xf in backend.ast_transforms
104✔
152
                    ast = Base.invokelatest(xf, ast)
122✔
153
                end
226✔
154
                value = Core.eval(mod, ast)
104✔
155
                backend.in_eval = false
100✔
156
                setglobal!(Base.MainInclude, :ans, value)
100✔
157
                put!(backend.response_channel, Pair{Any, Bool}(value, false))
100✔
158
            end
159
            break
106✔
160
        catch err
161
            if lasterr !== nothing
3✔
162
                println("SYSTEM ERROR: Failed to report error to REPL frontend")
×
163
                println(err)
×
164
            end
165
            lasterr = current_exceptions()
3✔
166
        end
167
    end
3✔
168
    Base.sigatomic_end()
103✔
169
    nothing
103✔
170
end
171

172
function check_for_missing_packages_and_run_hooks(ast)
×
173
    isa(ast, Expr) || return
×
174
    mods = modules_to_be_loaded(ast)
×
175
    filter!(mod -> isnothing(Base.identify_package(String(mod))), mods) # keep missing modules
×
176
    if !isempty(mods)
×
177
        for f in install_packages_hooks
×
178
            Base.invokelatest(f, mods) && return
×
179
        end
×
180
    end
181
end
182

183
function modules_to_be_loaded(ast::Expr, mods::Vector{Symbol} = Symbol[])
73✔
184
    ast.head === :quote && return mods # don't search if it's not going to be run during this eval
73✔
185
    if ast.head === :using || ast.head === :import
88✔
186
        for arg in ast.args
17✔
187
            arg = arg::Expr
21✔
188
            arg1 = first(arg.args)
21✔
189
            if arg1 isa Symbol # i.e. `Foo`
21✔
190
                if arg1 != :. # don't include local imports
18✔
191
                    push!(mods, arg1)
17✔
192
                end
193
            else # i.e. `Foo: bar`
194
                push!(mods, first((arg1::Expr).args))
3✔
195
            end
196
        end
38✔
197
    end
198
    for arg in ast.args
51✔
199
        if isexpr(arg, (:block, :if, :using, :import))
130✔
200
            modules_to_be_loaded(arg, mods)
29✔
201
        end
202
    end
144✔
203
    filter!(mod -> !in(String(mod), ["Base", "Main", "Core"]), mods) # Exclude special non-package modules
101✔
204
    return unique(mods)
51✔
205
end
206

207
"""
208
    start_repl_backend(repl_channel::Channel, response_channel::Channel)
209

210
    Starts loop for REPL backend
211
    Returns a REPLBackend with backend_task assigned
212

213
    Deprecated since sync / async behavior cannot be selected
214
"""
215
function start_repl_backend(repl_channel::Channel{Any}, response_channel::Channel{Any}
×
216
                            ; get_module::Function = ()->Main)
217
    # Maintain legacy behavior of asynchronous backend
218
    backend = REPLBackend(repl_channel, response_channel, false)
×
219
    # Assignment will be made twice, but will be immediately available
220
    backend.backend_task = @async start_repl_backend(backend; get_module)
×
221
    return backend
×
222
end
223

224
"""
225
    start_repl_backend(backend::REPLBackend)
226

227
    Call directly to run backend loop on current Task.
228
    Use @async for run backend on new Task.
229

230
    Does not return backend until loop is finished.
231
"""
232
function start_repl_backend(backend::REPLBackend,  @nospecialize(consumer = x -> nothing); get_module::Function = ()->Main)
56✔
233
    backend.backend_task = Base.current_task()
24✔
234
    consumer(backend)
24✔
235
    repl_backend_loop(backend, get_module)
24✔
236
    return backend
23✔
237
end
238

239
function repl_backend_loop(backend::REPLBackend, get_module::Function)
24✔
240
    # include looks at this to determine the relative include path
241
    # nothing means cwd
242
    while true
×
243
        tls = task_local_storage()
127✔
244
        tls[:SOURCE_PATH] = nothing
127✔
245
        ast, show_value = take!(backend.repl_channel)
127✔
246
        if show_value == -1
127✔
247
            # exit flag
248
            break
23✔
249
        end
250
        eval_user_input(ast, backend, get_module())
104✔
251
    end
103✔
252
    return nothing
23✔
253
end
254

255
struct REPLDisplay{Repl<:AbstractREPL} <: AbstractDisplay
256
    repl::Repl
33✔
257
end
258

259
function display(d::REPLDisplay, mime::MIME"text/plain", x)
61✔
260
    x = Ref{Any}(x)
61✔
261
    with_repl_linfo(d.repl) do io
61✔
262
        io = IOContext(io, :limit => true, :module => active_module(d)::Module)
119✔
263
        if d.repl isa LineEditREPL
3✔
264
            mistate = d.repl.mistate
58✔
265
            mode = LineEdit.mode(mistate)
58✔
266
            if mode isa LineEdit.Prompt
58✔
267
                LineEdit.write_output_prefix(io, mode, get(io, :color, false)::Bool)
232✔
268
            end
269
        end
270
        get(io, :color, false)::Bool && write(io, answer_color(d.repl))
67✔
271
        if isdefined(d.repl, :options) && isdefined(d.repl.options, :iocontext)
3✔
272
            # this can override the :limit property set initially
273
            io = foldl(IOContext, d.repl.options.iocontext, init=io)
58✔
274
        end
275
        show(io, mime, x[])
61✔
276
        println(io)
60✔
277
    end
278
    return nothing
60✔
279
end
280
display(d::REPLDisplay, x) = display(d, MIME("text/plain"), x)
61✔
281

282
function print_response(repl::AbstractREPL, response, show_value::Bool, have_color::Bool)
100✔
283
    repl.waserror = response[2]
100✔
284
    with_repl_linfo(repl) do io
100✔
285
        io = IOContext(io, :module => active_module(repl)::Module)
197✔
286
        print_response(io, response, show_value, have_color, specialdisplay(repl))
100✔
287
    end
288
    return nothing
100✔
289
end
290

291
function repl_display_error(errio::IO, @nospecialize errval)
7✔
292
    # this will be set to true if types in the stacktrace are truncated
293
    limitflag = Ref(false)
7✔
294
    errio = IOContext(errio, :stacktrace_types_limited => limitflag)
7✔
295
    Base.invokelatest(Base.display_error, errio, errval)
7✔
296
    if limitflag[]
5✔
297
        print(errio, "Some type information was truncated. Use `show(err)` to see complete types.")
2✔
298
        println(errio)
2✔
299
    end
300
    return nothing
5✔
301
end
302

303
function print_response(errio::IO, response, show_value::Bool, have_color::Bool, specialdisplay::Union{AbstractDisplay,Nothing}=nothing)
101✔
304
    Base.sigatomic_begin()
101✔
305
    val, iserr = response
101✔
306
    while true
102✔
307
        try
102✔
308
            Base.sigatomic_end()
102✔
309
            if iserr
102✔
310
                val = Base.scrub_repl_backtrace(val)
6✔
311
                Base.istrivialerror(val) || setglobal!(Base.MainInclude, :err, val)
10✔
312
                repl_display_error(errio, val)
6✔
313
            else
314
                if val !== nothing && show_value
96✔
315
                    try
61✔
316
                        if specialdisplay === nothing
61✔
317
                            Base.invokelatest(display, val)
47✔
318
                        else
319
                            Base.invokelatest(display, specialdisplay, val)
60✔
320
                        end
321
                    catch
322
                        println(errio, "Error showing value of type ", typeof(val), ":")
1✔
323
                        rethrow()
1✔
324
                    end
325
                end
326
            end
327
            break
102✔
328
        catch ex
329
            if iserr
2✔
330
                println(errio) # an error during printing is likely to leave us mid-line
1✔
331
                println(errio, "SYSTEM (REPL): showing an error caused an error")
1✔
332
                try
1✔
333
                    excs = Base.scrub_repl_backtrace(current_exceptions())
1✔
334
                    setglobal!(Base.MainInclude, :err, excs)
1✔
335
                    repl_display_error(errio, excs)
2✔
336
                catch e
337
                    # at this point, only print the name of the type as a Symbol to
338
                    # minimize the possibility of further errors.
339
                    println(errio)
1✔
340
                    println(errio, "SYSTEM (REPL): caught exception of type ", typeof(e).name.name,
1✔
341
                            " while trying to handle a nested exception; giving up")
342
                end
343
                break
1✔
344
            end
345
            val = current_exceptions()
1✔
346
            iserr = true
1✔
347
        end
348
    end
1✔
349
    Base.sigatomic_end()
101✔
350
    nothing
101✔
351
end
352

353
# A reference to a backend that is not mutable
354
struct REPLBackendRef
355
    repl_channel::Channel{Any}
22✔
356
    response_channel::Channel{Any}
357
end
358
REPLBackendRef(backend::REPLBackend) = REPLBackendRef(backend.repl_channel, backend.response_channel)
22✔
359

360
function destroy(ref::REPLBackendRef, state::Task)
21✔
361
    if istaskfailed(state)
21✔
362
        close(ref.repl_channel, TaskFailedException(state))
×
363
        close(ref.response_channel, TaskFailedException(state))
×
364
    end
365
    close(ref.repl_channel)
21✔
366
    close(ref.response_channel)
21✔
367
end
368

369
"""
370
    run_repl(repl::AbstractREPL)
371
    run_repl(repl, consumer = backend->nothing; backend_on_current_task = true)
372

373
    Main function to start the REPL
374

375
    consumer is an optional function that takes a REPLBackend as an argument
376
"""
377
function run_repl(repl::AbstractREPL, @nospecialize(consumer = x -> nothing); backend_on_current_task::Bool = true, backend = REPLBackend())
86✔
378
    backend_ref = REPLBackendRef(backend)
22✔
379
    cleanup = @task try
43✔
380
            destroy(backend_ref, t)
21✔
381
        catch e
382
            Core.print(Core.stderr, "\nINTERNAL ERROR: ")
×
383
            Core.println(Core.stderr, e)
×
384
            Core.println(Core.stderr, catch_backtrace())
×
385
        end
386
    get_module = () -> active_module(repl)
122✔
387
    if backend_on_current_task
22✔
388
        t = @async run_frontend(repl, backend_ref)
44✔
389
        errormonitor(t)
22✔
390
        Base._wait2(t, cleanup)
22✔
391
        start_repl_backend(backend, consumer; get_module)
22✔
392
    else
393
        t = @async start_repl_backend(backend, consumer; get_module)
×
394
        errormonitor(t)
×
395
        Base._wait2(t, cleanup)
×
396
        run_frontend(repl, backend_ref)
×
397
    end
398
    return backend
21✔
399
end
400

401
## BasicREPL ##
402

403
mutable struct BasicREPL <: AbstractREPL
404
    terminal::TextTerminal
405
    waserror::Bool
406
    frontend_task::Task
407
    BasicREPL(t) = new(t, false)
3✔
408
end
409

410
outstream(r::BasicREPL) = r.terminal
6✔
411
hascolor(r::BasicREPL) = hascolor(r.terminal)
×
412

413
function run_frontend(repl::BasicREPL, backend::REPLBackendRef)
3✔
414
    repl.frontend_task = current_task()
3✔
415
    d = REPLDisplay(repl)
3✔
416
    dopushdisplay = !in(d,Base.Multimedia.displays)
6✔
417
    dopushdisplay && pushdisplay(d)
3✔
418
    hit_eof = false
3✔
419
    while true
6✔
420
        Base.reseteof(repl.terminal)
6✔
421
        write(repl.terminal, JULIA_PROMPT)
6✔
422
        line = ""
6✔
423
        ast = nothing
6✔
424
        interrupted = false
6✔
425
        while true
6✔
426
            try
6✔
427
                line *= readline(repl.terminal, keep=true)
6✔
428
            catch e
429
                if isa(e,InterruptException)
×
430
                    try # raise the debugger if present
×
431
                        ccall(:jl_raise_debugger, Int, ())
×
432
                    catch
×
433
                    end
434
                    line = ""
×
435
                    interrupted = true
×
436
                    break
×
437
                elseif isa(e,EOFError)
×
438
                    hit_eof = true
×
439
                    break
×
440
                else
441
                    rethrow()
×
442
                end
443
            end
444
            ast = Base.parse_input_line(line)
12✔
445
            (isa(ast,Expr) && ast.head === :incomplete) || break
12✔
446
        end
×
447
        if !isempty(line)
6✔
448
            response = eval_with_backend(ast, backend)
4✔
449
            print_response(repl, response, !ends_with_semicolon(line), false)
3✔
450
        end
451
        write(repl.terminal, '\n')
5✔
452
        ((!interrupted && isempty(line)) || hit_eof) && break
8✔
453
    end
3✔
454
    # terminate backend
455
    put!(backend.repl_channel, (nothing, -1))
2✔
456
    dopushdisplay && popdisplay(d)
2✔
457
    nothing
2✔
458
end
459

460
## LineEditREPL ##
461

462
mutable struct LineEditREPL <: AbstractREPL
463
    t::TextTerminal
464
    hascolor::Bool
465
    prompt_color::String
466
    input_color::String
467
    answer_color::String
468
    shell_color::String
469
    help_color::String
470
    history_file::Bool
471
    in_shell::Bool
472
    in_help::Bool
473
    envcolors::Bool
474
    waserror::Bool
475
    specialdisplay::Union{Nothing,AbstractDisplay}
476
    options::Options
477
    mistate::Union{MIState,Nothing}
478
    last_shown_line_infos::Vector{Tuple{String,Int}}
479
    interface::ModalInterface
480
    backendref::REPLBackendRef
481
    frontend_task::Task
482
    function LineEditREPL(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell,in_help,envcolors)
26✔
483
        opts = Options()
26✔
484
        opts.hascolor = hascolor
26✔
485
        if !hascolor
26✔
486
            opts.beep_colors = [""]
×
487
        end
488
        new(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell,
26✔
489
            in_help,envcolors,false,nothing, opts, nothing, Tuple{String,Int}[])
490
    end
491
end
492
outstream(r::LineEditREPL) = (t = r.t; t isa TTYTerminal ? t.out_stream : t)
495✔
493
specialdisplay(r::LineEditREPL) = r.specialdisplay
97✔
494
specialdisplay(r::AbstractREPL) = nothing
3✔
495
terminal(r::LineEditREPL) = r.t
150✔
496
hascolor(r::LineEditREPL) = r.hascolor
195✔
497

498
LineEditREPL(t::TextTerminal, hascolor::Bool, envcolors::Bool=false) =
52✔
499
    LineEditREPL(t, hascolor,
500
        hascolor ? Base.text_colors[:green] : "",
501
        hascolor ? Base.input_color() : "",
502
        hascolor ? Base.answer_color() : "",
503
        hascolor ? Base.text_colors[:red] : "",
504
        hascolor ? Base.text_colors[:yellow] : "",
505
        false, false, false, envcolors
506
    )
507

508
mutable struct REPLCompletionProvider <: CompletionProvider
509
    modifiers::LineEdit.Modifiers
23✔
510
end
511
REPLCompletionProvider() = REPLCompletionProvider(LineEdit.Modifiers())
23✔
512

513
mutable struct ShellCompletionProvider <: CompletionProvider end
23✔
514
struct LatexCompletions <: CompletionProvider end
515

516
function active_module() # this method is also called from Base
5,683✔
517
    isdefined(Base, :active_repl) || return Main
11,366✔
518
    return active_module(Base.active_repl::AbstractREPL)
×
519
end
520
active_module((; mistate)::LineEditREPL) = mistate === nothing ? Main : mistate.active_module
4,663✔
521
active_module(::AbstractREPL) = Main
10✔
522
active_module(d::REPLDisplay) = active_module(d.repl)
119✔
523

524
setmodifiers!(c::CompletionProvider, m::LineEdit.Modifiers) = nothing
×
525

526
setmodifiers!(c::REPLCompletionProvider, m::LineEdit.Modifiers) = c.modifiers = m
×
527

528
"""
529
    activate(mod::Module=Main)
530

531
Set `mod` as the default contextual module in the REPL,
532
both for evaluating expressions and printing them.
533
"""
534
function activate(mod::Module=Main)
×
535
    mistate = (Base.active_repl::LineEditREPL).mistate
×
536
    mistate === nothing && return nothing
×
537
    mistate.active_module = mod
×
538
    Base.load_InteractiveUtils(mod)
×
539
    return nothing
×
540
end
541

542
beforecursor(buf::IOBuffer) = String(buf.data[1:buf.ptr-1])
2,149✔
543

544
function complete_line(c::REPLCompletionProvider, s::PromptState, mod::Module)
1,681✔
545
    partial = beforecursor(s.input_buffer)
1,681✔
546
    full = LineEdit.input_string(s)
1,681✔
547
    ret, range, should_complete = completions(full, lastindex(partial), mod, c.modifiers.shift)
1,681✔
548
    c.modifiers = LineEdit.Modifiers()
1,681✔
549
    return unique!(map(completion_text, ret)), partial[range], should_complete
1,681✔
550
end
551

552
function complete_line(c::ShellCompletionProvider, s::PromptState)
436✔
553
    # First parse everything up to the current position
554
    partial = beforecursor(s.input_buffer)
436✔
555
    full = LineEdit.input_string(s)
436✔
556
    ret, range, should_complete = shell_completions(full, lastindex(partial))
436✔
557
    return unique!(map(completion_text, ret)), partial[range], should_complete
436✔
558
end
559

560
function complete_line(c::LatexCompletions, s)
×
561
    partial = beforecursor(LineEdit.buffer(s))
×
562
    full = LineEdit.input_string(s)::String
×
563
    ret, range, should_complete = bslash_completions(full, lastindex(partial))[2]
×
564
    return unique!(map(completion_text, ret)), partial[range], should_complete
×
565
end
566

567
with_repl_linfo(f, repl) = f(outstream(repl))
6✔
568
function with_repl_linfo(f, repl::LineEditREPL)
155✔
569
    linfos = Tuple{String,Int}[]
155✔
570
    io = IOContext(outstream(repl), :last_shown_line_infos => linfos)
310✔
571
    f(io)
155✔
572
    if !isempty(linfos)
154✔
573
        repl.last_shown_line_infos = linfos
5✔
574
    end
575
    nothing
154✔
576
end
577

578
mutable struct REPLHistoryProvider <: HistoryProvider
579
    history::Vector{String}
28✔
580
    file_path::String
581
    history_file::Union{Nothing,IO}
582
    start_idx::Int
583
    cur_idx::Int
584
    last_idx::Int
585
    last_buffer::IOBuffer
586
    last_mode::Union{Nothing,Prompt}
587
    mode_mapping::Dict{Symbol,Prompt}
588
    modes::Vector{Symbol}
589
end
590
REPLHistoryProvider(mode_mapping::Dict{Symbol}) =
28✔
591
    REPLHistoryProvider(String[], "", nothing, 0, 0, -1, IOBuffer(),
592
                        nothing, mode_mapping, UInt8[])
593

594
invalid_history_message(path::String) = """
×
595
Invalid history file ($path) format:
596
If you have a history file left over from an older version of Julia,
597
try renaming or deleting it.
598
Invalid character: """
599

600
munged_history_message(path::String) = """
×
601
Invalid history file ($path) format:
602
An editor may have converted tabs to spaces at line """
603

604
function hist_open_file(hp::REPLHistoryProvider)
×
605
    f = open(hp.file_path, read=true, write=true, create=true)
4✔
606
    hp.history_file = f
4✔
607
    seekend(f)
4✔
608
end
609

610
function hist_from_file(hp::REPLHistoryProvider, path::String)
8✔
611
    getline(lines, i) = i > length(lines) ? "" : lines[i]
276✔
612
    file_lines = readlines(path)
8✔
613
    countlines = 0
×
614
    while true
42✔
615
        # First parse the metadata that starts with '#' in particular the REPL mode
616
        countlines += 1
42✔
617
        line = getline(file_lines, countlines)
76✔
618
        mode = :julia
×
619
        isempty(line) && break
42✔
620
        line[1] != '#' &&
68✔
621
            error(invalid_history_message(path), repr(line[1]), " at line ", countlines)
622
        while !isempty(line)
102✔
623
            startswith(line, '#') || break
102✔
624
            if startswith(line, "# mode: ")
136✔
625
                mode = Symbol(SubString(line, 9))
34✔
626
            end
627
            countlines += 1
68✔
628
            line = getline(file_lines, countlines)
136✔
629
        end
68✔
630
        isempty(line) && break
34✔
631

632
        # Now parse the code for the current REPL mode
633
        line[1] == ' '  &&
68✔
634
            error(munged_history_message(path), countlines)
635
        line[1] != '\t' &&
68✔
636
            error(invalid_history_message(path), repr(line[1]), " at line ", countlines)
637
        lines = String[]
34✔
638
        while !isempty(line)
34✔
639
            push!(lines, chomp(SubString(line, 2)))
34✔
640
            next_line = getline(file_lines, countlines+1)
64✔
641
            isempty(next_line) && break
34✔
642
            first(next_line) == ' '  && error(munged_history_message(path), countlines)
30✔
643
            # A line not starting with a tab means we are done with code for this entry
644
            first(next_line) != '\t' && break
30✔
645
            countlines += 1
×
646
            line = getline(file_lines, countlines)
×
647
        end
×
648
        push!(hp.modes, mode)
34✔
649
        push!(hp.history, join(lines, '\n'))
34✔
650
    end
34✔
651
    hp.start_idx = length(hp.history)
8✔
652
    return hp
8✔
653
end
654

655
function add_history(hist::REPLHistoryProvider, s::PromptState)
115✔
656
    str = rstrip(String(take!(copy(s.input_buffer))))
115✔
657
    isempty(strip(str)) && return
115✔
658
    mode = mode_idx(hist, LineEdit.mode(s))
97✔
659
    !isempty(hist.history) &&
158✔
660
        isequal(mode, hist.modes[end]) && str == hist.history[end] && return
661
    push!(hist.modes, mode)
91✔
662
    push!(hist.history, str)
91✔
663
    hist.history_file === nothing && return
91✔
664
    entry = """
16✔
665
    # time: $(Libc.strftime("%Y-%m-%d %H:%M:%S %Z", time()))
666
    # mode: $mode
667
    $(replace(str, r"^"ms => "\t"))
668
    """
669
    # TODO: write-lock history file
670
    try
16✔
671
        seekend(hist.history_file)
16✔
672
    catch err
673
        (err isa SystemError) || rethrow()
×
674
        # File handle might get stale after a while, especially under network file systems
675
        # If this doesn't fix it (e.g. when file is deleted), we'll end up rethrowing anyway
676
        hist_open_file(hist)
×
677
    end
678
    print(hist.history_file, entry)
32✔
679
    flush(hist.history_file)
16✔
680
    nothing
16✔
681
end
682

683
function history_move(s::Union{LineEdit.MIState,LineEdit.PrefixSearchState}, hist::REPLHistoryProvider, idx::Int, save_idx::Int = hist.cur_idx)
100✔
684
    max_idx = length(hist.history) + 1
136✔
685
    @assert 1 <= hist.cur_idx <= max_idx
96✔
686
    (1 <= idx <= max_idx) || return :none
98✔
687
    idx != hist.cur_idx || return :none
94✔
688

689
    # save the current line
690
    if save_idx == max_idx
94✔
691
        hist.last_mode = LineEdit.mode(s)
46✔
692
        hist.last_buffer = copy(LineEdit.buffer(s))
46✔
693
    else
694
        hist.history[save_idx] = LineEdit.input_string(s)
84✔
695
        hist.modes[save_idx] = mode_idx(hist, LineEdit.mode(s))
63✔
696
    end
697

698
    # load the saved line
699
    if idx == max_idx
94✔
700
        last_buffer = hist.last_buffer
10✔
701
        LineEdit.transition(s, hist.last_mode) do
10✔
702
            LineEdit.replace_line(s, last_buffer)
10✔
703
        end
704
        hist.last_mode = nothing
10✔
705
        hist.last_buffer = IOBuffer()
10✔
706
    else
707
        if haskey(hist.mode_mapping, hist.modes[idx])
84✔
708
            LineEdit.transition(s, hist.mode_mapping[hist.modes[idx]]) do
68✔
709
                LineEdit.replace_line(s, hist.history[idx])
68✔
710
            end
711
        else
712
            return :skip
16✔
713
        end
714
    end
715
    hist.cur_idx = idx
78✔
716

717
    return :ok
78✔
718
end
719

720
# REPL History can also transitions modes
721
function LineEdit.accept_result_newmode(hist::REPLHistoryProvider)
27✔
722
    if 1 <= hist.cur_idx <= length(hist.modes)
27✔
723
        return hist.mode_mapping[hist.modes[hist.cur_idx]]
23✔
724
    end
725
    return nothing
4✔
726
end
727

728
function history_prev(s::LineEdit.MIState, hist::REPLHistoryProvider,
58✔
729
                      num::Int=1, save_idx::Int = hist.cur_idx)
730
    num <= 0 && return history_next(s, hist, -num, save_idx)
58✔
731
    hist.last_idx = -1
32✔
732
    m = history_move(s, hist, hist.cur_idx-num, save_idx)
32✔
733
    if m === :ok
32✔
734
        LineEdit.move_input_start(s)
24✔
735
        LineEdit.reset_key_repeats(s) do
24✔
736
            LineEdit.move_line_end(s)
24✔
737
        end
738
        return LineEdit.refresh_line(s)
24✔
739
    elseif m === :skip
8✔
740
        return history_prev(s, hist, num+1, save_idx)
8✔
741
    else
742
        return Terminals.beep(s)
×
743
    end
744
end
745

746
function history_next(s::LineEdit.MIState, hist::REPLHistoryProvider,
44✔
747
                      num::Int=1, save_idx::Int = hist.cur_idx)
748
    if num == 0
44✔
749
        Terminals.beep(s)
×
750
        return
×
751
    end
752
    num < 0 && return history_prev(s, hist, -num, save_idx)
26✔
753
    cur_idx = hist.cur_idx
24✔
754
    max_idx = length(hist.history) + 1
24✔
755
    if cur_idx == max_idx && 0 < hist.last_idx
24✔
756
        # issue #6312
757
        cur_idx = hist.last_idx
×
758
        hist.last_idx = -1
×
759
    end
760
    m = history_move(s, hist, cur_idx+num, save_idx)
24✔
761
    if m === :ok
24✔
762
        LineEdit.move_input_end(s)
16✔
763
        return LineEdit.refresh_line(s)
16✔
764
    elseif m === :skip
8✔
765
        return history_next(s, hist, num+1, save_idx)
6✔
766
    else
767
        return Terminals.beep(s)
2✔
768
    end
769
end
770

771
history_first(s::LineEdit.MIState, hist::REPLHistoryProvider) =
6✔
772
    history_prev(s, hist, hist.cur_idx - 1 -
773
                 (hist.cur_idx > hist.start_idx+1 ? hist.start_idx : 0))
774

775
history_last(s::LineEdit.MIState, hist::REPLHistoryProvider) =
4✔
776
    history_next(s, hist, length(hist.history) - hist.cur_idx + 1)
777

778
function history_move_prefix(s::LineEdit.PrefixSearchState,
62✔
779
                             hist::REPLHistoryProvider,
780
                             prefix::AbstractString,
781
                             backwards::Bool,
782
                             cur_idx::Int = hist.cur_idx)
783
    cur_response = String(take!(copy(LineEdit.buffer(s))))
74✔
784
    # when searching forward, start at last_idx
785
    if !backwards && hist.last_idx > 0
38✔
786
        cur_idx = hist.last_idx
1✔
787
    end
788
    hist.last_idx = -1
38✔
789
    max_idx = length(hist.history)+1
38✔
790
    idxs = backwards ? ((cur_idx-1):-1:1) : ((cur_idx+1):1:max_idx)
65✔
791
    for idx in idxs
74✔
792
        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)))
192✔
793
            m = history_move(s, hist, idx)
36✔
794
            if m === :ok
36✔
795
                if idx == max_idx
38✔
796
                    # on resuming the in-progress edit, leave the cursor where the user last had it
797
                elseif isempty(prefix)
30✔
798
                    # on empty prefix search, move cursor to the end
799
                    LineEdit.move_input_end(s)
14✔
800
                else
801
                    # otherwise, keep cursor at the prefix position as a visual cue
802
                    seek(LineEdit.buffer(s), sizeof(prefix))
16✔
803
                end
804
                LineEdit.refresh_line(s)
34✔
805
                return :ok
34✔
806
            elseif m === :skip
2✔
807
                return history_move_prefix(s,hist,prefix,backwards,idx)
2✔
808
            end
809
        end
810
    end
124✔
811
    Terminals.beep(s)
×
812
    nothing
2✔
813
end
814
history_next_prefix(s::LineEdit.PrefixSearchState, hist::REPLHistoryProvider, prefix::AbstractString) =
5✔
815
    history_move_prefix(s, hist, prefix, false)
816
history_prev_prefix(s::LineEdit.PrefixSearchState, hist::REPLHistoryProvider, prefix::AbstractString) =
31✔
817
    history_move_prefix(s, hist, prefix, true)
818

819
function history_search(hist::REPLHistoryProvider, query_buffer::IOBuffer, response_buffer::IOBuffer,
28✔
820
                        backwards::Bool=false, skip_current::Bool=false)
821

822
    qpos = position(query_buffer)
28✔
823
    qpos > 0 || return true
28✔
824
    searchdata = beforecursor(query_buffer)
28✔
825
    response_str = String(take!(copy(response_buffer)))
28✔
826

827
    # Alright, first try to see if the current match still works
828
    a = position(response_buffer) + 1 # position is zero-indexed
28✔
829
    # FIXME: I'm pretty sure this is broken since it uses an index
830
    # into the search data to index into the response string
831
    b = a + sizeof(searchdata)
28✔
832
    b = b ≤ ncodeunits(response_str) ? prevind(response_str, b) : b-1
48✔
833
    b = min(lastindex(response_str), b) # ensure that b is valid
28✔
834

835
    searchstart = backwards ? b : a
28✔
836
    if searchdata == response_str[a:b]
44✔
837
        if skip_current
10✔
838
            searchstart = backwards ? prevind(response_str, b) : nextind(response_str, a)
4✔
839
        else
840
            return true
6✔
841
        end
842
    end
843

844
    # Start searching
845
    # First the current response buffer
846
    if 1 <= searchstart <= lastindex(response_str)
22✔
847
        match = backwards ? findprev(searchdata, response_str, searchstart) :
14✔
848
                            findnext(searchdata, response_str, searchstart)
849
        if match !== nothing
14✔
850
            seek(response_buffer, first(match) - 1)
6✔
851
            return true
6✔
852
        end
853
    end
854

855
    # Now search all the other buffers
856
    idxs = backwards ? ((hist.cur_idx-1):-1:1) : ((hist.cur_idx+1):1:length(hist.history))
32✔
857
    for idx in idxs
32✔
858
        h = hist.history[idx]
40✔
859
        match = backwards ? findlast(searchdata, h) : findfirst(searchdata, h)
40✔
860
        if match !== nothing && h != response_str && haskey(hist.mode_mapping, hist.modes[idx])
40✔
861
            truncate(response_buffer, 0)
12✔
862
            write(response_buffer, h)
12✔
863
            seek(response_buffer, first(match) - 1)
12✔
864
            hist.cur_idx = idx
12✔
865
            return true
12✔
866
        end
867
    end
52✔
868

869
    return false
4✔
870
end
871

872
function history_reset_state(hist::REPLHistoryProvider)
7✔
873
    if hist.cur_idx != length(hist.history) + 1
266✔
874
        hist.last_idx = hist.cur_idx
127✔
875
        hist.cur_idx = length(hist.history) + 1
127✔
876
    end
877
    nothing
266✔
878
end
879
LineEdit.reset_state(hist::REPLHistoryProvider) = history_reset_state(hist)
236✔
880

881
function return_callback(s)
94✔
882
    ast = Base.parse_input_line(String(take!(copy(LineEdit.buffer(s)))), depwarn=false)
94✔
883
    return !(isa(ast, Expr) && ast.head === :incomplete)
94✔
884
end
885

886
find_hist_file() = get(ENV, "JULIA_HISTORY",
8✔
887
                       !isempty(DEPOT_PATH) ? joinpath(DEPOT_PATH[1], "logs", "repl_history.jl") :
888
                       error("DEPOT_PATH is empty and and ENV[\"JULIA_HISTORY\"] not set."))
889

890
backend(r::AbstractREPL) = r.backendref
96✔
891

892
function eval_with_backend(ast, backend::REPLBackendRef)
100✔
893
    put!(backend.repl_channel, (ast, 1))
100✔
894
    return take!(backend.response_channel) # (val, iserr)
100✔
895
end
896

897
function respond(f, repl, main; pass_empty::Bool = false, suppress_on_semicolon::Bool = true)
69✔
898
    return function do_respond(s::MIState, buf, ok::Bool)
200✔
899
        if !ok
131✔
900
            return transition(s, :abort)
19✔
901
        end
902
        line = String(take!(buf)::Vector{UInt8})
112✔
903
        if !isempty(line) || pass_empty
127✔
904
            reset(repl)
97✔
905
            local response
×
906
            try
97✔
907
                ast = Base.invokelatest(f, line)
97✔
908
                response = eval_with_backend(ast, backend(repl))
97✔
909
            catch
910
                response = Pair{Any, Bool}(current_exceptions(), true)
1✔
911
            end
912
            hide_output = suppress_on_semicolon && ends_with_semicolon(line)
97✔
913
            print_response(repl, response, !hide_output, hascolor(repl))
97✔
914
        end
915
        prepare_next(repl)
112✔
916
        reset_state(s)
112✔
917
        return s.current_mode.sticky ? true : transition(s, main)
112✔
918
    end
919
end
920

921
function reset(repl::LineEditREPL)
97✔
922
    raw!(repl.t, false)
97✔
923
    hascolor(repl) && print(repl.t, Base.text_colors[:normal])
97✔
924
    nothing
97✔
925
end
926

927
function prepare_next(repl::LineEditREPL)
112✔
928
    println(terminal(repl))
112✔
929
end
930

931
function mode_keymap(julia_prompt::Prompt)
2✔
932
    AnyDict(
25✔
933
    '\b' => function (s::MIState,o...)
7✔
934
        if isempty(s) || position(LineEdit.buffer(s)) == 0
7✔
935
            buf = copy(LineEdit.buffer(s))
7✔
936
            transition(s, julia_prompt) do
7✔
937
                LineEdit.state(s, julia_prompt).input_buffer = buf
7✔
938
            end
939
        else
940
            LineEdit.edit_backspace(s)
×
941
        end
942
    end,
943
    "^C" => function (s::MIState,o...)
944
        LineEdit.move_input_end(s)
945
        LineEdit.refresh_line(s)
946
        print(LineEdit.terminal(s), "^C\n\n")
947
        transition(s, julia_prompt)
948
        transition(s, :reset)
949
        LineEdit.refresh_line(s)
950
    end)
951
end
952

953
repl_filename(repl, hp::REPLHistoryProvider) = "REPL[$(max(length(hp.history)-hp.start_idx, 1))]"
86✔
954
repl_filename(repl, hp) = "REPL"
×
955

956
const JL_PROMPT_PASTE = Ref(true)
957
enable_promptpaste(v::Bool) = JL_PROMPT_PASTE[] = v
×
958

959
function contextual_prompt(repl::LineEditREPL, prompt::Union{String,Function})
×
960
    function ()
2,130✔
961
        mod = active_module(repl)
4,161✔
962
        prefix = mod == Main ? "" : string('(', mod, ") ")
2,116✔
963
        pr = prompt isa String ? prompt : prompt()
2,084✔
964
        prefix * pr
2,084✔
965
    end
966
end
967

968
setup_interface(
65✔
969
    repl::LineEditREPL;
970
    # those keyword arguments may be deprecated eventually in favor of the Options mechanism
971
    hascolor::Bool = repl.options.hascolor,
972
    extra_repl_keymap::Any = repl.options.extra_keymap
973
) = setup_interface(repl, hascolor, extra_repl_keymap)
974

975
# This non keyword method can be precompiled which is important
976
function setup_interface(
23✔
977
    repl::LineEditREPL,
978
    hascolor::Bool,
979
    extra_repl_keymap::Any, # Union{Dict,Vector{<:Dict}},
980
)
981
    # The precompile statement emitter has problem outputting valid syntax for the
982
    # type of `Union{Dict,Vector{<:Dict}}` (see #28808).
983
    # This function is however important to precompile for REPL startup time, therefore,
984
    # make the type Any and just assert that we have the correct type below.
985
    @assert extra_repl_keymap isa Union{Dict,Vector{<:Dict}}
23✔
986

987
    ###
988
    #
989
    # This function returns the main interface that describes the REPL
990
    # functionality, it is called internally by functions that setup a
991
    # Terminal-based REPL frontend.
992
    #
993
    # See run_frontend(repl::LineEditREPL, backend::REPLBackendRef)
994
    # for usage
995
    #
996
    ###
997

998
    ###
999
    # We setup the interface in two stages.
1000
    # First, we set up all components (prompt,rsearch,shell,help)
1001
    # Second, we create keymaps with appropriate transitions between them
1002
    #   and assign them to the components
1003
    #
1004
    ###
1005

1006
    ############################### Stage I ################################
1007

1008
    # This will provide completions for REPL and help mode
1009
    replc = REPLCompletionProvider()
23✔
1010

1011
    # Set up the main Julia prompt
1012
    julia_prompt = Prompt(contextual_prompt(repl, JULIA_PROMPT);
46✔
1013
        # Copy colors from the prompt object
1014
        prompt_prefix = hascolor ? repl.prompt_color : "",
1015
        prompt_suffix = hascolor ?
1016
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
1017
        repl = repl,
1018
        complete = replc,
1019
        on_enter = return_callback)
1020

1021
    # Setup help mode
1022
    help_mode = Prompt(contextual_prompt(repl, "help?> "),
46✔
1023
        prompt_prefix = hascolor ? repl.help_color : "",
1024
        prompt_suffix = hascolor ?
1025
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
1026
        repl = repl,
1027
        complete = replc,
1028
        # When we're done transform the entered line into a call to helpmode function
1029
        on_done = respond(line::String->helpmode(outstream(repl), line, repl.mistate.active_module),
2✔
1030
                          repl, julia_prompt, pass_empty=true, suppress_on_semicolon=false))
1031

1032

1033
    # Set up shell mode
1034
    shell_mode = Prompt(SHELL_PROMPT;
46✔
1035
        prompt_prefix = hascolor ? repl.shell_color : "",
1036
        prompt_suffix = hascolor ?
1037
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
1038
        repl = repl,
1039
        complete = ShellCompletionProvider(),
1040
        # Transform "foo bar baz" into `foo bar baz` (shell quoting)
1041
        # and pass into Base.repl_cmd for processing (handles `ls` and `cd`
1042
        # special)
1043
        on_done = respond(repl, julia_prompt) do line
1044
            Expr(:call, :(Base.repl_cmd),
9✔
1045
                :(Base.cmd_gen($(Base.shell_parse(line::String)[1]))),
1046
                outstream(repl))
1047
        end,
1048
        sticky = true)
1049

1050

1051
    ################################# Stage II #############################
1052

1053
    # Setup history
1054
    # We will have a unified history for all REPL modes
1055
    hp = REPLHistoryProvider(Dict{Symbol,Prompt}(:julia => julia_prompt,
23✔
1056
                                                 :shell => shell_mode,
1057
                                                 :help  => help_mode))
1058
    if repl.history_file
23✔
1059
        try
4✔
1060
            hist_path = find_hist_file()
8✔
1061
            mkpath(dirname(hist_path))
4✔
1062
            hp.file_path = hist_path
4✔
1063
            hist_open_file(hp)
4✔
1064
            finalizer(replc) do replc
4✔
1065
                close(hp.history_file)
4✔
1066
            end
1067
            hist_from_file(hp, hist_path)
4✔
1068
        catch
1069
            # use REPL.hascolor to avoid using the local variable with the same name
1070
            print_response(repl, Pair{Any, Bool}(current_exceptions(), true), true, REPL.hascolor(repl))
×
1071
            println(outstream(repl))
×
1072
            @info "Disabling history file for this session"
×
1073
            repl.history_file = false
×
1074
        end
1075
    end
1076
    history_reset_state(hp)
23✔
1077
    julia_prompt.hist = hp
23✔
1078
    shell_mode.hist = hp
23✔
1079
    help_mode.hist = hp
23✔
1080

1081
    julia_prompt.on_done = respond(x->Base.parse_input_line(x,filename=repl_filename(repl,hp)), repl, julia_prompt)
109✔
1082

1083

1084
    search_prompt, skeymap = LineEdit.setup_search_keymap(hp)
23✔
1085
    search_prompt.complete = LatexCompletions()
23✔
1086

1087
    shell_prompt_len = length(SHELL_PROMPT)
×
1088
    help_prompt_len = length(HELP_PROMPT)
×
1089
    jl_prompt_regex = r"^In \[[0-9]+\]: |^(?:\(.+\) )?julia> "
×
1090
    pkg_prompt_regex = r"^(?:\(.+\) )?pkg> "
×
1091

1092
    # Canonicalize user keymap input
1093
    if isa(extra_repl_keymap, Dict)
23✔
1094
        extra_repl_keymap = AnyDict[extra_repl_keymap]
×
1095
    end
1096

1097
    repl_keymap = AnyDict(
23✔
1098
        ';' => function (s::MIState,o...)
53✔
1099
            if isempty(s) || position(LineEdit.buffer(s)) == 0
99✔
1100
                buf = copy(LineEdit.buffer(s))
7✔
1101
                transition(s, shell_mode) do
7✔
1102
                    LineEdit.state(s, shell_mode).input_buffer = buf
7✔
1103
                end
1104
            else
1105
                edit_insert(s, ';')
46✔
1106
            end
1107
        end,
1108
        '?' => function (s::MIState,o...)
1✔
1109
            if isempty(s) || position(LineEdit.buffer(s)) == 0
1✔
1110
                buf = copy(LineEdit.buffer(s))
1✔
1111
                transition(s, help_mode) do
1✔
1112
                    LineEdit.state(s, help_mode).input_buffer = buf
1✔
1113
                end
1114
            else
1115
                edit_insert(s, '?')
×
1116
            end
1117
        end,
1118
        ']' => function (s::MIState,o...)
3✔
1119
            if isempty(s) || position(LineEdit.buffer(s)) == 0
6✔
1120
                pkgid = Base.PkgId(Base.UUID("44cfe95a-1eb2-52ea-b672-e2afdf69b78f"), "Pkg")
×
1121
                if Base.locate_package(pkgid) !== nothing # Only try load Pkg if we can find it
×
1122
                    Pkg = Base.require(pkgid)
×
1123
                    # Pkg should have loaded its REPL mode by now, let's find it so we can transition to it.
1124
                    pkg_mode = nothing
×
1125
                    for mode in repl.interface.modes
×
1126
                        if mode isa LineEdit.Prompt && mode.complete isa Pkg.REPLMode.PkgCompletionProvider
×
1127
                            pkg_mode = mode
×
1128
                            break
×
1129
                        end
1130
                    end
×
1131
                    # TODO: Cache the `pkg_mode`?
1132
                    if pkg_mode !== nothing
×
1133
                        buf = copy(LineEdit.buffer(s))
×
1134
                        transition(s, pkg_mode) do
×
1135
                            LineEdit.state(s, pkg_mode).input_buffer = buf
1136
                        end
1137
                        return
×
1138
                    end
1139
                end
1140
            end
1141
            edit_insert(s, ']')
3✔
1142
        end,
1143

1144
        # Bracketed Paste Mode
1145
        "\e[200~" => (s::MIState,o...)->begin
8✔
1146
            input = LineEdit.bracketed_paste(s) # read directly from s until reaching the end-bracketed-paste marker
8✔
1147
            sbuffer = LineEdit.buffer(s)
8✔
1148
            curspos = position(sbuffer)
8✔
1149
            seek(sbuffer, 0)
8✔
1150
            shouldeval = (bytesavailable(sbuffer) == curspos && !occursin(UInt8('\n'), sbuffer))
8✔
1151
            seek(sbuffer, curspos)
8✔
1152
            if curspos == 0
8✔
1153
                # if pasting at the beginning, strip leading whitespace
1154
                input = lstrip(input)
7✔
1155
            end
1156
            if !shouldeval
8✔
1157
                # when pasting in the middle of input, just paste in place
1158
                # don't try to execute all the WIP, since that's rather confusing
1159
                # and is often ill-defined how it should behave
1160
                edit_insert(s, input)
×
1161
                return
×
1162
            end
1163
            LineEdit.push_undo(s)
8✔
1164
            edit_insert(sbuffer, input)
9✔
1165
            input = String(take!(sbuffer))
8✔
1166
            oldpos = firstindex(input)
×
1167
            firstline = true
×
1168
            isprompt_paste = false
×
1169
            curr_prompt_len = 0
×
1170
            pasting_help = false
×
1171

1172
            while oldpos <= lastindex(input) # loop until all lines have been executed
25✔
1173
                if JL_PROMPT_PASTE[]
24✔
1174
                    # Check if the next statement starts with a prompt i.e. "julia> ", in that case
1175
                    # skip it. But first skip whitespace unless pasting in a docstring which may have
1176
                    # indented prompt examples that we don't want to execute
1177
                    while input[oldpos] in (pasting_help ? ('\n') : ('\n', ' ', '\t'))
66✔
1178
                        oldpos = nextind(input, oldpos)
14✔
1179
                        oldpos >= sizeof(input) && return
14✔
1180
                    end
14✔
1181
                    substr = SubString(input, oldpos)
24✔
1182
                    # Check if input line starts with "julia> ", remove it if we are in prompt paste mode
1183
                    if (firstline || isprompt_paste) && startswith(substr, jl_prompt_regex)
24✔
1184
                        detected_jl_prompt = match(jl_prompt_regex, substr).match
22✔
1185
                        isprompt_paste = true
×
1186
                        curr_prompt_len = sizeof(detected_jl_prompt)
11✔
1187
                        oldpos += curr_prompt_len
11✔
1188
                        transition(s, julia_prompt)
11✔
1189
                        pasting_help = false
11✔
1190
                    # Check if input line starts with "pkg> " or "(...) pkg> ", remove it if we are in prompt paste mode and switch mode
1191
                    elseif (firstline || isprompt_paste) && startswith(substr, pkg_prompt_regex)
13✔
1192
                        detected_pkg_prompt = match(pkg_prompt_regex, substr).match
×
1193
                        isprompt_paste = true
×
1194
                        curr_prompt_len = sizeof(detected_pkg_prompt)
×
1195
                        oldpos += curr_prompt_len
×
1196
                        Base.active_repl.interface.modes[1].keymap_dict[']'](s, o...)
×
1197
                        pasting_help = false
×
1198
                    # Check if input line starts with "shell> ", remove it if we are in prompt paste mode and switch mode
1199
                    elseif (firstline || isprompt_paste) && startswith(substr, SHELL_PROMPT)
24✔
1200
                        isprompt_paste = true
×
1201
                        oldpos += shell_prompt_len
2✔
1202
                        curr_prompt_len = shell_prompt_len
2✔
1203
                        transition(s, shell_mode)
2✔
1204
                        pasting_help = false
2✔
1205
                    # Check if input line starts with "help?> ", remove it if we are in prompt paste mode and switch mode
1206
                    elseif (firstline || isprompt_paste) && startswith(substr, HELP_PROMPT)
20✔
1207
                        isprompt_paste = true
×
1208
                        oldpos += help_prompt_len
1✔
1209
                        curr_prompt_len = help_prompt_len
1✔
1210
                        transition(s, help_mode)
1✔
1211
                        pasting_help = true
1✔
1212
                    # If we are prompt pasting and current statement does not begin with a mode prefix, skip to next line
1213
                    elseif isprompt_paste
10✔
1214
                        while input[oldpos] != '\n'
316✔
1215
                            oldpos = nextind(input, oldpos)
151✔
1216
                            oldpos >= sizeof(input) && return
151✔
1217
                        end
149✔
1218
                        continue
7✔
1219
                    end
1220
                end
1221
                dump_tail = false
15✔
1222
                nl_pos = findfirst('\n', input[oldpos:end])
30✔
1223
                if s.current_mode == julia_prompt
15✔
1224
                    ast, pos = Meta.parse(input, oldpos, raise=false, depwarn=false)
12✔
1225
                    if (isa(ast, Expr) && (ast.head === :error || ast.head === :incomplete)) ||
22✔
1226
                            (pos > ncodeunits(input) && !endswith(input, '\n'))
1227
                        # remaining text is incomplete (an error, or parser ran to the end but didn't stop with a newline):
1228
                        # Insert all the remaining text as one line (might be empty)
1229
                        dump_tail = true
12✔
1230
                    end
1231
                elseif isnothing(nl_pos) # no newline at end, so just dump the tail into the prompt and don't execute
6✔
1232
                    dump_tail = true
×
1233
                elseif s.current_mode == shell_mode # handle multiline shell commands
3✔
1234
                    lines = split(input[oldpos:end], '\n')
4✔
1235
                    pos = oldpos + sizeof(lines[1]) + 1
2✔
1236
                    if length(lines) > 1
2✔
1237
                        for line in lines[2:end]
2✔
1238
                            # to be recognized as a multiline shell command, the lines must be indented to the
1239
                            # same prompt position
1240
                            if !startswith(line, ' '^curr_prompt_len)
5✔
1241
                                break
2✔
1242
                            end
1243
                            pos += sizeof(line) + 1
1✔
1244
                        end
3✔
1245
                    end
1246
                else
1247
                    pos = oldpos + nl_pos
1✔
1248
                end
1249
                if dump_tail
15✔
1250
                    tail = input[oldpos:end]
10✔
1251
                    if !firstline
5✔
1252
                        # strip leading whitespace, but only if it was the result of executing something
1253
                        # (avoids modifying the user's current leading wip line)
1254
                        tail = lstrip(tail)
1✔
1255
                    end
1256
                    if isprompt_paste # remove indentation spaces corresponding to the prompt
5✔
1257
                        tail = replace(tail, r"^"m * ' '^curr_prompt_len => "")
7✔
1258
                    end
1259
                    LineEdit.replace_line(s, tail, true)
10✔
1260
                    LineEdit.refresh_line(s)
5✔
1261
                    break
5✔
1262
                end
1263
                # get the line and strip leading and trailing whitespace
1264
                line = strip(input[oldpos:prevind(input, pos)])
20✔
1265
                if !isempty(line)
10✔
1266
                    if isprompt_paste # remove indentation spaces corresponding to the prompt
10✔
1267
                        line = replace(line, r"^"m * ' '^curr_prompt_len => "")
10✔
1268
                    end
1269
                    # put the line on the screen and history
1270
                    LineEdit.replace_line(s, line)
20✔
1271
                    LineEdit.commit_line(s)
10✔
1272
                    # execute the statement
1273
                    terminal = LineEdit.terminal(s) # This is slightly ugly but ok for now
10✔
1274
                    raw!(terminal, false) && disable_bracketed_paste(terminal)
10✔
1275
                    LineEdit.mode(s).on_done(s, LineEdit.buffer(s), true)
10✔
1276
                    raw!(terminal, true) && enable_bracketed_paste(terminal)
10✔
1277
                    LineEdit.push_undo(s) # when the last line is incomplete
10✔
1278
                end
1279
                oldpos = pos
10✔
1280
                firstline = false
×
1281
            end
23✔
1282
        end,
1283

1284
        # Open the editor at the location of a stackframe or method
1285
        # This is accessing a contextual variable that gets set in
1286
        # the show_backtrace and show_method_table functions.
1287
        "^Q" => (s::MIState, o...) -> begin
1288
            linfos = repl.last_shown_line_infos
1289
            str = String(take!(LineEdit.buffer(s)))
1290
            n = tryparse(Int, str)
1291
            n === nothing && @goto writeback
1292
            if n <= 0 || n > length(linfos) || startswith(linfos[n][1], "REPL[")
1293
                @goto writeback
1294
            end
1295
            try
1296
                InteractiveUtils.edit(Base.fixup_stdlib_path(linfos[n][1]), linfos[n][2])
1297
            catch ex
1298
                ex isa ProcessFailedException || ex isa Base.IOError || ex isa SystemError || rethrow()
1299
                @info "edit failed" _exception=ex
1300
            end
1301
            LineEdit.refresh_line(s)
1302
            return
1303
            @label writeback
1304
            write(LineEdit.buffer(s), str)
1305
            return
1306
        end,
1307
    )
1308

1309
    prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, julia_prompt)
23✔
1310

1311
    a = Dict{Any,Any}[skeymap, repl_keymap, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
138✔
1312
    prepend!(a, extra_repl_keymap)
23✔
1313

1314
    julia_prompt.keymap_dict = LineEdit.keymap(a)
23✔
1315

1316
    mk = mode_keymap(julia_prompt)
23✔
1317

1318
    b = Dict{Any,Any}[skeymap, mk, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
138✔
1319
    prepend!(b, extra_repl_keymap)
23✔
1320

1321
    shell_mode.keymap_dict = help_mode.keymap_dict = LineEdit.keymap(b)
23✔
1322

1323
    allprompts = LineEdit.TextInterface[julia_prompt, shell_mode, help_mode, search_prompt, prefix_prompt]
23✔
1324
    return ModalInterface(allprompts)
23✔
1325
end
1326

1327
function run_frontend(repl::LineEditREPL, backend::REPLBackendRef)
19✔
1328
    repl.frontend_task = current_task()
19✔
1329
    d = REPLDisplay(repl)
19✔
1330
    dopushdisplay = repl.specialdisplay === nothing && !in(d,Base.Multimedia.displays)
32✔
1331
    dopushdisplay && pushdisplay(d)
19✔
1332
    if !isdefined(repl,:interface)
19✔
1333
        interface = repl.interface = setup_interface(repl)
22✔
1334
    else
1335
        interface = repl.interface
8✔
1336
    end
1337
    repl.backendref = backend
19✔
1338
    repl.mistate = LineEdit.init_state(terminal(repl), interface)
19✔
1339
    run_interface(terminal(repl), interface, repl.mistate)
19✔
1340
    # Terminate Backend
1341
    put!(backend.repl_channel, (nothing, -1))
19✔
1342
    dopushdisplay && popdisplay(d)
19✔
1343
    nothing
19✔
1344
end
1345

1346
## StreamREPL ##
1347

1348
mutable struct StreamREPL <: AbstractREPL
1349
    stream::IO
1350
    prompt_color::String
1351
    input_color::String
1352
    answer_color::String
1353
    waserror::Bool
1354
    frontend_task::Task
1355
    StreamREPL(stream,pc,ic,ac) = new(stream,pc,ic,ac,false)
×
1356
end
1357
StreamREPL(stream::IO) = StreamREPL(stream, Base.text_colors[:green], Base.input_color(), Base.answer_color())
×
1358
run_repl(stream::IO) = run_repl(StreamREPL(stream))
×
1359

1360
outstream(s::StreamREPL) = s.stream
×
1361
hascolor(s::StreamREPL) = get(s.stream, :color, false)::Bool
×
1362

1363
answer_color(r::LineEditREPL) = r.envcolors ? Base.answer_color() : r.answer_color
×
1364
answer_color(r::StreamREPL) = r.answer_color
×
1365
input_color(r::LineEditREPL) = r.envcolors ? Base.input_color() : r.input_color
×
1366
input_color(r::StreamREPL) = r.input_color
×
1367

1368
let matchend = Dict("\"" => r"\"", "\"\"\"" => r"\"\"\"", "'" => r"'",
1369
    "`" => r"`", "```" => r"```", "#" => r"$"m, "#=" => r"=#|#=")
1370
    global _rm_strings_and_comments
1371
    function _rm_strings_and_comments(code::Union{String,SubString{String}})
122✔
1372
        buf = IOBuffer(sizehint = sizeof(code))
244✔
1373
        pos = 1
×
1374
        while true
161✔
1375
            i = findnext(r"\"(?!\"\")|\"\"\"|'|`(?!``)|```|#(?!=)|#=", code, pos)
322✔
1376
            isnothing(i) && break
206✔
1377
            match = SubString(code, i)
45✔
1378
            j = findnext(matchend[match]::Regex, code, nextind(code, last(i)))
90✔
1379
            if match == "#=" # possibly nested
85✔
1380
                nested = 1
×
1381
                while j !== nothing
11✔
1382
                    nested += SubString(code, j) == "#=" ? +1 : -1
10✔
1383
                    iszero(nested) && break
10✔
1384
                    j = findnext(r"=#|#=", code, nextind(code, last(j)))
12✔
1385
                end
11✔
1386
            elseif match[1] != '#' # quote match: check non-escaped
40✔
1387
                while j !== nothing
37✔
1388
                    notbackslash = findprev(!=('\\'), code, prevind(code, first(j)))::Int
64✔
1389
                    isodd(first(j) - notbackslash) && break # not escaped
32✔
1390
                    j = findnext(matchend[match]::Regex, code, nextind(code, first(j)))
14✔
1391
                end
7✔
1392
            end
1393
            isnothing(j) && break
84✔
1394
            if match[1] == '#'
39✔
1395
                print(buf, SubString(code, pos, prevind(code, first(i))))
14✔
1396
            else
1397
                print(buf, SubString(code, pos, last(i)), ' ', SubString(code, j))
25✔
1398
            end
1399
            pos = nextind(code, last(j))
78✔
1400
        end
39✔
1401
        print(buf, SubString(code, pos, lastindex(code)))
122✔
1402
        return String(take!(buf))
122✔
1403
    end
1404
end
1405

1406
# heuristic function to decide if the presence of a semicolon
1407
# at the end of the expression was intended for suppressing output
1408
ends_with_semicolon(code::AbstractString) = ends_with_semicolon(String(code))
×
1409
ends_with_semicolon(code::Union{String,SubString{String}}) =
122✔
1410
    contains(_rm_strings_and_comments(code), r";\s*$")
1411

1412
function run_frontend(repl::StreamREPL, backend::REPLBackendRef)
×
1413
    repl.frontend_task = current_task()
×
1414
    have_color = hascolor(repl)
×
1415
    Base.banner(repl.stream)
×
1416
    d = REPLDisplay(repl)
×
1417
    dopushdisplay = !in(d,Base.Multimedia.displays)
×
1418
    dopushdisplay && pushdisplay(d)
×
1419
    while !eof(repl.stream)::Bool
×
1420
        if have_color
×
1421
            print(repl.stream,repl.prompt_color)
×
1422
        end
1423
        print(repl.stream, "julia> ")
×
1424
        if have_color
×
1425
            print(repl.stream, input_color(repl))
×
1426
        end
1427
        line = readline(repl.stream, keep=true)
×
1428
        if !isempty(line)
×
1429
            ast = Base.parse_input_line(line)
×
1430
            if have_color
×
1431
                print(repl.stream, Base.color_normal)
×
1432
            end
1433
            response = eval_with_backend(ast, backend)
×
1434
            print_response(repl, response, !ends_with_semicolon(line), have_color)
×
1435
        end
1436
    end
×
1437
    # Terminate Backend
1438
    put!(backend.repl_channel, (nothing, -1))
×
1439
    dopushdisplay && popdisplay(d)
×
1440
    nothing
×
1441
end
1442

1443
module Numbered
1444

1445
using ..REPL
1446

1447
__current_ast_transforms() = isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1448

1449
function repl_eval_counter(hp)
813✔
1450
    return length(hp.history) - hp.start_idx
813✔
1451
end
1452

1453
function out_transform(@nospecialize(x), n::Ref{Int})
16✔
1454
    return Expr(:toplevel, get_usings!([], x)..., quote
16✔
1455
        let __temp_val_a72df459 = $x
1456
            $capture_result($n, __temp_val_a72df459)
1457
            __temp_val_a72df459
1458
        end
1459
    end)
1460
end
1461

1462
function get_usings!(usings, ex)
25✔
1463
    ex isa Expr || return usings
25✔
1464
    # get all `using` and `import` statements which are at the top level
1465
    for (i, arg) in enumerate(ex.args)
50✔
1466
        if Base.isexpr(arg, :toplevel)
73✔
1467
            get_usings!(usings, arg)
9✔
1468
        elseif Base.isexpr(arg, [:using, :import])
64✔
1469
            push!(usings, popat!(ex.args, i))
2✔
1470
        end
1471
    end
71✔
1472
    return usings
25✔
1473
end
1474

1475
function capture_result(n::Ref{Int}, @nospecialize(x))
16✔
1476
    n = n[]
16✔
1477
    mod = Base.MainInclude
16✔
1478
    if !isdefined(mod, :Out)
16✔
1479
        @eval mod global Out
1✔
1480
        @eval mod export Out
1✔
1481
        setglobal!(mod, :Out, Dict{Int, Any}())
1✔
1482
    end
1483
    if x !== getglobal(mod, :Out) && x !== nothing # remove this?
16✔
1484
        getglobal(mod, :Out)[n] = x
14✔
1485
    end
1486
    nothing
16✔
1487
end
1488

1489
function set_prompt(repl::LineEditREPL, n::Ref{Int})
1✔
1490
    julia_prompt = repl.interface.modes[1]
1✔
1491
    julia_prompt.prompt = function()
814✔
1492
        n[] = repl_eval_counter(julia_prompt.hist)+1
813✔
1493
        string("In [", n[], "]: ")
813✔
1494
    end
1495
    nothing
1✔
1496
end
1497

1498
function set_output_prefix(repl::LineEditREPL, n::Ref{Int})
1✔
1499
    julia_prompt = repl.interface.modes[1]
1✔
1500
    if REPL.hascolor(repl)
1✔
1501
        julia_prompt.output_prefix_prefix = Base.text_colors[:red]
1✔
1502
    end
1503
    julia_prompt.output_prefix = () -> string("Out[", n[], "]: ")
15✔
1504
    nothing
1✔
1505
end
1506

1507
function __current_ast_transforms(backend)
1✔
1508
    if backend === nothing
1✔
1509
        isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1510
    else
1511
        backend.ast_transforms
1✔
1512
    end
1513
end
1514

1515

1516
function numbered_prompt!(repl::LineEditREPL=Base.active_repl, backend=nothing)
1✔
1517
    n = Ref{Int}(0)
1✔
1518
    set_prompt(repl, n)
1✔
1519
    set_output_prefix(repl, n)
1✔
1520
    push!(__current_ast_transforms(backend), @nospecialize(ast) -> out_transform(ast, n))
17✔
1521
    return
1✔
1522
end
1523

1524
"""
1525
    Out[n]
1526

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

1530
See also [`ans`](@ref).
1531
"""
1532
Base.MainInclude.Out
1533

1534
end
1535

1536
import .Numbered.numbered_prompt!
1537

1538
# this assignment won't survive precompilation,
1539
# but will stick if REPL is baked into a sysimg.
1540
# Needs to occur after this module is finished.
1541
Base.REPL_MODULE_REF[] = REPL
1542

1543
if Base.generating_output()
1544
    include("precompile.jl")
1545
end
1546

1547
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