本文簡要介紹ruby語言中 Readline.completion_proc =
的用法。
用法
completion_proc = proc
指定 Proc
對象 proc
以確定完成行為。它應該接受輸入字符串並返回一個完成候選數組。
如果 proc
為 nil,則使用默認完成。
傳遞給 Proc
的 String
取決於 Readline.completer_word_break_characters
屬性。默認情況下,光標下的單詞被傳遞給 Proc
。例如,如果輸入是 “foo bar” 那麽隻有 “bar” 會被傳遞給完成 Proc
。
成功完成後, Readline.completion_append_character
將附加到輸入中,以便用戶可以開始處理他們的下一個參數。
例子
完成靜態列表
require 'readline'
LIST = [
'search', 'download', 'open',
'help', 'history', 'quit',
'url', 'next', 'clear',
'prev', 'past'
].sort
comp = proc { |s| LIST.grep(/^#{Regexp.escape(s)}/) }
Readline.completion_append_character = " "
Readline.completion_proc = comp
while line = Readline.readline('> ', true)
p line
end
完成目錄內容
require 'readline'
Readline.completion_append_character = " "
Readline.completion_proc = Proc.new do |str|
Dir[str+'*'].grep(/^#{Regexp.escape(str)}/)
end
while line = Readline.readline('> ', true)
p line
end
自動完成策略
使用 auto-complete 時,有些策略效果很好。要獲得一些想法,您可以查看 irb 的completion.rb 文件。
常見的策略是獲取可能的完成列表並將其過濾到以用戶輸入開頭的那些完成。在上述示例中,使用了 Enumerator.grep
。輸入被轉義以防止 Regexp
特殊字符幹擾匹配。
使用 Abbrev
庫生成補全也可能會有所幫助。
如果 proc
不響應調用方法,則引發 ArgumentError
。
相關用法
- Ruby Readline.completion_case_fold用法及代碼示例
- Ruby Readline.completion_append_character =用法及代碼示例
- Ruby Readline.readline用法及代碼示例
- Ruby Readline.point用法及代碼示例
- Ruby Readline模塊用法及代碼示例
- Ruby Regexp named_captures()用法及代碼示例
- Ruby Recorder類用法及代碼示例
- Ruby Regexp to_s()用法及代碼示例
- Ruby Regexp.eql?用法及代碼示例
- Ruby Regexp hash()用法及代碼示例
- Ruby Resolution.new用法及代碼示例
- Ruby Regexp.fixed_encoding?用法及代碼示例
- Ruby Resolver.resolve用法及代碼示例
- Ruby Regexp類用法及代碼示例
- Ruby Regexp.options用法及代碼示例
- Ruby Refinement.import_methods用法及代碼示例
- Ruby Regexp inspect()用法及代碼示例
- Ruby Regexp.inspect用法及代碼示例
- Ruby Regexp.names用法及代碼示例
- Ruby Resolution.require_nested_dependencies_for用法及代碼示例
- Ruby Requirement.parse用法及代碼示例
- Ruby Regexp source()用法及代碼示例
- Ruby Resolution.possibility用法及代碼示例
- Ruby Regexp match()用法及代碼示例
- Ruby Regexp.rxp =~ str用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Readline.completion_proc =。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。