如何编写支持 Tab 补全的 Ruby 命令行应用程序? [英] How to write a Ruby command line app that supports tab completion?

查看:27
本文介绍了如何编写支持 Tab 补全的 Ruby 命令行应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 Ruby 编写一个命令行应用程序,如果您愿意,可以编写一个 shell.

I want to write a command line app, a shell if you will, in Ruby.

我希望用户能够在某些点按 Tab 并提供值的补全.

I want the user to be able to press Tab at certain points and offer completion of values.

我该怎么做?我必须使用什么库?你能指点我一些代码示例吗?

How do I do this? What library must I use? Can you point me to some code examples?

推荐答案

啊,看来标准库毕竟是我的朋友.我正在寻找的是 Readline 库.

Ah, it seems the standard library is my friend after all. What I was looking for is the Readline library.

此处的文档和示例:http://www.ruby-doc.org/stdlib-1.9.3/libdoc/readline/rdoc/Readline.html

特别是,这是该页面中展示补全工作原理的一个很好的例子:

In particular, this is a good example from that page to show how completion works:

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

注意:proc 只接收输入的最后一个单词.如果您希望到目前为止输入整行(因为您想要执行特定于上下文的补全),请将以下行添加到上述代码中:

NOTE: The proc receives only the last word entered. If you want the whole line typed so far (because you want to do context-specific completion), add the following line to the above code:

Readline.completer_word_break_characters = "" #Pass whole line to proc each time

(默认设置为代表单词边界的字符列表,并且仅将最后一个单词传递到您的 proc).

(This is by default set to a list of characters that represent word boundaries and causes only the last word to be passed into your proc).

这篇关于如何编写支持 Tab 补全的 Ruby 命令行应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆