Skip to content
Myr

Merge branch 'devel'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Junegunn Choi · committed by Junegunn Choi · parents ff34c6b, 6037e1e · Browse files · 5 files+979 added−482 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+979 added−482 removed

  • tests:+297 added−0 removed
  • other:+682 added−482 removed

5 files+979 added−482 removed

added:test/test_fzf.rb+297 added
1#!/usr/bin/env ruby2# encoding: utf-834require 'minitest/autorun'5$LOAD_PATH.unshift File.expand_path('../..', __FILE__)6load 'fzf'78class TestFZF < MiniTest::Unit::TestCase9 def test_default_options10 fzf = FZF.new []11 assert_equal 500, fzf.sort12 assert_equal false, fzf.multi13 assert_equal true, fzf.color14 assert_equal Regexp::IGNORECASE, fzf.rxflag1516 begin17 ENV['FZF_DEFAULT_SORT'] = '1000'18 fzf = FZF.new []19 assert_equal 1000, fzf.sort20 ensure21 ENV.delete 'FZF_DEFAULT_SORT'22 end23 end2425 def test_option_parser26 # Long opts27 fzf = FZF.new %w[--sort=2000 --no-color --multi +i]28 assert_equal 2000, fzf.sort29 assert_equal true, fzf.multi30 assert_equal false, fzf.color31 assert_equal 0, fzf.rxflag3233 # Short opts34 fzf = FZF.new %w[-s 2000 +c -m +i]35 assert_equal 2000, fzf.sort36 assert_equal true, fzf.multi37 assert_equal false, fzf.color38 assert_equal 0, fzf.rxflag39 end4041 def test_invalid_option42 [%w[-s 2000 +s], %w[yo dawg]].each do |argv|43 assert_raises(SystemExit) do44 fzf = FZF.new argv45 end46 end47 end4849 # FIXME Only on 1.9 or above50 def test_width51 fzf = FZF.new []52 assert_equal 5, fzf.width('abcde')53 assert_equal 4, fzf.width('한글')54 assert_equal 5, fzf.width('한글.')55 end5657 def test_trim58 fzf = FZF.new []59 assert_equal ['사.', 6], fzf.trim('가나다라마바사.', 4, true)60 assert_equal ['바사.', 5], fzf.trim('가나다라마바사.', 5, true)61 assert_equal ['바사.', 5], fzf.trim('가나다라마바사.', 6, true)62 assert_equal ['마바사.', 4], fzf.trim('가나다라마바사.', 7, true)63 assert_equal ['가나', 6], fzf.trim('가나다라마바사.', 4, false)64 assert_equal ['가나', 6], fzf.trim('가나다라마바사.', 5, false)65 assert_equal ['가나a', 6], fzf.trim('가나ab라마바사.', 5, false)66 assert_equal ['가나ab', 5], fzf.trim('가나ab라마바사.', 6, false)67 assert_equal ['가나ab', 5], fzf.trim('가나ab라마바사.', 7, false)68 end6970 def test_format71 fzf = FZF.new []72 assert_equal [['01234..', false]], fzf.format('0123456789', 7, [])73 assert_equal [['012', false], ['34', true], ['..', false]],74 fzf.format('0123456789', 7, [[3, 5]])75 assert_equal [['..56', false], ['789', true]],76 fzf.format('0123456789', 7, [[7, 10]])77 assert_equal [['..56', false], ['78', true], ['9', false]],78 fzf.format('0123456789', 7, [[7, 9]])7980 (3..5).each do |i|81 assert_equal [['..', false], ['567', true], ['89', false]],82 fzf.format('0123456789', 7, [[i, 8]])83 end8485 assert_equal [['..', false], ['345', true], ['..', false]],86 fzf.format('0123456789', 7, [[3, 6]])87 assert_equal [['012', false], ['34', true], ['..', false]],88 fzf.format('0123456789', 7, [[3, 5]])8990 # Multi-region91 assert_equal [["0", true], ["1", false], ["2", true], ["34..", false]],92 fzf.format('0123456789', 7, [[0, 1], [2, 3]])9394 assert_equal [["..", false], ["5", true], ["6", false], ["78", true], ["9", false]],95 fzf.format('0123456789', 7, [[3, 6], [7, 9]])9697 assert_equal [["..", false], ["3", true], ["4", false], ["5", true], ["..", false]],98 fzf.format('0123456789', 7, [[3, 4], [5, 6]])99100 # Multi-region Overlap101 assert_equal [["..", false], ["345", true], ["..", false]],102 fzf.format('0123456789', 7, [[4, 5], [3, 6]])103 end104105 def test_fuzzy_matcher106 matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE107 list = %w[108 juice109 juiceful110 juiceless111 juicily112 juiciness113 juicy]114 assert matcher.caches.empty?115 assert_equal(116 [["juice", [[0, 1]]],117 ["juiceful", [[0, 1]]],118 ["juiceless", [[0, 1]]],119 ["juicily", [[0, 1]]],120 ["juiciness", [[0, 1]]],121 ["juicy", [[0, 1]]]], matcher.match(list, 'j', '', '').sort)122 assert !matcher.caches.empty?123 assert_equal [list.object_id], matcher.caches.keys124 assert_equal 1, matcher.caches[list.object_id].length125 assert_equal 6, matcher.caches[list.object_id]['j'].length126127 assert_equal(128 [["juicily", [[0, 5]]],129 ["juiciness", [[0, 5]]]], matcher.match(list, 'jii', '', '').sort)130131 assert_equal(132 [["juicily", [[2, 5]]],133 ["juiciness", [[2, 5]]]], matcher.match(list, 'ii', '', '').sort)134135 assert_equal 3, matcher.caches[list.object_id].length136 assert_equal 2, matcher.caches[list.object_id]['ii'].length137138 # TODO : partial_cache139 end140141 def test_fuzzy_matcher_case_sensitive142 assert_equal [['Fruit', [[0, 5]]]],143 FZF::FuzzyMatcher.new(0).match(%w[Fruit Grapefruit], 'Fruit', '', '').sort144145 assert_equal [["Fruit", [[0, 5]]], ["Grapefruit", [[5, 10]]]],146 FZF::FuzzyMatcher.new(Regexp::IGNORECASE).147 match(%w[Fruit Grapefruit], 'Fruit', '', '').sort148 end149150 def test_extended_fuzzy_matcher151 matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE152 list = %w[153 juice154 juiceful155 juiceless156 juicily157 juiciness158 juicy159 _juice]160 match = proc { |q, prefix|161 matcher.match(list, q, prefix, '').sort.map { |p| [p.first, p.last.sort] }162 }163164 assert matcher.caches.empty?165 3.times do166 ['y j', 'j y'].each do |pat|167 (0..pat.length - 1).each do |prefix_length|168 prefix = pat[0, prefix_length]169 assert_equal(170 [["juicily", [[0, 1], [6, 7]]],171 ["juicy", [[0, 1], [4, 5]]]],172 match.call(pat, prefix))173 end174 end175176 # $177 assert_equal [["juiceful", [[7, 8]]]], match.call('l$', '')178 assert_equal [["juiceful", [[7, 8]]],179 ["juiceless", [[5, 6]]],180 ["juicily", [[5, 6]]]], match.call('l', '')181182 # ^183 assert_equal list.length, match.call('j', '').length184 assert_equal list.length - 1, match.call('^j', '').length185186 # !187 assert_equal 0, match.call('!j', '').length188189 # ! + ^190 assert_equal [["_juice", []]], match.call('!^j', '')191192 # ! + $193 assert_equal list.length - 1, match.call('!l$', '').length194195 # ! + f196 assert_equal [["juicy", [[4, 5]]]], match.call('y !l', '')197 end198 assert !matcher.caches.empty?199 end200201 def test_xfuzzy_matcher_prefix_cache202 matcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE203 list = %w[204 a.java205 b.java206 java.jive207 c.java$208 d.java209 ]210 2.times do211 assert_equal 5, matcher.match(list, 'java', 'java', '').length212 assert_equal 3, matcher.match(list, 'java$', 'java$', '').length213 assert_equal 1, matcher.match(list, 'java$$', 'java$$', '').length214215 assert_equal 0, matcher.match(list, '!java', '!java', '').length216 assert_equal 4, matcher.match(list, '!^jav', '!^jav', '').length217 assert_equal 4, matcher.match(list, '!^java', '!^java', '').length218 assert_equal 2, matcher.match(list, '!^java !b !c', '!^java', '').length219 end220 end221222 def test_sort_by_rank223 matcher = FZF::FuzzyMatcher.new Regexp::IGNORECASE224 xmatcher = FZF::ExtendedFuzzyMatcher.new Regexp::IGNORECASE225 list = %w[226 0____1227 0_____1228 01229 ____0_1230 01_231 _01_232 0______1233 ___01___234 ]235 assert_equal(236 [["01", [[0, 2]]],237 ["01_", [[0, 2]]],238 ["_01_", [[1, 3]]],239 ["___01___", [[3, 5]]],240 ["____0_1", [[4, 7]]],241 ["0____1", [[0, 6]]],242 ["0_____1", [[0, 7]]],243 ["0______1", [[0, 8]]]],244 FZF.new([]).sort_by_rank(matcher.match(list, '01', '', '')))245246 assert_equal(247 [["01", [[0, 1], [1, 2]]],248 ["01_", [[0, 1], [1, 2]]],249 ["_01_", [[1, 2], [2, 3]]],250 ["0____1", [[0, 1], [5, 6]]],251 ["0_____1", [[0, 1], [6, 7]]],252 ["____0_1", [[4, 5], [6, 7]]],253 ["0______1", [[0, 1], [7, 8]]],254 ["___01___", [[3, 4], [4, 5]]]],255 FZF.new([]).sort_by_rank(xmatcher.match(list, '0 1', '', '')))256257 assert_equal(258 [["_01_", [[1, 3], [0, 4]]],259 ["0____1", [[0, 6], [1, 3]]],260 ["0_____1", [[0, 7], [1, 3]]],261 ["0______1", [[0, 8], [1, 3]]],262 ["___01___", [[3, 5], [0, 2]]],263 ["____0_1", [[4, 7], [0, 2]]]],264 FZF.new([]).sort_by_rank(xmatcher.match(list, '01 __', '', '')))265 end266267 if RUBY_PLATFORM =~ /darwin/268 NFD = '한글'269 def test_nfc270 assert_equal 6, NFD.length271 assert_equal ["한글", [[0, 1], [1, 2]]],272 FZF::UConv.nfc(NFD, [[0, 3], [3, 6]])273274 nfd2 = 'before' + NFD + 'after'275 assert_equal 6 + 6 + 5, nfd2.length276277 nfc, offsets = FZF::UConv.nfc(nfd2, [[4, 14], [9, 13]])278 o1, o2 = offsets279 assert_equal 'before한글after', nfc280 assert_equal 're한글af', nfc[(o1.first...o1.last)]281 assert_equal '글a', nfc[(o2.first...o2.last)]282 end283284 def test_nfd285 nfc = '한글'286 nfd = FZF::UConv.nfd(nfc)287 assert_equal 6, nfd.length288 assert_equal NFD, nfd289 end290 end291292 def test_split293 assert_equal ["a", "b", "c", "\xFF", "d", "e", "f"],294 FZF::UConv.split("abc\xFFdef")295 end296end297
modified:fzf+661 added-481 removed
8 unmodified lines
9#10# URL: https://github.com/junegunn/fzf11# Author: Junegunn Choi12# License: MIT13# Last update: November 10, 201313# Last update: November 15, 201314#15# Copyright (c) 2013 Junegunn Choi16#17# MIT License
16 unmodified lines
34# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION35# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION36# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.3738def usage x39 puts %[usage: fzf [options]38require 'thread'39require 'curses'4041 -m, --multi Enable multi-select42 -s, --sort=MAX Maximum number of matched items to sort. Default: 500.43 +s, --no-sort Do not sort the result. Keep the sequence unchanged.44 +i Case-sensitive match45 +c, --no-color Disable colors]46 exit x47end41class FZF42 C = Curses43 attr_reader :rxflag, :sort, :color, :multi4449stdout = $stdout.clone50$stdout.reopen($stderr)45 class AtomicVar46 def initialize value47 @value = value48 @mutex = Mutex.new49 end5052usage 0 unless (%w[--help -h] & ARGV).empty?53@rxflag = ARGV.delete('+i') ? 0 : Regexp::IGNORECASE54@sort = %w[+s --no-sort].map { |e| ARGV.delete e }.compact.empty? ?55 ENV.fetch('FZF_DEFAULT_SORT', 500).to_i : nil56@color = %w[+c --no-color].map { |e| ARGV.delete e }.compact.empty?57@multi = !%w[-m --multi].map { |e| ARGV.delete e }.compact.empty?58rest = ARGV.join ' '59if sort = rest.match(/(-s|--sort=?) ?([0-9]+)/)60 usage 1 unless @sort61 @sort = sort[2].to_i62 rest = rest.delete sort[0]63end64usage 1 unless rest.empty?51 def get52 @mutex.synchronize { @value }53 end5466require 'thread'67require 'curses'55 def set value = nil56 if block_given?57 @mutex.synchronize { @value = yield @value }58 else59 @mutex.synchronize { @value = value }60 end61 end6269@mtx = Mutex.new70@smtx = Mutex.new71@cv = ConditionVariable.new72@lists = []73@new = []74@query = ''75@matches = []76@count = 077@cursor_x = 078@vcursor = 079@events = {}80@selects = {} # ordered >= 1.963 def method_missing sym, *args, &blk64 @mutex.synchronize { @value.send(sym, *args, &blk) }65 end66 end6782case RUBY_PLATFORM83when /darwin/84 module UConv85 CHOSUNG = 0x110086 JUNGSUNG = 0x116187 JONGSUNG = 0x11A788 CHOSUNGS = 1989 JUNGSUNGS = 2190 JONGSUNGS = 2891 JJCOUNT = JUNGSUNGS * JONGSUNGS92 NFC_BEGIN = 0xAC0093 NFC_END = NFC_BEGIN + CHOSUNGS * JUNGSUNGS * JONGSUNGS68 def initialize argv, source = $stdin69 usage 0 unless (%w[--help -h] & argv).empty?70 @rxflag = argv.delete('+i') ? 0 : Regexp::IGNORECASE71 @sort = %w[+s --no-sort].map { |e| argv.delete e }.compact.empty? ?72 ENV.fetch('FZF_DEFAULT_SORT', 500).to_i : nil73 @color = %w[+c --no-color].map { |e| argv.delete e }.compact.empty?74 @multi = !%w[-m --multi].map { |e| argv.delete e }.compact.empty?75 @xmode = !%w[-x --extended].map { |e| argv.delete e }.compact.empty?76 rest = argv.join ' '77 if sort = rest.match(/(-s|--sort=?) ?([0-9]+)/)78 usage 1 unless @sort79 @sort = sort[2].to_i80 rest = rest.delete sort[0]81 end82 usage 1 unless rest.empty?8384 @source = source85 @mtx = Mutex.new86 @cv = ConditionVariable.new87 @events = {}88 @new = []89 @smtx = Mutex.new90 @cursor_x = AtomicVar.new(0)91 @query = AtomicVar.new('')92 @matches = AtomicVar.new([])93 @count = AtomicVar.new(0)94 @vcursor = AtomicVar.new(0)95 @fan = AtomicVar.new('-\|/-\|/'.split(//))96 @selects = AtomicVar.new({}) # ordered >= 1.997 end9899 def start100 @stdout = $stdout.clone101 $stdout.reopen($stderr)102103 init_screen104 start_reader105 start_search106 start_loop107 end108109 def usage x110 $stderr.puts %[usage: fzf [options]111112 -m, --multi Enable multi-select113 -x, --extended Extended mode114 -s, --sort=MAX Maximum number of matched items to sort. Default: 500.115 +s, --no-sort Do not sort the result. Keep the sequence unchanged.116 +i Case-sensitive match117 +c, --no-color Disable colors]118 exit x119 end120121 case RUBY_PLATFORM122 when /darwin/123 module UConv124 CHOSUNG = 0x1100125 JUNGSUNG = 0x1161126 JONGSUNG = 0x11A7127 CHOSUNGS = 19128 JUNGSUNGS = 21129 JONGSUNGS = 28130 JJCOUNT = JUNGSUNGS * JONGSUNGS131 NFC_BEGIN = 0xAC00132 NFC_END = NFC_BEGIN + CHOSUNGS * JUNGSUNGS * JONGSUNGS13395 def self.nfd str96 ret = ''97 str.split(//).each do |c|98 cp = c.ord99 if cp >= NFC_BEGIN && cp < NFC_END100 idx = cp - NFC_BEGIN101 cho = CHOSUNG + idx / JJCOUNT102 jung = JUNGSUNG + (idx % JJCOUNT) / JONGSUNGS103 jong = JONGSUNG + idx % JONGSUNGS104 ret << cho << jung105 ret << jong if jong != JONGSUNG106 else107 ret << c134 def self.nfd str135 ret = ''136 str.split(//).each do |c|137 cp = c.ord138 if cp >= NFC_BEGIN && cp < NFC_END139 idx = cp - NFC_BEGIN140 cho = CHOSUNG + idx / JJCOUNT141 jung = JUNGSUNG + (idx % JJCOUNT) / JONGSUNGS142 jong = JONGSUNG + idx % JONGSUNGS143 ret << cho << jung144 ret << jong if jong != JONGSUNG145 else146 ret << c147 end148 end149 ret150 end110 ret111 end151152 def self.to_nfc arr153 [NFC_BEGIN + arr[0] * JJCOUNT +154 (arr[1] || 0) * JONGSUNGS +155 (arr[2] || 0)].pack('U*')156 end157158 if String.method_defined?(:each_char)159 def self.split str160 str.each_char.to_a161 end162 else163 def self.split str164 str.split('')165 end166 end167168 def self.nfc str, offsets = []169 ret = ''170 omap = []171 pend = []172 split(str).each_with_index do |c, idx|113 def self.nfc str, b = 0, e = 0114 ret = ''115 omap = []116 pend = []117 str.split(//).each_with_index do |c, idx|118 cp = c.ord119 omap << ret.length120 unless pend.empty?121 if cp >= JUNGSUNG && cp < JUNGSUNG + JUNGSUNGS122 pend << cp - JUNGSUNG123 next124 elsif cp >= JONGSUNG && cp < JONGSUNG + JONGSUNGS125 pend << cp - JONGSUNG126 next173 cp =174 begin175 c.ord176 rescue Exception177 next178 end179 omap << ret.length180 unless pend.empty?181 if cp >= JUNGSUNG && cp < JUNGSUNG + JUNGSUNGS182 pend << cp - JUNGSUNG183 next184 elsif cp >= JONGSUNG && cp < JONGSUNG + JONGSUNGS185 pend << cp - JONGSUNG186 next187 else188 omap[-1] = omap[-1] + 1189 ret << to_nfc(pend)190 pend.clear191 end192 end193 if cp >= CHOSUNG && cp < CHOSUNG + CHOSUNGS194 pend << cp - CHOSUNG195 else128 omap[-1] = omap[-1] + 1129 ret << [NFC_BEGIN + pend[0] * JJCOUNT +130 (pend[1] || 0) * JONGSUNGS +131 (pend[2] || 0)].pack('U*')132 pend.clear196 ret << c197 end198 end135 if cp >= CHOSUNG && cp < CHOSUNG + CHOSUNGS136 pend << cp - CHOSUNG137 else138 ret << c139 end199 ret << to_nfc(pend) unless pend.empty?200 return [ret,201 offsets.map { |pair|202 b, e = pair203 [omap[b] || 0, omap[e] || ((omap.last || 0) + 1)] }]204 end141 return [ret, omap[b] || 0, omap[e] || ((omap.last || 0) + 1)]205 end206207 def convert_item item208 UConv.nfc(*item)209 end210211 class Matcher212 def convert_query q213 UConv.nfd(q).split(//)214 end215 end216 else217 def convert_item item218 item219 end220221 class Matcher222 def convert_query q223 q.split(//)224 end225 end226 end227145 def convert_query q146 UConv.nfd(q).split(//)228 def emit event229 @mtx.synchronize do230 @events[event] = yield231 @cv.broadcast232 end233 end234149 def convert_item item150 UConv.nfc(*item)235 def max_items; C.lines - 2; end236 def cursor_y; C.lines - 1; end237 def cprint str, col238 C.attron(col) do239 addstr_safe str240 end if str241 end152else153 def convert_query q154 q.split(//)242 def addstr_safe str243 C.addstr str.gsub("\0", '')244 end245157 def convert_item item158 item246 def print_input247 C.setpos cursor_y, 0248 C.clrtoeol249 cprint '> ', color(:blue, true)250 C.attron(C::A_BOLD) do251 C.addstr @query.get252 end253 end160end254162def emit event163 @mtx.synchronize do164 @events[event] = yield165 @cv.broadcast255 def print_info msg = nil256 C.setpos cursor_y - 1, 0257 C.clrtoeol258 prefix =259 if fan = @fan.shift260 @fan.push fan261 cprint fan, color(:fan, true)262 ' '263 else264 ' '265 end266 C.attron color(:info, false) do267 C.addstr "#{prefix}#{@matches.length}/#{@count.get}"268 if (selected = @selects.length) > 0269 C.addstr " (#{selected})"270 end271 C.addstr msg if msg272 end273 end167end274169C = Curses170def max_items; C.lines - 2; end171def cursor_y; C.lines - 1; end172def cprint str, col173 C.attron(col) do174 C.addstr str.gsub("\0", '')175 end if str176end275 def refresh276 C.setpos cursor_y, 2 + width(@query[0, @cursor_x.get])277 C.refresh278 end279178def print_input179 C.setpos cursor_y, 0180 C.clrtoeol181 cprint '> ', color(:blue, true)182 C.attron(C::A_BOLD) do183 C.addstr @query280 def ctrl char281 char.to_s.ord - 'a'.ord + 1282 end185end283187def print_info selected, msg = nil188 @fan ||= '-\|/-\|/'.split(//)189 C.setpos cursor_y - 1, 0190 C.clrtoeol191 prefix =192 if fan = @fan.shift193 @fan.push fan194 cprint fan, color(:fan, true)195 ' '196 else197 ' '284 def format line, limit, offsets285 offsets ||= []286 maxe = offsets.map { |e| e.last }.max || 0287288 # Overflow289 if width(line) > limit290 ewidth = width(line[0...maxe])291 # Stri..292 if ewidth <= limit - 2293 line, _ = trim line, limit - 2, false294 line << '..'295 # ..ring296 else297 # ..ri..298 line = line[0...maxe] + '..' if ewidth < width(line) - 2299 line, diff = trim line, limit - 2, true300 offsets = offsets.map { |pair|301 b, e = pair302 b += 2 - diff303 e += 2 - diff304 b = [2, b].max305 [b, e]306 }307 line = '..' + line308 end309 end199 C.attron color(:info, false) do200 C.addstr "#{prefix}#{@matches.length}/#{@count}"201 C.addstr " (#{selected})" if selected > 0202 C.addstr msg if msg310311 tokens = []312 index = 0313 offsets.select { |pair| pair.first < pair.last }.314 sort_by { |pair| pair }.each do |pair|315 b, e = pair.map { |x| [index, x].max }316 tokens << [line[index...b], false]317 tokens << [line[b...e], true]318 index = e319 end320 tokens << [line[index..-1], false]321 tokens.reject { |pair| pair.first.empty? }322 end204end323206def refresh207 C.setpos cursor_y, 2 + width(@query[0, @cursor_x])208 C.refresh209end324 def print_item row, tokens, chosen, selected325 # Cursor326 C.setpos row, 0327 C.clrtoeol328 cprint chosen ? '>' : ' ', color(:red, true)329 cprint selected ? '>' : ' ',330 chosen ? color(:chosen) : (selected ? color(:red, true) : 0)331211def ctrl char212 char.to_s.ord - 'a'.ord + 1213end332 # Highlighted item333 C.attron color(:chosen, true) if chosen334 tokens.each do |pair|335 token, highlighted = pair336215if RUBY_VERSION.split('.').map { |e| e.rjust(3, '0') }.join > '001009'216 @wrx = Regexp.new '\p{Han}|\p{Katakana}|\p{Hiragana}|\p{Hangul}'217 def width str218 str.gsub(@wrx, ' ').length337 if highlighted338 cprint token, color(chosen ? :match! : :match, chosen)339 C.attron color(:chosen, true) if chosen340 else341 addstr_safe token342 end343 end344 C.attroff color(:chosen, true) if chosen345 end346221 def trim str, len, left222 width = width str223 diff = 0224 while width > len225 width -= (left ? str[0, 1] : str[-1, 1]) =~ @wrx ? 2 : 1226 str = left ? str[1..-1] : str[0...-1]227 diff += 1228 end229 [str, diff]347 def sort_by_rank list348 list.sort_by { |tuple|349 line, offsets = tuple350 matchlen = 0351 pe = nil352 offsets.sort.each do |pair|353 b, e = pair354 b = pe if pe && pe > b355 pe = e356 matchlen += e - b357 end358 [matchlen, line.length, line]359 }360 end231else232 def width str233 str.length234 end361236 def trim str, len, left237 diff = str.length - len238 if diff > 0239 [left ? str[diff..-1] : str[0...-diff], diff]240 else241 [str, 0]362 if RUBY_VERSION.split('.').map { |e| e.rjust(3, '0') }.join > '001009'363 @@wrx = Regexp.new '\p{Han}|\p{Katakana}|\p{Hiragana}|\p{Hangul}'364 def width str365 str.gsub(@@wrx, ' ').length366 end243 end367245 class String246 def ord247 self.unpack('c').first368 def trim str, len, left369 width = width str370 diff = 0371 while width > len372 width -= (left ? str[0, 1] : str[-1, 1]) =~ @@wrx ? 2 : 1373 str = left ? str[1..-1] : str[0...-1]374 diff += 1375 end376 [str, diff]377 end378 else379 def width str380 str.length249 end381 end382251 class Fixnum252 def ord253 self383 def trim str, len, left384 diff = str.length - len385 if diff > 0386 [left ? str[diff..-1] : str[0...-diff], diff]387 else388 [str, 0]389 end390 end255 end256end391258C.init_screen259C.start_color260dbg =261 if C.respond_to?(:use_default_colors)262 C.use_default_colors263 -1264 else265 C::COLOR_BLACK266 end267C.raw268C.noecho392 class ::String393 def ord394 self.unpack('c').first395 end396 end397270if @color271 if C.can_change_color?272 fg = ENV.fetch('FZF_FG', 252).to_i273 bg = ENV.fetch('FZF_BG', 236).to_i274 C.init_pair 1, 110, dbg275 C.init_pair 2, 108, dbg276 C.init_pair 3, fg + 2, bg277 C.init_pair 4, 151, bg278 C.init_pair 5, 148, dbg279 C.init_pair 6, 144, dbg280 C.init_pair 7, 161, bg281 else282 C.init_pair 1, C::COLOR_BLUE, dbg283 C.init_pair 2, C::COLOR_GREEN, dbg284 C.init_pair 3, C::COLOR_YELLOW, C::COLOR_BLACK285 C.init_pair 4, C::COLOR_GREEN, C::COLOR_BLACK286 C.init_pair 5, C::COLOR_GREEN, dbg287 C.init_pair 6, C::COLOR_WHITE, dbg288 C.init_pair 7, C::COLOR_RED, C::COLOR_BLACK398 class ::Fixnum399 def ord400 self401 end402 end403 end404291 def color sym, bold = false292 C.color_pair([:blue, :match, :chosen,293 :match!, :fan, :info, :red].index(sym) + 1) |294 (bold ? C::A_BOLD : 0)295 end296else297 def color sym, bold = false298 case sym299 when :chosen300 bold ? C::A_REVERSE : 0301 when :match302 C::A_UNDERLINE303 when :match!304 C::A_REVERSE | C::A_UNDERLINE305 else306 0307 end | (bold ? C::A_BOLD : 0)308 end309end405 def init_screen406 C.init_screen407 C.start_color408 dbg =409 if C.respond_to?(:use_default_colors)410 C.use_default_colors411 -1412 else413 C::COLOR_BLACK414 end415 C.raw416 C.noecho417311@read =312 if $stdin.tty?313 if default_command = ENV['FZF_DEFAULT_COMMAND']314 IO.popen(default_command)315 elsif !`which find`.empty?316 IO.popen("find * -path '*/\\.*' -prune -o -type f -print -o -type l -print 2> /dev/null")418 if @color419 if C.can_change_color?420 fg = ENV.fetch('FZF_FG', 252).to_i421 bg = ENV.fetch('FZF_BG', 236).to_i422 C.init_pair 1, 110, dbg423 C.init_pair 2, 108, dbg424 C.init_pair 3, fg + 2, bg425 C.init_pair 4, 151, bg426 C.init_pair 5, 148, dbg427 C.init_pair 6, 144, dbg428 C.init_pair 7, 161, bg429 else430 C.init_pair 1, C::COLOR_BLUE, dbg431 C.init_pair 2, C::COLOR_GREEN, dbg432 C.init_pair 3, C::COLOR_YELLOW, C::COLOR_BLACK433 C.init_pair 4, C::COLOR_GREEN, C::COLOR_BLACK434 C.init_pair 5, C::COLOR_GREEN, dbg435 C.init_pair 6, C::COLOR_WHITE, dbg436 C.init_pair 7, C::COLOR_RED, C::COLOR_BLACK437 end438439 def self.color sym, bold = false440 C.color_pair([:blue, :match, :chosen,441 :match!, :fan, :info, :red].index(sym) + 1) |442 (bold ? C::A_BOLD : 0)443 end444 else318 exit 1445 def self.color sym, bold = false446 case sym447 when :chosen448 bold ? C::A_REVERSE : 0449 when :match450 C::A_UNDERLINE451 when :match!452 C::A_REVERSE | C::A_UNDERLINE453 else454 0455 end | (bold ? C::A_BOLD : 0)456 end457 end320 else321 $stdin458 end459460 def start_reader461 stream =462 if @source.tty?463 if default_command = ENV['FZF_DEFAULT_COMMAND']464 IO.popen(default_command)465 elsif !`which find`.empty?466 IO.popen("find * -path '*/\\.*' -prune -o -type f -print -o -type l -print 2> /dev/null")467 else468 exit 1469 end470 else471 @source472 end473324reader = Thread.new {325 while line = @read.gets326 emit(:new) { @new << line.chomp }474 Thread.new do475 while line = stream.gets476 emit(:new) { @new << line.chomp }477 end478 emit(:loaded) { true }479 @fan.clear480 end481 end328 emit(:loaded) { true }329 @smtx.synchronize { @fan = [] }330}482332main = Thread.current333searcher = Thread.new {334 events = {}335 fcache = {}336 matches = []337 selects = {}338 mcount = 0 # match count339 plcount = 0 # prev list count340 q = ''341 vcursor = 0342 delay = -5483 def start_search484 main = Thread.current485 matcher = (@xmode ? ExtendedFuzzyMatcher : FuzzyMatcher).new @rxflag486 searcher = Thread.new {487 lists = []488 events = {}489 fcache = {}490 mcount = 0 # match count491 plcount = 0 # prev list count492 q = ''493 delay = -5494344 begin345 while true346 @mtx.synchronize do495 begin496 while true497 @mtx.synchronize do498 while true348 events.merge! @events499 events.merge! @events500350 if @events.empty? # No new events351 @cv.wait @mtx352 next353 end354 @events.clear355 break356 end501 if @events.empty? # No new events502 @cv.wait @mtx503 next504 end505 @events.clear506 break507 end508358 if events[:new]359 @lists << [@new, {}]360 @count += @new.length361 @new = []362 fcache = {}363 end509 if events[:new]510 lists << @new511 @count.set { |c| c + @new.length }512 @new = []513 fcache = {}514 end515 end#mtx516365 if events[:select]366 selects = @selects.dup367 end368 end#mtx517 new_search = events[:key] || events.delete(:new)518 user_input = events[:key] || events[:vcursor] || events.delete(:select)519 progress = 0520 started_at = Time.now521370 new_search = events[:key] || events.delete(:new)371 user_input = events[:key] || events[:vcursor] || events.delete(:select)372 progress = 0373 started_at = Time.now522 if new_search && !lists.empty?523 q, cx = events.delete(:key) || [q, 0]524375 if new_search && !@lists.empty?376 q = events.delete(:key) || q525 plcount = [@matches.length, max_items].min526 @matches.set(fcache[q] ||=527 begin528 found = []529 skip = false530 cnt = 0531 lists.each do |list|532 cnt += list.length533 skip = @mtx.synchronize { @events[:key] }534 break if skip535378 unless q.empty?379 q = q.downcase if @rxflag != 0380 regexp = Regexp.new(convert_query(q).inject('') { |sum, e|381 e = Regexp.escape e382 sum << "#{e}[^#{e}]*?"383 }, @rxflag)384 end385386 matches = fcache[q] ||=387 begin388 found = []389 skip = false390 cnt = 0391 @lists.each do |pair|392 list, cache = pair393 cnt += list.length394395 @mtx.synchronize {396 skip = @events[:key]397 progress = (100 * cnt / @count)398 }399 break if skip400401 found.concat(cache[q] ||= q.empty? ? list : begin402 if progress < 100 && Time.now - started_at > 0.5403 @smtx.synchronize do404 print_info selects.length, " (#{progress}%)"405 refresh536 progress = (100 * cnt / @count.get)537 if progress < 100 && Time.now - started_at > 0.5 && !q.empty?538 @smtx.synchronize do539 print_info " (#{progress}%)"540 refresh541 end542 end407 end543409 prefix, suffix = @query[0, @cursor_x], @query[@cursor_x..-1] || ''410 prefix_cache = suffix_cache = nil411412 (prefix.length - 1).downto(1) do |len|413 break if prefix_cache = cache[prefix[0, len]]544 found.concat(q.empty? ? list :545 matcher.match(list, q, q[0, cx], q[cx..-1]))546 end415416 0.upto(suffix.length - 1) do |idx|417 break if suffix_cache = cache[suffix[idx..-1]]418 end unless suffix.empty?419420 partial_cache = [prefix_cache, suffix_cache].compact.sort_by { |e| e.length }.first421 (partial_cache ? partial_cache.map { |e| e.first } : list).map { |line|422 # Ignore errors: e.g. invalid byte sequence in UTF-8423 md = line.match(regexp) rescue nil424 md && [line, *md.offset(0)]425 }.compact547 next if skip548 @sort ? found : found.reverse549 end)550551 mcount = @matches.length552 if @sort && mcount <= @sort && !q.empty?553 @matches.set { |m| sort_by_rank m }554 end428 next if skip429 @sort ? found : found.reverse430 end555 end#new_search556432 mcount = matches.length433 if @sort && mcount <= @sort && !q.empty?434 matches.replace matches.sort_by { |triple|435 line, b, e = triple436 [b ? (e - b) : 0, line.length, line]437 }438 end439 end#new_search557 # This small delay reduces the number of partial lists558 sleep((delay = [20, delay + 5].min) * 0.01) unless user_input559441 # This small delay reduces the number of partial lists442 sleep((delay = [20, delay + 5].min) * 0.01) unless user_input443444 if events.delete(:vcursor) || new_search445 @mtx.synchronize do560 if events.delete(:vcursor) || new_search561 @vcursor.set { |v| [0, [v, mcount - 1, max_items - 1].min].max }446 plcount = [@matches.length, max_items].min447 @matches = matches448 vcursor = @vcursor = [0, [@vcursor, mcount - 1, max_items - 1].min].max449 end450 end451452 # Output453 @smtx.synchronize do454 item_length = [mcount, max_items].min455 if item_length < plcount456 plcount.downto(item_length) do |idx|457 C.setpos cursor_y - idx - 2, 0458 C.clrtoeol562 end460 end563462 maxc = C.cols - 3463 matches[0, max_items].each_with_index do |item, idx|464 next if !new_search && !((vcursor-1)..(vcursor+1)).include?(idx)564 # Output565 @smtx.synchronize do566 item_length = [mcount, max_items].min567 if item_length < plcount568 plcount.downto(item_length) do |idx|569 C.setpos cursor_y - idx - 2, 0570 C.clrtoeol571 end572 end573466 line, b, e = convert_item item467 b ||= 0468 e ||= 0469 row = cursor_y - idx - 2470 chosen = idx == vcursor471472 # Overflow473 if width(line) > maxc474 ewidth = width(line[0...e])475 # Stri..476 if ewidth <= maxc - 2477 line, _ = trim line, maxc - 2, false478 line << '..'479 # ..ring480 else481 # ..ri..482 line = line[0...e] + '..' if ewidth < width(line) - 2483 line, diff = trim line, maxc - 2, true484 b += 2 - diff485 e += 2 - diff486 b = [2, b].max487 line = '..' + line574 maxc = C.cols - 3575 vcursor = @vcursor.get576 @matches[0, max_items].each_with_index do |item, idx|577 next if !new_search && !((vcursor-1)..(vcursor+1)).include?(idx)578 row = cursor_y - idx - 2579 chosen = idx == vcursor580 selected = @selects.include?([*item][0])581 line, offsets = convert_item item582 tokens = format line, maxc, offsets583 print_item row, tokens, chosen, selected584 end585586 print_info if !lists.empty? || events[:loaded]587 refresh588 end589 end#while590 rescue Exception => e591 main.raise e592 end593 }594 end595491 C.setpos row, 0492 C.clrtoeol493 cprint chosen ? '>' : ' ', color(:red, true)494 selected = selects.include?([*item][0])495 cprint selected ? '>' : ' ',496 chosen ? color(:chosen) : (selected ? color(:red, true) : 0)596 def start_loop597 got = nil598 begin599 tty = IO.open(IO.sysopen('/dev/tty'), 'r')600 input = ''601 cursor = 0602 actions = {603 :nop => proc {},604 ctrl(:c) => proc { exit 1 },605 ctrl(:d) => proc { exit 1 if input.empty? },606 ctrl(:m) => proc {607 got = [*@matches.fetch(@vcursor.get, [])][0]608 exit 0609 },610 ctrl(:u) => proc { input = input[cursor..-1]; cursor = 0 },611 ctrl(:a) => proc { cursor = 0 },612 ctrl(:e) => proc { cursor = input.length },613 ctrl(:j) => proc { emit(:vcursor) { @vcursor.set { |v| v - 1 } } },614 ctrl(:k) => proc { emit(:vcursor) { @vcursor.set { |v| v + 1 } } },615 ctrl(:w) => proc {616 ridx = (input[0...cursor - 1].rindex(/\S\s/) || -2) + 2617 input = input[0...ridx] + input[cursor..-1]618 cursor = ridx619 },620 127 => proc { input[cursor -= 1] = '' if cursor > 0 },621 9 => proc { |o|622 emit(:select) {623 if sel = [*@matches.fetch(@vcursor.get, [])][0]624 if @selects.has_key? sel625 @selects.delete sel626 else627 @selects[sel] = 1628 end629 @vcursor.set { |v| [0, v + (o == :stab ? 1 : -1)].max }630 end631 } if @multi632 },633 :left => proc { cursor = [0, cursor - 1].max },634 :right => proc { cursor = [input.length, cursor + 1].min },635 }636 actions[ctrl(:b)] = actions[:left]637 actions[ctrl(:f)] = actions[:right]638 actions[ctrl(:h)] = actions[127]639 actions[ctrl(:n)] = actions[ctrl(:j)]640 actions[ctrl(:p)] = actions[ctrl(:k)]641 actions[:stab] = actions[9]642498 C.attron color(:chosen, true) if chosen643 while true644 @cursor_x.set cursor645 # Update user input646 @smtx.synchronize do647 print_input648 refresh649 end650500 if b < e501 C.addstr line[0, b]502 cprint line[b...e], color(chosen ? :match! : :match, chosen)503 C.attron color(:chosen, true) if chosen504 C.addstr line[e..-1] || ''505 else506 C.addstr line651 ord = tty.getc.ord652 if ord == 27653 ord = tty.getc.ord654 if ord == 91655 ord = case tty.getc.ord656 when 68 then :left657 when 67 then :right658 when 66 then ctrl(:j)659 when 65 then ctrl(:k)660 when 90 then :stab661 else :nop662 end663 end508 C.attroff color(:chosen, true) if chosen664 end665511 print_info selects.length if !@lists.empty? || events[:loaded]512 refresh513 end514 end#while515 rescue Exception => e516 main.raise e517 end518}666 actions.fetch(ord, proc { |ord|667 char = [ord].pack('U*')668 if char =~ /[[:print:]]/669 input.insert cursor, char670 cursor += 1671 end672 }).call(ord)673520got = nil521begin522 tty = IO.open(IO.sysopen('/dev/tty'), 'r')523 input = ''524 cursor = 0525 actions = {526 :nop => proc {},527 ctrl(:c) => proc { exit 1 },528 ctrl(:d) => proc { exit 1 if input.empty? },529 ctrl(:m) => proc {530 @mtx.synchronize do531 got = [*@matches.fetch(@vcursor, [])][0]674 # Dispatch key event675 emit(:key) { [@query.set(input.dup), cursor] }676 end533 exit 0534 },535 ctrl(:u) => proc { input = input[cursor..-1]; cursor = 0 },536 ctrl(:a) => proc { cursor = 0 },537 ctrl(:e) => proc { cursor = input.length },538 ctrl(:j) => proc { emit(:vcursor) { @vcursor -= 1 } },539 ctrl(:k) => proc { emit(:vcursor) { @vcursor += 1 } },540 ctrl(:w) => proc {541 ridx = (input[0...cursor - 1].rindex(/\S\s/) || -2) + 2542 input = input[0...ridx] + input[cursor..-1]543 cursor = ridx544 },545 127 => proc { input[cursor -= 1] = '' if cursor > 0 },546 9 => proc { |o|547 emit(:select) {548 if sel = [*@matches.fetch(@vcursor, [])][0]549 if @selects.has_key? sel550 @selects.delete sel551 else552 @selects[sel] = 1553 end554 @vcursor = [0, @vcursor + (o == :stab ? 1 : -1)].max677 ensure678 C.close_screen679 if got680 @selects.delete got681 @selects.each do |sel, _|682 @stdout.puts sel683 end556 } if @multi557 },558 :left => proc { cursor = [0, cursor - 1].max },559 :right => proc { cursor = [input.length, cursor + 1].min },560 }561 actions[ctrl(:b)] = actions[:left]562 actions[ctrl(:f)] = actions[:right]563 actions[ctrl(:h)] = actions[127]564 actions[ctrl(:n)] = actions[ctrl(:j)]565 actions[ctrl(:p)] = actions[ctrl(:k)]566 actions[:stab] = actions[9]684 @stdout.puts got685 end686 end687 end688568 while true569 # Update user input570 @smtx.synchronize do571 @cursor_x = cursor572 print_input573 refresh689 class FuzzyMatcher < Matcher690 attr_reader :caches, :rxflag691692 def initialize rxflag693 @caches = Hash.new { |h, k| h[k] = {} }694 @regexp = {}695 @rxflag = rxflag696 end697576 ord = tty.getc.ord577 if ord == 27578 ord = tty.getc.ord579 if ord == 91580 ord = case tty.getc.ord581 when 68 then :left582 when 67 then :right583 when 66 then ctrl(:j)584 when 65 then ctrl(:k)585 when 90 then :stab586 else :nop587 end698 def fuzzy_regex q699 @regexp[q] ||= begin700 q = q.downcase if @rxflag != 0701 Regexp.new(convert_query(q).inject('') { |sum, e|702 e = Regexp.escape e703 sum << "#{e}[^#{e}]*?"704 }, @rxflag)705 end706 end707591 actions.fetch(ord, proc { |ord|592 char = [ord].pack('U*')593 if char =~ /[[:print:]]/594 input.insert cursor, char595 cursor += 1708 def match list, q, prefix, suffix709 regexp = fuzzy_regex q710711 cache = @caches[list.object_id]712 prefix_cache = nil713 (prefix.length - 1).downto(1) do |len|714 break if prefix_cache = cache[prefix[0, len]]715 end597 }).call(ord)716599 # Dispatch key event600 emit(:key) { @query = input.dup }717 suffix_cache = nil718 0.upto(suffix.length - 1) do |idx|719 break if suffix_cache = cache[suffix[idx..-1]]720 end unless suffix.empty?721722 partial_cache = [prefix_cache,723 suffix_cache].compact.sort_by { |e| e.length }.first724 cache[q] ||= (partial_cache ?725 partial_cache.map { |e| e.first } : list).map { |line|726 # Ignore errors: e.g. invalid byte sequence in UTF-8727 md = line.match(regexp) rescue nil728 md && [line, [md.offset(0)]]729 }.compact730 end731 end602ensure603 C.close_screen604 if got605 @selects.delete got606 @selects.each do |sel, _|607 stdout.puts sel732733 class ExtendedFuzzyMatcher < FuzzyMatcher734 def initialize rxflag735 super736 require 'set'737 @regexps = {}738 end609 stdout.puts got739740 def match list, q, prefix, suffix741 q = q.strip742743 regexps = @regexps[q] ||= q.split(/\s+/).map { |w|744 invert =745 if w =~ /^!/746 w = w[1..-1]747 true748 end749750 [ @regexp[w] ||=751 case w752 when ''753 nil754 when /^\^/755 w.length > 1 ?756 Regexp.new('^' << Regexp.escape(w[1..-1]), rxflag) : nil757 when /\$$/758 w.length > 1 ?759 Regexp.new(Regexp.escape(w[0..-2]) << '$', rxflag) : nil760 else761 fuzzy_regex w762 end, invert ]763 }.select { |pair| pair.first }764765 # Look for prefix cache766 cache = @caches[list.object_id]767 prefix = prefix.strip.sub(/\$\S+$/, '').sub(/!\S+$/, '')768 prefix_cache = nil769 (prefix.length - 1).downto(1) do |len|770 break if prefix_cache = cache[Set[@regexps[prefix[0, len]]]]771 end772773 cache[Set[regexps]] ||= (prefix_cache ?774 prefix_cache.map { |e| e.first } :775 list).map { |line|776 offsets = []777 regexps.all? { |pair|778 regexp, invert = pair779 md = line.match(regexp) rescue nil780 if md && !invert781 offsets << md.offset(0)782 elsif !md && invert783 true784 end785 } && [line, offsets]786 }.select { |e| e }787 end788 end611end789end#FZF790791FZF.new(ARGV, $stdin).start if $0 == __FILE__792
modified:fzf.gemspec+1 added-1 removed
1# coding: utf-82Gem::Specification.new do |spec|3 spec.name = 'fzf'4 spec.version = '0.3.1'4 spec.version = '0.4.0'5 spec.authors = ['Junegunn Choi']6 spec.email = ['junegunn.c@gmail.com']7 spec.description = %q{Fuzzy finder for your shell}8 spec.summary = %q{Fuzzy finder for your shell}
7 unmodified lines
modified:Rakefile+7 added
1require "bundler/gem_tasks"2require 'rake/testtask'34Rake::TestTask.new(:test) do |test|5 test.pattern = 'test/**/test_*.rb'6 test.verbose = true7end8
modified:README.md+13 added
112 unmodified lines
113114If you enable multi-select mode with `-m` option, you can select multiple items115with TAB or Shift-TAB key.116117### Extended mode118119With `-x` or `--extended` option, fzf will start in "extended mode".120121In extended mode, you can specify multiple patterns delimited by spaces, such as: `^music .mp3$ sbtrkt !rmx`122123| Token | Description | Match type |124| -------- | ----------------------------- | -------------------- |125| `^music` | Items that start with `music` | prefix-exact-match |126| `.mp3$` | Items that end with `.mp3` | suffix-exact-match |127| `sbtrkt` | Items that match `sbtrkt` | fuzzy-match |128| `!rmx` | Items that do not match `rmx` | invert-fuzzy-match |129130Usage as Vim plugin131-------------------132133If you install fzf as a Vim plugin, `:FZF` command will be added.
130 unmodified lines