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

JuliaLang / julia / #37593

pending completion
#37593

push

local

web-flow
fix O(n^2) `length` calls in compact-ir lowering step (#50756)

This can be a problem for very long function bodies.

73982 of 84556 relevant lines covered (87.49%)

20204653.74 hits per line

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

82.28
/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}
30✔
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)) =
44✔
95
        new(repl_channel, response_channel, in_eval, ast_transforms)
96
end
97
REPLBackend() = REPLBackend(Channel(1), Channel(1), false)
22✔
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)
104✔
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)
104✔
169
    isa(ast, Expr) || return
104✔
170
    mods = modules_to_be_loaded(ast)
104✔
171
    filter!(mod -> isnothing(Base.identify_package(String(mod))), mods) # keep missing modules
106✔
172
    if !isempty(mods)
104✔
173
        for f in install_packages_hooks
×
174
            Base.invokelatest(f, mods) && return
×
175
        end
104✔
176
    end
177
end
178

179
function modules_to_be_loaded(ast::Expr, mods::Vector{Symbol} = Symbol[])
180✔
180
    ast.head === :quote && return mods # don't search if it's not going to be run during this eval
284✔
181
    if ast.head === :using || ast.head === :import
302✔
182
        for arg in ast.args
18✔
183
            arg = arg::Expr
22✔
184
            arg1 = first(arg.args)
22✔
185
            if arg1 isa Symbol # i.e. `Foo`
22✔
186
                if arg1 != :. # don't include local imports
19✔
187
                    push!(mods, arg1)
18✔
188
                end
189
            else # i.e. `Foo: bar`
190
                push!(mods, first((arg1::Expr).args))
3✔
191
            end
192
        end
40✔
193
    end
194
    for arg in ast.args
158✔
195
        if isexpr(arg, (:block, :if, :using, :import))
511✔
196
            modules_to_be_loaded(arg, mods)
32✔
197
        end
198
    end
494✔
199
    filter!(mod -> !in(String(mod), ["Base", "Main", "Core"]), mods) # Exclude special non-package modules
210✔
200
    return unique(mods)
158✔
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)
52✔
229
    backend.backend_task = Base.current_task()
22✔
230
    consumer(backend)
22✔
231
    repl_backend_loop(backend, get_module)
22✔
232
    return backend
21✔
233
end
234

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

251
struct REPLDisplay{Repl<:AbstractREPL} <: AbstractDisplay
252
    repl::Repl
31✔
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
61✔
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)
61✔
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}
20✔
352
    response_channel::Channel{Any}
353
end
354
REPLBackendRef(backend::REPLBackend) = REPLBackendRef(backend.repl_channel, backend.response_channel)
20✔
355

356
function destroy(ref::REPLBackendRef, state::Task)
19✔
357
    if istaskfailed(state)
19✔
358
        close(ref.repl_channel, TaskFailedException(state))
×
359
        close(ref.response_channel, TaskFailedException(state))
×
360
    end
361
    close(ref.repl_channel)
19✔
362
    close(ref.response_channel)
19✔
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())
78✔
374
    backend_ref = REPLBackendRef(backend)
20✔
375
    cleanup = @task try
39✔
376
            destroy(backend_ref, t)
19✔
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)
120✔
383
    if backend_on_current_task
20✔
384
        t = @async run_frontend(repl, backend_ref)
40✔
385
        errormonitor(t)
20✔
386
        Base._wait2(t, cleanup)
20✔
387
        start_repl_backend(backend, consumer; get_module)
20✔
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
19✔
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)
24✔
479
        opts = Options()
24✔
480
        opts.hascolor = hascolor
24✔
481
        if !hascolor
24✔
482
            opts.beep_colors = [""]
×
483
        end
484
        new(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell,
24✔
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
146✔
492
hascolor(r::LineEditREPL) = r.hascolor
195✔
493

494
LineEditREPL(t::TextTerminal, hascolor::Bool, envcolors::Bool=false) =
48✔
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
21✔
506
end
507
REPLCompletionProvider() = REPLCompletionProvider(LineEdit.Modifiers())
21✔
508

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

512
function active_module() # this method is also called from Base
66,245✔
513
    isdefined(Base, :active_repl) || return Main
132,490✔
514
    return active_module(Base.active_repl::AbstractREPL)
×
515
end
516
active_module((; mistate)::LineEditREPL) = mistate === nothing ? Main : mistate.active_module
3,751✔
517
active_module(::AbstractREPL) = Main
10✔
518
active_module(d::REPLDisplay) = active_module(d.repl)
119✔
519

520
setmodifiers!(c::REPLCompletionProvider, m::LineEdit.Modifiers) = c.modifiers = m
×
521

522
"""
523
    activate(mod::Module=Main)
524

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

536
beforecursor(buf::IOBuffer) = String(buf.data[1:buf.ptr-1])
35✔
537

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

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

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

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

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

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

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

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

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

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

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

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

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

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

711
    return :ok
78✔
712
end
713

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

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

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

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

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

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

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

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

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

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

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

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

863
    return false
4✔
864
end
865

866
function history_reset_state(hist::REPLHistoryProvider)
7✔
867
    if hist.cur_idx != length(hist.history) + 1
264✔
868
        hist.last_idx = hist.cur_idx
125✔
869
        hist.cur_idx = length(hist.history) + 1
125✔
870
    end
871
    nothing
264✔
872
end
873
LineEdit.reset_state(hist::REPLHistoryProvider) = history_reset_state(hist)
236✔
874

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

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

884
backend(r::AbstractREPL) = r.backendref
96✔
885

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

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

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

921
function prepare_next(repl::LineEditREPL)
112✔
922
    println(terminal(repl))
112✔
923
end
924

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

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

950
const JL_PROMPT_PASTE = Ref(true)
951
enable_promptpaste(v::Bool) = JL_PROMPT_PASTE[] = v
×
952

953
function contextual_prompt(repl::LineEditREPL, prompt::Union{String,Function})
×
954
    function ()
1,670✔
955
        mod = active_module(repl)
3,249✔
956
        prefix = mod == Main ? "" : string('(', mod, ") ")
1,656✔
957
        pr = prompt isa String ? prompt : prompt()
1,628✔
958
        prefix * pr
1,628✔
959
    end
960
end
961

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

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

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

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

1000
    ############################### Stage I ################################
1001

1002
    # This will provide completions for REPL and help mode
1003
    replc = REPLCompletionProvider()
21✔
1004

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

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

1026

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

1044

1045
    ################################# Stage II #############################
1046

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

1075
    julia_prompt.on_done = respond(x->Base.parse_input_line(x,filename=repl_filename(repl,hp)), repl, julia_prompt)
107✔
1076

1077

1078
    search_prompt, skeymap = LineEdit.setup_search_keymap(hp)
21✔
1079
    search_prompt.complete = LatexCompletions()
21✔
1080

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

1086
    # Canonicalize user keymap input
1087
    if isa(extra_repl_keymap, Dict)
21✔
1088
        extra_repl_keymap = AnyDict[extra_repl_keymap]
×
1089
    end
1090

1091
    repl_keymap = AnyDict(
21✔
1092
        ';' => function (s::MIState,o...)
53✔
1093
            if isempty(s) || position(LineEdit.buffer(s)) == 0
99✔
1094
                buf = copy(LineEdit.buffer(s))
7✔
1095
                transition(s, shell_mode) do
7✔
1096
                    LineEdit.state(s, shell_mode).input_buffer = buf
7✔
1097
                end
1098
            else
1099
                edit_insert(s, ';')
46✔
1100
            end
1101
        end,
1102
        '?' => function (s::MIState,o...)
1✔
1103
            if isempty(s) || position(LineEdit.buffer(s)) == 0
1✔
1104
                buf = copy(LineEdit.buffer(s))
1✔
1105
                transition(s, help_mode) do
1✔
1106
                    LineEdit.state(s, help_mode).input_buffer = buf
1✔
1107
                end
1108
            else
1109
                edit_insert(s, '?')
×
1110
            end
1111
        end,
1112

1113
        # Bracketed Paste Mode
1114
        "\e[200~" => (s::MIState,o...)->begin
8✔
1115
            input = LineEdit.bracketed_paste(s) # read directly from s until reaching the end-bracketed-paste marker
8✔
1116
            sbuffer = LineEdit.buffer(s)
8✔
1117
            curspos = position(sbuffer)
8✔
1118
            seek(sbuffer, 0)
8✔
1119
            shouldeval = (bytesavailable(sbuffer) == curspos && !occursin(UInt8('\n'), sbuffer))
8✔
1120
            seek(sbuffer, curspos)
8✔
1121
            if curspos == 0
8✔
1122
                # if pasting at the beginning, strip leading whitespace
1123
                input = lstrip(input)
7✔
1124
            end
1125
            if !shouldeval
8✔
1126
                # when pasting in the middle of input, just paste in place
1127
                # don't try to execute all the WIP, since that's rather confusing
1128
                # and is often ill-defined how it should behave
1129
                edit_insert(s, input)
×
1130
                return
×
1131
            end
1132
            LineEdit.push_undo(s)
8✔
1133
            edit_insert(sbuffer, input)
9✔
1134
            input = String(take!(sbuffer))
8✔
1135
            oldpos = firstindex(input)
×
1136
            firstline = true
×
1137
            isprompt_paste = false
×
1138
            curr_prompt_len = 0
×
1139
            pasting_help = false
×
1140

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

1253
        # Open the editor at the location of a stackframe or method
1254
        # This is accessing a contextual variable that gets set in
1255
        # the show_backtrace and show_method_table functions.
1256
        "^Q" => (s::MIState, o...) -> begin
1257
            linfos = repl.last_shown_line_infos
1258
            str = String(take!(LineEdit.buffer(s)))
1259
            n = tryparse(Int, str)
1260
            n === nothing && @goto writeback
1261
            if n <= 0 || n > length(linfos) || startswith(linfos[n][1], "REPL[")
1262
                @goto writeback
1263
            end
1264
            try
1265
                InteractiveUtils.edit(Base.fixup_stdlib_path(linfos[n][1]), linfos[n][2])
1266
            catch ex
1267
                ex isa ProcessFailedException || ex isa Base.IOError || ex isa SystemError || rethrow()
1268
                @info "edit failed" _exception=ex
1269
            end
1270
            LineEdit.refresh_line(s)
1271
            return
1272
            @label writeback
1273
            write(LineEdit.buffer(s), str)
1274
            return
1275
        end,
1276
    )
1277

1278
    prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, julia_prompt)
21✔
1279

1280
    a = Dict{Any,Any}[skeymap, repl_keymap, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
126✔
1281
    prepend!(a, extra_repl_keymap)
21✔
1282

1283
    julia_prompt.keymap_dict = LineEdit.keymap(a)
21✔
1284

1285
    mk = mode_keymap(julia_prompt)
21✔
1286

1287
    b = Dict{Any,Any}[skeymap, mk, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
126✔
1288
    prepend!(b, extra_repl_keymap)
21✔
1289

1290
    shell_mode.keymap_dict = help_mode.keymap_dict = LineEdit.keymap(b)
21✔
1291

1292
    allprompts = LineEdit.TextInterface[julia_prompt, shell_mode, help_mode, search_prompt, prefix_prompt]
21✔
1293
    return ModalInterface(allprompts)
21✔
1294
end
1295

1296
function run_frontend(repl::LineEditREPL, backend::REPLBackendRef)
17✔
1297
    repl.frontend_task = current_task()
17✔
1298
    d = REPLDisplay(repl)
17✔
1299
    dopushdisplay = repl.specialdisplay === nothing && !in(d,Base.Multimedia.displays)
28✔
1300
    dopushdisplay && pushdisplay(d)
17✔
1301
    if !isdefined(repl,:interface)
17✔
1302
        interface = repl.interface = setup_interface(repl)
18✔
1303
    else
1304
        interface = repl.interface
8✔
1305
    end
1306
    repl.backendref = backend
17✔
1307
    repl.mistate = LineEdit.init_state(terminal(repl), interface)
17✔
1308
    run_interface(terminal(repl), interface, repl.mistate)
17✔
1309
    # Terminate Backend
1310
    put!(backend.repl_channel, (nothing, -1))
17✔
1311
    dopushdisplay && popdisplay(d)
17✔
1312
    nothing
17✔
1313
end
1314

1315
## StreamREPL ##
1316

1317
mutable struct StreamREPL <: AbstractREPL
1318
    stream::IO
1319
    prompt_color::String
1320
    input_color::String
1321
    answer_color::String
1322
    waserror::Bool
1323
    frontend_task::Task
1324
    StreamREPL(stream,pc,ic,ac) = new(stream,pc,ic,ac,false)
×
1325
end
1326
StreamREPL(stream::IO) = StreamREPL(stream, Base.text_colors[:green], Base.input_color(), Base.answer_color())
×
1327
run_repl(stream::IO) = run_repl(StreamREPL(stream))
×
1328

1329
outstream(s::StreamREPL) = s.stream
×
1330
hascolor(s::StreamREPL) = get(s.stream, :color, false)::Bool
×
1331

1332
answer_color(r::LineEditREPL) = r.envcolors ? Base.answer_color() : r.answer_color
×
1333
answer_color(r::StreamREPL) = r.answer_color
×
1334
input_color(r::LineEditREPL) = r.envcolors ? Base.input_color() : r.input_color
×
1335
input_color(r::StreamREPL) = r.input_color
×
1336

1337
let matchend = Dict("\"" => r"\"", "\"\"\"" => r"\"\"\"", "'" => r"'",
1338
    "`" => r"`", "```" => r"```", "#" => r"$"m, "#=" => r"=#|#=")
1339
    global _rm_strings_and_comments
1340
    function _rm_strings_and_comments(code::Union{String,SubString{String}})
122✔
1341
        buf = IOBuffer(sizehint = sizeof(code))
244✔
1342
        pos = 1
×
1343
        while true
161✔
1344
            i = findnext(r"\"(?!\"\")|\"\"\"|'|`(?!``)|```|#(?!=)|#=", code, pos)
322✔
1345
            isnothing(i) && break
206✔
1346
            match = SubString(code, i)
45✔
1347
            j = findnext(matchend[match]::Regex, code, nextind(code, last(i)))
90✔
1348
            if match == "#=" # possibly nested
85✔
1349
                nested = 1
×
1350
                while j !== nothing
11✔
1351
                    nested += SubString(code, j) == "#=" ? +1 : -1
10✔
1352
                    iszero(nested) && break
10✔
1353
                    j = findnext(r"=#|#=", code, nextind(code, last(j)))
12✔
1354
                end
11✔
1355
            elseif match[1] != '#' # quote match: check non-escaped
40✔
1356
                while j !== nothing
37✔
1357
                    notbackslash = findprev(!=('\\'), code, prevind(code, first(j)))::Int
64✔
1358
                    isodd(first(j) - notbackslash) && break # not escaped
32✔
1359
                    j = findnext(matchend[match]::Regex, code, nextind(code, first(j)))
14✔
1360
                end
7✔
1361
            end
1362
            isnothing(j) && break
84✔
1363
            if match[1] == '#'
39✔
1364
                print(buf, SubString(code, pos, prevind(code, first(i))))
14✔
1365
            else
1366
                print(buf, SubString(code, pos, last(i)), ' ', SubString(code, j))
25✔
1367
            end
1368
            pos = nextind(code, last(j))
78✔
1369
        end
39✔
1370
        print(buf, SubString(code, pos, lastindex(code)))
122✔
1371
        return String(take!(buf))
122✔
1372
    end
1373
end
1374

1375
# heuristic function to decide if the presence of a semicolon
1376
# at the end of the expression was intended for suppressing output
1377
ends_with_semicolon(code::AbstractString) = ends_with_semicolon(String(code))
×
1378
ends_with_semicolon(code::Union{String,SubString{String}}) =
122✔
1379
    contains(_rm_strings_and_comments(code), r";\s*$")
1380

1381
function run_frontend(repl::StreamREPL, backend::REPLBackendRef)
×
1382
    repl.frontend_task = current_task()
×
1383
    have_color = hascolor(repl)
×
1384
    Base.banner(repl.stream)
×
1385
    d = REPLDisplay(repl)
×
1386
    dopushdisplay = !in(d,Base.Multimedia.displays)
×
1387
    dopushdisplay && pushdisplay(d)
×
1388
    while !eof(repl.stream)::Bool
×
1389
        if have_color
×
1390
            print(repl.stream,repl.prompt_color)
×
1391
        end
1392
        print(repl.stream, "julia> ")
×
1393
        if have_color
×
1394
            print(repl.stream, input_color(repl))
×
1395
        end
1396
        line = readline(repl.stream, keep=true)
×
1397
        if !isempty(line)
×
1398
            ast = Base.parse_input_line(line)
×
1399
            if have_color
×
1400
                print(repl.stream, Base.color_normal)
×
1401
            end
1402
            response = eval_with_backend(ast, backend)
×
1403
            print_response(repl, response, !ends_with_semicolon(line), have_color)
×
1404
        end
1405
    end
×
1406
    # Terminate Backend
1407
    put!(backend.repl_channel, (nothing, -1))
×
1408
    dopushdisplay && popdisplay(d)
×
1409
    nothing
×
1410
end
1411

1412
module Numbered
1413

1414
using ..REPL
1415

1416
__current_ast_transforms() = isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1417

1418
function repl_eval_counter(hp)
567✔
1419
    return length(hp.history) - hp.start_idx
567✔
1420
end
1421

1422
function out_transform(@nospecialize(x), n::Ref{Int})
16✔
1423
    return Expr(:toplevel, get_usings!([], x)..., quote
16✔
1424
        let __temp_val_a72df459 = $x
1425
            $capture_result($n, __temp_val_a72df459)
1426
            __temp_val_a72df459
1427
        end
1428
    end)
1429
end
1430

1431
function get_usings!(usings, ex)
25✔
1432
    ex isa Expr || return usings
25✔
1433
    # get all `using` and `import` statements which are at the top level
1434
    for (i, arg) in enumerate(ex.args)
50✔
1435
        if Base.isexpr(arg, :toplevel)
73✔
1436
            get_usings!(usings, arg)
9✔
1437
        elseif Base.isexpr(arg, [:using, :import])
64✔
1438
            push!(usings, popat!(ex.args, i))
2✔
1439
        end
1440
    end
71✔
1441
    return usings
25✔
1442
end
1443

1444
function capture_result(n::Ref{Int}, @nospecialize(x))
16✔
1445
    n = n[]
16✔
1446
    mod = Base.MainInclude
16✔
1447
    if !isdefined(mod, :Out)
16✔
1448
        @eval mod global Out
1✔
1449
        @eval mod export Out
1✔
1450
        setglobal!(mod, :Out, Dict{Int, Any}())
1✔
1451
    end
1452
    if x !== getglobal(mod, :Out) && x !== nothing # remove this?
16✔
1453
        getglobal(mod, :Out)[n] = x
14✔
1454
    end
1455
    nothing
16✔
1456
end
1457

1458
function set_prompt(repl::LineEditREPL, n::Ref{Int})
1✔
1459
    julia_prompt = repl.interface.modes[1]
1✔
1460
    julia_prompt.prompt = function()
568✔
1461
        n[] = repl_eval_counter(julia_prompt.hist)+1
567✔
1462
        string("In [", n[], "]: ")
567✔
1463
    end
1464
    nothing
1✔
1465
end
1466

1467
function set_output_prefix(repl::LineEditREPL, n::Ref{Int})
1✔
1468
    julia_prompt = repl.interface.modes[1]
1✔
1469
    if REPL.hascolor(repl)
1✔
1470
        julia_prompt.output_prefix_prefix = Base.text_colors[:red]
1✔
1471
    end
1472
    julia_prompt.output_prefix = () -> string("Out[", n[], "]: ")
15✔
1473
    nothing
1✔
1474
end
1475

1476
function __current_ast_transforms(backend)
1✔
1477
    if backend === nothing
1✔
1478
        isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1479
    else
1480
        backend.ast_transforms
1✔
1481
    end
1482
end
1483

1484

1485
function numbered_prompt!(repl::LineEditREPL=Base.active_repl, backend=nothing)
1✔
1486
    n = Ref{Int}(0)
1✔
1487
    set_prompt(repl, n)
1✔
1488
    set_output_prefix(repl, n)
1✔
1489
    push!(__current_ast_transforms(backend), @nospecialize(ast) -> out_transform(ast, n))
17✔
1490
    return
1✔
1491
end
1492

1493
"""
1494
    Out[n]
1495

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

1499
See also [`ans`](@ref).
1500
"""
1501
Base.MainInclude.Out
1502

1503
end
1504

1505
import .Numbered.numbered_prompt!
1506

1507
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

© 2026 Coveralls, Inc