Julia REPL
Julia 內建於 julia
可執行檔中,具備完整功能的互動式命令列 REPL (讀取-評估-列印迴圈)。除了允許快速且輕鬆地評估 Julia 陳述式外,它還具有可搜尋的記錄、標籤完成、許多有用的按鍵繫結,以及專用的說明和 shell 模式。只要不帶任何引數呼叫 julia
或雙擊可執行檔,即可啟動 REPL
$ julia
_
_ _ _(_)_ | Documentation: https://julia-docs.dev.org.tw
(_) | (_) (_) |
_ _ _| |_ __ _ | Type "?" for help, "]?" for Pkg help.
| | | | | | |/ _` | |
| | |_| | | | (_| | | Version 1.10.2 (2024-03-01)
_/ |\__'_|_|_|\__'_| | Official https://julialang.org/ release
|__/ |
julia>
若要結束互動式工作階段,請在空白列中輸入 ^D
– 控制鍵與 d
鍵 – 或輸入 exit()
,然後按 Enter 或 Return 鍵。REPL 會以標語和 julia>
提示字元歡迎您。
不同的提示模式
Julian 模式
REPL 有五種主要操作模式。第一個也是最常見的是 Julian 提示。它是預設的操作模式;每一行最初都以 julia>
開頭。您可以在這裡輸入 Julia 表達式。在輸入完整的表達式後按 Enter 或 Return,將會評估輸入並顯示最後一個表達式的結果。
julia> string(1 + 2)
"3"
有許多實用的功能是互動式工作的獨特之處。除了顯示結果之外,REPL 還會將結果繫結到變數 ans
。行尾的分號可以用作標記,以抑制顯示結果。
julia> string(3 * 4);
julia> ans
"12"
在 Julia 模式中,REPL 支援稱為「提示貼上」的功能。當貼上以 julia>
開頭的文字到 REPL 中時,此功能會啟用。在這種情況下,只有以 julia>
開頭的表達式(以及其他 REPL 模式提示:shell>
、help?>
、pkg>
)會被解析,但其他則會被移除。這使得可以貼上從 REPL 會話中複製的一段文字,而無需清除提示和輸出。此功能預設啟用,但可以使用 REPL.enable_promptpaste(::Bool)
隨意停用或啟用。如果啟用,您可以透過將此段落上方的程式碼區塊直接貼上到 REPL 中來試用它。由於標準 Windows 命令提示字元在偵測貼上動作時有其限制,因此此功能無法在標準 Windows 命令提示字元上使用。
使用 show
函數搭配特定的 IOContext
,在 REPL 中列印物件。特別地,:limit
屬性設為 true
。其他屬性可以在某些 show
方法中接收預設值,如果尚未設定,例如 :compact
。作為實驗性功能,可以透過 Base.active_repl.options.iocontext
字典(將值與屬性關聯)來指定 REPL 使用的屬性。例如
julia> rand(2, 2)
2×2 Array{Float64,2}:
0.8833 0.329197
0.719708 0.59114
julia> show(IOContext(stdout, :compact => false), "text/plain", rand(2, 2))
0.43540323669187075 0.15759787870609387
0.2540832269192739 0.4597637838786053
julia> Base.active_repl.options.iocontext[:compact] = false;
julia> rand(2, 2)
2×2 Array{Float64,2}:
0.2083967319174056 0.13330606013126012
0.6244375177790158 0.9777957560761545
為了在啟動時自動定義此字典的值,可以在 ~/.julia/config/startup.jl
檔案中使用 atreplinit
函數,例如
atreplinit() do repl
repl.options.iocontext[:compact] = false
end
說明模式
當游標位於行首時,可以輸入 ?
將提示符號變更為說明模式。Julia 會嘗試列印說明模式中輸入的任何內容的說明或文件
julia> ? # upon typing ?, the prompt changes (in place) to: help?>
help?> string
search: string String Cstring Cwstring RevString randstring bytestring SubString
string(xs...)
Create a string from any values using the print function.
也可以查詢巨集、類型和變數
help?> @time
@time
A macro to execute an expression, printing the time it took to execute, the number of allocations,
and the total number of bytes its execution caused to be allocated, before returning the value of the
expression.
See also @timev, @timed, @elapsed, and @allocated.
help?> Int32
search: Int32 UInt32
Int32 <: Signed
32-bit signed integer type.
字串或正規表示式文字會使用 apropos
搜尋所有文件字串
help?> "aprop"
REPL.stripmd
Base.Docs.apropos
help?> r"ap..p"
Base.:∘
Base.shell_escape_posixly
Distributed.CachingPool
REPL.stripmd
Base.Docs.apropos
說明模式的另一個功能是可以存取延伸文件字串。你可以輸入類似 ??Print
而不是 ?Print
來執行此操作,這將顯示原始碼文件中的 # 延伸說明
區段。
可以在行首按退格鍵來退出說明模式。
Shell 模式
就像協助模式對快速存取文件很有用一樣,另一個常見的任務是使用系統殼層來執行系統指令。就像在行首輸入?
會進入協助模式一樣,分號 (;
) 會進入殼層模式。而且它可以在行首按 Backspace 來退出。
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> echo hello
hello
對於 Windows 使用者,Julia 的殼層模式不會公開 Windows 殼層指令。因此,這會失敗
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> dir
ERROR: IOError: could not spawn `dir`: no such file or directory (ENOENT)
Stacktrace!
.......
不過,你可以像這樣存取 PowerShell
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\Users\elm>
... 以及像這樣存取 cmd.exe
(請參閱 dir
指令)
julia> ; # upon typing ;, the prompt changes (in place) to: shell>
shell> cmd
Microsoft Windows [version 10.0.17763.973]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Users\elm>dir
Volume in drive C has no label
Volume Serial Number is 1643-0CD7
Directory of C:\Users\elm
29/01/2020 22:15 <DIR> .
29/01/2020 22:15 <DIR> ..
02/02/2020 08:06 <DIR> .atom
Pkg 模式
套件管理員模式接受專門用於載入和更新套件的指令。它是在 Julian REPL 提示字元按 ]
鍵進入,並按 CTRL-C 或在行首按 Backspace 鍵退出。此模式的提示字元為 pkg>
。它支援自己的協助模式,可以在 pkg>
提示字元的行首按 ?
進入。套件管理員模式記載於 Pkg 手冊中,可於 https://julialang.github.io/Pkg.jl/v1/ 取得。
搜尋模式
在以上所有模式中,執行的行會儲存到一個可以搜尋的歷程記錄檔。若要對先前的歷程記錄進行增量搜尋,請輸入 ^R
– 控制鍵與 r
鍵。提示字元會變更為 (reverse-i-search)`':
,而且當你輸入時,搜尋查詢會出現在引號中。與查詢相符的最新結果會在輸入更多字元時動態更新到冒號的右邊。若要使用相同的查詢尋找較舊的結果,請再次輸入 ^R
。
就像 ^R
是反向搜尋一樣,^S
是正向搜尋,提示字元為 (i-search)`':
。兩者可以結合使用,分別移動到先前的或下一個相符的結果。
在 Julia REPL 中執行的所有指令都會記錄在 ~/.julia/logs/repl_history.jl
中,並附上執行時間戳記和您當時所在的 REPL 模式。搜尋模式會查詢此記錄檔,以找出您先前執行的指令。可以在啟動時傳遞 --history-file=no
旗標給 Julia,以停用此功能。
鍵盤繫結
Julia REPL 廣泛使用鍵盤繫結。上面已經介紹了幾個控制鍵繫結(^D
退出、^R
和 ^S
搜尋),但還有更多。除了控制鍵之外,還有 meta 鍵繫結。這些繫結因平台而異,但大多數終端機預設使用 alt 或 option 搭配按鍵來發送 meta 鍵(或可以設定為這樣做),或按 Esc 再按鍵。
鍵盤繫結 | 說明 |
---|---|
程式控制 | |
^D | 退出(當緩衝區為空時) |
^C | 中斷或取消 |
^L | 清除主控台畫面 |
Return/Enter、^J | 換行,如果完整則執行 |
meta-Return/Enter | 插入換行符號而不執行 |
? 或 ; | 進入說明或 shell 模式(當在行首時) |
^R 、^S | 增量式歷程記錄搜尋,如上所述 |
游標移動 | |
右箭頭、^F | 向右移動一個字元 |
左箭頭、^B | 向左移動一個字元 |
ctrl-右、meta-F | 向右移動一個字 |
ctrl-左、meta-B | 向左移動一個字 |
首頁,^A | 移動到行首 |
結尾,^E | 移動到行尾 |
向上鍵,^P | 向上移動一行(或變更為游標前文字相符的上一個歷史記錄項目) |
向下鍵,^N | 向下移動一行(或變更為游標前文字相符的下一筆歷史記錄項目) |
Shift-箭頭鍵 | 根據箭頭鍵的方向移動游標,同時啟用區域(「Shift 選取」) |
向上翻頁,meta-P | 變更為上一個歷史記錄項目 |
向下翻頁,meta-N | 變更為下一個歷史記錄項目 |
meta-< | 變更為第一個歷史記錄項目(如果在歷史記錄中的目前位置之前,則為目前工作階段的第一個歷史記錄項目) |
meta-> | 變更為最後一個歷史記錄項目 |
^-Space | 在編輯區域中設定「標記」(如果區域已啟用,則停用區域) |
^-Space ^-Space | 在編輯區域中設定「標記」並使區域「啟用」,亦即反白顯示 |
^G | 停用區域(亦即不反白顯示) |
^X^X | 將目前位置與標記交換 |
編輯 | |
退格鍵,^H | 刪除前一個字元,或在區域已啟用時刪除整個區域 |
刪除,^D | 向前刪除一個字元(當緩衝區有文字時) |
meta-退格鍵 | 刪除前一個字 |
meta-d | 向前刪除下一個字 |
^W | 刪除到最近空白處的先前文字 |
meta-w | 將目前區域複製到剪貼簿中 |
meta-W | 「剪下」目前區域,將文字置於剪貼簿中 |
^U | 「刪除」至行首,將文字置於刪除環 |
^K | 「刪除」至行尾,將文字置於刪除環 |
^Y | 「擷取」將文字從刪除環插入 |
meta-y | 用刪除環中較舊的項目取代先前擷取的文字 |
^T | 交換游標周圍的字元 |
meta-向上箭頭 | 將目前行與上方行交換 |
meta-向下箭頭 | 將目前行與下方行交換 |
meta-u | 將下一個字詞變為大寫 |
meta-c | 將下一個字詞變為首字大寫 |
meta-l | 將下一個字詞變為小寫 |
^/ , ^_ | 復原前一個編輯動作 |
^Q | 在 REPL 中輸入數字並按下 ^Q 以在對應的堆疊框架或方法中開啟編輯器 |
meta-向左箭頭 | 向左縮排目前行 |
meta-向右箭頭 | 向右縮排目前行 |
meta-. | 插入前一個歷程記錄項目的最後一個字詞 |
meta-e | 在編輯器中編輯目前輸入 |
自訂鍵盤快速鍵
Julia 的 REPL 鍵盤綁定可以透過傳遞字典給 REPL.setup_interface
來完全自訂成使用者的喜好。此字典的鍵可以是字元或字串。鍵 '*'
指的是預設動作。Control 加上字元 x
的綁定用 "^x"
表示。Meta 加上 x
可以寫成 "\\M-x"
或 "\ex"
,而 Control 加上 x
可以寫成 "\\C-x"
或 "^x"
。自訂鍵盤配置的值必須是 nothing
(表示應該略過輸入)或接受簽章 (PromptState, AbstractREPL, Char)
的函式。REPL.setup_interface
函式必須在 REPL 初始化之前呼叫,方法是使用 atreplinit
註冊操作。例如,要將上下箭頭鍵綁定到在不使用前綴搜尋的情況下瀏覽歷史記錄,可以在 ~/.julia/config/startup.jl
中放入以下程式碼
import REPL
import REPL.LineEdit
const mykeys = Dict{Any,Any}(
# Up Arrow
"\e[A" => (s,o...)->(LineEdit.edit_move_up(s) || LineEdit.history_prev(s, LineEdit.mode(s).hist)),
# Down Arrow
"\e[B" => (s,o...)->(LineEdit.edit_move_down(s) || LineEdit.history_next(s, LineEdit.mode(s).hist))
)
function customize_keys(repl)
repl.interface = REPL.setup_interface(repl; extra_repl_keymap = mykeys)
end
atreplinit(customize_keys)
使用者應該參考 LineEdit.jl
來找出鍵盤輸入的可用動作。
Tab 完成
在 REPL 的 Julian 和說明模式中,使用者可以輸入函式或類型的開頭幾個字元,然後按下 tab 鍵來取得所有符合項目的清單
julia> x[TAB]
julia> xor
在某些情況下,它只會完成名稱的一部分,直到下一個歧義
julia> mapf[TAB]
julia> mapfold
如果你再次按下 tab 鍵,你會取得可能完成此名稱的清單
julia> mapfold[TAB]
mapfoldl mapfoldr
與 REPL 的其他組件一樣,搜尋具有大小寫敏感性
julia> stri[TAB]
stride strides string strip
julia> Stri[TAB]
StridedArray StridedMatrix StridedVecOrMat StridedVector String
tab 鍵也可以用來用 Unicode 等價物取代 LaTeX 數學符號,並取得 LaTeX 符合項目的清單
julia> \pi[TAB]
julia> π
π = 3.1415926535897...
julia> e\_1[TAB] = [1,0]
julia> e₁ = [1,0]
2-element Array{Int64,1}:
1
0
julia> e\^1[TAB] = [1 0]
julia> e¹ = [1 0]
1×2 Array{Int64,2}:
1 0
julia> \sqrt[TAB]2 # √ is equivalent to the sqrt function
julia> √2
1.4142135623730951
julia> \hbar[TAB](h) = h / 2\pi[TAB]
julia> ħ(h) = h / 2π
ħ (generic function with 1 method)
julia> \h[TAB]
\hat \hermitconjmatrix \hkswarow \hrectangle
\hatapprox \hexagon \hookleftarrow \hrectangleblack
\hbar \hexagonblack \hookrightarrow \hslash
\heartsuit \hksearow \house \hspace
julia> α="\alpha[TAB]" # LaTeX completion also works in strings
julia> α="α"
可以在手冊的 Unicode 輸入 區段中找到 tab 完成的完整清單。
路徑完成適用於字串和 Julia 的 shell 模式
julia> path="/[TAB]"
.dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/
.dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/
shell> /[TAB]
.dockerenv .juliabox/ boot/ etc/ lib/ media/ opt/ root/ sbin/ sys/ usr/
.dockerinit bin/ dev/ home/ lib64/ mnt/ proc/ run/ srv/ tmp/ var/
字典金鑰也可以使用 Tab 完成
julia> foo = Dict("qwer1"=>1, "qwer2"=>2, "asdf"=>3)
Dict{String,Int64} with 3 entries:
"qwer2" => 2
"asdf" => 3
"qwer1" => 1
julia> foo["q[TAB]
"qwer1" "qwer2"
julia> foo["qwer
Tab 完成也可以協助完成欄位
julia> x = 3 + 4im;
julia> x.[TAB][TAB]
im re
julia> import UUIDs
julia> UUIDs.uuid[TAB][TAB]
uuid1 uuid4 uuid5 uuid_version
函數輸出的欄位也可以完成
julia> split("","")[1].[TAB]
lastindex offset string
函數輸出的欄位完成使用類型推論,而且只有在函數類型穩定時才會建議欄位。
Tab 完成可以協助調查與輸入引數相符的可用方法
julia> max([TAB] # All methods are displayed, not shown here due to size of the list
julia> max([1, 2], [TAB] # All methods where `Vector{Int}` matches as first argument
max(x, y) in Base at operators.jl:215
max(a, b, c, xs...) in Base at operators.jl:281
julia> max([1, 2], max(1, 2), [TAB] # All methods matching the arguments.
max(x, y) in Base at operators.jl:215
max(a, b, c, xs...) in Base at operators.jl:281
在建議的方法中,關鍵字也會顯示在 ;
之後,請參閱下方行,其中 limit
和 keepempty
為關鍵字引數
julia> split("1 1 1", [TAB]
split(str::AbstractString; limit, keepempty) in Base at strings/util.jl:302
split(str::T, splitter; limit, keepempty) where T<:AbstractString in Base at strings/util.jl:277
方法的完成使用類型推論,因此即使引數是函數輸出,也能判斷引數是否相符。函數必須類型穩定,才能讓完成移除不符的方法。
如果您想知道哪些方法可以用於特定引數類型,請使用 ?
作為函數名稱。這顯示一個在 InteractiveUtils 中尋找接受單一字串的函數範例
julia> InteractiveUtils.?("somefile")[TAB]
edit(path::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:197
less(file::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:266
這列出可以在字串上呼叫的 InteractiveUtils
模組中的方法。預設情況下,這會排除所有引數都設定為 Any
的方法,但您可以按住 SHIFT-TAB 而不是 TAB 來查看這些方法
julia> InteractiveUtils.?("somefile")[SHIFT-TAB]
apropos(string) in REPL at REPL/src/docview.jl:796
clipboard(x) in InteractiveUtils at InteractiveUtils/src/clipboard.jl:64
code_llvm(f) in InteractiveUtils at InteractiveUtils/src/codeview.jl:221
code_native(f) in InteractiveUtils at InteractiveUtils/src/codeview.jl:243
edit(path::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:197
edit(f) in InteractiveUtils at InteractiveUtils/src/editless.jl:225
eval(x) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:3
include(x) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:3
less(file::AbstractString) in InteractiveUtils at InteractiveUtils/src/editless.jl:266
less(f) in InteractiveUtils at InteractiveUtils/src/editless.jl:274
report_bug(kind) in InteractiveUtils at InteractiveUtils/src/InteractiveUtils.jl:391
separate_kwargs(args...; kwargs...) in InteractiveUtils at InteractiveUtils/src/macros.jl:7
您也可以使用 ?("somefile")[TAB]
並查看所有模組,但方法清單可能會很長。
透過省略右括號,您可以包含可能需要其他引數的函數
julia> using Mmap
help?> Mmap.?("file",[TAB]
Mmap.Anonymous(name::String, readonly::Bool, create::Bool) in Mmap at Mmap/src/Mmap.jl:16
mmap(file::AbstractString) in Mmap at Mmap/src/Mmap.jl:245
mmap(file::AbstractString, ::Type{T}) where T<:Array in Mmap at Mmap/src/Mmap.jl:245
mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}) where {T<:Array, N} in Mmap at Mmap/src/Mmap.jl:245
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
mmap(file::AbstractString, ::Type{T}, len::Integer) where T<:Array in Mmap at Mmap/src/Mmap.jl:251
mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer; grow, shared) where T<:Array in Mmap at Mmap/src/Mmap.jl:251
mmap(file::AbstractString, ::Type{T}, dims::Tuple{Vararg{Integer, N}}) where {T<:BitArray, N} in Mmap at Mmap/src/Mmap.jl:316
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
mmap(file::AbstractString, ::Type{T}, len::Integer) where T<:BitArray in Mmap at Mmap/src/Mmap.jl:322
mmap(file::AbstractString, ::Type{T}, len::Integer, offset::Integer; grow, shared) where T<:BitArray in Mmap at Mmap/src/Mmap.jl:322
自訂顏色
Julia 和 REPL 使用的顏色也可以自訂。若要變更 Julia 提示字元的顏色,您可以在您的 ~/.julia/config/startup.jl
檔案中新增類似以下的內容,該檔案應放置在您的家目錄中
function customize_colors(repl)
repl.prompt_color = Base.text_colors[:cyan]
end
atreplinit(customize_colors)
在 REPL 的說明模式中輸入 Base.text_colors
可以看到可用的顏色金鑰。此外,對於支援 256 色的終端機,整數 0 到 255 可以用作顏色金鑰。
您也可以透過設定上述 `customize_colors` 函式中 `repl` 的適當欄位(分別為 `help_color`、`shell_color`、`input_color` 和 `answer_color`)來變更說明和 shell 提示、輸入和答案文字的顏色。對於後兩者,請務必將 `envcolors` 欄位設定為 false。
也可以使用 `Base.text_colors[:bold]` 作為顏色來套用粗體格式。例如,若要以粗體字型列印答案,可以在 `~/.julia/config/startup.jl` 中使用下列內容
function customize_colors(repl)
repl.envcolors = false
repl.answer_color = Base.text_colors[:bold]
end
atreplinit(customize_colors)
您也可以透過設定適當的環境變數來自訂用於呈現警告和資訊訊息的顏色。例如,若要分別以洋紅色、黃色和青色呈現錯誤、警告和資訊訊息,您可以在 `~/.julia/config/startup.jl` 檔案中新增下列內容
ENV["JULIA_ERROR_COLOR"] = :magenta
ENV["JULIA_WARN_COLOR"] = :yellow
ENV["JULIA_INFO_COLOR"] = :cyan
變更在 REPL 中作用中的情境模組
在 REPL 中輸入運算式時,它們會預設在 `Main` 模組中評估;
julia> @__MODULE__
Main
您可以透過函式 `REPL.activate(m)` 來變更這個情境模組,其中 `m` 是 `Module`,或是在 REPL 中輸入模組並按下鍵盤組合鍵 Alt-m(游標必須在模組名稱上)。作用中的模組會顯示在提示中
julia> using REPL
julia> REPL.activate(Base)
(Base) julia> @__MODULE__
Base
(Base) julia> using REPL # Need to load REPL into Base module to use it
(Base) julia> REPL.activate(Main)
julia>
julia> Core<Alt-m> # using the keybinding to change module
(Core) julia>
(Core) julia> Main<Alt-m> # going back to Main via keybinding
julia>
接受選用模組引數的函式通常預設為 REPL 情境模組。例如,呼叫 `varinfo()` 會顯示目前作用中模組的變數
julia> module CustomMod
export var, f
var = 1
f(x) = x^2
end;
julia> REPL.activate(CustomMod)
(Main.CustomMod) julia> varinfo()
name size summary
––––––––– ––––––– ––––––––––––––––––––––––––––––––––
CustomMod Module
f 0 bytes f (generic function with 1 method)
var 8 bytes Int64
編號提示
可以取得類似於 IPython REPL 和 Mathematica notebook 的介面,其中包含編號的輸入提示和輸出前綴。這可透過呼叫 REPL.numbered_prompt!()
來完成。如果你想要在啟動時啟用此功能,請將
atreplinit() do repl
@eval import REPL
if !isdefined(repl, :interface)
repl.interface = REPL.setup_interface(repl)
end
REPL.numbered_prompt!(repl)
end
加入你的 startup.jl
檔案。在編號提示中,變數 Out[n]
(其中 n
為整數)可用於參照較早的結果
In [1]: 5 + 3
Out[1]: 8
In [2]: Out[1] + 5
Out[2]: 13
In [3]: Out
Out[3]: Dict{Int64, Any} with 2 entries:
2 => 13
1 => 8
由於先前 REPL 評估的所有輸出都儲存在 Out
變數中,因此如果你傳回許多大型記憶體內物件(例如陣列),則應小心處理,因為只要 Out
中仍有它們的參考,它們就會受到垃圾回收保護。如果你需要移除 Out
中的物件參考,你可以使用 empty!(Out)
清除它儲存的整個歷程記錄,或使用 Out[n] = nothing
清除個別項目。
TerminalMenus
TerminalMenus 是 Julia REPL 的子模組,可在終端機中啟用小型、低調的互動式選單。
範例
import REPL
using REPL.TerminalMenus
options = ["apple", "orange", "grape", "strawberry",
"blueberry", "peach", "lemon", "lime"]
RadioMenu
RadioMenu 允許使用者從清單中選擇一個選項。request
函式會顯示互動式選單,並傳回所選選項的索引。如果使用者按下 'q' 或 ctrl-c
,request
會傳回 -1
。
# `pagesize` is the number of items to be displayed at a time.
# The UI will scroll if the number of options is greater
# than the `pagesize`
menu = RadioMenu(options, pagesize=4)
# `request` displays the menu and returns the index after the
# user has selected a choice
choice = request("Choose your favorite fruit:", menu)
if choice != -1
println("Your favorite fruit is ", options[choice], "!")
else
println("Menu canceled.")
end
輸出
Choose your favorite fruit:
^ grape
strawberry
> blueberry
v peach
Your favorite fruit is blueberry!
MultiSelectMenu
MultiSelectMenu 允許使用者從清單中選取多個選項。
# here we use the default `pagesize` 10
menu = MultiSelectMenu(options)
# `request` returns a `Set` of selected indices
# if the menu us canceled (ctrl-c or q), return an empty set
choices = request("Select the fruits you like:", menu)
if length(choices) > 0
println("You like the following fruits:")
for i in choices
println(" - ", options[i])
end
else
println("Menu canceled.")
end
輸出
Select the fruits you like:
[press: Enter=toggle, a=all, n=none, d=done, q=abort]
[ ] apple
> [X] orange
[X] grape
[ ] strawberry
[ ] blueberry
[X] peach
[ ] lemon
[ ] lime
You like the following fruits:
- orange
- grape
- peach
客製化 / 組態
ConfiguredMenu 子類型
從 Julia 1.6 開始,建議透過建構函式來組態選單。例如,預設的多重選取選單
julia> menu = MultiSelectMenu(options, pagesize=5);
julia> request(menu) # ASCII is used by default
[press: Enter=toggle, a=all, n=none, d=done, q=abort]
[ ] apple
[X] orange
[ ] grape
> [X] strawberry
v [ ] blueberry
可以使用 Unicode 選取和導覽字元來呈現
julia> menu = MultiSelectMenu(options, pagesize=5, charset=:unicode);
julia> request(menu)
[press: Enter=toggle, a=all, n=none, d=done, q=abort]
⬚ apple
✓ orange
⬚ grape
→ ✓ strawberry
↓ ⬚ blueberry
也可以進行更細緻的組態
julia> menu = MultiSelectMenu(options, pagesize=5, charset=:unicode, checked="YEP!", unchecked="NOPE", cursor='⧐');
julia> request(menu)
julia> request(menu)
[press: Enter=toggle, a=all, n=none, d=done, q=abort]
NOPE apple
YEP! orange
NOPE grape
⧐ YEP! strawberry
↓ NOPE blueberry
除了整體的 charset
選項之外,RadioMenu
的可組態選項有
cursor::Char='>'|'→'
:用於游標的字元up_arrow::Char='^'|'↑'
:用於向上箭頭的字元down_arrow::Char='v'|'↓'
:用於向下箭頭的字元updown_arrow::Char='I'|'↕'
:用於一行頁面中的上下箭頭的字元scroll_wrap::Bool=false
:在選單的開頭/結尾處選擇性地換行ctrl_c_interrupt::Bool=true
:如果為false
,則在 ^C 時傳回空值,如果為true
,則在 ^C 時擲回 InterruptException()
MultiSelectMenu
新增
checked::String="[X]"|"✓"
:用於已選取的字串unchecked::String="[ ]"|"⬚")
:用於未選取的字串
你可以建立自己的新選單類型。衍生自 TerminalMenus.ConfiguredMenu
的類型會在建構時組態選單選項。
舊式介面
在 Julia 1.6 之前,且在整個 Julia 1.x 中仍受支援,也可以透過呼叫 TerminalMenus.config()
來設定選單。
參考資料
REPL
Base.atreplinit
— 函式atreplinit(f)
在互動式工作階段中,在 REPL 介面初始化之前,註冊一個一元函式來呼叫;這對於自訂介面很有用。f
的引數是 REPL 物件。此函式應該從 .julia/config/startup.jl
初始化檔案中呼叫。
TerminalMenus
選單
REPL.TerminalMenus.RadioMenu
— 類型RadioMenu
一個允許使用者從清單中選取單一選項的選單。
範例輸出
julia> request(RadioMenu(options, pagesize=4))
Choose your favorite fruit:
^ grape
strawberry
> blueberry
v peach
Your favorite fruit is blueberry!
REPL.TerminalMenus.MultiSelectMenu
— 類型MultiSelectMenu
一個允許使用者從清單中選取多個選項的選單。
範例輸出
julia> request(MultiSelectMenu(options))
Select the fruits you like:
[press: Enter=toggle, a=all, n=none, d=done, q=abort]
[ ] apple
> [X] orange
[X] grape
[ ] strawberry
[ ] blueberry
[X] peach
[ ] lemon
[ ] lime
You like the following fruits:
- orange
- grape
- peach
設定
REPL.TerminalMenus.Config
— 類型Config(; scroll_wrap=false, ctrl_c_interrupt=true, charset=:ascii, cursor::Char, up_arrow::Char, down_arrow::Char)
透過關鍵字引數設定選取選單的行為
scroll_wrap
,如果為true
,則在捲動至第一個或最後一個項目上方或下方時,會導致選單環繞ctrl_c_interrupt
,如果為true
,則在選單選取期間使用者按下 Ctrl-C 時,會擲回InterruptException
。如果為false
,TerminalMenus.request
會從TerminalMenus.selected
傳回預設結果。charset
會影響cursor
、up_arrow
和down_arrow
的預設值,可以為:ascii
或:unicode
cursor
是用來表示按下「Enter」後將會選取的選項的字元。預設值為「>」或「→」,視charset
而定。up_arrow
是在顯示畫面不包含第一個項目時印出的字元。預設值為「^」或「↑」,視charset
而定。down_arrow
是在顯示畫面不包含最後一個項目時印出的字元。預設值為「v」或「↓」,視charset
而定。
ConfiguredMenu
的子類型會在需要時自動印出 cursor
、up_arrow
和 down_arrow
,您的 writeline
方法不應印出這些字元。
Config
在 Julia 1.6 中才可用。在較舊的版本中,請使用全域的 CONFIG
。
REPL.TerminalMenus.MultiSelectConfig
— 類型MultiSelectConfig(; charset=:ascii, checked::String, unchecked::String, kwargs...)
透過關鍵字引數設定多重選取選單的行為
checked
是在選取選項時印出的字串。預設值為「[X]」或「✓」,視charset
而定。unchecked
是在未選取選項時印出的字串。預設值為「[ ]」或「⬚」,視charset
而定。
所有其他關鍵字引數的說明如 TerminalMenus.Config
所述。checked
和 unchecked
不會自動印出,且應由您的 writeline
方法印出。
MultiSelectConfig
可在 Julia 1.6 中使用。在較舊的版本中,請使用全域 CONFIG
。
REPL.TerminalMenus.config
— 函數config( <see arguments> )
僅限關鍵字的函數,用於設定全域選單參數
引數
charset::Symbol=:na
:要使用的 UI 字元(:ascii
或:unicode
);會被其他引數覆寫cursor::Char='>'|'→'
:用於游標的字元up_arrow::Char='^'|'↑'
:用於向上箭頭的字元down_arrow::Char='v'|'↓'
:用於向下箭頭的字元checked::String="[X]"|"✓"
:用於已選取的字串unchecked::String="[ ]"|"⬚")
:用於未選取的字串scroll::Symbol=:nowrap
:如果:wrap
會在頂部和底部折返游標,如果:nowrap
則不會折返游標supress_output::Bool=false
:忽略的舊版引數,請改為將suppress_output
作為關鍵字引數傳遞給request
。ctrl_c_interrupt::Bool=true
:如果為false
,則在 ^C 時傳回空值,如果為true
,則在 ^C 時擲回 InterruptException()
自 Julia 1.6 起,config
已棄用。請改用 Config
或 MultiSelectConfig
。
使用者互動
REPL.TerminalMenus.request
— 函數request(m::AbstractMenu; cursor=1)
顯示選單並進入互動模式。cursor
表示用於初始游標位置的項目編號。cursor
可以是 Int
或 RefValue{Int}
。後者對於從外部觀察和控制游標位置很有用。
傳回 selected(m)
。
cursor
引數需要 Julia 1.6 或更新版本。
request([term,] msg::AbstractString, m::AbstractMenu)
println(msg); request(m)
的簡寫。
AbstractMenu 延伸介面
AbstractMenu
的任何子類型都必須是可變的,並且必須包含欄位 pagesize::Int
和 pageoffset::Int
。任何子類型還必須實作下列函數
REPL.TerminalMenus.pick
— 函數pick(m::AbstractMenu, cursor::Int)
定義當使用者在選單開啟時按下 Enter 鍵時會發生什麼事。如果傳回 true
,request()
將會結束。cursor
會索引選取的位置。
REPL.TerminalMenus.cancel
— 函數cancel(m::AbstractMenu)
定義當使用者取消('q' 或 ctrl-c)一個選單時會發生什麼事。request()
在呼叫此函數後將會永遠結束。
REPL.TerminalMenus.writeline
— 函數writeline(buf::IO, m::AbstractMenu, idx::Int, iscursor::Bool)
將索引 idx
處的選項寫入 buf
。iscursor
若為 true
,表示此項目位於目前的游標位置(按下「Enter」鍵會選取的項目)。
若 m
是 ConfiguredMenu
,TerminalMenus
會印出游標指標。否則,預期呼叫者會處理此類印出。
writeline
需要 Julia 1.6 或更新版本。
在較舊版本的 Julia 中,此函數為 writeLine(buf::IO, m::AbstractMenu, idx, iscursor::Bool)
,且假設 m
未設定。選取和游標指標可以從 TerminalMenus.CONFIG
取得。
此較舊的函數在所有 Julia 1.x 版本中都獲得支援,但會在 Julia 2.0 中移除。
它也必須實作 options
或 numoptions
REPL.TerminalMenus.options
— 函數options(m::AbstractMenu)
傳回一個字串清單,這些字串會顯示為目前頁面中的選項。
或者,實作 numoptions
,如此一來便不需要 options
。
REPL.TerminalMenus.numoptions
— 函數numoptions(m::AbstractMenu) -> Int
傳回選單 m
中的選項數。預設為 length(options(m))
。
此函數需要 Julia 1.6 或更新版本。
如果子類型沒有名為 selected
的欄位,它也必須實作
REPL.TerminalMenus.selected
— 函數selected(m::AbstractMenu)
傳回使用者選取選項的資訊。預設傳回 m.selected
。
以下為選用,但可以允許額外的自訂
REPL.TerminalMenus.header
— 函數header(m::AbstractMenu) -> String
傳回要列印在選單上方的標頭字串。預設為 ""。
REPL.TerminalMenus.keypress
— 函數keypress(m::AbstractMenu, i::UInt32) -> Bool
處理任何非標準的按鍵事件。如果傳回 true
,TerminalMenus.request
將會結束。預設為 false
。