Module: Fargo::CLI::Completion

Included in:
Console
Defined in:
lib/fargo/cli/completion.rb

Instance Method Summary collapse

Instance Method Details

#add_completion(regex, &block) ⇒ Object



34
35
36
37
# File 'lib/fargo/cli/completion.rb', line 34

def add_completion regex, &block
  @completions ||= {}
  @completions[regex] = block
end

#setup_consoleObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/fargo/cli/completion.rb', line 7

def setup_console
  old_proc = Readline.completion_proc
  Readline.basic_word_break_characters = " \t\n\\'"
  Readline.basic_quote_characters = ''

  Readline.completion_proc = lambda { |str|
    input = Readline.get_input

    candidates, data = [], nil
    regex, proc = @completions.detect{ |k, _|
      data = input.match(k)
    }
    if data
      data = data.to_a
      data.shift
      candidates = proc.call *data
    end

    if candidates.empty?
      old_proc.call str
    else
      str = str.gsub /^"/, ''
      candidates.select{ |n| n.start_with? str }.map{ |s| s.inspect }
    end
  }
end