1
0
Fork 0
mirror of https://github.com/pry/pry.git synced 2022-11-09 12:35:05 -05:00

Refactor completion API (git diff -w)

This commit is contained in:
Conrad Irwin 2012-12-28 15:19:21 -08:00
parent 2c95c99735
commit fdb703a8de
6 changed files with 218 additions and 216 deletions

View file

@ -12,8 +12,6 @@ class Pry
else else
_pry_.push_prompt Pry::SHELL_PROMPT _pry_.push_prompt Pry::SHELL_PROMPT
_pry_.custom_completions = Pry::FILE_COMPLETIONS _pry_.custom_completions = Pry::FILE_COMPLETIONS
Readline.completion_proc = Pry::InputCompleter.build_completion_proc target,
_pry_.instance_eval(&Pry::FILE_COMPLETIONS)
end end
end end
end end

View file

@ -3,37 +3,38 @@
class Pry class Pry
module BondCompleter module BondCompleter
def self.call(input, options)
def self.build_completion_proc(target, pry=nil, commands=[""]) Pry.th[:pry] = options[:pry]
if !@started Bond.agent.call(input)
@started = true
start
end
Pry.th[:pry] = pry
proc{ |*a| Bond.agent.call(*a) }
end end
def self.start def self.start
Bond.start(:eval_binding => lambda{ Pry.th[:pry].current_context }) Bond.start(:eval_binding => lambda{ Pry.th[:pry] && Pry.th[:pry].current_context || TOPLEVEL_BINDING })
Bond.complete(:on => /\A/) do |input| Bond.complete(:on => /\A/) do |input|
Pry.commands.complete(input.line, Pry.commands.complete(input.line,
:pry_instance => Pry.th[:pry], :pry_instance => Pry.th[:pry],
:target => Pry.th[:pry].current_context, :target => Pry.th[:pry].current_context,
:command_set => Pry.th[:pry].commands) :command_set => Pry.th[:pry].commands)
end end
self
end end
end end
# Implements tab completion for Readline in Pry # Implements tab completion for Readline in Pry
module InputCompleter module InputCompleter
if Readline.respond_to?("basic_word_break_characters=") def self.call(input, options)
Readline.basic_word_break_characters = " \t\n\"\\'`><=;|&{(" build_completion_proc(options[:target], options[:pry], options[:custom_completions]).call input
end end
Readline.completion_append_character = nil def self.start
if Readline.respond_to?("basic_word_break_characters=")
Readline.basic_word_break_characters = " \t\n\"\\'`><=;|&{("
end
Readline.completion_append_character = nil
self
end
ReservedWords = [ ReservedWords = [
"BEGIN", "END", "BEGIN", "END",
@ -63,199 +64,200 @@ class Pry
# Return a new completion proc for use by Readline. # Return a new completion proc for use by Readline.
# @param [Binding] target The current binding context. # @param [Binding] target The current binding context.
# @param [Array<String>] commands The array of Pry commands. # @param [Array<String>] commands The array of Pry commands.
def self.build_completion_proc(target, pry=nil, commands=[""]) def self.call(input, options)
proc do |input| custom_completions = options[:custom_completions] || []
# if there are multiple contexts e.g. cd 1/2/3 # if there are multiple contexts e.g. cd 1/2/3
# get new target for 1/2 and find candidates for 3 # get new target for 1/2 and find candidates for 3
path, input = build_path(input) path, input = build_path(input)
unless path.call.empty? if path.call.empty?
target, _ = Pry::Helpers::BaseHelpers.context_from_object_path(path.call, pry) target = options[:target]
target = target.last else
end target, _ = Pry::Helpers::BaseHelpers.context_from_object_path(path.call, options[:pry])
target = target.last
end
begin begin
bind = target bind = target
case input case input
# Complete stdlib symbols # Complete stdlib symbols
when /^(\/[^\/]*\/)\.([^.]*)$/ when /^(\/[^\/]*\/)\.([^.]*)$/
# Regexp # Regexp
receiver = $1 receiver = $1
message = Regexp.quote($2) message = Regexp.quote($2)
candidates = Regexp.instance_methods.collect(&:to_s) candidates = Regexp.instance_methods.collect(&:to_s)
select_message(path, receiver, message, candidates) select_message(path, receiver, message, candidates)
when /^([^\]]*\])\.([^.]*)$/ when /^([^\]]*\])\.([^.]*)$/
# Array # Array
receiver = $1 receiver = $1
message = Regexp.quote($2) message = Regexp.quote($2)
candidates = Array.instance_methods.collect(&:to_s) candidates = Array.instance_methods.collect(&:to_s)
select_message(path, receiver, message, candidates) select_message(path, receiver, message, candidates)
when /^([^\}]*\})\.([^.]*)$/ when /^([^\}]*\})\.([^.]*)$/
# Proc or Hash # Proc or Hash
receiver = $1 receiver = $1
message = Regexp.quote($2) message = Regexp.quote($2)
candidates = Proc.instance_methods.collect(&:to_s) candidates = Proc.instance_methods.collect(&:to_s)
candidates |= Hash.instance_methods.collect(&:to_s) candidates |= Hash.instance_methods.collect(&:to_s)
select_message(path, receiver, message, candidates) select_message(path, receiver, message, candidates)
when /^(:[^:.]*)$/ when /^(:[^:.]*)$/
# Symbol # Symbol
if Symbol.respond_to?(:all_symbols) if Symbol.respond_to?(:all_symbols)
sym = Regexp.quote($1) sym = Regexp.quote($1)
candidates = Symbol.all_symbols.collect{|s| ":" + s.id2name} candidates = Symbol.all_symbols.collect{|s| ":" + s.id2name}
candidates.grep(/^#{sym}/)
else
[]
end
when /^::([A-Z][^:\.\(]*)$/
# Absolute Constant or class methods
receiver = $1
candidates = Object.constants.collect(&:to_s)
candidates.grep(/^#{receiver}/).collect{|e| "::" + e}
# Complete target symbols
when /^([A-Z][A-Za-z0-9]*)$/
# Constant
message = $1
begin
context = target.eval("self")
context = context.class unless context.respond_to? :constants
candidates = context.constants.collect(&:to_s)
rescue
candidates = []
end
candidates = candidates.grep(/^#{message}/).collect(&path)
when /^([A-Z].*)::([^:.]*)$/
# Constant or class methods
receiver = $1
message = Regexp.quote($2)
begin
candidates = eval("#{receiver}.constants.collect(&:to_s)", bind)
candidates |= eval("#{receiver}.methods.collect(&:to_s)", bind)
rescue RescuableException
candidates = []
end
candidates.grep(/^#{message}/).collect{|e| receiver + "::" + e}
when /^(:[^:.]+)\.([^.]*)$/
# Symbol
receiver = $1
message = Regexp.quote($2)
candidates = Symbol.instance_methods.collect(&:to_s)
select_message(path, receiver, message, candidates)
when /^(-?(0[dbo])?[0-9_]+(\.[0-9_]+)?([eE]-?[0-9]+)?)\.([^.]*)$/
# Numeric
receiver = $1
message = Regexp.quote($5)
begin
candidates = eval(receiver, bind).methods.collect(&:to_s)
rescue RescuableException
candidates = []
end
select_message(path, receiver, message, candidates)
when /^(-?0x[0-9a-fA-F_]+)\.([^.]*)$/#
# Numeric(0xFFFF)
receiver = $1
message = Regexp.quote($2)
begin
candidates = eval(receiver, bind).methods.collect(&:to_s)
rescue RescuableException
candidates = []
end
select_message(path, receiver, message, candidates)
when /^(\$[^.]*)$/
# Global variables
regmessage = Regexp.new(Regexp.quote($1))
candidates = global_variables.collect(&:to_s).grep(regmessage)
when /^([^."].*)\.([^.]*)$/
# Variable
receiver = $1
message = Regexp.quote($2)
gv = eval("global_variables", bind).collect(&:to_s)
lv = eval("local_variables", bind).collect(&:to_s)
cv = eval("self.class.constants", bind).collect(&:to_s)
if (gv | lv | cv).include?(receiver) or /^[A-Z]/ =~ receiver && /\./ !~ receiver
# foo.func and foo is local var. OR
# Foo::Bar.func
begin
candidates = eval("#{receiver}.methods", bind).collect(&:to_s)
rescue RescuableException
candidates = []
end
else
# func1.func2
candidates = []
ObjectSpace.each_object(Module){|m|
begin
name = m.name.to_s
rescue RescuableException
name = ""
end
next if name != "IRB::Context" and
/^(IRB|SLex|RubyLex|RubyToken)/ =~ name
# jruby doesn't always provide #instance_methods() on each
# object.
if m.respond_to?(:instance_methods)
candidates.concat m.instance_methods(false).collect(&:to_s)
end
}
candidates.sort!
candidates.uniq!
end
select_message(path, receiver, message, candidates)
when /^\.([^.]*)$/
# Unknown(maybe String)
receiver = ""
message = Regexp.quote($1)
candidates = String.instance_methods(true).collect(&:to_s)
select_message(path, receiver, message, candidates)
candidates.grep(/^#{sym}/)
else else
[]
candidates = eval(
"methods | private_methods | local_variables | " \
"self.class.constants | instance_variables",
bind
).collect(&:to_s)
if eval("respond_to?(:class_variables)", bind)
candidates += eval("class_variables", bind).collect(&:to_s)
end
candidates = (candidates|ReservedWords|commands).grep(/^#{Regexp.quote(input)}/)
candidates.collect(&path)
end end
rescue RescuableException
[] when /^::([A-Z][^:\.\(]*)$/
# Absolute Constant or class methods
receiver = $1
candidates = Object.constants.collect(&:to_s)
candidates.grep(/^#{receiver}/).collect{|e| "::" + e}
# Complete target symbols
when /^([A-Z][A-Za-z0-9]*)$/
# Constant
message = $1
begin
context = target.eval("self")
context = context.class unless context.respond_to? :constants
candidates = context.constants.collect(&:to_s)
rescue
candidates = []
end
candidates = candidates.grep(/^#{message}/).collect(&path)
when /^([A-Z].*)::([^:.]*)$/
# Constant or class methods
receiver = $1
message = Regexp.quote($2)
begin
candidates = eval("#{receiver}.constants.collect(&:to_s)", bind)
candidates |= eval("#{receiver}.methods.collect(&:to_s)", bind)
rescue RescuableException
candidates = []
end
candidates.grep(/^#{message}/).collect{|e| receiver + "::" + e}
when /^(:[^:.]+)\.([^.]*)$/
# Symbol
receiver = $1
message = Regexp.quote($2)
candidates = Symbol.instance_methods.collect(&:to_s)
select_message(path, receiver, message, candidates)
when /^(-?(0[dbo])?[0-9_]+(\.[0-9_]+)?([eE]-?[0-9]+)?)\.([^.]*)$/
# Numeric
receiver = $1
message = Regexp.quote($5)
begin
candidates = eval(receiver, bind).methods.collect(&:to_s)
rescue RescuableException
candidates = []
end
select_message(path, receiver, message, candidates)
when /^(-?0x[0-9a-fA-F_]+)\.([^.]*)$/#
# Numeric(0xFFFF)
receiver = $1
message = Regexp.quote($2)
begin
candidates = eval(receiver, bind).methods.collect(&:to_s)
rescue RescuableException
candidates = []
end
select_message(path, receiver, message, candidates)
when /^(\$[^.]*)$/
# Global variables
regmessage = Regexp.new(Regexp.quote($1))
candidates = global_variables.collect(&:to_s).grep(regmessage)
when /^([^."].*)\.([^.]*)$/
# Variable
receiver = $1
message = Regexp.quote($2)
gv = eval("global_variables", bind).collect(&:to_s)
lv = eval("local_variables", bind).collect(&:to_s)
cv = eval("self.class.constants", bind).collect(&:to_s)
if (gv | lv | cv).include?(receiver) or /^[A-Z]/ =~ receiver && /\./ !~ receiver
# foo.func and foo is local var. OR
# Foo::Bar.func
begin
candidates = eval("#{receiver}.methods", bind).collect(&:to_s)
rescue RescuableException
candidates = []
end
else
# func1.func2
candidates = []
ObjectSpace.each_object(Module){|m|
begin
name = m.name.to_s
rescue RescuableException
name = ""
end
next if name != "IRB::Context" and
/^(IRB|SLex|RubyLex|RubyToken)/ =~ name
# jruby doesn't always provide #instance_methods() on each
# object.
if m.respond_to?(:instance_methods)
candidates.concat m.instance_methods(false).collect(&:to_s)
end
}
candidates.sort!
candidates.uniq!
end
select_message(path, receiver, message, candidates)
when /^\.([^.]*)$/
# Unknown(maybe String)
receiver = ""
message = Regexp.quote($1)
candidates = String.instance_methods(true).collect(&:to_s)
select_message(path, receiver, message, candidates)
else
candidates = eval(
"methods | private_methods | local_variables | " \
"self.class.constants | instance_variables",
bind
).collect(&:to_s)
if eval("respond_to?(:class_variables)", bind)
candidates += eval("class_variables", bind).collect(&:to_s)
end
candidates = (candidates|ReservedWords|custom_completions).grep(/^#{Regexp.quote(input)}/)
candidates.collect(&path)
end end
rescue RescuableException
[]
end end
end end

View file

@ -270,9 +270,9 @@ class Pry
config.output_prefix = "=> " config.output_prefix = "=> "
if defined?(Bond) && Readline::VERSION !~ /editline/i if defined?(Bond) && Readline::VERSION !~ /editline/i
config.completer = Pry::BondCompleter config.completer = Pry::BondCompleter.start
else else
config.completer = Pry::InputCompleter config.completer = Pry::InputCompleter.start
end end
config.gist ||= OpenStruct.new config.gist ||= OpenStruct.new

View file

@ -171,6 +171,18 @@ class Pry
end end
end end
# Generate completions.
#
# @param [String] what the user has typed so far
# @return [Array<String>] possible completions
def complete(input)
Pry.critical_section do
Pry.config.completer.call(input, :target => current_binding,
:pry => self,
:custom_completions => instance_eval(&custom_completions))
end
end
# Injects a local variable into the provided binding. # Injects a local variable into the provided binding.
# @param [String] name The name of the local to inject. # @param [String] name The name of the local to inject.
# @param [Object] value The value to set the local to. # @param [Object] value The value to set the local to.

View file

@ -70,15 +70,11 @@ class Pry
@indent.reset if pry.eval_string.empty? @indent.reset if pry.eval_string.empty?
current_prompt = pry.select_prompt current_prompt = pry.select_prompt
completion_proc = Pry.config.completer.build_completion_proc(pry.current_binding, pry,
pry.instance_eval(&pry.custom_completions))
safe_completion_proc = proc{ |*a| Pry.critical_section{ completion_proc.call(*a) } }
indentation = Pry.config.auto_indent ? @indent.current_prefix : '' indentation = Pry.config.auto_indent ? @indent.current_prefix : ''
begin begin
val = read_line("#{current_prompt}#{indentation}", safe_completion_proc) val = read_line("#{current_prompt}#{indentation}")
# Handle <Ctrl+C> like Bash, empty the current input buffer but do not quit. # Handle <Ctrl+C> like Bash, empty the current input buffer but do not quit.
# This is only for ruby-1.9; other versions of ruby do not let you send Interrupt # This is only for ruby-1.9; other versions of ruby do not let you send Interrupt
@ -148,15 +144,17 @@ class Pry
# Returns the next line of input to be used by the pry instance. # Returns the next line of input to be used by the pry instance.
# @param [String] current_prompt The prompt to use for input. # @param [String] current_prompt The prompt to use for input.
# @return [String] The next line of input. # @return [String] The next line of input.
def read_line(current_prompt="> ", completion_proc=nil) def read_line(current_prompt)
handle_read_errors do handle_read_errors do
if defined? Coolline and input.is_a? Coolline if defined? Coolline and input.is_a? Coolline
input.completion_proc = proc do |cool| input.completion_proc = proc do |cool|
completions = completion_proc.call cool.completed_word completions = @pry.complete cool.completed_word
completions.compact completions.compact
end end
elsif input.respond_to? :completion_proc= elsif input.respond_to? :completion_proc=
input.completion_proc = completion_proc input.completion_proc = proc do |input|
@pry.complete input
end
end end
if input == Readline if input == Readline

View file

@ -1,12 +1,8 @@
require 'helper' require 'helper'
def new_completer(bind, pry=nil)
Pry::InputCompleter.build_completion_proc(Pry.binding_for(bind), pry)
end
def completer_test(bind, pry=nil, assert_flag=true) def completer_test(bind, pry=nil, assert_flag=true)
completer = new_completer(bind, pry) test = proc {|symbol|
test = proc {|symbol| completer.call(symbol[0..-2]).include?(symbol).should == assert_flag} Pry::InputCompleter.call(symbol[0..-2], :target => Pry.binding_for(bind), :pry => pry).include?(symbol).should == assert_flag}
return proc {|*symbols| symbols.each(&test) } return proc {|*symbols| symbols.each(&test) }
end end
@ -40,16 +36,12 @@ describe Pry::InputCompleter do
# another jruby hack :(( # another jruby hack :((
if !Pry::Helpers::BaseHelpers.jruby? if !Pry::Helpers::BaseHelpers.jruby?
it "should not crash if there's a Module that has a symbolic name." do it "should not crash if there's a Module that has a symbolic name." do
completer = Pry::InputCompleter.build_completion_proc(Pry.binding_for(Object.new)) lambda{ Pry::InputCompleter.call "a.to_s.", :target => Pry.binding_for(Object.new) }.should.not.raise Exception
lambda{ completer.call "a.to_s." }.should.not.raise Exception
end end
end end
it 'should take parenthesis and other characters into account for symbols' do it 'should take parenthesis and other characters into account for symbols' do
b = Pry.binding_for(Object.new) lambda { Pry::InputCompleter.call(":class)", :target => Pry.binding_for(Object.new)) }.should.not.raise(RegexpError)
completer = Pry::InputCompleter.build_completion_proc(b)
lambda { completer.call(":class)") }.should.not.raise(RegexpError)
end end
it 'should complete instance variables' do it 'should complete instance variables' do
@ -128,7 +120,7 @@ describe Pry::InputCompleter do
completer_test(binding).call('o.foo') completer_test(binding).call('o.foo')
# trailing slash # trailing slash
new_completer(Mod).call('Mod2/').include?('Mod2/').should == true Pry::InputCompleter.call('Mod2/', :target => Pry.binding_for(Mod)).include?('Mod2/').should == true
end end
it 'should complete for arbitrary scopes' do it 'should complete for arbitrary scopes' do
@ -199,7 +191,7 @@ describe Pry::InputCompleter do
completer_test(binding).call('o.foo') completer_test(binding).call('o.foo')
# trailing slash # trailing slash
new_completer(Mod).call('Mod2/').include?('Mod2/').should == true Pry::InputCompleter.call('Mod2/', :target => Pry.binding_for(Mod)).include?('Mod2/').should == true
end end