Merge pull request #104 from junegunn/add-with-nth
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add --with-nth option
authored by Junegunn Choi · committed by Junegunn Choi · parents 6fd6fff, 7571baa · Browse files · 5 files·+250 added−97 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+250 added−97 removed
- tests:+127 added−17 removed
- other:+123 added−80 removed
Provenance
- Commit
80819f3- Tree
53c5022- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent 1
6fd6fff- Parent 2
7571baa
5 files changed+250 added−97 removed
modified:test/test_fzf.rb+127 added-17 removed
1 #!/usr/bin/env ruby2 # encoding: utf-83 4+require 'rubygems'5 require 'curses'6 require 'timeout'7 require 'stringio'8 require 'minitest/autorun'1 unmodified line10 $LOAD_PATH.unshift File.expand_path('../..', __FILE__)11 ENV['FZF_EXECUTABLE'] = '0'12 load 'fzf'13 14+class MockTTY15+ def initialize16+ @buffer = ''17+ @mutex = Mutex.new18+ @condv = ConditionVariable.new19+ end20+21+ def read_nonblock sz22+ @mutex.synchronize do23+ take sz24+ end25+ end26+27+ def take sz28+ if @buffer.length >= sz29+ ret = @buffer[0, sz]30+ @buffer = @buffer[sz..-1]31+ ret32+ end33+ end34+35+ def getc36+ sleep 0.137+ while true38+ @mutex.synchronize do39+ if char = take(1)40+ return char41+ else42+ @condv.wait(@mutex)43+ end44+ end45+ end46+ end47+48+ def << str49+ @mutex.synchronize do50+ @buffer << str51+ @condv.broadcast52+ end53+ end54+end55+56 class TestFZF < MiniTest::Unit::TestCase57 def setup58 ENV.delete 'FZF_DEFAULT_SORT'59 ENV.delete 'FZF_DEFAULT_OPTS'7 unmodified lines67 assert_equal true, fzf.color68 assert_equal nil, fzf.rxflag69 assert_equal true, fzf.mouse70 assert_equal nil, fzf.nth71+ assert_equal nil, fzf.with_nth72 assert_equal true, fzf.color73 assert_equal false, fzf.black74 assert_equal true, fzf.ansi25675 assert_equal '', fzf.query14 unmodified lines90 assert_equal nil, fzf.nth91 92 ENV['FZF_DEFAULT_OPTS'] =93 '-x -m -s 10000 -q " hello world " +c +2 --select-1 -0 ' <<50- '--no-mouse -f "goodbye world" --black --nth=3,-1,2 --reverse --print-query'94+ '--no-mouse -f "goodbye world" --black --with-nth=3,-3..,2 --nth=3,-1,2 --reverse --print-query'95 fzf = FZF.new []96 assert_equal 10000, fzf.sort97 assert_equal ' hello world ',98 fzf.query9 unmodified lines108 assert_equal true, fzf.exit0109 assert_equal true, fzf.reverse110 assert_equal true, fzf.print_query111 assert_equal [2..2, -1..-1, 1..1], fzf.nth112+ assert_equal [2..2, -3..-1, 1..1], fzf.with_nth113 end114 115 def test_option_parser116 # Long opts117 fzf = FZF.new %w[--sort=2000 --no-color --multi +i --query hello --select-1118 --exit-0 --filter=howdy --extended-exact74- --no-mouse --no-256 --nth=1 --reverse --prompt (hi)119+ --no-mouse --no-256 --nth=1 --with-nth=.. --reverse --prompt (hi)120 --print-query]121 assert_equal 2000, fzf.sort122 assert_equal true, fzf.multi123 assert_equal false, fzf.color6 unmodified lines130 assert_equal true, fzf.exit0131 assert_equal 'howdy', fzf.filter132 assert_equal :exact, fzf.extended133 assert_equal [0..0], fzf.nth134+ assert_equal nil, fzf.with_nth135 assert_equal true, fzf.reverse136 assert_equal '(hi)', fzf.prompt137 assert_equal true, fzf.print_query138 74 unmodified lines213 end214 end215 end216 171- # FIXME Only on 1.9 or above217 def test_width218 fzf = FZF.new []219 assert_equal 5, fzf.width('abcde')220 assert_equal 4, fzf.width('한글')221 assert_equal 5, fzf.width('한글.')177- end222+ end if RUBY_VERSION >= '1.9'223 224 def test_trim225 fzf = FZF.new []226 assert_equal ['사.', 6], fzf.trim('가나다라마바사.', 4, true)4 unmodified lines231 assert_equal ['가나', 6], fzf.trim('가나다라마바사.', 5, false)232 assert_equal ['가나a', 6], fzf.trim('가나ab라마바사.', 5, false)233 assert_equal ['가나ab', 5], fzf.trim('가나ab라마바사.', 6, false)234 assert_equal ['가나ab', 5], fzf.trim('가나ab라마바사.', 7, false)190- end235+ end if RUBY_VERSION >= '1.9'236 237 def test_format238 fzf = FZF.new []239 assert_equal [['01234..', false]], fzf.format('0123456789', 7, [])367 unmodified lines607 matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE, :fuzzy, [1..-1]608 assert_equal [[list[0], [[8, 9]]]], matcher.match(list, '^s', '', '')609 end610 566- def stream_for str611+ def stream_for str, delay = 0612 StringIO.new(str).tap do |sio|613 sio.instance_eval do614 alias org_gets gets615 616 def gets572- org_gets.tap { |e| sleep 0.5 unless e.nil? }617+ org_gets.tap { |e| sleep(@delay) unless e.nil? }618 end619+620+ def reopen _621+ end622 end623+ sio.instance_variable_set :@delay, delay624 end625 end626 627 def assert_fzf_output opts, given, expected628 stream = stream_for given580- output = StringIO.new629+ output = stream_for ''630 631+ def sorted_lines line632+ line.split($/).sort633+ end634+635 begin636+ tty = MockTTY.new637 $stdout = output584- FZF.new(opts, stream).start638+ fzf = FZF.new(opts, stream)639+ fzf.instance_variable_set :@tty, tty640+ thr = block_given? && Thread.new { yield tty }641+ fzf.start642+ thr && thr.join643 rescue SystemExit => e644 assert_equal 0, e.status587- assert_equal expected, output.string.chomp645+ assert_equal sorted_lines(expected), sorted_lines(output.string)646 ensure647 $stdout = STDOUT648 end649 end20 unmodified lines670 assert_fzf_output %w[--select-1], 'Hello World', 'Hello World'671 end672 673 def test_select_1_ambiguity616- stream = stream_for "Hello\nWorld"674 begin618- Timeout::timeout(2) do619- FZF.new(%w[--query=o --select-1], stream).start675+ Timeout::timeout(0.5) do676+ assert_fzf_output %w[--query=o --select-1], "hello\nworld", "should not match"677 end621- flunk 'Should not reach here'622- rescue Exception => e678+ rescue Timeout::Error679 Curses.close_screen624- assert_instance_of Timeout::Error, e680 end681 end682 683 def test_exit_08 unmodified lines692 def test_exit_0_without_query693 assert_fzf_output %w[--exit-0], '', ''694 end695 696+ def test_with_nth697+ source = "hello world\nbatman"698+ assert_fzf_output %w[-0 -1 --with-nth=2,1 -x -q ^worl],699+ source, 'hello world'700+ assert_fzf_output %w[-0 -1 --with-nth=2,1 -x -q llo$],701+ source, 'hello world'702+ assert_fzf_output %w[-0 -1 --with-nth=.. -x -q llo$],703+ source, ''704+ assert_fzf_output %w[-0 -1 --with-nth=2,2,2,..,1 -x -q worlworlworlhellworlhell],705+ source, 'hello world'706+ assert_fzf_output %w[-0 -1 --with-nth=1,1,-1,1 -x -q batbatbatbat],707+ source, 'batman'708+ end709+710+ def test_with_nth_transform711+ fzf = FZF.new %w[--with-nth 2..,1]712+ assert_equal 'my world hello', fzf.transform('hello my world')713+ assert_equal 'my world hello', fzf.transform('hello my world')714+ assert_equal 'my world hello', fzf.transform('hello my world ')715+716+ fzf = FZF.new %w[--with-nth 2,-1,2]717+ assert_equal 'my world my', fzf.transform('hello my world')718+ assert_equal 'world world world', fzf.transform('hello world')719+ assert_equal 'world world world', fzf.transform('hello world ')720+ end721+722 def test_ranking_overlap_match_regions723 list = [724 '1 3 4 2',725 '1 2 3 4'42 unmodified lines768 tmp = Tempfile.new('fzf')769 tmp << 'hello ' << [0xff].pack('C*') << ' world' << $/ << [0xff].pack('C*')770 tmp.close771 begin691- Timeout::timeout(1) do772+ Timeout::timeout(0.5) do773 FZF.new(%w[-n..,1,2.. -q^ -x], File.open(tmp.path)).start774 end775 rescue Timeout::Error776+ Curses.close_screen777 end778 ensure779 tmp.unlink780 end781+782+ def test_with_nth_mock_tty783+ # Manual selection with input784+ assert_fzf_output ["--with-nth=2,1"], "hello world", "hello world" do |tty|785+ tty << "world"786+ tty << "hell"787+ tty << "\r"788+ end789+790+ # Manual selection without input791+ assert_fzf_output ["--with-nth=2,1"], "hello world", "hello world" do |tty|792+ tty << "\r"793+ end794+795+ # Manual selection with input and --multi796+ lines = "hello world\ngoodbye world"797+ assert_fzf_output %w[-m --with-nth=2,1], lines, lines do |tty|798+ tty << "o"799+ tty << "\e[Z\e[Z"800+ tty << "\r"801+ end802+803+ # Manual selection without input and --multi804+ assert_fzf_output %w[-m --with-nth=2,1], lines, lines do |tty|805+ tty << "\e[Z\e[Z"806+ tty << "\r"807+ end808+ end809 end810 added:.travis.yml+9 added
123456789language: rubyrvm: - "1.8.7" - "1.9.3" - "2.0.0" - "2.1.1"
install: gem install curses minitest
modified:fzf+88 added-56 removed
5 unmodified lines6 # / /_/_ / / /_7 # / __/ / /_/ __/8 # /_/ /___/_/ Fuzzy finder for your shell9 #10-# Version: 0.8.7 (Aug 17, 2014)10+# Version: 0.8.8 (Nov 4, 2014)11 #12 # Author: Junegunn Choi13 # URL: https://github.com/junegunn/fzf14 # License: MIT37 unmodified lines52 end53 end54 end55 56+class String57+ attr_accessor :orig58+59+ def tokenize delim, nth60+ unless delim61+ # AWK default62+ prefix_length = (index(/\S/) || 0) rescue 063+ tokens = scan(/\S+\s*/) rescue []64+ else65+ prefix_length = 066+ tokens = scan(delim) rescue []67+ end68+ nth.map { |n|69+ if n.begin == 0 && n.end == -170+ [prefix_length, tokens.join]71+ elsif part = tokens[n]72+ [prefix_length + (tokens[0...(n.begin)] || []).join.length,73+ part.join]74+ end75+ }.compact76+ end77+end78+79 class FZF80 C = Curses81 attr_reader :rxflag, :sort, :nth, :color, :black, :ansi256, :reverse, :prompt,82 :mouse, :multi, :query, :select1, :exit0, :filter, :extended,60- :print_query83+ :print_query, :with_nth84 85 def sync86 @shr_mtx.synchronize { yield }87 end29 unmodified lines117 @select1 = false118 @exit0 = false119 @filter = nil120 @nth = nil121+ @with_nth = nil122 @delim = nil123 @reverse = false124 @prompt = '> '125 @shr_mtx = Mutex.new45 unmodified lines171 usage 1, 'field expression required' unless nth = argv.shift172 @nth = parse_nth nth173 when /^-n([0-9,-\.]+)$/, /^--nth=([0-9,-\.]+)$/174 @nth = parse_nth $1175+ when '--with-nth'176+ usage 1, 'field expression required' unless nth = argv.shift177+ @with_nth = parse_nth nth178+ when /^--with-nth=([0-9,-\.]+)$/179+ @with_nth = parse_nth $1180 when '-d', '--delimiter'181 usage 1, 'delimiter required' unless delim = argv.shift182 @delim = FZF.build_delim_regex delim183 when /^-d(.+)$/, /^--delimiter=(.+)$/25 unmodified lines209 @new = []210 @queue = Queue.new211 @pending = nil212 @rev_dir = @reverse ? -1 : 1213+ @stdout = $stdout.clone214 215 unless @filter216 # Shared variables: needs protection217 @query ||= ''11 unmodified lines229 end230 end231 232 def parse_nth nth203- nth.split(',').map { |expr|233+ ranges = nth.split(',').map { |expr|234 x = proc { usage 1, "invalid field expression: #{expr}" }235 first, second = expr.split('..', 2)236 x.call if !first.empty? && first.to_i == 0 ||237 second && !second.empty? && (second.to_i == 0 || second.include?('.'))6 unmodified lines244 end245 246 Range.new(*[first, second].map { |e| e > 0 ? e - 1 : e })247 }248+ ranges == [0..-1] ? nil : ranges249 end250 251 def FZF.build_delim_regex delim252 Regexp.compile(delim) rescue (delim = Regexp.escape(delim))253 Regexp.compile "(?:.*?#{delim})|(?:.+?$)"254 end255 256+ def burp string, orig = nil257+ @stdout.puts(orig || string.orig || string)258+ end259+260 def start261 if @filter262 start_reader.join263 filter_list @new6 unmodified lines270 len = empty ? get(:@count) : matches.length271 if loaded272 if @select1 && len == 1273 puts @query if @print_query239- puts empty ? matches.first : matches.first.first274+ burp(empty ? matches.first : matches.first.first)275 exit 0276 elsif @exit0 && len == 0277 puts @query if @print_query278 exit 067 unmodified lines346 $stderr.puts message if message347 $stderr.puts %[usage: fzf [options]348 349 Search315- -x, --extended Extended-search mode316- -e, --extended-exact Extended-search mode (exact match)317- -i Case-insensitive match (default: smart-case match)318- +i Case-sensitive match319- -n, --nth=N[,..] Comma-separated list of field index expressions320- for limiting search scope. Each can be a non-zero321- integer or a range expression ([BEGIN]..[END])322- -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)350+ -x, --extended Extended-search mode351+ -e, --extended-exact Extended-search mode (exact match)352+ -i Case-insensitive match (default: smart-case match)353+ +i Case-sensitive match354+ -n, --nth=N[,..] Comma-separated list of field index expressions355+ for limiting search scope. Each can be a non-zero356+ integer or a range expression ([BEGIN]..[END])357+ --with-nth=N[,..] Transform the item using index expressions for search358+ -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)359 360 Search result325- -s, --sort=MAX Maximum number of matched items to sort (default: 1000)326- +s, --no-sort Do not sort the result. Keep the sequence unchanged.361+ -s, --sort=MAX Maximum number of matched items to sort (default: 1000)362+ +s, --no-sort Do not sort the result. Keep the sequence unchanged.363 364 Interface329- -m, --multi Enable multi-select with tab/shift-tab330- --no-mouse Disable mouse331- +c, --no-color Disable colors332- +2, --no-256 Disable 256-color333- --black Use black background334- --reverse Reverse orientation335- --prompt=STR Input prompt (default: '> ')365+ -m, --multi Enable multi-select with tab/shift-tab366+ --no-mouse Disable mouse367+ +c, --no-color Disable colors368+ +2, --no-256 Disable 256-color369+ --black Use black background370+ --reverse Reverse orientation371+ --prompt=STR Input prompt (default: '> ')372 373 Scripting338- -q, --query=STR Start the finder with the given query339- -1, --select-1 Automatically select the only match340- -0, --exit-0 Exit immediately when there's no match341- -f, --filter=STR Filter mode. Do not start interactive finder.342- --print-query Print query as the first line374+ -q, --query=STR Start the finder with the given query375+ -1, --select-1 Automatically select the only match376+ -0, --exit-0 Exit immediately when there's no match377+ -f, --filter=STR Filter mode. Do not start interactive finder.378+ --print-query Print query as the first line379 380 Environment variables345- FZF_DEFAULT_COMMAND Default command to use when input is tty346- FZF_DEFAULT_OPTS Defaults options. (e.g. "-x -m --sort 10000")] + $/ + $/347- exit x381+ FZF_DEFAULT_COMMAND Default command to use when input is tty382+ FZF_DEFAULT_OPTS Defaults options. (e.g. "-x -m --sort 10000")] + $/ + $/383+ exit x384 end385 386 def emit event387 @evt_mtx.synchronize do167 unmodified lines555 end556 end557 558 def init_screen523- @stdout = $stdout.clone559 $stdout.reopen($stderr)560 561 C.init_screen562 C.mousemask C::ALL_MOUSE_EVENTS if @mouse66 unmodified lines629 @source630 end631 632 Thread.new do633+ if @with_nth634+ while line = stream.gets635+ emit(:new) { @new << transform(line) }636+ end637+ else598- while line = stream.gets599- emit(:new) { @new << line.chomp }638+ while line = stream.gets639+ emit(:new) { @new << line.chomp }640+ end641 end642 emit(:loaded) { true }643 @spinner.clear if @spinner644 end645 end646 647+ def transform line648+ line = line.chomp649+ mut = (line =~ / $/ ? line : line + ' ').650+ tokenize(@delim, @with_nth).map { |e| e.last }.join('').sub(/ *$/, '')651+ mut.orig = line652+ mut653+ end654+655 def start_search &callback656 Thread.new do657 lists = []658 events = {}83 unmodified lines742 end743 744 def pick745 sync do697- [*@matches.fetch(@ycur, [])][0]746+ item = @matches[@ycur]747+ item.is_a?(Array) ? item[0] : item748 end749 end750 751 def constrain offset, cursor, count, height297 unmodified lines1049 sync do1050 if @selects.has_key? sel1051 @selects.delete sel1052 else1003- @selects[sel] = 11053+ @selects[sel] = sel.orig1054 end1055 end1056 vselect { |v| v + case o1057 when :stab then 171 unmodified lines1129 q, selects = geta(:@query, :@selects)1130 @stdout.puts q if @print_query1131 if got1132 if selects.empty?1083- @stdout.puts got1133+ burp got1134 else1085- selects.each do |sel, _|1086- @stdout.puts sel1135+ selects.each do |sel, orig|1136+ burp sel, orig1137 end1138 end1139 end1140 end16 unmodified lines1157 @tokens_cache = {}1158 end1159 1160 def tokenize str1111- @tokens_cache[str] ||=1112- begin1113- unless @delim1114- # AWK default1115- prefix_length = (str.index(/\S/) || 0) rescue 01116- tokens = str.scan(/\S+\s*/) rescue []1117- else1118- prefix_length = 01119- tokens = str.scan(@delim) rescue []1120- end1121- @nth.map { |n|1122- if n.begin == 0 && n.end == -11123- [prefix_length, tokens.join]1124- elsif part = tokens[n]1125- [prefix_length + (tokens[0...(n.begin)] || []).join.length,1126- part.join]1127- end1128- }.compact1129- end1161+ @tokens_cache[str] ||= str.tokenize(@delim, @nth)1162 end1163 1164 def do_match str, pat1165 if @nth145 unmodified linesmodified:Rakefile+1 added
4 unmodified lines5 test.pattern = 'test/**/test_*.rb'6 test.verbose = true7 end8 9+task :default => :testmodified:README.md+25 added-24 removed
63 unmodified lines64 ```65 usage: fzf [options]66 67 Search68- -x, --extended Extended-search mode69- -e, --extended-exact Extended-search mode (exact match)70- -i Case-insensitive match (default: smart-case match)71- +i Case-sensitive match72- -n, --nth=N[,..] Comma-separated list of field index expressions73- for limiting search scope. Each can be a non-zero74- integer or a range expression ([BEGIN]..[END])75- -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)68+ -x, --extended Extended-search mode69+ -e, --extended-exact Extended-search mode (exact match)70+ -i Case-insensitive match (default: smart-case match)71+ +i Case-sensitive match72+ -n, --nth=N[,..] Comma-separated list of field index expressions73+ for limiting search scope. Each can be a non-zero74+ integer or a range expression ([BEGIN]..[END])75+ --with-nth=N[,..] Transform the item using index expressions for search76+ -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)77 78 Search result78- -s, --sort=MAX Maximum number of matched items to sort (default: 1000)79- +s, --no-sort Do not sort the result. Keep the sequence unchanged.79+ -s, --sort=MAX Maximum number of matched items to sort (default: 1000)80+ +s, --no-sort Do not sort the result. Keep the sequence unchanged.81 82 Interface82- -m, --multi Enable multi-select with tab/shift-tab83- --no-mouse Disable mouse84- +c, --no-color Disable colors85- +2, --no-256 Disable 256-color86- --black Use black background87- --reverse Reverse orientation88- --prompt=STR Input prompt (default: '> ')83+ -m, --multi Enable multi-select with tab/shift-tab84+ --no-mouse Disable mouse85+ +c, --no-color Disable colors86+ +2, --no-256 Disable 256-color87+ --black Use black background88+ --reverse Reverse orientation89+ --prompt=STR Input prompt (default: '> ')90 91 Scripting91- -q, --query=STR Start the finder with the given query92- -1, --select-1 Automatically select the only match93- -0, --exit-0 Exit immediately when there's no match94- -f, --filter=STR Filter mode. Do not start interactive finder.95- --print-query Print query as the first line92+ -q, --query=STR Start the finder with the given query93+ -1, --select-1 Automatically select the only match94+ -0, --exit-0 Exit immediately when there's no match95+ -f, --filter=STR Filter mode. Do not start interactive finder.96+ --print-query Print query as the first line97 98 Environment variables98- FZF_DEFAULT_COMMAND Default command to use when input is tty99- FZF_DEFAULT_OPTS Defaults options. (e.g. "-x -m --sort 10000")99+ FZF_DEFAULT_COMMAND Default command to use when input is tty100+ FZF_DEFAULT_OPTS Defaults options. (e.g. "-x -m --sort 10000")101 ```102 103 fzf will launch curses-based finder, read the list from STDIN, and write the104 selected item to STDOUT.467 unmodified lines