Remove Ruby version
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Related #832
authored by Junegunn Choi · committed by Junegunn Choi · parent ee5aeb8 · Browse files · 2 files·+5 added−1424 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+5 added−1424 removed
- other:+5 added−1424 removed
Provenance
- Commit
876c233- Tree
2fd2d86- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
ee5aeb8
2 files changed+5 added−1424 removed
deleted:fzf-1348 removed
1-#!/usr/bin/env ruby2-# encoding: utf-83-#4-# ____ ____5-# / __/___ / __/6-# / /_/_ / / /_7-# / __/ / /_/ __/8-# /_/ /___/_/ Fuzzy finder for your shell9-#10-# Version: 0.8.9 (Dec 24, 2014)11-# Deprecation alert:12-# This script is no longer maintained. Use the new Go version.13-#14-# Author: Junegunn Choi15-# URL: https://github.com/junegunn/fzf16-# License: MIT17-#18-# Copyright (c) 2014 Junegunn Choi19-#20-# MIT License21-#22-# Permission is hereby granted, free of charge, to any person obtaining23-# a copy of this software and associated documentation files (the24-# "Software"), to deal in the Software without restriction, including25-# without limitation the rights to use, copy, modify, merge, publish,26-# distribute, sublicense, and/or sell copies of the Software, and to27-# permit persons to whom the Software is furnished to do so, subject to28-# the following conditions:29-#30-# The above copyright notice and this permission notice shall be31-# included in all copies or substantial portions of the Software.32-#33-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,34-# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF35-# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND36-# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE37-# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION38-# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION39-# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.40-41-begin42- require 'curses'43-rescue LoadError44- $stderr.puts 'curses gem is not installed. Try `gem install curses`.'45- sleep 146- exit 147-end48-require 'thread'49-require 'set'50-51-unless String.method_defined? :force_encoding52- class String53- def force_encoding *arg54- self55- end56- end57-end58-59-class String60- attr_accessor :orig61-62- def tokenize delim, nth63- unless delim64- # AWK default65- prefix_length = (index(/\S/) || 0) rescue 066- tokens = scan(/\S+\s*/) rescue []67- else68- prefix_length = 069- tokens = scan(delim) rescue []70- end71- nth.map { |n|72- if n.begin == 0 && n.end == -173- [prefix_length, tokens.join]74- elsif part = tokens[n]75- [prefix_length + (tokens[0...(n.begin)] || []).join.length,76- part.join]77- end78- }.compact79- end80-end81-82-class FZF83- C = Curses84- attr_reader :rxflag, :sort, :nth, :color, :black, :ansi256, :reverse, :prompt,85- :mouse, :multi, :query, :select1, :exit0, :filter, :extended,86- :print_query, :with_nth87-88- def sync89- @shr_mtx.synchronize { yield }90- end91-92- def get name93- sync { instance_variable_get name }94- end95-96- def geta(*names)97- sync { names.map { |name| instance_variable_get name } }98- end99-100- def call(name, method, *args)101- sync { instance_variable_get(name).send(method, *args) }102- end103-104- def set name, value = nil105- sync do106- instance_variable_set name,107- (block_given? ? yield(instance_variable_get(name)) : value)108- end109- end110-111- def initialize argv, source = $stdin112- @rxflag = nil113- @sort = ENV.fetch('FZF_DEFAULT_SORT', 1000).to_i114- @color = true115- @ansi256 = true116- @black = false117- @multi = false118- @mouse = true119- @extended = nil120- @select1 = false121- @exit0 = false122- @filter = nil123- @nth = nil124- @with_nth = nil125- @delim = nil126- @reverse = false127- @prompt = '> '128- @shr_mtx = Mutex.new129- @expect = false130- @print_query = false131-132- argv =133- if opts = ENV['FZF_DEFAULT_OPTS']134- require 'shellwords'135- Shellwords.shellwords(opts) + argv136- else137- argv.dup138- end139- while o = argv.shift140- case o141- when '--version' then FZF.version142- when '-h', '--help' then usage 0143- when '-m', '--multi' then @multi = true144- when '+m', '--no-multi' then @multi = false145- when '-x', '--extended' then @extended = :fuzzy146- when '+x', '--no-extended' then @extended = nil147- when '-i' then @rxflag = Regexp::IGNORECASE148- when '+i' then @rxflag = 0149- when '-c', '--color' then @color = true150- when '+c', '--no-color' then @color = false151- when '-2', '--256' then @ansi256 = true152- when '+2', '--no-256' then @ansi256 = false153- when '--black' then @black = true154- when '--no-black' then @black = false155- when '--mouse' then @mouse = true156- when '--no-mouse' then @mouse = false157- when '--reverse' then @reverse = true158- when '--no-reverse' then @reverse = false159- when '+s', '--no-sort' then @sort = nil160- when '-1', '--select-1' then @select1 = true161- when '+1', '--no-select-1' then @select1 = false162- when '-0', '--exit-0' then @exit0 = true163- when '+0', '--no-exit-0' then @exit0 = false164- when '-q', '--query'165- usage 1, 'query string required' unless query = argv.shift166- @query = query167- when /^-q(.*)$/, /^--query=(.*)$/168- @query = $1169- when '-f', '--filter'170- usage 1, 'query string required' unless query = argv.shift171- @filter = query172- when /^-f(.*)$/, /^--filter=(.*)$/173- @filter = $1174- when '-n', '--nth'175- usage 1, 'field expression required' unless nth = argv.shift176- @nth = parse_nth nth177- when /^-n([0-9,-\.]+)$/, /^--nth=([0-9,-\.]+)$/178- @nth = parse_nth $1179- when '--with-nth'180- usage 1, 'field expression required' unless nth = argv.shift181- @with_nth = parse_nth nth182- when /^--with-nth=([0-9,-\.]+)$/183- @with_nth = parse_nth $1184- when '-d', '--delimiter'185- usage 1, 'delimiter required' unless delim = argv.shift186- @delim = FZF.build_delim_regex delim187- when /^-d(.+)$/, /^--delimiter=(.+)$/188- @delim = FZF.build_delim_regex $1189- when '-s', '--sort'190- usage 1, 'sort size required' unless sort = argv.shift191- usage 1, 'invalid sort size' unless sort =~ /^[0-9]+$/192- @sort = sort.to_i193- when /^-s([0-9]+)$/, /^--sort=([0-9]+)$/194- @sort = $1.to_i195- when '--prompt'196- usage 1, 'prompt string required' unless prompt = argv.shift197- @prompt = prompt198- when /^--prompt=(.*)$/199- @prompt = $1200- when '--print-query' then @print_query = true201- when '--no-print-query' then @print_query = false202- when '-e', '--extended-exact' then @extended = :exact203- when '+e', '--no-extended-exact' then @extended = nil204- when '--expect'205- argv.shift206- @expect = true207- when /^--expect=(.*)$/208- @expect = true209- when '--toggle-sort', '--tiebreak', '--color', '--bind', '--history', '--history-size'210- argv.shift211- when '--tac', '--no-tac', '--sync', '--no-sync', '--hscroll', '--no-hscroll',212- '--inline-info', '--no-inline-info', '--read0', '--cycle', /^--bind=(.*)$/,213- /^--color=(.*)$/, /^--toggle-sort=(.*)$/, /^--tiebreak=(.*)$/, /^--history(-max)?=(.*)$/214- # XXX215- else216- usage 1, "illegal option: #{o}"217- end218- end219-220- @source = source.clone221- @evt_mtx = Mutex.new222- @cv = ConditionVariable.new223- @events = {}224- @new = []225- @queue = Queue.new226- @pending = nil227- @rev_dir = @reverse ? -1 : 1228- @stdout = $stdout.clone229-230- unless @filter231- # Shared variables: needs protection232- @query ||= ''233- @matches = []234- @count = 0235- @xcur = @query.length236- @ycur = 0237- @yoff = 0238- @dirty = Set.new239- @spinner = '-\|/-\|/'.split(//)240- @selects = {} # ordered >= 1.9241-242- @main = Thread.current243- @plcount = 0244- end245- end246-247- def parse_nth nth248- ranges = nth.split(',').map { |expr|249- x = proc { usage 1, "invalid field expression: #{expr}" }250- first, second = expr.split('..', 2)251- x.call if !first.empty? && first.to_i == 0 ||252- second && !second.empty? && (second.to_i == 0 || second.include?('.'))253-254- first = first.empty? ? 1 : first.to_i255- second = case second256- when nil then first257- when '' then -1258- else second.to_i259- end260-261- Range.new(*[first, second].map { |e| e > 0 ? e - 1 : e })262- }263- ranges == [0..-1] ? nil : ranges264- end265-266- def FZF.build_delim_regex delim267- Regexp.compile(delim) rescue (delim = Regexp.escape(delim))268- Regexp.compile "(?:.*?#{delim})|(?:.+?$)"269- end270-271- def burp string, orig = nil272- @stdout.puts(orig || string.orig || string)273- end274-275- def start276- if @filter277- start_reader.join278- filter_list @new279- else280- start_reader281- query = get(:@query)282- emit(:key) { [query, query.length] } unless empty = query.empty?283- if @select1 || @exit0284- start_search do |loaded, matches|285- len = empty ? get(:@count) : matches.length286- if loaded287- if @select1 && len == 1288- puts @query if @print_query289- puts if @expect290- burp(empty ? matches.first : matches.first.first)291- exit 0292- elsif @exit0 && len == 0293- puts @query if @print_query294- puts if @expect295- exit 0296- end297- end298-299- if loaded || len > 1300- start_renderer301- Thread.new { start_loop }302- end303- end304-305- sleep306- else307- start_search308- start_renderer309- start_loop310- end311- end312- end313-314- def filter_list list315- puts @filter if @print_query316- matches = matcher.match(list, @filter, '', '')317- if @sort && matches.length <= @sort318- matches = FZF.sort(matches)319- end320- matches.each { |m| puts m.first }321- end322-323- def matcher324- @matcher ||=325- if @extended326- ExtendedFuzzyMatcher.new @rxflag, @extended, @nth, @delim327- else328- FuzzyMatcher.new @rxflag, @nth, @delim329- end330- end331-332- class << self333- def version334- File.open(__FILE__, 'r') do |f|335- f.each_line do |line|336- if line =~ /Version: (.*)/337- $stdout.puts 'fzf ' << $1338- exit339- end340- end341- end342- end343-344- def sort list345- list.sort_by { |tuple| rank tuple }346- end347-348- def rank tuple349- line, offsets = tuple350- matchlen = 0351- pe = 0352- offsets.sort.each do |pair|353- b, e = pair354- b = pe if pe > b355- pe = e if e > pe356- matchlen += e - b if e > b357- end358- [matchlen, line.length, line]359- end360- end361-362- def usage x, message = nil363- $stderr.puts message if message364- $stderr.puts %[usage: fzf [options]365-366- Search367- -x, --extended Extended-search mode368- -e, --extended-exact Extended-search mode (exact match)369- -i Case-insensitive match (default: smart-case match)370- +i Case-sensitive match371- -n, --nth=N[,..] Comma-separated list of field index expressions372- for limiting search scope. Each can be a non-zero373- integer or a range expression ([BEGIN]..[END]).374- --with-nth=N[,..] Transform the item using index expressions for search375- -d, --delimiter=STR Field delimiter regex for --nth (default: AWK-style)376-377- Search result378- -s, --sort=MAX Maximum number of matched items to sort (default: 1000)379- +s, --no-sort Do not sort the result. Keep the sequence unchanged.380-381- Interface382- -m, --multi Enable multi-select with tab/shift-tab383- --no-mouse Disable mouse384- +c, --no-color Disable colors385- +2, --no-256 Disable 256-color386- --black Use black background387- --reverse Reverse orientation388- --prompt=STR Input prompt (default: '> ')389-390- Scripting391- -q, --query=STR Start the finder with the given query392- -1, --select-1 Automatically select the only match393- -0, --exit-0 Exit immediately when there's no match394- -f, --filter=STR Filter mode. Do not start interactive finder.395- --print-query Print query as the first line396-397- Environment variables398- FZF_DEFAULT_COMMAND Default command to use when input is tty399- FZF_DEFAULT_OPTS Default options (e.g. "-x -m --sort 10000")] + $/ + $/400- exit x401- end402-403- def emit event404- @evt_mtx.synchronize do405- @events[event] = yield406- @cv.broadcast407- end408- end409-410- def max_items; C.lines - 2; end411-412- def cursor_y offset = 0413- @reverse ? (offset) : (C.lines - 1 - offset)414- end415-416- def cprint str, col417- C.attron(col) do418- addstr_safe str419- end if str420- end421- def addstr_safe str422- str = str.gsub("\0", '') rescue str423- C.addstr str424- end425-426- def print_input427- C.setpos cursor_y, 0428- C.clrtoeol429- cprint @prompt, color(:prompt, true)430- C.attron(C::A_BOLD) do431- C.addstr get(:@query)432- end433- end434-435- def print_info msg = nil436- C.setpos cursor_y(1), 0437- C.clrtoeol438-439- prefix =440- if spin_char = call(:@spinner, :first)441- cprint spin_char, color(:spinner, true)442- ' '443- else444- ' '445- end446- C.attron color(:info, false) do447- sync do448- C.addstr "#{prefix}#{@matches.length}/#{@count}"449- if (selected = @selects.length) > 0450- C.addstr " (#{selected})"451- end452- end453- C.addstr msg if msg454- end455- end456-457- def refresh458- query, xcur = geta(:@query, :@xcur)459- C.setpos cursor_y, @prompt.length + width(query[0, xcur])460- C.refresh461- end462-463- def ctrl char464- char.to_s.ord - 'a'.ord + 1465- end466-467- def format line, limit, offsets468- offsets ||= []469- maxe = offsets.map { |e| e.last }.max || 0470-471- # Overflow472- if width(line) > limit473- ewidth = width(line[0...maxe])474- # Stri..475- if ewidth <= limit - 2476- line, _ = trim line, limit - 2, false477- line << '..'478- # ..ring479- else480- # ..ri..481- line = line[0...maxe] + '..' if ewidth < width(line) - 2482- line, diff = trim line, limit - 2, true483- offsets = offsets.map { |pair|484- b, e = pair485- b += 2 - diff486- e += 2 - diff487- b = [2, b].max488- [b, e]489- }490- line = '..' + line491- end492- end493-494- tokens = []495- index = 0496- offsets.select { |pair| pair.first < pair.last }.497- sort_by { |pair| pair }.each do |pair|498- b, e = pair.map { |x| [index, x].max }499- tokens << [line[index...b], false]500- tokens << [line[b...e], true]501- index = e502- end503- tokens << [line[index..-1], false] if index < line.length504- tokens.reject { |pair| pair.first.empty? }505- end506-507- def print_item row, tokens, chosen, selected508- # Cursor509- C.setpos row, 0510- C.clrtoeol511- cprint chosen ? '>' : ' ', color(:cursor, true)512- cprint selected ? '>' : ' ',513- chosen ? color(:chosen) : (selected ? color(:selected, true) : 0)514-515- # Highlighted item516- C.attron color(:chosen, true) if chosen517- tokens.each do |pair|518- token, highlighted = pair519-520- if highlighted521- cprint token, color(chosen ? :match! : :match, chosen)522- C.attron color(:chosen, true) if chosen523- else524- addstr_safe token525- end526- end527- C.attroff color(:chosen, true) if chosen528- end529-530- AFTER_1_9 = RUBY_VERSION.split('.').map { |e| e.rjust(3, '0') }.join >= '001009'531-532- if AFTER_1_9533- @@wrx = Regexp.new '\p{Han}|\p{Katakana}|\p{Hiragana}|\p{Hangul}'534- def width str535- str.gsub(@@wrx, ' ').length rescue str.length536- end537-538- def trim str, len, left539- width = width str540- diff = 0541- while width > len542- width -= ((left ? str[0, 1] : str[-1, 1]) =~ @@wrx ? 2 : 1) rescue 1543- str = left ? str[1..-1] : str[0...-1]544- diff += 1545- end546- [str, diff]547- end548- else549- def width str550- str.length551- end552-553- def trim str, len, left554- diff = str.length - len555- if diff > 0556- [left ? str[diff..-1] : str[0...-diff], diff]557- else558- [str, 0]559- end560- end561-562- class ::String563- def ord564- self.unpack('c').first565- end566- end567-568- class ::Fixnum569- def ord570- self571- end572- end573- end574-575- def init_screen576- $stdout.reopen($stderr)577-578- C.init_screen579- C.mousemask C::ALL_MOUSE_EVENTS if @mouse580- C.start_color581- dbg =582- if !@black && C.respond_to?(:use_default_colors)583- C.use_default_colors584- -1585- else586- C::COLOR_BLACK587- end588- C.raw589- C.noecho590-591- if @color592- if @ansi256 && ENV['TERM'].to_s =~ /256/593- C.init_pair 1, 110, dbg594- C.init_pair 2, 108, dbg595- C.init_pair 3, 254, 236596- C.init_pair 4, 151, 236597- C.init_pair 5, 148, dbg598- C.init_pair 6, 144, dbg599- C.init_pair 7, 161, 236600- C.init_pair 8, 168, 236601- else602- C.init_pair 1, C::COLOR_BLUE, dbg603- C.init_pair 2, C::COLOR_GREEN, dbg604- C.init_pair 3, C::COLOR_YELLOW, C::COLOR_BLACK605- C.init_pair 4, C::COLOR_GREEN, C::COLOR_BLACK606- C.init_pair 5, C::COLOR_GREEN, dbg607- C.init_pair 6, C::COLOR_WHITE, dbg608- C.init_pair 7, C::COLOR_RED, C::COLOR_BLACK609- C.init_pair 8, C::COLOR_MAGENTA, C::COLOR_BLACK610- end611-612- def self.color sym, bold = false613- C.color_pair([:prompt, :match, :chosen, :match!,614- :spinner, :info, :cursor, :selected].index(sym) + 1) |615- (bold ? C::A_BOLD : 0)616- end617- else618- def self.color sym, bold = false619- case sym620- when :chosen621- bold ? C::A_REVERSE : 0622- when :match623- C::A_UNDERLINE624- when :match!625- C::A_REVERSE | C::A_UNDERLINE626- else627- 0628- end | (bold ? C::A_BOLD : 0)629- end630- end631-632- C.refresh633- end634-635- def start_reader636- stream =637- if @source.tty?638- default_command = ENV['FZF_DEFAULT_COMMAND']639- if default_command && !default_command.empty?640- IO.popen(default_command)641- elsif !`which find`.empty?642- IO.popen("find * -path '*/\\.*' -prune -o -type f -print -o -type l -print 2> /dev/null")643- else644- exit 1645- end646- else647- @source648- end649-650- Thread.new do651- if @with_nth652- while line = stream.gets653- emit(:new) { @new << transform(line) }654- end655- else656- while line = stream.gets657- emit(:new) { @new << line.chomp }658- end659- end660- emit(:loaded) { true }661- @spinner.clear if @spinner662- end663- end664-665- def transform line666- line = line.chomp667- mut = (line =~ / $/ ? line : line + ' ').668- tokenize(@delim, @with_nth).map { |e| e.last }.join('').sub(/ *$/, '')669- mut.orig = line670- mut671- end672-673- def start_search &callback674- Thread.new do675- lists = []676- events = {}677- fcache = {}678- q = ''679- delay = -5680-681- begin682- while true683- @evt_mtx.synchronize do684- while true685- events.merge! @events686-687- if @events.empty? # No new events688- @cv.wait @evt_mtx689- next690- end691- @events.clear692- break693- end694-695- if events[:new]696- lists << @new697- set(:@count) { |c| c + @new.length }698- set(:@spinner) { |spinner|699- if e = spinner.shift700- spinner.push e701- end; spinner702- }703- @new = []704- fcache.clear705- end706- end#mtx707-708- new_search = events[:key] || events.delete(:new)709- user_input = events[:key]710- progress = 0711- started_at = Time.now712-713- if updated = new_search && !lists.empty?714- q, cx = events.delete(:key) || [q, 0]715- empty = matcher.empty?(q)716- unless matches = fcache[q]717- found = []718- skip = false719- cnt = 0720- lists.each do |list|721- cnt += list.length722- skip = @evt_mtx.synchronize { @events[:key] }723- break if skip724-725- if !empty && (progress = 100 * cnt / get(:@count)) < 100 && Time.now - started_at > 0.5726- render { print_info " (#{progress}%)" }727- end728-729- found.concat(q.empty? ? list :730- matcher.match(list, q, q[0, cx], q[cx..-1]))731- end732- if skip733- sleep 0.1734- next735- end736- matches = @sort ? found : found.reverse737- if !empty && @sort && matches.length <= @sort738- matches = FZF.sort(matches)739- end740- fcache[q] = matches741- end742-743- # Atomic update744- set(:@matches, matches)745- end#new_search746-747- callback = nil if callback &&748- (updated || events[:loaded]) &&749- callback.call(events[:loaded], matches)750-751- # This small delay reduces the number of partial lists752- sleep((delay = [20, delay + 5].min) * 0.01) unless user_input753-754- update_list new_search755- end#while756- rescue Exception => e757- @main.raise e758- end759- end760- end761-762- def pick763- sync do764- item = @matches[@ycur]765- item.is_a?(Array) ? item[0] : item766- end767- end768-769- def constrain offset, cursor, count, height770- original = [offset, cursor]771- diffpos = cursor - offset772-773- # Constrain cursor774- cursor = [0, [cursor, count - 1].min].max775-776- # Ceil777- if cursor > offset + (height - 1)778- offset = cursor - (height - 1)779- # Floor780- elsif offset > cursor781- offset = cursor782- end783-784- # Adjustment785- if count - offset < height786- offset = [0, count - height].max787- cursor = [0, [offset + diffpos, count - 1].min].max788- end789-790- [[offset, cursor] != original, offset, cursor]791- end792-793- def update_list wipe794- render do795- pos, items = sync {796- changed, @yoff, @ycur =797- constrain(@yoff, @ycur, @matches.length, max_items)798- wipe ||= changed799-800- [@ycur - @yoff, @matches[@yoff, max_items]]801- }802-803- # Wipe804- if items.length < @plcount805- @plcount.downto(items.length) do |idx|806- C.setpos cursor_y(idx + 2), 0807- C.clrtoeol808- end809- end810- @plcount = items.length811-812- dirty = Set[pos]813- set(:@dirty) do |vs|814- dirty.merge vs815- Set.new816- end817- items.each_with_index do |item, idx|818- next unless wipe || dirty.include?(idx)819- row = cursor_y(idx + 2)820- chosen = idx == pos821- selected = @selects.include?([*item][0])822- line, offsets = item823- tokens = format line, C.cols - 3, offsets824- print_item row, tokens, chosen, selected825- end826- print_info827- print_input828- end829- end830-831- def start_renderer832- init_screen833-834- Thread.new do835- begin836- while blk = @queue.shift837- blk.call838- refresh839- end840- rescue Exception => e841- @main.raise e842- end843- end844- end845-846- def render &blk847- @queue.push blk848- nil849- end850-851- def vselect &prc852- sync do853- @dirty << @ycur - @yoff854- @ycur = prc.call @ycur855- end856- update_list false857- end858-859- def num_unicode_bytes chr860- # http://en.wikipedia.org/wiki/UTF-8861- if chr & 0b10000000 > 0862- bytes = 0863- 7.downto(2) do |shift|864- break if (chr >> shift) & 0x1 == 0865- bytes += 1866- end867- bytes868- else869- 1870- end871- end872-873- def read_nb chars = 1, default = nil, tries = 10874- tries.times do |_|875- begin876- return @tty.read_nonblock(chars).ord877- rescue Exception878- sleep 0.01879- end880- end881- default882- end883-884- def read_nbs885- ords = []886- while ord = read_nb887- ords << ord888- end889- ords890- end891-892- def get_mouse893- case ord = read_nb894- when 32, 36, 40, 48, # mouse-down / shift / cmd / ctrl895- 35, 39, 43, 51 # mouse-up / shift / cmd / ctrl896- x = read_nb - 33897- y = read_nb - 33898- { :event => (ord % 2 == 0 ? :click : :release),899- :x => x, :y => y, :shift => ord >= 36 }900- when 96, 100, 104, 112, # scroll-up / shift / cmd / ctrl901- 97, 101, 105, 113 # scroll-down / shift / cmd / ctrl902- read_nb(2)903- { :event => :scroll, :diff => (ord % 2 == 0 ? -1 : 1), :shift => ord >= 100 }904- else905- # e.g. 40, 43, 104, 105906- read_nb(2)907- nil908- end909- end910-911- def get_input actions912- @tty ||=913- begin914- require 'io/console'915- IO.console916- rescue LoadError917- IO.open(IO.sysopen('/dev/tty'), 'r')918- end919-920- if pending = @pending921- @pending = nil922- return pending923- end924-925- str = ''926- while true927- ord =928- if str.empty?929- @tty.getc.ord930- else931- begin932- ord = @tty.read_nonblock(1).ord933- if (nb = num_unicode_bytes(ord)) > 1934- ords = [ord]935- (nb - 1).times do |_|936- ords << @tty.read_nonblock(1).ord937- end938- # UTF-8 TODO Ruby 1.8939- ords.pack('C*').force_encoding('UTF-8')940- else941- ord942- end943- rescue Exception944- return str945- end946- end947-948- ord =949- case read_nb(1, :esc)950- when 91, 79951- case read_nb(1, nil)952- when 68 then ctrl(:b)953- when 67 then ctrl(:f)954- when 66 then ctrl(:j)955- when 65 then ctrl(:k)956- when 90 then :stab957- when 50 then read_nb; :ins958- when 51 then read_nb; :del959- when 53 then read_nb; :pgup960- when 54 then read_nb; :pgdn961- when 49962- case read_nbs963- when [59, 50, 68] then ctrl(:a)964- when [59, 50, 67] then ctrl(:e)965- when [59, 53, 68] then :alt_b966- when [59, 53, 67] then :alt_f967- when [126] then ctrl(:a)968- end969- when 52 then read_nb; ctrl(:e)970- when 72 then ctrl(:a)971- when 70 then ctrl(:e)972- when 77973- get_mouse974- end975- when 'b', 98 then :alt_b976- when 'd', 100 then :alt_d977- when 'f', 102 then :alt_f978- when :esc then :esc979- when 127 then :alt_bs980- else next981- end if ord == 27982-983- return ord if ord.nil? || ord.is_a?(Hash)984-985- if actions.has_key?(ord)986- if str.empty?987- return ord988- else989- @pending = ord990- return str991- end992- else993- unless ord.is_a? String994- ord = [ord].pack('U*')995- end996- str << ord if ord =~ /[[:print:]]/997- end998- end999- end1000-1001- class MouseEvent1002- DOUBLE_CLICK_INTERVAL = 0.51003-1004- attr_reader :v1005-1006- def initialize v = nil1007- @c = 01008- @v = v1009- @t = Time.at 01010- end1011-1012- def v= v1013- @c = (@v == v && within?) ? @c + 1 : 01014- @v = v1015- @t = Time.now1016- end1017-1018- def double? v1019- @c == 1 && @v == v && within?1020- end1021-1022- def within?1023- (Time.now - @t) < DOUBLE_CLICK_INTERVAL1024- end1025- end1026-1027- def start_loop1028- got = nil1029- begin1030- input = call(:@query, :dup)1031- cursor = input.length1032- yanked = ''1033- mouse_event = MouseEvent.new1034- backword = proc {1035- cursor = (input[0, cursor].rindex(/[^[:alnum:]][[:alnum:]]/) || -1) + 11036- nil1037- }1038- forward = proc {1039- cursor += (input[cursor..-1].index(/([[:alnum:]][^[:alnum:]])|(.$)/) || -1) + 11040- nil1041- }1042- rubout = proc { |regex|1043- pcursor = cursor1044- cursor = (input[0, cursor].rindex(regex) || -1) + 11045- if pcursor > cursor1046- yanked = input[cursor...pcursor]1047- input = input[0...cursor] + input[pcursor..-1]1048- end1049- }1050- actions = {1051- :esc => proc { exit 1 },1052- ctrl(:d) => proc {1053- if input.empty?1054- exit 11055- elsif cursor < input.length1056- input = input[0...cursor] + input[(cursor + 1)..-1]1057- end1058- },1059- ctrl(:m) => proc {1060- got = pick1061- exit 01062- },1063- ctrl(:u) => proc {1064- yanked = input[0...cursor] if cursor > 01065- input = input[cursor..-1]1066- cursor = 01067- },1068- ctrl(:a) => proc { cursor = 0; nil },1069- ctrl(:e) => proc { cursor = input.length; nil },1070- ctrl(:j) => proc { vselect { |v| v - @rev_dir } },1071- ctrl(:k) => proc { vselect { |v| v + @rev_dir } },1072- ctrl(:w) => proc { rubout.call /\s\S/ },1073- ctrl(:y) => proc { actions[:default].call yanked },1074- ctrl(:h) => proc { input[cursor -= 1] = '' if cursor > 0 },1075- ctrl(:i) => proc { |o|1076- if @multi && sel = pick1077- sync do1078- if @selects.has_key? sel1079- @selects.delete sel1080- else1081- @selects[sel] = sel.orig1082- end1083- end1084- vselect { |v| v + case o1085- when :stab then 11086- when :sclick then 01087- else -11088- end * @rev_dir }1089- end1090- },1091- ctrl(:b) => proc { cursor = [0, cursor - 1].max; nil },1092- ctrl(:f) => proc { cursor = [input.length, cursor + 1].min; nil },1093- ctrl(:l) => proc { render { C.clear; C.refresh }; update_list true },1094- :del => proc { input[cursor] = '' if input.length > cursor },1095- :pgup => proc { vselect { |v| v + @rev_dir * (max_items - 1) } },1096- :pgdn => proc { vselect { |v| v - @rev_dir * (max_items - 1) } },1097- :alt_bs => proc { rubout.call /[^[:alnum:]][[:alnum:]]/ },1098- :alt_b => proc { backword.call },1099- :alt_d => proc {1100- pcursor = cursor1101- forward.call1102- if cursor > pcursor1103- yanked = input[pcursor...cursor]1104- input = input[0...pcursor] + input[cursor..-1]1105- cursor = pcursor1106- end1107- },1108- :alt_f => proc {1109- forward.call1110- },1111- :default => proc { |val|1112- case val1113- when String1114- input.insert cursor, val1115- cursor += val.length1116- when Hash1117- event = val[:event]1118- case event1119- when :click, :release1120- x, y, shift = val.values_at :x, :y, :shift1121- y = @reverse ? (C.lines - 1 - y) : y1122- if y == C.lines - 11123- cursor = [0, [input.length, x - @prompt.length].min].max1124- elsif x > 1 && y <= max_items1125- tv = get(:@yoff) + max_items - y - 11126-1127- case event1128- when :click1129- vselect { |_| tv }1130- actions[ctrl(:i)].call(:sclick) if shift1131- mouse_event.v = tv1132- when :release1133- if !shift && mouse_event.double?(tv)1134- actions[ctrl(:m)].call1135- end1136- end1137- end1138- when :scroll1139- diff, shift = val.values_at :diff, :shift1140- actions[ctrl(:i)].call(:sclick) if shift1141- actions[ctrl(diff > 0 ? :j : :k)].call1142- end1143- nil1144- end1145- }1146- }1147- actions[ctrl(:p)] = actions[ctrl(:k)]1148- actions[ctrl(:n)] = actions[ctrl(:j)]1149- actions[:stab] = actions[ctrl(:i)]1150- actions[127] = actions[ctrl(:h)]1151- actions[ctrl(:q)] = actions[ctrl(:g)] = actions[ctrl(:c)] = actions[:esc]1152-1153- while true1154- set(:@xcur, cursor)1155- render { print_input }1156-1157- if key = get_input(actions)1158- upd = actions.fetch(key, actions[:default]).call(key)1159-1160- # Dispatch key event1161- emit(:key) { [set(:@query, input.dup), cursor] } if upd1162- end1163- end1164- ensure1165- C.close_screen1166- q, selects = geta(:@query, :@selects)1167- @stdout.puts q if @print_query1168- @stdout.puts if @expect1169- if got1170- if selects.empty?1171- burp got1172- else1173- selects.each do |sel, orig|1174- burp sel, orig1175- end1176- end1177- end1178- end1179- end1180-1181- class Matcher1182- class MatchData1183- def initialize n1184- @n = n1185- end1186-1187- def offset _1188- @n1189- end1190- end1191-1192- def initialize nth, delim1193- @nth = nth1194- @delim = delim1195- @tokens_cache = {}1196- end1197-1198- def tokenize str1199- @tokens_cache[str] ||= str.tokenize(@delim, @nth)1200- end1201-1202- def do_match str, pat1203- if @nth1204- tokenize(str).each do |pair|1205- prefix_length, token = pair1206- if md = token.match(pat) rescue nil1207- return MatchData.new(md.offset(0).map { |o| o + prefix_length })1208- end1209- end1210- nil1211- else1212- str.match(pat) rescue nil1213- end1214- end1215- end1216-1217- class FuzzyMatcher < Matcher1218- attr_reader :caches, :rxflag1219-1220- def initialize rxflag, nth = nil, delim = nil1221- super nth, delim1222- @caches = Hash.new { |h, k| h[k] = {} }1223- @regexp = {}1224- @rxflag = rxflag1225- end1226-1227- def empty? q1228- q.empty?1229- end1230-1231- def rxflag_for q1232- @rxflag || (q =~ /[A-Z]/ ? 0 : Regexp::IGNORECASE)1233- end1234-1235- def fuzzy_regex q1236- @regexp[q] ||= begin1237- q = q.downcase if @rxflag == Regexp::IGNORECASE1238- Regexp.new(q.split(//).inject('') { |sum, e|1239- e = Regexp.escape e1240- sum << (e.length > 1 ? "(?:#{e}).*?" : # FIXME: not equivalent1241- "#{e}[^#{e}]*?")1242- }, rxflag_for(q))1243- end1244- end1245-1246- def match list, q, prefix, suffix1247- regexp = fuzzy_regex q1248-1249- cache = @caches[list.object_id]1250- prefix_cache = nil1251- (prefix.length - 1).downto(1) do |len|1252- break if prefix_cache = cache[prefix[0, len]]1253- end1254-1255- suffix_cache = nil1256- 0.upto(suffix.length - 1) do |idx|1257- break if suffix_cache = cache[suffix[idx..-1]]1258- end unless suffix.empty?1259-1260- partial_cache = [prefix_cache,1261- suffix_cache].compact.sort_by { |e| e.length }.first1262- cache[q] ||= (partial_cache ?1263- partial_cache.map { |e| e.first } : list).map { |line|1264- # Ignore errors: e.g. invalid byte sequence in UTF-81265- md = do_match(line, regexp)1266- md && [line, [md.offset(0)]]1267- }.compact1268- end1269- end1270-1271- class ExtendedFuzzyMatcher < FuzzyMatcher1272- def initialize rxflag, mode = :fuzzy, nth = nil, delim = nil1273- super rxflag, nth, delim1274- @regexps = {}1275- @mode = mode1276- end1277-1278- def empty? q1279- parse(q).empty?1280- end1281-1282- def parse q1283- q = q.strip1284- @regexps[q] ||= q.split(/\s+/).map { |w|1285- invert =1286- if w =~ /^!/1287- w = w[1..-1]1288- true1289- end1290-1291- [ @regexp[w] ||=1292- case w1293- when ''1294- nil1295- when /^\^(.*)\$$/1296- Regexp.new('^' << Regexp.escape($1) << '$', rxflag_for(w))1297- when /^'/1298- if @mode == :fuzzy && w.length > 11299- exact_regex w[1..-1]1300- elsif @mode == :exact1301- exact_regex w1302- end1303- when /^\^/1304- w.length > 1 ?1305- Regexp.new('^' << Regexp.escape(w[1..-1]), rxflag_for(w)) : nil1306- when /\$$/1307- w.length > 1 ?1308- Regexp.new(Regexp.escape(w[0..-2]) << '$', rxflag_for(w)) : nil1309- else1310- @mode == :fuzzy ? fuzzy_regex(w) : exact_regex(w)1311- end, invert ]1312- }.select { |pair| pair.first }1313- end1314-1315- def exact_regex w1316- Regexp.new(Regexp.escape(w), rxflag_for(w))1317- end1318-1319- def match list, q, prefix, suffix1320- regexps = parse q1321- # Look for prefix cache1322- cache = @caches[list.object_id]1323- prefix = prefix.strip.sub(/\$\S*$/, '').sub(/(^|\s)!\S*$/, '')1324- prefix_cache = nil1325- (prefix.length - 1).downto(1) do |len|1326- break if prefix_cache = cache[Set[@regexps[prefix[0, len]]]]1327- end1328-1329- cache[Set[regexps]] ||= (prefix_cache ?1330- prefix_cache.map { |e| e.first } :1331- list).map { |line|1332- offsets = []1333- regexps.all? { |pair|1334- regexp, invert = pair1335- md = do_match(line, regexp)1336- if md && !invert1337- offsets << md.offset(0)1338- elsif !md && invert1339- true1340- end1341- } && [line, offsets]1342- }.select { |e| e }1343- end1344- end1345-end#FZF1346-1347-FZF.new(ARGV, $stdin).start if ENV.fetch('FZF_EXECUTABLE', '1') == '1'1348-modified:install+5 added-76 removed
156 unmodified lines157 FreeBSD\ *64) download fzf-$version-freebsd_${binary_arch:-amd64} ;;158 FreeBSD\ *86) download fzf-$version-freebsd_${binary_arch:-386} ;;159 OpenBSD\ *64) download fzf-$version-openbsd_${binary_arch:-amd64} ;;160 OpenBSD\ *86) download fzf-$version-openbsd_${binary_arch:-386} ;;161- *) binary_available=0 binary_error=1 ;;161+ *) binary_available=0 binary_error=1 ;;162 esac163 164-install_ruby_fzf() {165- if [ -z "$allow_legacy" ]; then166- ask "Do you want to install legacy Ruby version instead?" && exit 1167- fi168- echo "Installing legacy Ruby version ..."169-170- # ruby executable171- echo -n "Checking Ruby executable ... "172- ruby=$(command -v ruby)173- if [ $? -ne 0 ]; then174- echo "ruby executable not found !!!"175- exit 1176- fi177-178- # System ruby is preferred179- system_ruby=/usr/bin/ruby180- if [ -x $system_ruby ] && [ $system_ruby != "$ruby" ]; then181- $system_ruby --disable-gems -rcurses -e0 2> /dev/null182- [ $? -eq 0 ] && ruby=$system_ruby183- fi184-185- echo "OK ($ruby)"186-187- # Curses-support188- echo -n "Checking Curses support ... "189- "$ruby" -rcurses -e0 2> /dev/null190- if [ $? -eq 0 ]; then191- echo "OK"192- else193- echo "Not found"194- echo "Installing 'curses' gem ... "195- if (( EUID )); then196- /usr/bin/env gem install curses --user-install197- else198- /usr/bin/env gem install curses199- fi200- if [ $? -ne 0 ]; then201- echo202- echo "Failed to install 'curses' gem."203- if [[ $(uname -r) =~ 'ARCH' ]]; then204- echo "Make sure that base-devel package group is installed."205- fi206- exit 1207- fi208- fi209-210- # Ruby version211- echo -n "Checking Ruby version ... "212- "$ruby" -e 'exit RUBY_VERSION >= "1.9"'213- if [ $? -eq 0 ]; then214- echo ">= 1.9"215- "$ruby" --disable-gems -rcurses -e0 2> /dev/null216- if [ $? -eq 0 ]; then217- fzf_cmd="$ruby --disable-gems $fzf_base/fzf"218- else219- fzf_cmd="$ruby $fzf_base/fzf"220- fi221- else222- echo "< 1.9"223- fzf_cmd="$ruby $fzf_base/fzf"224- fi225-226- # Create fzf script227- echo -n "Creating wrapper script for fzf ... "228- rm -f "$fzf_base"/bin/fzf229- echo "#!/bin/sh" > "$fzf_base"/bin/fzf230- echo "$fzf_cmd \"\$@\"" >> "$fzf_base"/bin/fzf231- chmod +x "$fzf_base"/bin/fzf232- echo "OK"233-}234-164 cd "$fzf_base"165 if [ -n "$binary_error" ]; then166 if [ $binary_available -eq 0 ]; then167 echo "No prebuilt binary for $archi ..."9 unmodified lines177 if go get -u github.com/junegunn/fzf/src/fzf; then178 echo "OK"179 cp "$GOPATH/bin/fzf" "$fzf_base/bin/"180 else252- echo "Failed to build binary ..."253- install_ruby_fzf181+ echo "Failed to build binary. Installation failed."182+ exit 1183 fi184 else256- echo "go executable not found. Cannot build binary ..."257- install_ruby_fzf185+ echo "go executable not found. Installation failed."186+ exit 1187 fi188 fi189 190 [[ "$*" =~ "--bin" ]] && exit 0136 unmodified lines