Julia REPL

要退出交互式会话,在空白行上键入 ^D——control 键和 d 键,或者先键入 quit(),然后键入 return 或 enter 键。REPL 用横幅和 julia> 提示符欢迎你。

REPL 有四种主要的操作模式。第一个也是最常见的是 Julian 提示符。这是默认的操作模式;每个新行最初都以 julia> 开头。就在这里,你可以输入 Julia 表达式。在输入完整表达式后按下 return 或 enter 将执行该表达式,并显示最后一个表达式的结果。

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

交互式运行有许多独特的实用功能。除了显示结果外,REPL 还将结果绑定到变量 ans 上。一行的尾随分号可用作禁止显示结果的标志。

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

Julia 模式中,REPL 支持称为 prompt pasting 的功能。当粘贴以 julia> 文本到 REPL 中时才会激活此功能。在这种情况下,只有以 julia> 开头的表达式才被解析,其它的表达式则被删除。这使得可以粘贴从 REPL 会话中复制的一大块代码,而无需擦除提示和输出。默认情况下启用此功能,但可以使用Base.REPL.enable_promptpaste(::Bool) 任意禁用或启用此功能。如果它已启用,您可以通过将本段上方的代码块直接粘贴到 REPL 中来尝试。此功能在标准的 Windows 命令提示符下不起作用,由于它在检测粘贴何时发生上的限制。

帮助模式

当光标在行首时,提示符可以通过键入 ? 改变为帮助模式。Julia 将尝试打印在帮助模式中输入的任何内容的帮助或文档:

  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.

还可以查询宏,类型和变量:

  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.

通过在行的开头按退格键可以退出帮助模式。

Shell 模式

正如帮助模式对快速访问文档很有用,另一个常见任务是使用系统 shell 执行系统命令。就像 ? 进入帮助模式,在行的开头,分号(;)将进入 shell 模式。并且通过在行的开头按退格键可以退出 shell 模式。

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

在所有上述模式中,执行过的行被保存到历史文件中,该文件可以被搜索。要通过之前的历史记录启动增量搜索,请键入 ^R——control 键和 r 键。提示符会变为 (reverse-i-search)`':,搜索查询在你输入时出现在引号中。匹配查询的最近结果会在输入更多内容时动态更新到冒号右侧。要使用相同的查询查找更旧的结果,只需再次键入 ^R

正如 ^R 是反向搜索,^S 是前向搜索,带有提示符 (i-search)`':。这两者可以彼此结合使用以分别移动至前一个或下一个匹配结果。

按键绑定

Julia REPL 充分利用了按键绑定。上面已经介绍了几个 control 键绑定(^D 退出,^R^S用于搜索),但还有更多按键绑定。除 control 键之外,还有 meta 键绑定。这些因平台而异,但大多数终端默认使用按住 alt- 或 option- 和一个键发送 meta 键(或者可以配置为执行此操作)。

自定义按键绑定

  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_up(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)

用户应该参考 LineEdit.jl 来发现输入按键的可用操作。

在 REPL 的 Julian 和帮助模式中,可以先输入函数或类型的前几个字符,接着按 tab 键来获取所有匹配的列表:

  1. julia> stri[TAB]
  2. julia> Stri[TAB]
  3. StridedArray StridedMatrix StridedVecOrMat StridedVector String

Tab 键也可用于将 LaTeX 数学符号替换为其 Unicode 等价字符,也可用于获取 LaTeX 匹配的列表:

Tab 补全的完整列表可以在手册的 Unicode 输入表章节中找到。

路径补全适用于字符串和 julia 的 shell 模式:

  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/

Tab 补全可以帮助查找与输入参数相匹配的可用方法:

  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

关键字也会在建议的方法中显示在 ; 之后,请看下面,其中 limitkeepempty 是关键字参数:

  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

方法的补全使用类型推断,因此即使参数是函数的输出,也可以查看参数是否匹配。函数需要是类型稳定的,这样补全才能删除不匹配的方法。

Tab 补全也可以帮助补全字段:

  1. julia> import UUIDs
  2. julia> UUIDs.uuid[TAB]
  3. uuid1 uuid4 uuid_version

函数输出的字段也可以补全:

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

函数输出的字段补全使用类型推断,它只能在函数是类型稳定时建议字段。

自定义配色

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

可用的颜色键通过在 REPL 的帮助模式中输入 Base.text_colors 可以看到。此外,从 0 到 255 的整数可用作具有 256 色支持的终端的颜色键。

你也可以改变帮助、shell 提示符、输入和输出的文本颜色,这通过在上面的 customize_colors 函数中设置 repl 的相应字段(分别为 help_colorshell_colorinput_coloranswer_color)。对于后两个字段,请确定 envcolors 字段也设置为 false。

通过将 Base.text_colors[:bold] 用作颜色,也可以使用粗体格式。例如,要以粗体字体打印输出,可以将以下内容作为 ~/.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)

你还可以自定义用于呈现 warning 和 informational 消息的颜色,这通过设置相应的环境变量。例如,要分别以 magenta、yellow 和 cyan 呈现 error、warning 和 informational 消息,你可以在你的 ~/.julia/config/startup.jl 文件中添加以下内容:

TerminalMenus

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

  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. # `request` displays the menu and returns the index after the
  5. # user has selected a choice
  6. choice = request("Choose your favorite fruit:", menu)
  7. if choice != -1
  8. println("Your favorite fruit is ", options[choice], "!")
  9. else
  10. println("Menu canceled.")
  11. end

Output:

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

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

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

Output:

  1. Select the fruits you like:
  2. [press: d=done, a=all, n=none]
  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

All interface customization is done through the keyword only TerminalMenus.config() function.

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=:na: If :wrap then wrap the cursor around top and bottom, if :nowrap do not wrap cursor
  • supress_output::Bool=false: For testing. If true, menu will not be printed to console.
  • ctrl_c_interrupt::Bool=true: If false, return empty on ^C, if true throw InterruptException() on ^C

Examples

  1. julia> menu = MultiSelectMenu(options, pagesize=5);
  2. julia> request(menu) # ASCII is used by default
  3. [press: d=done, a=all, n=none]
  4. [ ] apple
  5. [X] orange
  6. [ ] grape
  7. > [X] strawberry
  8. v [ ] blueberry
  9. Set([4, 2])
  10. julia> TerminalMenus.config(charset=:unicode)
  11. julia> request(menu)
  12. [press: d=done, a=all, n=none]
  13. apple
  14. orange
  15. grape
  16. strawberry
  17. blueberry
  18. Set([4, 2])
  19. julia> TerminalMenus.config(checked="YEP!", unchecked="NOPE", cursor='⧐')
  20. julia> request(menu)
  21. [press: d=done, a=all, n=none]
  22. NOPE apple
  23. YEP! orange
  24. NOPE grape
  25. YEP! strawberry
  26. NOPE blueberry
  27. Set([4, 2])

References

Base.atreplinit — Function