The Julia REPL

Julia comes with a full-featured interactive command-line REPL (read-eval-print loop) built into the julia executable. In addition to allowing quick and easy evaluation of Julia statements, it has a searchable history, tab-completion, many helpful keybindings, and dedicated help and shell modes. The REPL can be started by simply calling julia with no arguments or double-clicking on the executable:

  1. $ julia
  2. _
  3. _ _ _(_)_ | Documentation: https://docs.julialang.org
  4. (_) | (_) (_) |
  5. _ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
  6. | | | | | | |/ _` | |
  7. | | |_| | | | (_| | | Version 1.9.0 (2023-05-07)
  8. _/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
  9. |__/ |
  10. julia>

To exit the interactive session, type ^D – the control key together with the d key on a blank line – or type exit() followed by the return or enter key. The REPL greets you with a banner and a julia> prompt.

The different prompt modes

The Julian mode

The REPL has five main modes of operation. The first and most common is the Julian prompt. It is the default mode of operation; each new line initially starts with julia>. It is here that you can enter Julia expressions. Hitting return or enter after a complete expression has been entered will evaluate the entry and show the result of the last expression.

  1. julia> string(1 + 2)
  2. "3"

There are a number of useful features unique to interactive work. In addition to showing the result, the REPL also binds the result to the variable ans. A trailing semicolon on the line can be used as a flag to suppress showing the result.

  1. julia> string(3 * 4);
  2. julia> ans
  3. "12"

In Julia mode, the REPL supports something called prompt pasting. This activates when pasting text that starts with julia> into the REPL. In that case, only expressions starting with julia> are parsed, others are removed. This makes it possible to paste a chunk of code that has been copied from a REPL session without having to scrub away prompts and outputs. This feature is enabled by default but can be disabled or enabled at will with REPL.enable_promptpaste(::Bool). If it is enabled, you can try it out by pasting the code block above this paragraph straight into the REPL. This feature does not work on the standard Windows command prompt due to its limitation at detecting when a paste occurs.

Objects are printed at the REPL using the show function with a specific IOContext. In particular, the :limit attribute is set to true. Other attributes can receive in certain show methods a default value if it’s not already set, like :compact. It’s possible, as an experimental feature, to specify the attributes used by the REPL via the Base.active_repl.options.iocontext dictionary (associating values to attributes). For example:

  1. julia> rand(2, 2)
  2. 2×2 Array{Float64,2}:
  3. 0.8833 0.329197
  4. 0.719708 0.59114
  5. julia> show(IOContext(stdout, :compact => false), "text/plain", rand(2, 2))
  6. 0.43540323669187075 0.15759787870609387
  7. 0.2540832269192739 0.4597637838786053
  8. julia> Base.active_repl.options.iocontext[:compact] = false;
  9. julia> rand(2, 2)
  10. 2×2 Array{Float64,2}:
  11. 0.2083967319174056 0.13330606013126012
  12. 0.6244375177790158 0.9777957560761545

In order to define automatically the values of this dictionary at startup time, one can use the atreplinit function in the ~/.julia/config/startup.jl file, for example:

  1. atreplinit() do repl
  2. repl.options.iocontext[:compact] = false
  3. end

Help mode

When the cursor is at the beginning of the line, the prompt can be changed to a help mode by typing ?. Julia will attempt to print help or documentation for anything entered in help mode:

  1. julia> ? # upon typing ?, the prompt changes (in place) to: help?>
  2. help?> string
  3. search: string String Cstring Cwstring RevString randstring bytestring SubString
  4. string(xs...)
  5. Create a string from any values using the print function.

Macros, types and variables can also be queried:

  1. help?> @time
  2. @time
  3. A macro to execute an expression, printing the time it took to execute, the number of allocations,
  4. and the total number of bytes its execution caused to be allocated, before returning the value of the
  5. expression.
  6. See also @timev, @timed, @elapsed, and @allocated.
  7. help?> Int32
  8. search: Int32 UInt32
  9. Int32 <: Signed
  10. 32-bit signed integer type.

A string or regex literal searches all docstrings using apropos:

  1. help?> "aprop"
  2. REPL.stripmd
  3. Base.Docs.apropos
  4. help?> r"ap..p"
  5. Base.:∘
  6. Base.shell_escape_posixly
  7. Distributed.CachingPool
  8. REPL.stripmd
  9. Base.Docs.apropos

Another feature of help mode is the ability to access extended docstrings. You can do this by typing something like ??Print rather than ?Print which will display the # Extended help section from the source codes documentation.

Help mode can be exited by pressing backspace at the beginning of the line.

Shell mode

Just as help mode is useful for quick access to documentation, another common task is to use the system shell to execute system commands. Just as ? entered help mode when at the beginning of the line, a semicolon (;) will enter the shell mode. And it can be exited by pressing backspace at the beginning of the line.

  1. julia> ; # upon typing ;, the prompt changes (in place) to: shell>
  2. shell> echo hello
  3. hello

Note

For Windows users, Julia’s shell mode does not expose windows shell commands. Hence, this will fail:

  1. julia> ; # upon typing ;, the prompt changes (in place) to: shell>
  2. shell> dir
  3. ERROR: IOError: could not spawn `dir`: no such file or directory (ENOENT)
  4. Stacktrace!
  5. .......

However, you can get access to PowerShell like this:

  1. julia> ; # upon typing ;, the prompt changes (in place) to: shell>
  2. shell> powershell
  3. Windows PowerShell
  4. Copyright (C) Microsoft Corporation. All rights reserved.
  5. PS C:\Users\elm>

… and to cmd.exe like that (see the dir command):

  1. julia> ; # upon typing ;, the prompt changes (in place) to: shell>
  2. shell> cmd
  3. Microsoft Windows [version 10.0.17763.973]
  4. (c) 2018 Microsoft Corporation. All rights reserved.
  5. C:\Users\elm>dir
  6. Volume in drive C has no label
  7. Volume Serial Number is 1643-0CD7
  8. Directory of C:\Users\elm
  9. 29/01/2020 22:15 <DIR> .
  10. 29/01/2020 22:15 <DIR> ..
  11. 02/02/2020 08:06 <DIR> .atom

Pkg mode

The Package manager mode accepts specialized commands for loading and updating packages. It is entered by pressing the ] key at the Julian REPL prompt and exited by pressing CTRL-C or pressing the backspace key at the beginning of the line. The prompt for this mode is pkg>. It supports its own help-mode, which is entered by pressing ? at the beginning of the line of the pkg> prompt. The Package manager mode is documented in the Pkg manual, available at https://julialang.github.io/Pkg.jl/v1/.

Search modes

In all of the above modes, the executed lines get saved to a history file, which can be searched. To initiate an incremental search through the previous history, type ^R – the control key together with the r key. The prompt will change to (reverse-i-search)`':, and as you type the search query will appear in the quotes. The most recent result that matches the query will dynamically update to the right of the colon as more is typed. To find an older result using the same query, simply type ^R again.

Just as ^R is a reverse search, ^S is a forward search, with the prompt (i-search)`':. The two may be used in conjunction with each other to move through the previous or next matching results, respectively.

All executed commands in the Julia REPL are logged into ~/.julia/logs/repl_history.jl along with a timestamp of when it was executed and the current REPL mode you were in. Search mode queries this log file in order to find the commands which you previously ran. This can be disabled at startup by passing the --history-file=no flag to Julia.

Key bindings

The Julia REPL makes great use of key bindings. Several control-key bindings were already introduced above (^D to exit, ^R and ^S for searching), but there are many more. In addition to the control-key, there are also meta-key bindings. These vary more by platform, but most terminals default to using alt- or option- held down with a key to send the meta-key (or can be configured to do so), or pressing Esc and then the key.

KeybindingDescription
Program control
^DExit (when buffer is empty)
^CInterrupt or cancel
^LClear console screen
Return/Enter, ^JNew line, executing if it is complete
meta-Return/EnterInsert new line without executing it
? or ;Enter help or shell mode (when at start of a line)
^R, ^SIncremental history search, described above
Cursor movement
Right arrow, ^FMove right one character
Left arrow, ^BMove left one character
ctrl-Right, meta-FMove right one word
ctrl-Left, meta-BMove left one word
Home, ^AMove to beginning of line
End, ^EMove to end of line
Up arrow, ^PMove up one line (or change to the previous history entry that matches the text before the cursor)
Down arrow, ^NMove down one line (or change to the next history entry that matches the text before the cursor)
Shift-Arrow KeyMove cursor according to the direction of the Arrow key, while activating the region (“shift selection”)
Page-up, meta-PChange to the previous history entry
Page-down, meta-NChange to the next history entry
meta-<Change to the first history entry (of the current session if it is before the current position in history)
meta->Change to the last history entry
^-SpaceSet the “mark” in the editing region (and de-activate the region if it’s active)
^-Space ^-SpaceSet the “mark” in the editing region and make the region “active”, i.e. highlighted
^GDe-activate the region (i.e. make it not highlighted)
^X^XExchange the current position with the mark
Editing
Backspace, ^HDelete the previous character, or the whole region when it’s active
Delete, ^DForward delete one character (when buffer has text)
meta-BackspaceDelete the previous word
meta-dForward delete the next word
^WDelete previous text up to the nearest whitespace
meta-wCopy the current region in the kill ring
meta-W“Kill” the current region, placing the text in the kill ring
^U“Kill” to beginning of line, placing the text in the kill ring
^K“Kill” to end of line, placing the text in the kill ring
^Y“Yank” insert the text from the kill ring
meta-yReplace a previously yanked text with an older entry from the kill ring
^TTranspose the characters about the cursor
meta-Up arrowTranspose current line with line above
meta-Down arrowTranspose current line with line below
meta-uChange the next word to uppercase
meta-cChange the next word to titlecase
meta-lChange the next word to lowercase
^/, ^_Undo previous editing action
^QWrite a number in REPL and press ^Q to open editor at corresponding stackframe or method
meta-Left ArrowIndent the current line on the left
meta-Right ArrowIndent the current line on the right
meta-.Insert last word from previous history entry
meta-eEdit the current input in an editor

Customizing keybindings

Julia’s REPL keybindings may be fully customized to a user’s preferences by passing a dictionary to REPL.setup_interface. The keys of this dictionary may be characters or strings. The key '*' refers to the default action. Control plus character x bindings are indicated with "^x". Meta plus x can be written "\\M-x" or "\ex", and Control plus x can be written "\\C-x" or "^x". The values of the custom keymap must be nothing (indicating that the input should be ignored) or functions that accept the signature (PromptState, AbstractREPL, Char). The REPL.setup_interface function must be called before the REPL is initialized, by registering the operation with atreplinit . For example, to bind the up and down arrow keys to move through history without prefix search, one could put the following code in ~/.julia/config/startup.jl:

  1. import REPL
  2. import REPL.LineEdit
  3. const mykeys = Dict{Any,Any}(
  4. # Up Arrow
  5. "\e[A" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_prev(s, LineEdit.mode(s).hist)),
  6. # Down Arrow
  7. "\e[B" => (s,o...)->(LineEdit.edit_move_down(s) || LineEdit.history_next(s, LineEdit.mode(s).hist))
  8. )
  9. function customize_keys(repl)
  10. repl.interface = REPL.setup_interface(repl; extra_repl_keymap = mykeys)
  11. end
  12. atreplinit(customize_keys)

Users should refer to LineEdit.jl to discover the available actions on key input.

Tab completion

In both the Julian and help modes of the REPL, one can enter the first few characters of a function or type and then press the tab key to get a list all matches:

  1. julia> x[TAB]
  2. julia> xor

In some cases it only completes part of the name, up to the next ambiguity:

  1. julia> mapf[TAB]
  2. julia> mapfold

If you hit tab again, then you get the list of things that might complete this:

  1. julia> mapfold[TAB]
  2. mapfoldl mapfoldr

Like other components of the REPL, the search is case-sensitive:

  1. julia> stri[TAB]
  2. stride strides string strip
  3. julia> Stri[TAB]
  4. StridedArray StridedMatrix StridedVecOrMat StridedVector String

The tab key can also be used to substitute LaTeX math symbols with their Unicode equivalents, and get a list of LaTeX matches as well:

  1. julia> \pi[TAB]
  2. julia> π
  3. π = 3.1415926535897...
  4. julia> e\_1[TAB] = [1,0]
  5. julia> e = [1,0]
  6. 2-element Array{Int64,1}:
  7. 1
  8. 0
  9. julia> e\^1[TAB] = [1 0]
  10. julia> e¹ = [1 0]
  11. 1×2 Array{Int64,2}:
  12. 1 0
  13. julia> \sqrt[TAB]2 # √ is equivalent to the sqrt function
  14. julia> 2
  15. 1.4142135623730951
  16. julia> \hbar[TAB](h) = h / 2\pi[TAB]
  17. julia> ħ(h) = h / 2π
  18. ħ (generic function with 1 method)
  19. julia> \h[TAB]
  20. \hat \hermitconjmatrix \hkswarow \hrectangle
  21. \hatapprox \hexagon \hookleftarrow \hrectangleblack
  22. \hbar \hexagonblack \hookrightarrow \hslash
  23. \heartsuit \hksearow \house \hspace
  24. julia> α="\alpha[TAB]" # LaTeX completion also works in strings
  25. julia> α="α"

A full list of tab-completions can be found in the Unicode Input section of the manual.

Completion of paths works for strings and julia’s shell mode:

  1. julia> path="/[TAB]"
  2. .dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/
  3. .dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/
  4. shell> /[TAB]
  5. .dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/
  6. .dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/

Dictionary keys can also be tab completed:

  1. julia> foo = Dict("qwer1"=>1, "qwer2"=>2, "asdf"=>3)
  2. Dict{String,Int64} with 3 entries:
  3. "qwer2" => 2
  4. "asdf" => 3
  5. "qwer1" => 1
  6. julia> foo["q[TAB]
  7. "qwer1" "qwer2"
  8. julia> foo["qwer

Tab completion can also help completing fields:

  1. julia> x = 3 + 4im;
  2. julia> x.[TAB][TAB]
  3. im re
  4. julia> import UUIDs
  5. julia> UUIDs.uuid[TAB][TAB]
  6. uuid1 uuid4 uuid5 uuid_version

Fields for output from functions can also be completed:

  1. julia> split("","")[1].[TAB]
  2. lastindex offset string

The completion of fields for output from functions uses type inference, and it can only suggest fields if the function is type stable.

Tab completion can help with investigation of the available methods matching the input arguments:

  1. julia> max([TAB] # All methods are displayed, not shown here due to size of the list
  2. julia> max([1, 2], [TAB] # All methods where `Vector{Int}` matches as first argument
  3. max(x, y) in Base at operators.jl:215
  4. max(a, b, c, xs...) in Base at operators.jl:281
  5. julia> max([1, 2], max(1, 2), [TAB] # All methods matching the arguments.
  6. max(x, y) in Base at operators.jl:215
  7. max(a, b, c, xs...) in Base at operators.jl:281

Keywords are also displayed in the suggested methods after ;, see below line where limit and keepempty are keyword arguments:

  1. julia> split("1 1 1", [TAB]
  2. split(str::AbstractString; limit, keepempty) in Base at strings/util.jl:302
  3. split(str::T, splitter; limit, keepempty) where T<:AbstractString in Base at strings/util.jl:277

The completion of the methods uses type inference and can therefore see if the arguments match even if the arguments are output from functions. The function needs to be type stable for the completion to be able to remove non-matching methods.

If you wonder which methods can be used with particular argument types, use ? as the function name. This shows an example of looking for functions in InteractiveUtils that accept a single string:

  1. julia> InteractiveUtils.?("somefile")[TAB]
  2. edit(path::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:197
  3. less(file::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:266

This listed methods in the InteractiveUtils module that can be called on a string. By default, this excludes methods where all arguments are typed as Any, but you can see those too by holding down SHIFT-TAB instead of TAB:

  1. julia> InteractiveUtils.?("somefile")[SHIFT-TAB]
  2. apropos(string) in REPL at REPL/src/docview.jl:796
  3. clipboard(x) in InteractiveUtils at InteractiveUtils/src/clipboard.jl:64
  4. code_llvm(f) in InteractiveUtils at InteractiveUtils/src/codeview.jl:221
  5. code_native(f) in InteractiveUtils at InteractiveUtils/src/codeview.jl:243
  6. edit(path::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:197
  7. edit(f) in InteractiveUtils at InteractiveUtils/src/editless.jl:225
  8. eval(x) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:3
  9. include(x) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:3
  10. less(file::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:266
  11. less(f) in InteractiveUtils at InteractiveUtils/src/editless.jl:274
  12. report_bug(kind) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:391
  13. separate_kwargs(args...; kwargs...) in InteractiveUtils at InteractiveUtils/src/macros.jl:7

You can also use ?("somefile")[TAB] and look across all modules, but the method lists can be long.

By omitting the closing parenthesis, you can include functions that might require additional arguments:

  1. julia> using Mmap
  2. help?> Mmap.?("file",[TAB]
  3. Mmap.Anonymous(name::String, readonly::Bool, create::Bool) in Mmap at Mmap/src/Mmap.jl:16
  4. mmap(file::AbstractString) in Mmap at Mmap/src/Mmap.jl:245
  5. mmap(file::AbstractString, ::Type{T}) where T<:Array in Mmap at Mmap/src/Mmap.jl:245
  6. mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}) where {T<:Array, N} in Mmap at Mmap/src/Mmap.jl:245
  7. mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}, offset::Integer; grow, shared) where {T<:Array, N} in Mmap at Mmap/src/Mmap.jl:245
  8. mmap(file::AbstractString, ::Type{T}, len::Integer) where T<:Array in Mmap at Mmap/src/Mmap.jl:251
  9. mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer; grow, shared) where T<:Array in Mmap at Mmap/src/Mmap.jl:251
  10. mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}) where {T<:BitArray, N} in Mmap at Mmap/src/Mmap.jl:316
  11. mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}, offset::Integer; grow, shared) where {T<:BitArray, N} in Mmap at Mmap/src/Mmap.jl:316
  12. mmap(file::AbstractString, ::Type{T}, len::Integer) where T<:BitArray in Mmap at Mmap/src/Mmap.jl:322
  13. mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer; grow, shared) where T<:BitArray in Mmap at Mmap/src/Mmap.jl:322

Customizing Colors

The colors used by Julia and the REPL can be customized, as well. To change the color of the Julia prompt you can add something like the following to your ~/.julia/config/startup.jl file, which is to be placed inside your home directory:

  1. function customize_colors(repl)
  2. repl.prompt_color = Base.text_colors[:cyan]
  3. end
  4. atreplinit(customize_colors)

The available color keys can be seen by typing Base.text_colors in the help mode of the REPL. In addition, the integers 0 to 255 can be used as color keys for terminals with 256 color support.

You can also change the colors for the help and shell prompts and input and answer text by setting the appropriate field of repl in the customize_colors function above (respectively, help_color, shell_color, input_color, and answer_color). For the latter two, be sure that the envcolors field is also set to false.

It is also possible to apply boldface formatting by using Base.text_colors[:bold] as a color. For instance, to print answers in boldface font, one can use the following as a ~/.julia/config/startup.jl:

  1. function customize_colors(repl)
  2. repl.envcolors = false
  3. repl.answer_color = Base.text_colors[:bold]
  4. end
  5. atreplinit(customize_colors)

You can also customize the color used to render warning and informational messages by setting the appropriate environment variables. For instance, to render error, warning, and informational messages respectively in magenta, yellow, and cyan you can add the following to your ~/.julia/config/startup.jl file:

  1. ENV["JULIA_ERROR_COLOR"] = :magenta
  2. ENV["JULIA_WARN_COLOR"] = :yellow
  3. ENV["JULIA_INFO_COLOR"] = :cyan

Changing the contextual module which is active at the REPL

When entering expressions at the REPL, they are by default evaluated in the Main module;

  1. julia> @__MODULE__
  2. Main

It is possible to change this contextual module via the function REPL.activate(m) where m is a Module or by typing the module in the REPL and pressing the keybinding Alt-m (the cursor must be on the module name). The active module is shown in the prompt:

  1. julia> using REPL
  2. julia> REPL.activate(Base)
  3. (Base) julia> @__MODULE__
  4. Base
  5. (Base) julia> using REPL # Need to load REPL into Base module to use it
  6. (Base) julia> REPL.activate(Main)
  7. julia>
  8. julia> Core<Alt-m> # using the keybinding to change module
  9. (Core) julia>
  10. (Core) julia> Main<Alt-m> # going back to Main via keybinding
  11. julia>

Functions that take an optional module argument often defaults to the REPL context module. As an example, calling varinfo() will show the variables of the current active module:

  1. julia> module CustomMod
  2. export var, f
  3. var = 1
  4. f(x) = x^2
  5. end;
  6. julia> REPL.activate(CustomMod)
  7. (Main.CustomMod) julia> varinfo()
  8. name size summary
  9. ––––––––– ––––––– ––––––––––––––––––––––––––––––––––
  10. CustomMod Module
  11. f 0 bytes f (generic function with 1 method)
  12. var 8 bytes Int64

Numbered prompt

It is possible to get an interface which is similar to the IPython REPL and the Mathematica notebook with numbered input prompts and output prefixes. This is done by calling REPL.numbered_prompt!(). If you want to have this enabled on startup, add

  1. atreplinit() do repl
  2. if !isdefined(repl, :interface)
  3. repl.interface = REPL.setup_interface(repl)
  4. end
  5. REPL.numbered_prompt!(repl)
  6. end

to your startup.jl file. In numbered prompt the variable Out[n] (where n is an integer) can be used to refer to earlier results:

  1. In [1]: 5 + 3
  2. Out[1]: 8
  3. In [2]: Out[1] + 5
  4. Out[2]: 13
  5. In [3]: Out
  6. Out[3]: Dict{Int64, Any} with 2 entries:
  7. 2 => 13
  8. 1 => 8

TerminalMenus

TerminalMenus is a submodule of the Julia REPL and enables small, low-profile interactive menus in the terminal.

Examples

  1. import REPL
  2. using REPL.TerminalMenus
  3. options = ["apple", "orange", "grape", "strawberry",
  4. "blueberry", "peach", "lemon", "lime"]

RadioMenu

The RadioMenu allows the user to select one option from the list. The request function displays the interactive menu and returns the index of the selected choice. If a user presses ‘q’ or ctrl-c, request will return a -1.

  1. # `pagesize` is the number of items to be displayed at a time.
  2. # The UI will scroll if the number of options is greater
  3. # than the `pagesize`
  4. menu = RadioMenu(options, pagesize=4)
  5. # `request` displays the menu and returns the index after the
  6. # user has selected a choice
  7. choice = request("Choose your favorite fruit:", menu)
  8. if choice != -1
  9. println("Your favorite fruit is ", options[choice], "!")
  10. else
  11. println("Menu canceled.")
  12. end

Output:

  1. Choose your favorite fruit:
  2. ^ grape
  3. strawberry
  4. > blueberry
  5. v peach
  6. Your favorite fruit is blueberry!

MultiSelectMenu

The MultiSelectMenu allows users to select many choices from a list.

  1. # here we use the default `pagesize` 10
  2. menu = MultiSelectMenu(options)
  3. # `request` returns a `Set` of selected indices
  4. # if the menu us canceled (ctrl-c or q), return an empty set
  5. choices = request("Select the fruits you like:", menu)
  6. if length(choices) > 0
  7. println("You like the following fruits:")
  8. for i in choices
  9. println(" - ", options[i])
  10. end
  11. else
  12. println("Menu canceled.")
  13. end

Output:

  1. Select the fruits you like:
  2. [press: Enter=toggle, a=all, n=none, d=done, q=abort]
  3. [ ] apple
  4. > [X] orange
  5. [X] grape
  6. [ ] strawberry
  7. [ ] blueberry
  8. [X] peach
  9. [ ] lemon
  10. [ ] lime
  11. You like the following fruits:
  12. - orange
  13. - grape
  14. - peach

Customization / Configuration

ConfiguredMenu subtypes

Starting with Julia 1.6, the recommended way to configure menus is via the constructor. For instance, the default multiple-selection menu

  1. julia> menu = MultiSelectMenu(options, pagesize=5);
  2. julia> request(menu) # ASCII is used by default
  3. [press: Enter=toggle, a=all, n=none, d=done, q=abort]
  4. [ ] apple
  5. [X] orange
  6. [ ] grape
  7. > [X] strawberry
  8. v [ ] blueberry

can instead be rendered with Unicode selection and navigation characters with

  1. julia> menu = MultiSelectMenu(options, pagesize=5, charset=:unicode);
  2. julia> request(menu)
  3. [press: Enter=toggle, a=all, n=none, d=done, q=abort]
  4. apple
  5. orange
  6. grape
  7. strawberry
  8. blueberry

More fine-grained configuration is also possible:

  1. julia> menu = MultiSelectMenu(options, pagesize=5, charset=:unicode, checked="YEP!", unchecked="NOPE", cursor='⧐');
  2. julia> request(menu)
  3. julia> request(menu)
  4. [press: Enter=toggle, a=all, n=none, d=done, q=abort]
  5. NOPE apple
  6. YEP! orange
  7. NOPE grape
  8. YEP! strawberry
  9. NOPE blueberry

Aside from the overall charset option, for RadioMenu the configurable options are:

  • cursor::Char='>'|'→': character to use for cursor
  • up_arrow::Char='^'|'↑': character to use for up arrow
  • down_arrow::Char='v'|'↓': character to use for down arrow
  • updown_arrow::Char='I'|'↕': character to use for up/down arrow in one-line page
  • scroll_wrap::Bool=false: optionally wrap-around at the beginning/end of a menu
  • ctrl_c_interrupt::Bool=true: If false, return empty on ^C, if true throw InterruptException() on ^C

MultiSelectMenu adds:

  • checked::String="[X]"|"✓": string to use for checked
  • unchecked::String="[ ]"|"⬚"): string to use for unchecked

You can create new menu types of your own. Types that are derived from TerminalMenus.ConfiguredMenu configure the menu options at construction time.

Legacy interface

Prior to Julia 1.6, and still supported throughout Julia 1.x, one can also configure menus by calling TerminalMenus.config().

References

REPL

Base.atreplinit — Function

  1. atreplinit(f)

Register a one-argument function to be called before the REPL interface is initialized in interactive sessions; this is useful to customize the interface. The argument of f is the REPL object. This function should be called from within the .julia/config/startup.jl initialization file.

source

TerminalMenus

Menus

REPL.TerminalMenus.RadioMenu — Type

  1. RadioMenu

A menu that allows a user to select a single option from a list.

Sample Output

  1. julia> request(RadioMenu(options, pagesize=4))
  2. Choose your favorite fruit:
  3. ^ grape
  4. strawberry
  5. > blueberry
  6. v peach
  7. Your favorite fruit is blueberry!

REPL.TerminalMenus.MultiSelectMenu — Type

  1. MultiSelectMenu

A menu that allows a user to select a multiple options from a list.

Sample Output

  1. julia> request(MultiSelectMenu(options))
  2. Select the fruits you like:
  3. [press: Enter=toggle, a=all, n=none, d=done, q=abort]
  4. [ ] apple
  5. > [X] orange
  6. [X] grape
  7. [ ] strawberry
  8. [ ] blueberry
  9. [X] peach
  10. [ ] lemon
  11. [ ] lime
  12. You like the following fruits:
  13. - orange
  14. - grape
  15. - peach

Configuration

REPL.TerminalMenus.Config — Type

  1. Config(; scroll_wrap=false, ctrl_c_interrupt=true, charset=:ascii, cursor::Char, up_arrow::Char, down_arrow::Char)

Configure behavior for selection menus via keyword arguments:

  • scroll_wrap, if true, causes the menu to wrap around when scrolling above the first or below the last entry
  • ctrl_c_interrupt, if true, throws an InterruptException if the user hits Ctrl-C during menu selection. If false, TerminalMenus.request will return the default result from TerminalMenus.selected.
  • charset affects the default values for cursor, up_arrow, and down_arrow, and can be :ascii or :unicode
  • cursor is the character printed to indicate the option that will be chosen by hitting “Enter.” Defaults are ‘>’ or ‘→’, depending on charset.
  • up_arrow is the character printed when the display does not include the first entry. Defaults are ‘^’ or ‘↑’, depending on charset.
  • down_arrow is the character printed when the display does not include the last entry. Defaults are ‘v’ or ‘↓’, depending on charset.

Subtypes of ConfiguredMenu will print cursor, up_arrow, and down_arrow automatically as needed, your writeline method should not print them.

Julia 1.6

Config is available as of Julia 1.6. On older releases use the global CONFIG.

REPL.TerminalMenus.MultiSelectConfig — Type

  1. MultiSelectConfig(; charset=:ascii, checked::String, unchecked::String, kwargs...)

Configure behavior for a multiple-selection menu via keyword arguments:

  • checked is the string to print when an option has been selected. Defaults are “[X]“ or “✓”, depending on charset.
  • unchecked is the string to print when an option has not been selected. Defaults are “[ ]“ or “⬚”, depending on charset.

All other keyword arguments are as described for TerminalMenus.Config. checked and unchecked are not printed automatically, and should be printed by your writeline method.

Julia 1.6

MultiSelectConfig is available as of Julia 1.6. On older releases use the global CONFIG.

REPL.TerminalMenus.config — Function

  1. config( <see arguments> )

Keyword-only function to configure global menu parameters

Arguments

  • charset::Symbol=:na: ui characters to use (:ascii or :unicode); overridden by other arguments
  • cursor::Char='>'|'→': character to use for cursor
  • up_arrow::Char='^'|'↑': character to use for up arrow
  • down_arrow::Char='v'|'↓': character to use for down arrow
  • checked::String="[X]"|"✓": string to use for checked
  • unchecked::String="[ ]"|"⬚"): string to use for unchecked
  • scroll::Symbol=:nowrap: If :wrap wrap cursor around top and bottom, if :nowrap do not wrap cursor
  • supress_output::Bool=false: Ignored legacy argument, pass suppress_output as a keyword argument to request instead.
  • ctrl_c_interrupt::Bool=true: If false, return empty on ^C, if true throw InterruptException() on ^C

Julia 1.6

As of Julia 1.6, config is deprecated. Use Config or MultiSelectConfig instead.

User interaction

REPL.TerminalMenus.request — Function

  1. request(m::AbstractMenu; cursor=1)

Display the menu and enter interactive mode. cursor indicates the item number used for the initial cursor position. cursor can be either an Int or a RefValue{Int}. The latter is useful for observation and control of the cursor position from the outside.

Returns selected(m).

Julia 1.6

The cursor argument requires Julia 1.6 or later.

  1. request([term,] msg::AbstractString, m::AbstractMenu)

Shorthand for println(msg); request(m).

AbstractMenu extension interface

Any subtype of AbstractMenu must be mutable, and must contain the fields pagesize::Int and pageoffset::Int. Any subtype must also implement the following functions:

REPL.TerminalMenus.pick — Function

  1. pick(m::AbstractMenu, cursor::Int)

Defines what happens when a user presses the Enter key while the menu is open. If true is returned, request() will exit. cursor indexes the position of the selection.

REPL.TerminalMenus.cancel — Function

  1. cancel(m::AbstractMenu)

Define what happens when a user cancels (‘q’ or ctrl-c) a menu. request() will always exit after calling this function.

REPL.TerminalMenus.writeline — Function

  1. writeline(buf::IO, m::AbstractMenu, idx::Int, iscursor::Bool)

Write the option at index idx to buf. iscursor, if true, indicates that this item is at the current cursor position (the one that will be selected by hitting “Enter”).

If m is a ConfiguredMenu, TerminalMenus will print the cursor indicator. Otherwise the callee is expected to handle such printing.

Julia 1.6

writeline requires Julia 1.6 or higher.

On older versions of Julia, this was writeLine(buf::IO, m::AbstractMenu, idx, iscursor::Bool) and m is assumed to be unconfigured. The selection and cursor indicators can be obtained from TerminalMenus.CONFIG.

This older function is supported on all Julia 1.x versions but will be dropped in Julia 2.0.

It must also implement either options or numoptions:

REPL.TerminalMenus.options — Function

  1. options(m::AbstractMenu)

Return a list of strings to be displayed as options in the current page.

Alternatively, implement numoptions, in which case options is not needed.

REPL.TerminalMenus.numoptions — Function

  1. numoptions(m::AbstractMenu) -> Int

Return the number of options in menu m. Defaults to length(options(m)).

Julia 1.6

This function requires Julia 1.6 or later.

If the subtype does not have a field named selected, it must also implement

REPL.TerminalMenus.selected — Function

  1. selected(m::AbstractMenu)

Return information about the user-selected option. By default it returns m.selected.

The following are optional but can allow additional customization:

REPL.TerminalMenus.header — Function

  1. header(m::AbstractMenu) -> String

Return a header string to be printed above the menu. Defaults to “”.

REPL.TerminalMenus.keypress — Function

  1. keypress(m::AbstractMenu, i::UInt32) -> Bool

Handle any non-standard keypress event. If true is returned, TerminalMenus.request will exit. Defaults to false.