Skip to content
Myr

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

5 files+250 added−97 removed

modified:test/test_fzf.rb+127 added-17 removed
1#!/usr/bin/env ruby2# encoding: utf-834require 'rubygems'5require 'curses'6require 'timeout'7require 'stringio'8require 'minitest/autorun'
1 unmodified line
10$LOAD_PATH.unshift File.expand_path('../..', __FILE__)11ENV['FZF_EXECUTABLE'] = '0'12load 'fzf'1314class MockTTY15 def initialize16 @buffer = ''17 @mutex = Mutex.new18 @condv = ConditionVariable.new19 end2021 def read_nonblock sz22 @mutex.synchronize do23 take sz24 end25 end2627 def take sz28 if @buffer.length >= sz29 ret = @buffer[0, sz]30 @buffer = @buffer[sz..-1]31 ret32 end33 end3435 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 end4748 def << str49 @mutex.synchronize do50 @buffer << str51 @condv.broadcast52 end53 end54end5556class TestFZF < MiniTest::Unit::TestCase57 def setup58 ENV.delete 'FZF_DEFAULT_SORT'59 ENV.delete 'FZF_DEFAULT_OPTS'
7 unmodified lines
67 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.query
14 unmodified lines
90 assert_equal nil, fzf.nth9192 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.query
9 unmodified lines
108 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 end114115 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.color
6 unmodified lines
130 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 lines
213 end214 end215 end216171 # 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'223224 def test_trim225 fzf = FZF.new []226 assert_equal ['사.', 6], fzf.trim('가나다라마바사.', 4, true)
4 unmodified lines
231 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'236237 def test_format238 fzf = FZF.new []239 assert_equal [['01234..', false]], fzf.format('0123456789', 7, [])
367 unmodified lines
607 matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE, :fuzzy, [1..-1]608 assert_equal [[list[0], [[8, 9]]]], matcher.match(list, '^s', '', '')609 end610566 def stream_for str611 def stream_for str, delay = 0612 StringIO.new(str).tap do |sio|613 sio.instance_eval do614 alias org_gets gets615616 def gets572 org_gets.tap { |e| sleep 0.5 unless e.nil? }617 org_gets.tap { |e| sleep(@delay) unless e.nil? }618 end619620 def reopen _621 end622 end623 sio.instance_variable_set :@delay, delay624 end625 end626627 def assert_fzf_output opts, given, expected628 stream = stream_for given580 output = StringIO.new629 output = stream_for ''630631 def sorted_lines line632 line.split($/).sort633 end634635 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 end
20 unmodified lines
670 assert_fzf_output %w[--select-1], 'Hello World', 'Hello World'671 end672673 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 end682683 def test_exit_0
8 unmodified lines
692 def test_exit_0_without_query693 assert_fzf_output %w[--exit-0], '', ''694 end695696 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 end709710 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 ')715716 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 end721722 def test_ranking_overlap_match_regions723 list = [724 '1 3 4 2',725 '1 2 3 4'
42 unmodified lines
768 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 end781782 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 end789790 # Manual selection without input791 assert_fzf_output ["--with-nth=2,1"], "hello world", "hello world" do |tty|792 tty << "\r"793 end794795 # 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 end802803 # 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 end809end810
added:.travis.yml+9 added
modified:fzf+88 added-56 removed
5 unmodified lines
6# / /_/_ / / /_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: MIT
37 unmodified lines
52 end53 end54end5556class String57 attr_accessor :orig5859 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 end77end7879class 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_nth8485 def sync86 @shr_mtx.synchronize { yield }87 end
29 unmodified lines
117 @select1 = false118 @exit0 = false119 @filter = nil120 @nth = nil121 @with_nth = nil122 @delim = nil123 @reverse = false124 @prompt = '> '125 @shr_mtx = Mutex.new
45 unmodified lines
171 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 lines
209 @new = []210 @queue = Queue.new211 @pending = nil212 @rev_dir = @reverse ? -1 : 1213 @stdout = $stdout.clone214215 unless @filter216 # Shared variables: needs protection217 @query ||= ''
11 unmodified lines
229 end230 end231232 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 lines
244 end245246 Range.new(*[first, second].map { |e| e > 0 ? e - 1 : e })247 }248 ranges == [0..-1] ? nil : ranges249 end250251 def FZF.build_delim_regex delim252 Regexp.compile(delim) rescue (delim = Regexp.escape(delim))253 Regexp.compile "(?:.*?#{delim})|(?:.+?$)"254 end255256 def burp string, orig = nil257 @stdout.puts(orig || string.orig || string)258 end259260 def start261 if @filter262 start_reader.join263 filter_list @new
6 unmodified lines
270 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 0
67 unmodified lines
346 $stderr.puts message if message347 $stderr.puts %[usage: fzf [options]348349 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)359360 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.363364 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: '> ')372373 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 line379380 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 end385386 def emit event387 @evt_mtx.synchronize do
167 unmodified lines
555 end556 end557558 def init_screen523 @stdout = $stdout.clone559 $stdout.reopen($stderr)560561 C.init_screen562 C.mousemask C::ALL_MOUSE_EVENTS if @mouse
66 unmodified lines
629 @source630 end631632 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 end646647 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 end654655 def start_search &callback656 Thread.new do657 lists = []658 events = {}
83 unmodified lines
742 end743744 def pick745 sync do697 [*@matches.fetch(@ycur, [])][0]746 item = @matches[@ycur]747 item.is_a?(Array) ? item[0] : item748 end749 end750751 def constrain offset, cursor, count, height
297 unmodified lines
1049 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 1
71 unmodified lines
1129 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 end
16 unmodified lines
1157 @tokens_cache = {}1158 end11591160 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 end11631164 def do_match str, pat1165 if @nth
145 unmodified lines
modified:Rakefile+1 added
4 unmodified lines
5 test.pattern = 'test/**/test_*.rb'6 test.verbose = true7end89task :default => :test
modified:README.md+25 added-24 removed
63 unmodified lines
64```65usage: fzf [options]6667 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)7778 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.8182 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: '> ')9091 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 line9798 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```102103fzf will launch curses-based finder, read the list from STDIN, and write the104selected item to STDOUT.
467 unmodified lines