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

JuliaLang / julia / #37627

21 Sep 2023 02:42AM UTC coverage: 85.841% (-0.1%) from 85.948%
#37627

push

local

web-flow
move Pkg out of the sysimage (take 2) (#51189)

Co-authored-by: Jonas Schulze <jonas.schulze@st.ovgu.de>
Co-authored-by: Valentin Churavy <vchuravy@users.noreply.github.com>
Co-authored-by: Tim Besard <tim.besard@gmail.com>

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

72249 of 84166 relevant lines covered (85.84%)

12728069.66 hits per line

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

80.53
/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
using Base.Meta, Sockets
21
import InteractiveUtils
22

23
export
24
    AbstractREPL,
25
    BasicREPL,
26
    LineEditREPL,
27
    StreamREPL
28

29
import Base:
30
    AbstractDisplay,
31
    display,
32
    show,
33
    AnyDict,
34
    ==
35

36
_displaysize(io::IO) = displaysize(io)::Tuple{Int,Int}
29✔
37

38
include("Terminals.jl")
39
using .Terminals
40

41
abstract type AbstractREPL end
42

43
include("options.jl")
44

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

67
include("REPLCompletions.jl")
68
using .REPLCompletions
69

70
include("TerminalMenus/TerminalMenus.jl")
71
include("docview.jl")
72

73
@nospecialize # use only declared type signatures
74

75
answer_color(::AbstractREPL) = ""
×
76

77
const JULIA_PROMPT = "julia> "
78
const PKG_PROMPT = "pkg> "
79
const SHELL_PROMPT = "shell> "
80
const HELP_PROMPT = "help?> "
81

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

94
    REPLBackend(repl_channel, response_channel, in_eval, ast_transforms=copy(repl_ast_transforms)) =
48✔
95
        new(repl_channel, response_channel, in_eval, ast_transforms)
96
end
97
REPLBackend() = REPLBackend(Channel(1), Channel(1), false)
24✔
98

99
"""
100
    softscope(ex)
101

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

123
# Temporary alias until Documenter updates
124
const softscope! = softscope
125

126
const repl_ast_transforms = Any[softscope] # defaults for new REPL backends
127

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

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

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

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

203
"""
204
    start_repl_backend(repl_channel::Channel, response_channel::Channel)
205

206
    Starts loop for REPL backend
207
    Returns a REPLBackend with backend_task assigned
208

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

220
"""
221
    start_repl_backend(backend::REPLBackend)
222

223
    Call directly to run backend loop on current Task.
224
    Use @async for run backend on new Task.
225

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

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

251
struct REPLDisplay{Repl<:AbstractREPL} <: AbstractDisplay
252
    repl::Repl
33✔
253
end
254

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

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

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

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

349
# A reference to a backend that is not mutable
350
struct REPLBackendRef
351
    repl_channel::Channel{Any}
22✔
352
    response_channel::Channel{Any}
353
end
354
REPLBackendRef(backend::REPLBackend) = REPLBackendRef(backend.repl_channel, backend.response_channel)
22✔
355

356
function destroy(ref::REPLBackendRef, state::Task)
21✔
357
    if istaskfailed(state)
21✔
358
        close(ref.repl_channel, TaskFailedException(state))
×
359
        close(ref.response_channel, TaskFailedException(state))
×
360
    end
361
    close(ref.repl_channel)
21✔
362
    close(ref.response_channel)
21✔
363
end
364

365
"""
366
    run_repl(repl::AbstractREPL)
367
    run_repl(repl, consumer = backend->nothing; backend_on_current_task = true)
368

369
    Main function to start the REPL
370

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

397
## BasicREPL ##
398

399
mutable struct BasicREPL <: AbstractREPL
400
    terminal::TextTerminal
401
    waserror::Bool
402
    frontend_task::Task
403
    BasicREPL(t) = new(t, false)
3✔
404
end
405

406
outstream(r::BasicREPL) = r.terminal
6✔
407
hascolor(r::BasicREPL) = hascolor(r.terminal)
×
408

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

456
## LineEditREPL ##
457

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

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

504
mutable struct REPLCompletionProvider <: CompletionProvider
505
    modifiers::LineEdit.Modifiers
23✔
506
end
507
REPLCompletionProvider() = REPLCompletionProvider(LineEdit.Modifiers())
23✔
508

509
mutable struct ShellCompletionProvider <: CompletionProvider end
23✔
510
struct LatexCompletions <: CompletionProvider end
511

512
function active_module() # this method is also called from Base
55,180✔
513
    isdefined(Base, :active_repl) || return Main
110,360✔
514
    return active_module(Base.active_repl::AbstractREPL)
×
515
end
516
active_module((; mistate)::LineEditREPL) = mistate === nothing ? Main : mistate.active_module
4,641✔
517
active_module(::AbstractREPL) = Main
10✔
518
active_module(d::REPLDisplay) = active_module(d.repl)
119✔
519

520
setmodifiers!(c::CompletionProvider, m::LineEdit.Modifiers) = nothing
×
521

522
setmodifiers!(c::REPLCompletionProvider, m::LineEdit.Modifiers) = c.modifiers = m
×
523

524
"""
525
    activate(mod::Module=Main)
526

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

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

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

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

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

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

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

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

596
munged_history_message(path::String) = """
×
597
Invalid history file ($path) format:
598
An editor may have converted tabs to spaces at line """
599

600
function hist_open_file(hp::REPLHistoryProvider)
×
601
    f = open(hp.file_path, read=true, write=true, create=true)
4✔
602
    hp.history_file = f
4✔
603
    seekend(f)
4✔
604
end
605

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

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

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

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

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

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

713
    return :ok
78✔
714
end
715

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

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

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

767
history_first(s::LineEdit.MIState, hist::REPLHistoryProvider) =
6✔
768
    history_prev(s, hist, hist.cur_idx - 1 -
769
                 (hist.cur_idx > hist.start_idx+1 ? hist.start_idx : 0))
770

771
history_last(s::LineEdit.MIState, hist::REPLHistoryProvider) =
4✔
772
    history_next(s, hist, length(hist.history) - hist.cur_idx + 1)
773

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

815
function history_search(hist::REPLHistoryProvider, query_buffer::IOBuffer, response_buffer::IOBuffer,
28✔
816
                        backwards::Bool=false, skip_current::Bool=false)
817

818
    qpos = position(query_buffer)
28✔
819
    qpos > 0 || return true
28✔
820
    searchdata = beforecursor(query_buffer)
28✔
821
    response_str = String(take!(copy(response_buffer)))
28✔
822

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

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

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

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

865
    return false
4✔
866
end
867

868
function history_reset_state(hist::REPLHistoryProvider)
7✔
869
    if hist.cur_idx != length(hist.history) + 1
266✔
870
        hist.last_idx = hist.cur_idx
127✔
871
        hist.cur_idx = length(hist.history) + 1
127✔
872
    end
873
    nothing
266✔
874
end
875
LineEdit.reset_state(hist::REPLHistoryProvider) = history_reset_state(hist)
236✔
876

877
function return_callback(s)
94✔
878
    ast = Base.parse_input_line(String(take!(copy(LineEdit.buffer(s)))), depwarn=false)
94✔
879
    return !(isa(ast, Expr) && ast.head === :incomplete)
94✔
880
end
881

882
find_hist_file() = get(ENV, "JULIA_HISTORY",
8✔
883
                       !isempty(DEPOT_PATH) ? joinpath(DEPOT_PATH[1], "logs", "repl_history.jl") :
884
                       error("DEPOT_PATH is empty and and ENV[\"JULIA_HISTORY\"] not set."))
885

886
backend(r::AbstractREPL) = r.backendref
96✔
887

888
function eval_with_backend(ast, backend::REPLBackendRef)
100✔
889
    put!(backend.repl_channel, (ast, 1))
100✔
890
    return take!(backend.response_channel) # (val, iserr)
100✔
891
end
892

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

917
function reset(repl::LineEditREPL)
97✔
918
    raw!(repl.t, false)
97✔
919
    hascolor(repl) && print(repl.t, Base.text_colors[:normal])
97✔
920
    nothing
97✔
921
end
922

923
function prepare_next(repl::LineEditREPL)
112✔
924
    println(terminal(repl))
112✔
925
end
926

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

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

952
const JL_PROMPT_PASTE = Ref(true)
953
enable_promptpaste(v::Bool) = JL_PROMPT_PASTE[] = v
×
954

955
function contextual_prompt(repl::LineEditREPL, prompt::Union{String,Function})
×
956
    function ()
2,119✔
957
        mod = active_module(repl)
4,139✔
958
        prefix = mod == Main ? "" : string('(', mod, ") ")
2,105✔
959
        pr = prompt isa String ? prompt : prompt()
2,073✔
960
        prefix * pr
2,073✔
961
    end
962
end
963

964
setup_interface(
×
965
    repl::LineEditREPL;
966
    # those keyword arguments may be deprecated eventually in favor of the Options mechanism
967
    hascolor::Bool = repl.options.hascolor,
968
    extra_repl_keymap::Any = repl.options.extra_keymap
969
) = setup_interface(repl, hascolor, extra_repl_keymap)
65✔
970

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

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

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

1002
    ############################### Stage I ################################
1003

1004
    # This will provide completions for REPL and help mode
1005
    replc = REPLCompletionProvider()
23✔
1006

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

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

1028

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

1046

1047
    ################################# Stage II #############################
1048

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

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

1079

1080
    search_prompt, skeymap = LineEdit.setup_search_keymap(hp)
23✔
1081
    search_prompt.complete = LatexCompletions()
23✔
1082

1083
    shell_prompt_len = length(SHELL_PROMPT)
×
1084
    help_prompt_len = length(HELP_PROMPT)
×
1085
    jl_prompt_regex = r"^In \[[0-9]+\]: |^(?:\(.+\) )?julia> "
×
1086
    pkg_prompt_regex = r"^(?:\(.+\) )?pkg> "
×
1087

1088
    # Canonicalize user keymap input
1089
    if isa(extra_repl_keymap, Dict)
23✔
1090
        extra_repl_keymap = AnyDict[extra_repl_keymap]
×
1091
    end
1092

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

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

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

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

1305
    prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, julia_prompt)
23✔
1306

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

1310
    julia_prompt.keymap_dict = LineEdit.keymap(a)
23✔
1311

1312
    mk = mode_keymap(julia_prompt)
23✔
1313

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

1317
    shell_mode.keymap_dict = help_mode.keymap_dict = LineEdit.keymap(b)
23✔
1318

1319
    allprompts = LineEdit.TextInterface[julia_prompt, shell_mode, help_mode, search_prompt, prefix_prompt]
23✔
1320
    return ModalInterface(allprompts)
23✔
1321
end
1322

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

1342
## StreamREPL ##
1343

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

1356
outstream(s::StreamREPL) = s.stream
×
1357
hascolor(s::StreamREPL) = get(s.stream, :color, false)::Bool
×
1358

1359
answer_color(r::LineEditREPL) = r.envcolors ? Base.answer_color() : r.answer_color
×
1360
answer_color(r::StreamREPL) = r.answer_color
×
1361
input_color(r::LineEditREPL) = r.envcolors ? Base.input_color() : r.input_color
×
1362
input_color(r::StreamREPL) = r.input_color
×
1363

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

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

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

1439
module Numbered
1440

1441
using ..REPL
1442

1443
__current_ast_transforms() = isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1444

1445
function repl_eval_counter(hp)
805✔
1446
    return length(hp.history) - hp.start_idx
805✔
1447
end
1448

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

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

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

1485
function set_prompt(repl::LineEditREPL, n::Ref{Int})
1✔
1486
    julia_prompt = repl.interface.modes[1]
1✔
1487
    julia_prompt.prompt = function()
806✔
1488
        n[] = repl_eval_counter(julia_prompt.hist)+1
805✔
1489
        string("In [", n[], "]: ")
805✔
1490
    end
1491
    nothing
1✔
1492
end
1493

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

1503
function __current_ast_transforms(backend)
1✔
1504
    if backend === nothing
1✔
1505
        isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1506
    else
1507
        backend.ast_transforms
1✔
1508
    end
1509
end
1510

1511

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

1520
"""
1521
    Out[n]
1522

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

1526
See also [`ans`](@ref).
1527
"""
1528
Base.MainInclude.Out
1529

1530
end
1531

1532
import .Numbered.numbered_prompt!
1533

1534
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