Skip to content

Instantly share code, notes, and snippets.

@stijlist
Created May 9, 2014 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stijlist/e08c8129b00b83c11248 to your computer and use it in GitHub Desktop.
Save stijlist/e08c8129b00b83c11248 to your computer and use it in GitHub Desktop.

autosuggest

Eventually, a library that enables me to do interactive fish-shell style autosuggestions from within Ruby command-line tools.

require 'colorize'
class Autosuggest
def self.complete(string, set, coloropts={})
res = set.detect {|completion| completion.match string } || string
res = res.gsub(/^#{string}/, "")
if coloropts.empty?
string << res
else
res = res.colorize(coloropts[:completion]) unless coloropts.empty?
string.colorize(coloropts[:input]) << res
end
end
def self.reposition(string, index)
string << ansi_back(string.length - index)
end
private
def ansi_back(num)
"\e[#{num}D"
end
end
# autosuggestions: take a set of strings, see if the input string is
# a completion of any of these
require_relative('../lib/autosuggest.rb')
describe Autosuggest do
let(:coloropts) { {input: :red, completion: :gray} }
context "given an empty completion set" do
let(:cset) { Set.new }
it "should return an unmodified version of the input" do
Autosuggest.complete("hello", cset).should == "hello"
end
context "given an input and completion color" do
it "colors the input substring to match that input color" do
Autosuggest.complete("hello", cset, coloropts)
.should == "hello".colorize(:red)
end
end
end
context "given a non-empty completion set" do
let(:cset) { Set.new(["hello"]) }
it "returns a completion if the input is a prefix of a completion in the set" do
Autosuggest.complete("hel", cset).should == "hello"
end
context "given an input and completion color" do
it "colors the completion substring to match the completion color" do
Autosuggest.complete("hel", cset, coloropts)
.should == "hel".colorize(:red) << "lo".colorize(:gray)
end
end
end
context "given a completion set with repeated substring matches of the input" do
let(:cset) { Set.new(["hello hello"]) }
it "only colorizes the first matched substring" do
Autosuggest.complete("hel", cset, coloropts)
.should == "hel".colorize(:red) << "lo hello".colorize(:gray)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment