Forum: Ruby Readline Question - capture full line (done) and completing on that (not done yet)

4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (shevegen)
on 2014-06-18 13:57
Hi,

I am still struggling to get readline-completion on a full line.

Consider this code example:

    require 'pp'
    require 'readline'

    MAIN_ARRAY = %w( abcde fghij )

    puts 'Type your input next:'
    Readline.completion_case_fold = true
    Readline.completer_word_break_characters = "\n"
    Readline.completion_append_character = ' '

    Readline.completion_proc = proc {|input|
      result = []
      case input
      when /^rcd/
        result << MAIN_ARRAY
      end
      result = result.flatten
      result
    }

    Readline.readline

Now I wish to type this:

"rcd a" and then press enter.

Then I would like this input to be completed to:

"rcd abcde"

This is stored in the constant MAIN_ARRAY

I never get the completion though...
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2014-06-19 04:03
> Now I wish to type this:

>>"rcd a" and then press enter.

> Then I would like this input to be completed to:

>> "rcd abcde"

Ruby's readline is an implementation of GNU readline, and GNU readline
uses "TAB" completion--not  "ENTER" completion, so I don't know if you
can get that.  But you *can* get this:

Type:

    rcd a<TAB>

and get:

   rcd abcde<SPACE>

and then you can hit <ENTER>.


require 'readline'

MAIN_ARRAY = %w( abcde fghij )

#puts 'Type your input next:'
Readline.completion_case_fold = true
Readline.completer_word_break_characters = "\n"
Readline.completion_append_character = ' '

Readline.completion_proc = proc {|input|
  first, second = input.split(/\s+/)

  if first == 'rcd'
    matching_words = MAIN_ARRAY.select do |word|
      word.match /^#{Regexp.escape(second)}/
    end

    matching_words.size == 1 ?
      'rcd ' + matching_words[0]
      : matching_words
  else
    ["something", "else?"]
  end

}

Readline.readline(
  "Type your input next:\n",
  add_hist = true,
)
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.