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

JuliaLang / julia / #37489

pending completion
#37489

push

local

web-flow
fix `obviously_disjoint` for Union Types (#49177)

70007 of 82924 relevant lines covered (84.42%)

33257777.23 hits per line

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

82.18
/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)) =
42✔
95
        new(repl_channel, response_channel, in_eval, ast_transforms)
96
end
97
REPLBackend() = REPLBackend(Channel(1), Channel(1), false)
21✔
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)
342✔
106
    if ex isa Expr
342✔
107
        h = ex.head
219✔
108
        if h === :toplevel
219✔
109
            ex′ = Expr(h)
124✔
110
            map!(softscope, resize!(ex′.args, length(ex.args)), ex.args)
124✔
111
            return ex′
124✔
112
        elseif h in (:meta, :import, :using, :export, :module, :error, :incomplete, :thunk)
95✔
113
            return ex
2✔
114
        elseif h === :global && all(x->isa(x, Symbol), ex.args)
95✔
115
            return ex
1✔
116
        else
117
            return Expr(:block, Expr(:softscope, true), ex)
92✔
118
        end
119
    end
120
    return ex
123✔
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)
100✔
135
    lasterr = nothing
×
136
    Base.sigatomic_begin()
100✔
137
    while true
102✔
138
        try
102✔
139
            Base.sigatomic_end()
102✔
140
            if lasterr !== nothing
102✔
141
                put!(backend.response_channel, Pair{Any, Bool}(lasterr, true))
2✔
142
            else
143
                backend.in_eval = true
100✔
144
                if !isempty(install_packages_hooks)
100✔
145
                    check_for_missing_packages_and_run_hooks(ast)
100✔
146
                end
147
                for xf in backend.ast_transforms
100✔
148
                    ast = Base.invokelatest(xf, ast)
116✔
149
                end
216✔
150
                value = Core.eval(mod, ast)
100✔
151
                backend.in_eval = false
97✔
152
                setglobal!(Base.MainInclude, :ans, value)
97✔
153
                put!(backend.response_channel, Pair{Any, Bool}(value, false))
97✔
154
            end
155
            break
101✔
156
        catch err
157
            if lasterr !== nothing
2✔
158
                println("SYSTEM ERROR: Failed to report error to REPL frontend")
×
159
                println(err)
×
160
            end
161
            lasterr = current_exceptions()
2✔
162
        end
163
    end
2✔
164
    Base.sigatomic_end()
99✔
165
    nothing
99✔
166
end
167

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

179
function modules_to_be_loaded(ast::Expr, mods::Vector{Symbol} = Symbol[])
173✔
180
    ast.head === :quote && return mods # don't search if it's not going to be run during this eval
270✔
181
    if ast.head === :using || ast.head === :import
288✔
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
151✔
195
        if isexpr(arg, (:block, :if, :using, :import))
493✔
196
            modules_to_be_loaded(arg, mods)
32✔
197
        end
198
    end
477✔
199
    filter!(mod -> !in(String(mod), ["Base", "Main", "Core"]), mods) # Exclude special non-package modules
203✔
200
    return unique(mods)
151✔
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)
50✔
229
    backend.backend_task = Base.current_task()
21✔
230
    consumer(backend)
21✔
231
    repl_backend_loop(backend, get_module)
21✔
232
    return backend
20✔
233
end
234

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

251
struct REPLDisplay{R<:AbstractREPL} <: AbstractDisplay
252
    repl::R
30✔
253
end
254

255
==(a::REPLDisplay, b::REPLDisplay) = a.repl === b.repl
13✔
256

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

278
function print_response(repl::AbstractREPL, response, show_value::Bool, have_color::Bool)
96✔
279
    repl.waserror = response[2]
96✔
280
    with_repl_linfo(repl) do io
96✔
281
        io = IOContext(io, :module => active_module(repl)::Module)
189✔
282
        print_response(io, response, show_value, have_color, specialdisplay(repl))
96✔
283
    end
284
    return nothing
96✔
285
end
286
function print_response(errio::IO, response, show_value::Bool, have_color::Bool, specialdisplay::Union{AbstractDisplay,Nothing}=nothing)
97✔
287
    Base.sigatomic_begin()
97✔
288
    val, iserr = response
97✔
289
    while true
98✔
290
        try
98✔
291
            Base.sigatomic_end()
98✔
292
            if iserr
98✔
293
                val = Base.scrub_repl_backtrace(val)
5✔
294
                Base.istrivialerror(val) || setglobal!(Base.MainInclude, :err, val)
8✔
295
                Base.invokelatest(Base.display_error, errio, val)
5✔
296
            else
297
                if val !== nothing && show_value
93✔
298
                    try
59✔
299
                        if specialdisplay === nothing
59✔
300
                            Base.invokelatest(display, val)
45✔
301
                        else
302
                            Base.invokelatest(display, specialdisplay, val)
58✔
303
                        end
304
                    catch
305
                        println(errio, "Error showing value of type ", typeof(val), ":")
1✔
306
                        rethrow()
1✔
307
                    end
308
                end
309
            end
310
            break
98✔
311
        catch ex
312
            if iserr
2✔
313
                println(errio) # an error during printing is likely to leave us mid-line
1✔
314
                println(errio, "SYSTEM (REPL): showing an error caused an error")
1✔
315
                try
1✔
316
                    excs = Base.scrub_repl_backtrace(current_exceptions())
1✔
317
                    setglobal!(Base.MainInclude, :err, excs)
1✔
318
                    Base.invokelatest(Base.display_error, errio, excs)
2✔
319
                catch e
320
                    # at this point, only print the name of the type as a Symbol to
321
                    # minimize the possibility of further errors.
322
                    println(errio)
1✔
323
                    println(errio, "SYSTEM (REPL): caught exception of type ", typeof(e).name.name,
1✔
324
                            " while trying to handle a nested exception; giving up")
325
                end
326
                break
1✔
327
            end
328
            val = current_exceptions()
1✔
329
            iserr = true
1✔
330
        end
331
    end
1✔
332
    Base.sigatomic_end()
97✔
333
    nothing
97✔
334
end
335

336
# A reference to a backend that is not mutable
337
struct REPLBackendRef
338
    repl_channel::Channel{Any}
19✔
339
    response_channel::Channel{Any}
340
end
341
REPLBackendRef(backend::REPLBackend) = REPLBackendRef(backend.repl_channel, backend.response_channel)
19✔
342

343
function destroy(ref::REPLBackendRef, state::Task)
18✔
344
    if istaskfailed(state)
18✔
345
        close(ref.repl_channel, TaskFailedException(state))
×
346
        close(ref.response_channel, TaskFailedException(state))
×
347
    end
348
    close(ref.repl_channel)
18✔
349
    close(ref.response_channel)
18✔
350
end
351

352
"""
353
    run_repl(repl::AbstractREPL)
354
    run_repl(repl, consumer = backend->nothing; backend_on_current_task = true)
355

356
    Main function to start the REPL
357

358
    consumer is an optional function that takes a REPLBackend as an argument
359
"""
360
function run_repl(repl::AbstractREPL, @nospecialize(consumer = x -> nothing); backend_on_current_task::Bool = true, backend = REPLBackend())
74✔
361
    backend_ref = REPLBackendRef(backend)
19✔
362
    cleanup = @task try
19✔
363
            destroy(backend_ref, t)
18✔
364
        catch e
365
            Core.print(Core.stderr, "\nINTERNAL ERROR: ")
×
366
            Core.println(Core.stderr, e)
×
367
            Core.println(Core.stderr, catch_backtrace())
×
368
        end
369
    get_module = () -> active_module(repl)
115✔
370
    if backend_on_current_task
19✔
371
        t = @async run_frontend(repl, backend_ref)
19✔
372
        errormonitor(t)
19✔
373
        Base._wait2(t, cleanup)
19✔
374
        start_repl_backend(backend, consumer; get_module)
19✔
375
    else
376
        t = @async start_repl_backend(backend, consumer; get_module)
×
377
        errormonitor(t)
×
378
        Base._wait2(t, cleanup)
×
379
        run_frontend(repl, backend_ref)
×
380
    end
381
    return backend
18✔
382
end
383

384
## BasicREPL ##
385

386
mutable struct BasicREPL <: AbstractREPL
387
    terminal::TextTerminal
388
    waserror::Bool
389
    frontend_task::Task
390
    BasicREPL(t) = new(t, false)
3✔
391
end
392

393
outstream(r::BasicREPL) = r.terminal
6✔
394
hascolor(r::BasicREPL) = hascolor(r.terminal)
×
395

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

443
## LineEditREPL ##
444

445
mutable struct LineEditREPL <: AbstractREPL
446
    t::TextTerminal
447
    hascolor::Bool
448
    prompt_color::String
449
    input_color::String
450
    answer_color::String
451
    shell_color::String
452
    help_color::String
453
    history_file::Bool
454
    in_shell::Bool
455
    in_help::Bool
456
    envcolors::Bool
457
    waserror::Bool
458
    specialdisplay::Union{Nothing,AbstractDisplay}
459
    options::Options
460
    mistate::Union{MIState,Nothing}
461
    last_shown_line_infos::Vector{Tuple{String,Int}}
462
    interface::ModalInterface
463
    backendref::REPLBackendRef
464
    frontend_task::Task
465
    function LineEditREPL(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell,in_help,envcolors)
23✔
466
        opts = Options()
23✔
467
        opts.hascolor = hascolor
23✔
468
        if !hascolor
23✔
469
            opts.beep_colors = [""]
×
470
        end
471
        new(t,hascolor,prompt_color,input_color,answer_color,shell_color,help_color,history_file,in_shell,
23✔
472
            in_help,envcolors,false,nothing, opts, nothing, Tuple{String,Int}[])
473
    end
474
end
475
outstream(r::LineEditREPL) = (t = r.t; t isa TTYTerminal ? t.out_stream : t)
477✔
476
specialdisplay(r::LineEditREPL) = r.specialdisplay
93✔
477
specialdisplay(r::AbstractREPL) = nothing
3✔
478
terminal(r::LineEditREPL) = r.t
140✔
479
hascolor(r::LineEditREPL) = r.hascolor
187✔
480

481
LineEditREPL(t::TextTerminal, hascolor::Bool, envcolors::Bool=false) =
46✔
482
    LineEditREPL(t, hascolor,
483
        hascolor ? Base.text_colors[:green] : "",
484
        hascolor ? Base.input_color() : "",
485
        hascolor ? Base.answer_color() : "",
486
        hascolor ? Base.text_colors[:red] : "",
487
        hascolor ? Base.text_colors[:yellow] : "",
488
        false, false, false, envcolors
489
    )
490

491
mutable struct REPLCompletionProvider <: CompletionProvider
492
    modifiers::LineEdit.Modifiers
20✔
493
end
494
REPLCompletionProvider() = REPLCompletionProvider(LineEdit.Modifiers())
20✔
495

496
mutable struct ShellCompletionProvider <: CompletionProvider end
20✔
497
struct LatexCompletions <: CompletionProvider end
498

499
function active_module() # this method is also called from Base
53,562✔
500
    isdefined(Base, :active_repl) || return Main
107,124✔
501
    return active_module(Base.active_repl::AbstractREPL)
×
502
end
503
active_module((; mistate)::LineEditREPL) = mistate === nothing ? Main : mistate.active_module
3,231✔
504
active_module(::AbstractREPL) = Main
10✔
505
active_module(d::REPLDisplay) = active_module(d.repl)
115✔
506

507
setmodifiers!(c::REPLCompletionProvider, m::LineEdit.Modifiers) = c.modifiers = m
×
508

509
"""
510
    activate(mod::Module=Main)
511

512
Set `mod` as the default contextual module in the REPL,
513
both for evaluating expressions and printing them.
514
"""
515
function activate(mod::Module=Main)
×
516
    mistate = (Base.active_repl::LineEditREPL).mistate
×
517
    mistate === nothing && return nothing
×
518
    mistate.active_module = mod
×
519
    Base.load_InteractiveUtils(mod)
×
520
    return nothing
×
521
end
522

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

525
function complete_line(c::REPLCompletionProvider, s::PromptState, mod::Module)
3✔
526
    partial = beforecursor(s.input_buffer)
3✔
527
    full = LineEdit.input_string(s)
3✔
528
    ret, range, should_complete = completions(full, lastindex(partial), mod, c.modifiers.shift)
3✔
529
    c.modifiers = LineEdit.Modifiers()
3✔
530
    return unique!(map(completion_text, ret)), partial[range], should_complete
3✔
531
end
532

533
function complete_line(c::ShellCompletionProvider, s::PromptState)
×
534
    # First parse everything up to the current position
535
    partial = beforecursor(s.input_buffer)
×
536
    full = LineEdit.input_string(s)
×
537
    ret, range, should_complete = shell_completions(full, lastindex(partial))
×
538
    return unique!(map(completion_text, ret)), partial[range], should_complete
×
539
end
540

541
function complete_line(c::LatexCompletions, s)
×
542
    partial = beforecursor(LineEdit.buffer(s))
×
543
    full = LineEdit.input_string(s)::String
×
544
    ret, range, should_complete = bslash_completions(full, lastindex(partial))[2]
×
545
    return unique!(map(completion_text, ret)), partial[range], should_complete
×
546
end
547

548
with_repl_linfo(f, repl) = f(outstream(repl))
6✔
549
function with_repl_linfo(f, repl::LineEditREPL)
149✔
550
    linfos = Tuple{String,Int}[]
149✔
551
    io = IOContext(outstream(repl), :last_shown_line_infos => linfos)
298✔
552
    f(io)
149✔
553
    if !isempty(linfos)
148✔
554
        repl.last_shown_line_infos = linfos
4✔
555
    end
556
    nothing
148✔
557
end
558

559
mutable struct REPLHistoryProvider <: HistoryProvider
560
    history::Vector{String}
25✔
561
    file_path::String
562
    history_file::Union{Nothing,IO}
563
    start_idx::Int
564
    cur_idx::Int
565
    last_idx::Int
566
    last_buffer::IOBuffer
567
    last_mode::Union{Nothing,Prompt}
568
    mode_mapping::Dict{Symbol,Prompt}
569
    modes::Vector{Symbol}
570
end
571
REPLHistoryProvider(mode_mapping::Dict{Symbol}) =
25✔
572
    REPLHistoryProvider(String[], "", nothing, 0, 0, -1, IOBuffer(),
573
                        nothing, mode_mapping, UInt8[])
574

575
invalid_history_message(path::String) = """
×
576
Invalid history file ($path) format:
577
If you have a history file left over from an older version of Julia,
578
try renaming or deleting it.
579
Invalid character: """
580

581
munged_history_message(path::String) = """
×
582
Invalid history file ($path) format:
583
An editor may have converted tabs to spaces at line """
584

585
function hist_open_file(hp::REPLHistoryProvider)
×
586
    f = open(hp.file_path, read=true, write=true, create=true)
4✔
587
    hp.history_file = f
4✔
588
    seekend(f)
4✔
589
end
590

591
function hist_from_file(hp::REPLHistoryProvider, path::String)
8✔
592
    getline(lines, i) = i > length(lines) ? "" : lines[i]
276✔
593
    file_lines = readlines(path)
8✔
594
    countlines = 0
×
595
    while true
42✔
596
        # First parse the metadata that starts with '#' in particular the REPL mode
597
        countlines += 1
42✔
598
        line = getline(file_lines, countlines)
76✔
599
        mode = :julia
×
600
        isempty(line) && break
42✔
601
        line[1] != '#' &&
68✔
602
            error(invalid_history_message(path), repr(line[1]), " at line ", countlines)
603
        while !isempty(line)
102✔
604
            startswith(line, '#') || break
102✔
605
            if startswith(line, "# mode: ")
136✔
606
                mode = Symbol(SubString(line, 9))
34✔
607
            end
608
            countlines += 1
68✔
609
            line = getline(file_lines, countlines)
136✔
610
        end
68✔
611
        isempty(line) && break
34✔
612

613
        # Now parse the code for the current REPL mode
614
        line[1] == ' '  &&
68✔
615
            error(munged_history_message(path), countlines)
616
        line[1] != '\t' &&
68✔
617
            error(invalid_history_message(path), repr(line[1]), " at line ", countlines)
618
        lines = String[]
34✔
619
        while !isempty(line)
34✔
620
            push!(lines, chomp(SubString(line, 2)))
34✔
621
            next_line = getline(file_lines, countlines+1)
64✔
622
            isempty(next_line) && break
34✔
623
            first(next_line) == ' '  && error(munged_history_message(path), countlines)
30✔
624
            # A line not starting with a tab means we are done with code for this entry
625
            first(next_line) != '\t' && break
30✔
626
            countlines += 1
×
627
            line = getline(file_lines, countlines)
×
628
        end
×
629
        push!(hp.modes, mode)
34✔
630
        push!(hp.history, join(lines, '\n'))
34✔
631
    end
34✔
632
    hp.start_idx = length(hp.history)
8✔
633
    return hp
8✔
634
end
635

636
function add_history(hist::REPLHistoryProvider, s::PromptState)
111✔
637
    str = rstrip(String(take!(copy(s.input_buffer))))
111✔
638
    isempty(strip(str)) && return
111✔
639
    mode = mode_idx(hist, LineEdit.mode(s))
93✔
640
    !isempty(hist.history) &&
151✔
641
        isequal(mode, hist.modes[end]) && str == hist.history[end] && return
642
    push!(hist.modes, mode)
87✔
643
    push!(hist.history, str)
87✔
644
    hist.history_file === nothing && return
87✔
645
    entry = """
16✔
646
    # time: $(Libc.strftime("%Y-%m-%d %H:%M:%S %Z", time()))
647
    # mode: $mode
648
    $(replace(str, r"^"ms => "\t"))
649
    """
650
    # TODO: write-lock history file
651
    try
16✔
652
        seekend(hist.history_file)
16✔
653
    catch err
654
        (err isa SystemError) || rethrow()
×
655
        # File handle might get stale after a while, especially under network file systems
656
        # If this doesn't fix it (e.g. when file is deleted), we'll end up rethrowing anyway
657
        hist_open_file(hist)
×
658
    end
659
    print(hist.history_file, entry)
32✔
660
    flush(hist.history_file)
16✔
661
    nothing
16✔
662
end
663

664
function history_move(s::Union{LineEdit.MIState,LineEdit.PrefixSearchState}, hist::REPLHistoryProvider, idx::Int, save_idx::Int = hist.cur_idx)
100✔
665
    max_idx = length(hist.history) + 1
136✔
666
    @assert 1 <= hist.cur_idx <= max_idx
96✔
667
    (1 <= idx <= max_idx) || return :none
98✔
668
    idx != hist.cur_idx || return :none
94✔
669

670
    # save the current line
671
    if save_idx == max_idx
94✔
672
        hist.last_mode = LineEdit.mode(s)
46✔
673
        hist.last_buffer = copy(LineEdit.buffer(s))
46✔
674
    else
675
        hist.history[save_idx] = LineEdit.input_string(s)
84✔
676
        hist.modes[save_idx] = mode_idx(hist, LineEdit.mode(s))
63✔
677
    end
678

679
    # load the saved line
680
    if idx == max_idx
94✔
681
        last_buffer = hist.last_buffer
10✔
682
        LineEdit.transition(s, hist.last_mode) do
10✔
683
            LineEdit.replace_line(s, last_buffer)
10✔
684
        end
685
        hist.last_mode = nothing
10✔
686
        hist.last_buffer = IOBuffer()
10✔
687
    else
688
        if haskey(hist.mode_mapping, hist.modes[idx])
168✔
689
            LineEdit.transition(s, hist.mode_mapping[hist.modes[idx]]) do
68✔
690
                LineEdit.replace_line(s, hist.history[idx])
68✔
691
            end
692
        else
693
            return :skip
16✔
694
        end
695
    end
696
    hist.cur_idx = idx
78✔
697

698
    return :ok
78✔
699
end
700

701
# REPL History can also transitions modes
702
function LineEdit.accept_result_newmode(hist::REPLHistoryProvider)
27✔
703
    if 1 <= hist.cur_idx <= length(hist.modes)
27✔
704
        return hist.mode_mapping[hist.modes[hist.cur_idx]]
23✔
705
    end
706
    return nothing
4✔
707
end
708

709
function history_prev(s::LineEdit.MIState, hist::REPLHistoryProvider,
58✔
710
                      num::Int=1, save_idx::Int = hist.cur_idx)
711
    num <= 0 && return history_next(s, hist, -num, save_idx)
58✔
712
    hist.last_idx = -1
32✔
713
    m = history_move(s, hist, hist.cur_idx-num, save_idx)
32✔
714
    if m === :ok
32✔
715
        LineEdit.move_input_start(s)
24✔
716
        LineEdit.reset_key_repeats(s) do
24✔
717
            LineEdit.move_line_end(s)
24✔
718
        end
719
        return LineEdit.refresh_line(s)
24✔
720
    elseif m === :skip
8✔
721
        return history_prev(s, hist, num+1, save_idx)
8✔
722
    else
723
        return Terminals.beep(s)
×
724
    end
725
end
726

727
function history_next(s::LineEdit.MIState, hist::REPLHistoryProvider,
44✔
728
                      num::Int=1, save_idx::Int = hist.cur_idx)
729
    if num == 0
44✔
730
        Terminals.beep(s)
×
731
        return
×
732
    end
733
    num < 0 && return history_prev(s, hist, -num, save_idx)
26✔
734
    cur_idx = hist.cur_idx
24✔
735
    max_idx = length(hist.history) + 1
24✔
736
    if cur_idx == max_idx && 0 < hist.last_idx
24✔
737
        # issue #6312
738
        cur_idx = hist.last_idx
×
739
        hist.last_idx = -1
×
740
    end
741
    m = history_move(s, hist, cur_idx+num, save_idx)
24✔
742
    if m === :ok
24✔
743
        LineEdit.move_input_end(s)
16✔
744
        return LineEdit.refresh_line(s)
16✔
745
    elseif m === :skip
8✔
746
        return history_next(s, hist, num+1, save_idx)
6✔
747
    else
748
        return Terminals.beep(s)
2✔
749
    end
750
end
751

752
history_first(s::LineEdit.MIState, hist::REPLHistoryProvider) =
6✔
753
    history_prev(s, hist, hist.cur_idx - 1 -
754
                 (hist.cur_idx > hist.start_idx+1 ? hist.start_idx : 0))
755

756
history_last(s::LineEdit.MIState, hist::REPLHistoryProvider) =
4✔
757
    history_next(s, hist, length(hist.history) - hist.cur_idx + 1)
758

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

800
function history_search(hist::REPLHistoryProvider, query_buffer::IOBuffer, response_buffer::IOBuffer,
28✔
801
                        backwards::Bool=false, skip_current::Bool=false)
802

803
    qpos = position(query_buffer)
28✔
804
    qpos > 0 || return true
28✔
805
    searchdata = beforecursor(query_buffer)
28✔
806
    response_str = String(take!(copy(response_buffer)))
28✔
807

808
    # Alright, first try to see if the current match still works
809
    a = position(response_buffer) + 1 # position is zero-indexed
28✔
810
    # FIXME: I'm pretty sure this is broken since it uses an index
811
    # into the search data to index into the response string
812
    b = a + sizeof(searchdata)
28✔
813
    b = b ≤ ncodeunits(response_str) ? prevind(response_str, b) : b-1
48✔
814
    b = min(lastindex(response_str), b) # ensure that b is valid
28✔
815

816
    searchstart = backwards ? b : a
28✔
817
    if searchdata == response_str[a:b]
44✔
818
        if skip_current
10✔
819
            searchstart = backwards ? prevind(response_str, b) : nextind(response_str, a)
4✔
820
        else
821
            return true
6✔
822
        end
823
    end
824

825
    # Start searching
826
    # First the current response buffer
827
    if 1 <= searchstart <= lastindex(response_str)
22✔
828
        match = backwards ? findprev(searchdata, response_str, searchstart) :
14✔
829
                            findnext(searchdata, response_str, searchstart)
830
        if match !== nothing
14✔
831
            seek(response_buffer, first(match) - 1)
6✔
832
            return true
6✔
833
        end
834
    end
835

836
    # Now search all the other buffers
837
    idxs = backwards ? ((hist.cur_idx-1):-1:1) : ((hist.cur_idx+1):1:length(hist.history))
16✔
838
    for idx in idxs
32✔
839
        h = hist.history[idx]
40✔
840
        match = backwards ? findlast(searchdata, h) : findfirst(searchdata, h)
40✔
841
        if match !== nothing && h != response_str && haskey(hist.mode_mapping, hist.modes[idx])
54✔
842
            truncate(response_buffer, 0)
12✔
843
            write(response_buffer, h)
12✔
844
            seek(response_buffer, first(match) - 1)
12✔
845
            hist.cur_idx = idx
12✔
846
            return true
12✔
847
        end
848
    end
52✔
849

850
    return false
4✔
851
end
852

853
function history_reset_state(hist::REPLHistoryProvider)
7✔
854
    if hist.cur_idx != length(hist.history) + 1
255✔
855
        hist.last_idx = hist.cur_idx
120✔
856
        hist.cur_idx = length(hist.history) + 1
120✔
857
    end
858
    nothing
255✔
859
end
860
LineEdit.reset_state(hist::REPLHistoryProvider) = history_reset_state(hist)
228✔
861

862
function return_callback(s)
90✔
863
    ast = Base.parse_input_line(String(take!(copy(LineEdit.buffer(s)))), depwarn=false)
90✔
864
    return !(isa(ast, Expr) && ast.head === :incomplete)
90✔
865
end
866

867
find_hist_file() = get(ENV, "JULIA_HISTORY",
8✔
868
                       !isempty(DEPOT_PATH) ? joinpath(DEPOT_PATH[1], "logs", "repl_history.jl") :
869
                       error("DEPOT_PATH is empty and and ENV[\"JULIA_HISTORY\"] not set."))
870

871
backend(r::AbstractREPL) = r.backendref
92✔
872

873
function eval_with_backend(ast, backend::REPLBackendRef)
96✔
874
    put!(backend.repl_channel, (ast, 1))
96✔
875
    return take!(backend.response_channel) # (val, iserr)
96✔
876
end
877

878
function respond(f, repl, main; pass_empty::Bool = false, suppress_on_semicolon::Bool = true)
60✔
879
    return function do_respond(s::MIState, buf, ok::Bool)
184✔
880
        if !ok
124✔
881
            return transition(s, :abort)
16✔
882
        end
883
        line = String(take!(buf)::Vector{UInt8})
108✔
884
        if !isempty(line) || pass_empty
123✔
885
            reset(repl)
93✔
886
            local response
×
887
            try
93✔
888
                ast = Base.invokelatest(f, line)
93✔
889
                response = eval_with_backend(ast, backend(repl))
93✔
890
            catch
891
                response = Pair{Any, Bool}(current_exceptions(), true)
1✔
892
            end
893
            hide_output = suppress_on_semicolon && ends_with_semicolon(line)
93✔
894
            print_response(repl, response, !hide_output, hascolor(repl))
93✔
895
        end
896
        prepare_next(repl)
108✔
897
        reset_state(s)
108✔
898
        return s.current_mode.sticky ? true : transition(s, main)
108✔
899
    end
900
end
901

902
function reset(repl::LineEditREPL)
93✔
903
    raw!(repl.t, false)
93✔
904
    hascolor(repl) && print(repl.t, Base.text_colors[:normal])
93✔
905
    nothing
93✔
906
end
907

908
function prepare_next(repl::LineEditREPL)
108✔
909
    println(terminal(repl))
108✔
910
end
911

912
function mode_keymap(julia_prompt::Prompt)
2✔
913
    AnyDict(
22✔
914
    '\b' => function (s::MIState,o...)
7✔
915
        if isempty(s) || position(LineEdit.buffer(s)) == 0
7✔
916
            buf = copy(LineEdit.buffer(s))
7✔
917
            transition(s, julia_prompt) do
7✔
918
                LineEdit.state(s, julia_prompt).input_buffer = buf
7✔
919
            end
920
        else
921
            LineEdit.edit_backspace(s)
×
922
        end
923
    end,
924
    "^C" => function (s::MIState,o...)
925
        LineEdit.move_input_end(s)
926
        LineEdit.refresh_line(s)
927
        print(LineEdit.terminal(s), "^C\n\n")
928
        transition(s, julia_prompt)
929
        transition(s, :reset)
930
        LineEdit.refresh_line(s)
931
    end)
932
end
933

934
repl_filename(repl, hp::REPLHistoryProvider) = "REPL[$(max(length(hp.history)-hp.start_idx, 1))]"
82✔
935
repl_filename(repl, hp) = "REPL"
×
936

937
const JL_PROMPT_PASTE = Ref(true)
938
enable_promptpaste(v::Bool) = JL_PROMPT_PASTE[] = v
×
939

940
function contextual_prompt(repl::LineEditREPL, prompt::Union{String,Function})
×
941
    function ()
1,418✔
942
        mod = active_module(repl)
2,749✔
943
        prefix = mod == Main ? "" : string('(', mod, ") ")
1,406✔
944
        pr = prompt isa String ? prompt : prompt()
1,378✔
945
        prefix * pr
1,378✔
946
    end
947
end
948

949
setup_interface(
950
    repl::LineEditREPL;
951
    # those keyword arguments may be deprecated eventually in favor of the Options mechanism
952
    hascolor::Bool = repl.options.hascolor,
953
    extra_repl_keymap::Any = repl.options.extra_keymap
954
) = setup_interface(repl, hascolor, extra_repl_keymap)
56✔
955

956
# This non keyword method can be precompiled which is important
957
function setup_interface(
20✔
958
    repl::LineEditREPL,
959
    hascolor::Bool,
960
    extra_repl_keymap::Any, # Union{Dict,Vector{<:Dict}},
961
)
962
    # The precompile statement emitter has problem outputting valid syntax for the
963
    # type of `Union{Dict,Vector{<:Dict}}` (see #28808).
964
    # This function is however important to precompile for REPL startup time, therefore,
965
    # make the type Any and just assert that we have the correct type below.
966
    @assert extra_repl_keymap isa Union{Dict,Vector{<:Dict}}
20✔
967

968
    ###
969
    #
970
    # This function returns the main interface that describes the REPL
971
    # functionality, it is called internally by functions that setup a
972
    # Terminal-based REPL frontend.
973
    #
974
    # See run_frontend(repl::LineEditREPL, backend::REPLBackendRef)
975
    # for usage
976
    #
977
    ###
978

979
    ###
980
    # We setup the interface in two stages.
981
    # First, we set up all components (prompt,rsearch,shell,help)
982
    # Second, we create keymaps with appropriate transitions between them
983
    #   and assign them to the components
984
    #
985
    ###
986

987
    ############################### Stage I ################################
988

989
    # This will provide completions for REPL and help mode
990
    replc = REPLCompletionProvider()
20✔
991

992
    # Set up the main Julia prompt
993
    julia_prompt = Prompt(contextual_prompt(repl, JULIA_PROMPT);
40✔
994
        # Copy colors from the prompt object
995
        prompt_prefix = hascolor ? repl.prompt_color : "",
996
        prompt_suffix = hascolor ?
997
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
998
        repl = repl,
999
        complete = replc,
1000
        on_enter = return_callback)
1001

1002
    # Setup help mode
1003
    help_mode = Prompt(contextual_prompt(repl, "help?> "),
40✔
1004
        prompt_prefix = hascolor ? repl.help_color : "",
1005
        prompt_suffix = hascolor ?
1006
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
1007
        repl = repl,
1008
        complete = replc,
1009
        # When we're done transform the entered line into a call to helpmode function
1010
        on_done = respond(line::String->helpmode(outstream(repl), line, repl.mistate.active_module),
2✔
1011
                          repl, julia_prompt, pass_empty=true, suppress_on_semicolon=false))
1012

1013

1014
    # Set up shell mode
1015
    shell_mode = Prompt(SHELL_PROMPT;
40✔
1016
        prompt_prefix = hascolor ? repl.shell_color : "",
1017
        prompt_suffix = hascolor ?
1018
            (repl.envcolors ? Base.input_color : repl.input_color) : "",
1019
        repl = repl,
1020
        complete = ShellCompletionProvider(),
1021
        # Transform "foo bar baz" into `foo bar baz` (shell quoting)
1022
        # and pass into Base.repl_cmd for processing (handles `ls` and `cd`
1023
        # special)
1024
        on_done = respond(repl, julia_prompt) do line
1025
            Expr(:call, :(Base.repl_cmd),
9✔
1026
                :(Base.cmd_gen($(Base.shell_parse(line::String)[1]))),
1027
                outstream(repl))
1028
        end,
1029
        sticky = true)
1030

1031

1032
    ################################# Stage II #############################
1033

1034
    # Setup history
1035
    # We will have a unified history for all REPL modes
1036
    hp = REPLHistoryProvider(Dict{Symbol,Prompt}(:julia => julia_prompt,
20✔
1037
                                                 :shell => shell_mode,
1038
                                                 :help  => help_mode))
1039
    if repl.history_file
20✔
1040
        try
4✔
1041
            hist_path = find_hist_file()
8✔
1042
            mkpath(dirname(hist_path))
4✔
1043
            hp.file_path = hist_path
4✔
1044
            hist_open_file(hp)
4✔
1045
            finalizer(replc) do replc
4✔
1046
                close(hp.history_file)
4✔
1047
            end
1048
            hist_from_file(hp, hist_path)
4✔
1049
        catch
1050
            # use REPL.hascolor to avoid using the local variable with the same name
1051
            print_response(repl, Pair{Any, Bool}(current_exceptions(), true), true, REPL.hascolor(repl))
×
1052
            println(outstream(repl))
×
1053
            @info "Disabling history file for this session"
×
1054
            repl.history_file = false
×
1055
        end
1056
    end
1057
    history_reset_state(hp)
20✔
1058
    julia_prompt.hist = hp
20✔
1059
    shell_mode.hist = hp
20✔
1060
    help_mode.hist = hp
20✔
1061

1062
    julia_prompt.on_done = respond(x->Base.parse_input_line(x,filename=repl_filename(repl,hp)), repl, julia_prompt)
102✔
1063

1064

1065
    search_prompt, skeymap = LineEdit.setup_search_keymap(hp)
20✔
1066
    search_prompt.complete = LatexCompletions()
20✔
1067

1068
    shell_prompt_len = length(SHELL_PROMPT)
×
1069
    help_prompt_len = length(HELP_PROMPT)
×
1070
    jl_prompt_regex = r"^In \[[0-9]+\]: |^(?:\(.+\) )?julia> "
×
1071
    pkg_prompt_regex = r"^(?:\(.+\) )?pkg> "
×
1072

1073
    # Canonicalize user keymap input
1074
    if isa(extra_repl_keymap, Dict)
20✔
1075
        extra_repl_keymap = AnyDict[extra_repl_keymap]
×
1076
    end
1077

1078
    repl_keymap = AnyDict(
20✔
1079
        ';' => function (s::MIState,o...)
47✔
1080
            if isempty(s) || position(LineEdit.buffer(s)) == 0
87✔
1081
                buf = copy(LineEdit.buffer(s))
7✔
1082
                transition(s, shell_mode) do
7✔
1083
                    LineEdit.state(s, shell_mode).input_buffer = buf
7✔
1084
                end
1085
            else
1086
                edit_insert(s, ';')
40✔
1087
            end
1088
        end,
1089
        '?' => function (s::MIState,o...)
1✔
1090
            if isempty(s) || position(LineEdit.buffer(s)) == 0
1✔
1091
                buf = copy(LineEdit.buffer(s))
1✔
1092
                transition(s, help_mode) do
1✔
1093
                    LineEdit.state(s, help_mode).input_buffer = buf
1✔
1094
                end
1095
            else
1096
                edit_insert(s, '?')
×
1097
            end
1098
        end,
1099

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

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

1240
        # Open the editor at the location of a stackframe or method
1241
        # This is accessing a contextual variable that gets set in
1242
        # the show_backtrace and show_method_table functions.
1243
        "^Q" => (s::MIState, o...) -> begin
1244
            linfos = repl.last_shown_line_infos
1245
            str = String(take!(LineEdit.buffer(s)))
1246
            n = tryparse(Int, str)
1247
            n === nothing && @goto writeback
1248
            if n <= 0 || n > length(linfos) || startswith(linfos[n][1], "REPL[")
1249
                @goto writeback
1250
            end
1251
            try
1252
                InteractiveUtils.edit(Base.fixup_stdlib_path(linfos[n][1]), linfos[n][2])
1253
            catch ex
1254
                ex isa ProcessFailedException || ex isa Base.IOError || ex isa SystemError || rethrow()
1255
                @info "edit failed" _exception=ex
1256
            end
1257
            LineEdit.refresh_line(s)
1258
            return
1259
            @label writeback
1260
            write(LineEdit.buffer(s), str)
1261
            return
1262
        end,
1263
    )
1264

1265
    prefix_prompt, prefix_keymap = LineEdit.setup_prefix_keymap(hp, julia_prompt)
20✔
1266

1267
    a = Dict{Any,Any}[skeymap, repl_keymap, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
120✔
1268
    prepend!(a, extra_repl_keymap)
20✔
1269

1270
    julia_prompt.keymap_dict = LineEdit.keymap(a)
20✔
1271

1272
    mk = mode_keymap(julia_prompt)
20✔
1273

1274
    b = Dict{Any,Any}[skeymap, mk, prefix_keymap, LineEdit.history_keymap, LineEdit.default_keymap, LineEdit.escape_defaults]
120✔
1275
    prepend!(b, extra_repl_keymap)
20✔
1276

1277
    shell_mode.keymap_dict = help_mode.keymap_dict = LineEdit.keymap(b)
20✔
1278

1279
    allprompts = LineEdit.TextInterface[julia_prompt, shell_mode, help_mode, search_prompt, prefix_prompt]
20✔
1280
    return ModalInterface(allprompts)
20✔
1281
end
1282

1283
function run_frontend(repl::LineEditREPL, backend::REPLBackendRef)
16✔
1284
    repl.frontend_task = current_task()
16✔
1285
    d = REPLDisplay(repl)
16✔
1286
    dopushdisplay = repl.specialdisplay === nothing && !in(d,Base.Multimedia.displays)
26✔
1287
    dopushdisplay && pushdisplay(d)
16✔
1288
    if !isdefined(repl,:interface)
16✔
1289
        interface = repl.interface = setup_interface(repl)
16✔
1290
    else
1291
        interface = repl.interface
8✔
1292
    end
1293
    repl.backendref = backend
16✔
1294
    repl.mistate = LineEdit.init_state(terminal(repl), interface)
16✔
1295
    run_interface(terminal(repl), interface, repl.mistate)
16✔
1296
    # Terminate Backend
1297
    put!(backend.repl_channel, (nothing, -1))
16✔
1298
    dopushdisplay && popdisplay(d)
16✔
1299
    nothing
16✔
1300
end
1301

1302
## StreamREPL ##
1303

1304
mutable struct StreamREPL <: AbstractREPL
1305
    stream::IO
1306
    prompt_color::String
1307
    input_color::String
1308
    answer_color::String
1309
    waserror::Bool
1310
    frontend_task::Task
1311
    StreamREPL(stream,pc,ic,ac) = new(stream,pc,ic,ac,false)
×
1312
end
1313
StreamREPL(stream::IO) = StreamREPL(stream, Base.text_colors[:green], Base.input_color(), Base.answer_color())
×
1314
run_repl(stream::IO) = run_repl(StreamREPL(stream))
×
1315

1316
outstream(s::StreamREPL) = s.stream
×
1317
hascolor(s::StreamREPL) = get(s.stream, :color, false)::Bool
×
1318

1319
answer_color(r::LineEditREPL) = r.envcolors ? Base.answer_color() : r.answer_color
×
1320
answer_color(r::StreamREPL) = r.answer_color
×
1321
input_color(r::LineEditREPL) = r.envcolors ? Base.input_color() : r.input_color
×
1322
input_color(r::StreamREPL) = r.input_color
×
1323

1324
let matchend = Dict("\"" => r"\"", "\"\"\"" => r"\"\"\"", "'" => r"'",
1325
    "`" => r"`", "```" => r"```", "#" => r"$"m, "#=" => r"=#|#=")
1326
    global _rm_strings_and_comments
1327
    function _rm_strings_and_comments(code::Union{String,SubString{String}})
118✔
1328
        buf = IOBuffer(sizehint = sizeof(code))
236✔
1329
        pos = 1
×
1330
        while true
154✔
1331
            i = findnext(r"\"(?!\"\")|\"\"\"|'|`(?!``)|```|#(?!=)|#=", code, pos)
308✔
1332
            isnothing(i) && break
196✔
1333
            match = SubString(code, i)
42✔
1334
            j = findnext(matchend[match]::Regex, code, nextind(code, last(i)))
84✔
1335
            if match == "#=" # possibly nested
79✔
1336
                nested = 1
×
1337
                while j !== nothing
11✔
1338
                    nested += SubString(code, j) == "#=" ? +1 : -1
10✔
1339
                    iszero(nested) && break
10✔
1340
                    j = findnext(r"=#|#=", code, nextind(code, last(j)))
12✔
1341
                end
11✔
1342
            elseif match[1] != '#' # quote match: check non-escaped
37✔
1343
                while j !== nothing
35✔
1344
                    notbackslash = findprev(!=('\\'), code, prevind(code, first(j)))::Int
60✔
1345
                    isodd(first(j) - notbackslash) && break # not escaped
30✔
1346
                    j = findnext(matchend[match]::Regex, code, nextind(code, first(j)))
14✔
1347
                end
7✔
1348
            end
1349
            isnothing(j) && break
78✔
1350
            if match[1] == '#'
36✔
1351
                print(buf, SubString(code, pos, prevind(code, first(i))))
13✔
1352
            else
1353
                print(buf, SubString(code, pos, last(i)), ' ', SubString(code, j))
23✔
1354
            end
1355
            pos = nextind(code, last(j))
72✔
1356
        end
36✔
1357
        print(buf, SubString(code, pos, lastindex(code)))
118✔
1358
        return String(take!(buf))
118✔
1359
    end
1360
end
1361

1362
# heuristic function to decide if the presence of a semicolon
1363
# at the end of the expression was intended for suppressing output
1364
ends_with_semicolon(code::AbstractString) = ends_with_semicolon(String(code))
×
1365
ends_with_semicolon(code::Union{String,SubString{String}}) =
118✔
1366
    contains(_rm_strings_and_comments(code), r";\s*$")
1367

1368
function run_frontend(repl::StreamREPL, backend::REPLBackendRef)
×
1369
    repl.frontend_task = current_task()
×
1370
    have_color = hascolor(repl)
×
1371
    Base.banner(repl.stream)
×
1372
    d = REPLDisplay(repl)
×
1373
    dopushdisplay = !in(d,Base.Multimedia.displays)
×
1374
    dopushdisplay && pushdisplay(d)
×
1375
    while !eof(repl.stream)::Bool
×
1376
        if have_color
×
1377
            print(repl.stream,repl.prompt_color)
×
1378
        end
1379
        print(repl.stream, "julia> ")
×
1380
        if have_color
×
1381
            print(repl.stream, input_color(repl))
×
1382
        end
1383
        line = readline(repl.stream, keep=true)
×
1384
        if !isempty(line)
×
1385
            ast = Base.parse_input_line(line)
×
1386
            if have_color
×
1387
                print(repl.stream, Base.color_normal)
×
1388
            end
1389
            response = eval_with_backend(ast, backend)
×
1390
            print_response(repl, response, !ends_with_semicolon(line), have_color)
×
1391
        end
1392
    end
×
1393
    # Terminate Backend
1394
    put!(backend.repl_channel, (nothing, -1))
×
1395
    dopushdisplay && popdisplay(d)
×
1396
    nothing
×
1397
end
1398

1399
module IPython
1400

1401
using ..REPL
1402

1403
__current_ast_transforms() = isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1404

1405
function repl_eval_counter(hp)
503✔
1406
    return length(hp.history) - hp.start_idx
503✔
1407
end
1408

1409
function out_transform(@nospecialize(x), n::Ref{Int})
14✔
1410
    return Expr(:toplevel, get_usings!([], x)..., quote
14✔
1411
        let __temp_val_a72df459 = $x
1412
            $capture_result($n, __temp_val_a72df459)
1413
            __temp_val_a72df459
1414
        end
1415
    end)
1416
end
1417

1418
function get_usings!(usings, ex)
22✔
1419
    # get all `using` and `import` statements which are at the top level
1420
    for (i, arg) in enumerate(ex.args)
44✔
1421
        if Base.isexpr(arg, :toplevel)
65✔
1422
            get_usings!(usings, arg)
8✔
1423
        elseif Base.isexpr(arg, [:using, :import])
58✔
1424
            push!(usings, popat!(ex.args, i))
2✔
1425
        end
1426
    end
64✔
1427
    return usings
22✔
1428
end
1429

1430
function capture_result(n::Ref{Int}, @nospecialize(x))
14✔
1431
    n = n[]
14✔
1432
    mod = Base.MainInclude
14✔
1433
    if !isdefined(mod, :Out)
14✔
1434
        @eval mod global Out
1✔
1435
        @eval mod export Out
1✔
1436
        setglobal!(mod, :Out, Dict{Int, Any}())
1✔
1437
    end
1438
    if x !== getglobal(mod, :Out) && x !== nothing # remove this?
14✔
1439
        getglobal(mod, :Out)[n] = x
13✔
1440
    end
1441
    nothing
14✔
1442
end
1443

1444
function set_prompt(repl::LineEditREPL, n::Ref{Int})
1✔
1445
    julia_prompt = repl.interface.modes[1]
1✔
1446
    julia_prompt.prompt = function()
504✔
1447
        n[] = repl_eval_counter(julia_prompt.hist)+1
503✔
1448
        string("In [", n[], "]: ")
503✔
1449
    end
1450
    nothing
1✔
1451
end
1452

1453
function set_output_prefix(repl::LineEditREPL, n::Ref{Int})
1✔
1454
    julia_prompt = repl.interface.modes[1]
1✔
1455
    if REPL.hascolor(repl)
1✔
1456
        julia_prompt.output_prefix_prefix = Base.text_colors[:red]
1✔
1457
    end
1458
    julia_prompt.output_prefix = () -> string("Out[", n[], "]: ")
14✔
1459
    nothing
1✔
1460
end
1461

1462
function __current_ast_transforms(backend)
1✔
1463
    if backend === nothing
1✔
1464
        isdefined(Base, :active_repl_backend) ? Base.active_repl_backend.ast_transforms : REPL.repl_ast_transforms
×
1465
    else
1466
        backend.ast_transforms
1✔
1467
    end
1468
end
1469

1470

1471
function ipython_mode!(repl::LineEditREPL=Base.active_repl, backend=nothing)
1✔
1472
    n = Ref{Int}(0)
1✔
1473
    set_prompt(repl, n)
1✔
1474
    set_output_prefix(repl, n)
1✔
1475
    push!(__current_ast_transforms(backend), @nospecialize(ast) -> out_transform(ast, n))
15✔
1476
    return
1✔
1477
end
1478

1479
"""
1480
    Out[n]
1481

1482
A variable referring to all previously computed values, automatically imported to the interactive prompt.
1483
Only defined and exists while using [IPython mode](@ref IPython-mode).
1484

1485
See also [`ans`](@ref).
1486
"""
1487
Base.MainInclude.Out
1488

1489
end
1490

1491
import .IPython.ipython_mode!
1492

1493
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