/
lusty-explorer.vim
2420 lines (2031 loc) · 67 KB
/
lusty-explorer.vim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
" Copyright: Copyright (C) 2007-2012 Stephen Bach
" Permission is hereby granted to use and distribute this code,
" with or without modifications, provided that this copyright
" notice is copied with it. Like anything else that's free,
" lusty-explorer.vim is provided *as is* and comes with no
" warranty of any kind, either expressed or implied. In no
" event will the copyright holder be liable for any damages
" resulting from the use of this software.
"
" Name Of File: lusty-explorer.vim
" Description: Dynamic Filesystem and Buffer Explorer Vim Plugin
" Maintainers: Stephen Bach <this-file@sjbach.com>
" Matt Tolton <matt-lusty-explorer@tolton.com>
" Contributors: Raimon Grau, Sergey Popov, Yuichi Tateno, Bernhard Walle,
" Rajendra Badapanda, cho45, Simo Salminen, Sami Samhuri,
" Matt Tolton, Björn Winckler, sowill, David Brown
" Brett DiFrischia, Ali Asad Lotia, Kenneth Love, Ben Boeckel,
" robquant, lilydjwg, Martin Wache, Johannes Holzfuß
" Donald Curtis, Jan Zwiener, Giuseppe Rota, Toby O'Connell,
" Göran Gustafsson, Joel Elkins
"
" Release Date: February 24, 2012
" Version: 4.3
"
" Usage:
" <Leader>lf - Opens the filesystem explorer.
" <Leader>lr - Opens the filesystem explorer from the
" directory of the current file.
" <Leader>lb - Opens the buffer explorer.
" <Leader>lg - Opens the buffer grep, for searching through
" all loaded buffers
"
" You can also use the commands:
"
" ":LustyFilesystemExplorer [optional-path]"
" ":LustyFilesystemExplorerFromHere"
" ":LustyBufferExplorer"
" ":LustyBufferGrep"
"
" To suppress the default mappings, set this option:
"
" let g:LustyExplorerDefaultMappings = 0
"
" When launched, a new window appears at bottom presenting a
" table of files/dirs or buffers, and in the status bar a
" prompt:
"
" >>
"
" As you type, the table updates for possible matches using a
" fuzzy matching algorithm (or regex matching, in the case of
" grep). Special keys include:
"
" <Enter> open selected match
" <Tab> open selected match
" <Esc> cancel
" <C-c> cancel
" <C-g> cancel
"
" <C-t> open selected match in a new [t]ab
" <C-o> open selected match in a new h[o]rizontal split
" <C-v> open selected match in a new [v]ertical split
"
" <C-n> select [n]ext match
" <C-p> select [p]revious match
" <C-f> select [f]orward one column
" <C-b> select [b]ack one column
"
" <C-u> clear prompt
"
" Additional shortcuts for the filesystem explorer:
"
" <C-w> ascend one directory at prompt
" <C-r> [r]efresh directory contents
" <C-a> open [a]ll files in current table
" <C-e> create new buffer with the given name and path
"
" Filesystem Explorer:
"
" - Directory contents are memoized. (<C-r> to refresh.)
" - You can recurse into and out of directories by typing the directory name
" and a slash, e.g. "stuff/" or "../".
" - Variable expansion, e.g. "$D" -> "/long/dir/path/".
" - Tilde (~) expansion, e.g. "~/" -> "/home/steve/".
" - Dotfiles are hidden by default, but are shown if the current search term
" begins with a '.'. To show these file at all times, set this option:
"
" let g:LustyExplorerAlwaysShowDotFiles = 1
"
" You can prevent certain files from appearing in the table with the
" following variable:
"
" set wildignore=*.o,*.fasl,CVS
"
" The above will mask all object files, compiled lisp files, and
" files/directories named CVS from appearing in the table. Note that they
" can still be opened by being named explicitly.
"
" See :help 'wildignore' for more information.
"
" Buffer Explorer:
"
" - Buffers are sorted first by fuzzy match and then by most-recently used.
" - The currently active buffer is highlighted.
"
" Buffer Grep:
"
" - Searches all loaded buffers.
" - Uses Ruby-style regexes instead of Vim style. This means:
"
" - \b instead of \< or \> for beginning/end of word.
" - (foo|bar) instead of \(foo\|bar\)
" - {2,5} instead of \{2,5}
" - + instead of \+
" - Generally, fewer backslashes. :-)
"
" - For now, searches are always case-insensitive.
" - Matches from the previous grep are remembered upon relaunch; clear with
" <C-u>.
"
"
" Install Details:
"
" Copy this file into $HOME/.vim/plugin directory so that it will be sourced
" on startup automatically.
"
" Note! This plugin requires Vim be compiled with Ruby interpretation. If you
" don't know if your build of Vim has this functionality, you can check by
" running "vim --version" from the command line and looking for "+ruby".
" Alternatively, just try sourcing this script.
"
" If your version of Vim does not have "+ruby" but you would still like to
" use this plugin, you can fix it. See the "Check for Ruby functionality"
" comment below for instructions.
"
" If you are using the same Vim configuration and plugins for multiple
" machines, some of which have Ruby and some of which don't, you may want to
" turn off the "Sorry, LustyExplorer requires ruby" warning. You can do so
" like this (in .vimrc):
"
" let g:LustyExplorerSuppressRubyWarning = 1
"
"
" Contributing:
"
" Patches and suggestions welcome. Note: lusty-explorer.vim is a generated
" file; if you'd like to submit a patch, check out the Github development
" repository:
"
" http://github.com/sjbach/lusty
"
"
" GetLatestVimScripts: 1890 1 :AutoInstall: lusty-explorer.vim
"
" TODO:
" - when an edited file is in nowrap mode and the explorer is called while the
" current window is scrolled to the right, name truncation occurs.
" - enable VimSwaps stuff
" - set callback when pipe is ready for read and force refresh()
" - uppercase character should make matching case-sensitive
" - FilesystemGrep
" - C-jhkl navigation to highlight a file?
" Exit quickly when already loaded.
if exists("g:loaded_lustyexplorer")
finish
endif
if &compatible
echohl ErrorMsg
echo "LustyExplorer is not designed to run in &compatible mode;"
echo "To use this plugin, first disable vi-compatible mode like so:\n"
echo " :set nocompatible\n"
echo "Or even better, just create an empty .vimrc file."
echohl none
finish
endif
if exists("g:FuzzyFinderMode.TextMate")
echohl WarningMsg
echo "Warning: LustyExplorer detects the presence of fuzzyfinder_textmate;"
echo "that plugin often interacts poorly with other Ruby plugins."
echo "If LustyExplorer gives you an error, you can probably fix it by"
echo "renaming fuzzyfinder_textmate.vim to zzfuzzyfinder_textmate.vim so"
echo "that it is last in the load order."
echohl none
endif
" Check for Ruby functionality.
if !has("ruby") || version < 700
if !exists("g:LustyExplorerSuppressRubyWarning") ||
\ g:LustyExplorerSuppressRubyWarning == "0"
if !exists("g:LustyJugglerSuppressRubyWarning") ||
\ g:LustyJugglerSuppressRubyWarning == "0"
echohl ErrorMsg
echon "Sorry, LustyExplorer requires ruby. "
echon "Here are some tips for adding it:\n"
echo "Debian / Ubuntu:"
echo " # apt-get install vim-ruby\n"
echo "Fedora:"
echo " # yum install vim-enhanced\n"
echo "Gentoo:"
echo " # USE=\"ruby\" emerge vim\n"
echo "FreeBSD:"
echo " # pkg_add -r vim+ruby\n"
echo "Windows:"
echo " 1. Download and install Ruby from here:"
echo " http://www.ruby-lang.org/"
echo " 2. Install a Vim binary with Ruby support:"
echo " http://segfault.hasno.info/vim/gvim72.zip\n"
echo "Manually (including Cygwin):"
echo " 1. Install Ruby."
echo " 2. Download the Vim source package (say, vim-7.0.tar.bz2)"
echo " 3. Build and install:"
echo " # tar -xvjf vim-7.0.tar.bz2"
echo " # ./configure --enable-rubyinterp"
echo " # make && make install"
echo "(If you just wish to stifle this message, set the following option:"
echo " let g:LustyExplorerSuppressRubyWarning = 1)"
echohl none
endif
endif
finish
endif
if ! &hidden
echohl WarningMsg
echo "You are running with 'hidden' mode off. LustyExplorer may"
echo "sometimes emit error messages in this mode -- you should turn"
echo "it on, like so:\n"
echo " :set hidden\n"
echo "Even better, put this in your .vimrc file."
echohl none
endif
let g:loaded_lustyexplorer = "yep"
" Commands.
command LustyBufferExplorer :call <SID>LustyBufferExplorerStart()
command -nargs=? LustyFilesystemExplorer :call <SID>LustyFilesystemExplorerStart("<args>")
command LustyFilesystemExplorerFromHere :call <SID>LustyFilesystemExplorerStart(expand("%:p:h"))
command LustyBufferGrep :call <SID>LustyBufferGrepStart()
" Deprecated command names.
command BufferExplorer :call
\ <SID>deprecated('BufferExplorer', 'LustyBufferExplorer')
command FilesystemExplorer :call
\ <SID>deprecated('FilesystemExplorer', 'LustyFilesystemExplorer')
command FilesystemExplorerFromHere :call
\ <SID>deprecated('FilesystemExplorerFromHere',
\ 'LustyFilesystemExplorerFromHere')
function! s:deprecated(old, new)
echohl WarningMsg
echo ":" . a:old . " is deprecated; use :" . a:new . " instead."
echohl none
endfunction
" Default mappings.
if !exists("g:LustyExplorerDefaultMappings")
let g:LustyExplorerDefaultMappings = 1
endif
if g:LustyExplorerDefaultMappings == 1
nmap <silent> <Leader>lf :LustyFilesystemExplorer<CR>
nmap <silent> <Leader>lr :LustyFilesystemExplorerFromHere<CR>
nmap <silent> <Leader>lb :LustyBufferExplorer<CR>
nmap <silent> <Leader>lg :LustyBufferGrep<CR>
endif
" Vim-to-ruby function calls.
function! s:LustyFilesystemExplorerStart(path)
ruby LustyE::profile() {
\ $lusty_filesystem_explorer.run_from_path(VIM::evaluate("a:path"))
\}
endfunction
function! s:LustyBufferExplorerStart()
ruby LustyE::profile() { $lusty_buffer_explorer.run }
endfunction
function! s:LustyBufferGrepStart()
ruby LustyE::profile() { $lusty_buffer_grep.run }
endfunction
function! s:LustyFilesystemExplorerCancel()
ruby LustyE::profile() { $lusty_filesystem_explorer.cancel }
endfunction
function! s:LustyBufferExplorerCancel()
ruby LustyE::profile() { $lusty_buffer_explorer.cancel }
endfunction
function! s:LustyBufferGrepCancel()
ruby LustyE::profile() { $lusty_buffer_grep.cancel }
endfunction
function! s:LustyFilesystemExplorerKeyPressed(code_arg)
ruby LustyE::profile() { $lusty_filesystem_explorer.key_pressed }
endfunction
function! s:LustyBufferExplorerKeyPressed(code_arg)
ruby LustyE::profile() { $lusty_buffer_explorer.key_pressed }
endfunction
function! s:LustyBufferGrepKeyPressed(code_arg)
ruby LustyE::profile() { $lusty_buffer_grep.key_pressed }
endfunction
" Setup the autocommands that handle buffer MRU ordering.
augroup LustyExplorer
autocmd!
autocmd BufEnter * ruby LustyE::profile() { $le_buffer_stack.push }
autocmd BufDelete * ruby LustyE::profile() { $le_buffer_stack.pop }
autocmd BufWipeout * ruby LustyE::profile() { $le_buffer_stack.pop }
augroup End
ruby << EOF
require 'pathname'
# For IO#ready -- but Cygwin doesn't have io/wait.
require 'io/wait' unless RUBY_PLATFORM =~ /cygwin/
# Needed for String#each_char in Ruby 1.8 on some platforms.
require 'jcode' unless "".respond_to? :each_char
# Needed for Array#each_slice in Ruby 1.8 on some platforms.
require 'enumerator' unless [].respond_to? :each_slice
$LUSTY_PROFILING = false
if $LUSTY_PROFILING
require 'rubygems'
require 'ruby-prof'
end
module VIM
unless const_defined? "MOST_POSITIVE_INTEGER"
MOST_POSITIVE_INTEGER = 2**(32 - 1) - 2 # Vim ints are signed 32-bit.
end
def self.zero?(var)
# In Vim 7.2 and older, VIM::evaluate returns Strings for boolean
# expressions; in later versions, Fixnums.
case var
when String
var == "0"
when Fixnum
var == 0
else
LustyE::assert(false, "unexpected type: #{var.class}")
end
end
def self.nonzero?(var)
not zero?(var)
end
def self.evaluate_bool(var)
nonzero? evaluate(var)
end
def self.exists?(s)
nonzero? evaluate("exists('#{s}')")
end
def self.has_syntax?
nonzero? evaluate('has("syntax")')
end
def self.has_ext_maparg?
# The 'dict' parameter to mapargs() was introduced in Vim 7.3.32
nonzero? evaluate('v:version > 703 || (v:version == 703 && has("patch32"))')
end
def self.columns
evaluate("&columns").to_i
end
def self.lines
evaluate("&lines").to_i
end
def self.getcwd
evaluate("getcwd()")
end
def self.bufname(i)
if evaluate_bool("empty(bufname(#{i}))")
"<Unknown #{i}>"
else
evaluate("bufname(#{i})")
end
end
def self.single_quote_escape(s)
# Everything in a Vim single-quoted string is literal, except single
# quotes. Single quotes are escaped by doubling them.
s.gsub("'", "''")
end
def self.regex_escape(s)
s.gsub(/[\]\[.~"^$\\*]/,'\\\\\0')
end
class Buffer
def modified?
VIM::nonzero? VIM::evaluate("getbufvar(#{number()}, '&modified')")
end
def listed?
VIM::nonzero? VIM::evaluate("getbufvar(#{number()}, '&buflisted')")
end
def self.obj_for_bufnr(n)
# There's gotta be a better way to do this...
(0..VIM::Buffer.count-1).each do |i|
obj = VIM::Buffer[i]
return obj if obj.number == n
end
return nil
end
end
# Print with colours
def self.pretty_msg(*rest)
return if rest.length == 0
return if rest.length % 2 != 0
command "redraw" # see :help echo-redraw
i = 0
while i < rest.length do
command "echohl #{rest[i]}"
command "echon '#{rest[i+1]}'"
i += 2
end
command 'echohl None'
end
end
# Hack for wide CJK characters.
if VIM::exists?("*strwidth")
module VIM
def self.strwidth(s)
# strwidth() is defined in Vim 7.3.
evaluate("strwidth('#{single_quote_escape(s)}')").to_i
end
end
else
module VIM
def self.strwidth(s)
s.length
end
end
end
if VIM::exists?("*fnameescape")
module VIM
def self.filename_escape(s)
# Escape slashes, open square braces, spaces, sharps, double
# quotes and percent signs, and remove leading ./ for files in
# pwd.
single_quote_escaped = single_quote_escape(s)
evaluate("fnameescape('#{single_quote_escaped}')").sub(/^\.\//,"")
end
end
else
module VIM
def self.filename_escape(s)
# Escape slashes, open square braces, spaces, sharps, double
# quotes and percent signs, and remove leading ./ for files in
# pwd.
s.gsub(/\\/, '\\\\\\').gsub(/[\[ #"%]/, '\\\\\0').sub(/^\.\//,"")
end
end
end
# Utility functions.
module LustyE
unless const_defined? "MOST_POSITIVE_FIXNUM"
MOST_POSITIVE_FIXNUM = 2**(0.size * 8 -2) -1
end
def self.simplify_path(s)
s = s.gsub(/\/+/, '/') # Remove redundant '/' characters
begin
if s[0] == ?~
# Tilde expansion - First expand the ~ part (e.g. '~' or '~steve')
# and then append the rest of the path. We can't just call
# expand_path() or it'll throw on bad paths.
s = File.expand_path(s.sub(/\/.*/,'')) + \
s.sub(/^[^\/]+/,'')
end
if s == '/'
# Special-case root so we don't add superfluous '/' characters,
# as this can make Cygwin choke.
s
elsif ends_with?(s, File::SEPARATOR)
File.expand_path(s) + File::SEPARATOR
else
dirname_expanded = File.expand_path(File.dirname(s))
if dirname_expanded == '/'
dirname_expanded + File.basename(s)
else
dirname_expanded + File::SEPARATOR + File.basename(s)
end
end
rescue ArgumentError
s
end
end
def self.longest_common_prefix(paths)
prefix = paths[0]
paths.each do |path|
for i in 0...prefix.length
if path.length <= i or prefix[i] != path[i]
prefix = prefix[0...i]
prefix = prefix[0..(prefix.rindex('/') or -1)]
break
end
end
end
prefix
end
def self.ready_for_read?(io)
if io.respond_to? :ready?
ready?
else
result = IO.select([io], nil, nil, 0)
result && (result.first.first == io)
end
end
def self.ends_with?(s1, s2)
tail = s1[-s2.length, s2.length]
tail == s2
end
def self.starts_with?(s1, s2)
head = s1[0, s2.length]
head == s2
end
def self.option_set?(opt_name)
opt_name = "g:LustyExplorer" + opt_name
VIM::evaluate_bool("exists('#{opt_name}') && #{opt_name} != '0'")
end
def self.profile
# Profile (if enabled) and provide better
# backtraces when there's an error.
if $LUSTY_PROFILING
if not RubyProf.running?
RubyProf.measure_mode = RubyProf::WALL_TIME
RubyProf.start
else
RubyProf.resume
end
end
begin
yield
rescue Exception => e
puts e
puts e.backtrace
end
if $LUSTY_PROFILING and RubyProf.running?
RubyProf.pause
end
end
class AssertionError < StandardError ; end
def self.assert(condition, message = 'assertion failure')
raise AssertionError.new(message) unless condition
end
def self.d(s)
# (Debug print)
$stderr.puts s
end
end
# Mercury fuzzy matching algorithm, written by Matt Tolton.
# based on the Quicksilver and LiquidMetal fuzzy matching algorithms
class Mercury
public
def self.score(string, abbrev)
return self.new(string, abbrev).score()
end
def score()
return @@SCORE_TRAILING if @abbrev.empty?
return @@SCORE_NO_MATCH if @abbrev.length > @string.length
raw_score = raw_score(0, 0, 0, false)
return raw_score / @string.length
end
def initialize(string, abbrev)
@string = string
@lower_string = string.downcase()
@abbrev = abbrev.downcase()
@level = 0
@branches = 0
end
private
@@SCORE_NO_MATCH = 0.0 # do not change, this is assumed to be 0.0
@@SCORE_EXACT_MATCH = 1.0
@@SCORE_MATCH = 0.9
@@SCORE_TRAILING = 0.7
@@SCORE_TRAILING_BUT_STARTED = 0.80
@@SCORE_BUFFER = 0.70
@@SCORE_BUFFER_BUT_STARTED = 0.80
@@BRANCH_LIMIT = 100
#def raw_score(a, b, c, d)
# @level += 1
# puts "#{' ' * @level}#{a}, #{b}, #{c}, #{d}"
# ret = recurse_and_score(a, b, c, d)
# puts "#{' ' * @level}#{a}, #{b}, #{c}, #{d} -> #{ret}"
# @level -= 1
# return ret
#end
def raw_score(abbrev_idx, match_idx, score_idx, first_char_matched)
index = @lower_string.index(@abbrev[abbrev_idx], match_idx)
return 0.0 if index.nil?
# TODO Instead of having two scores, should there be a sliding "match"
# score based on the distance of the matched character to the beginning
# of the string?
if abbrev_idx == index
score = @@SCORE_EXACT_MATCH
else
score = @@SCORE_MATCH
end
started = (index == 0 or first_char_matched)
# If matching on a word boundary, score the characters since the last match
if index > score_idx
buffer_score = started ? @@SCORE_BUFFER_BUT_STARTED : @@SCORE_BUFFER
if " \t/._-".include?(@string[index - 1])
score += @@SCORE_MATCH
score += buffer_score * ((index - 1) - score_idx)
elsif @string[index] >= "A"[0] and @string[index] <= "Z"[0]
score += buffer_score * (index - score_idx)
end
end
if abbrev_idx + 1 == @abbrev.length
trailing_score = started ? @@SCORE_TRAILING_BUT_STARTED : @@SCORE_TRAILING
# We just matched the last character in the pattern
score += trailing_score * (@string.length - (index + 1))
else
tail_score = raw_score(abbrev_idx + 1, index + 1, index + 1, started)
return 0.0 if tail_score == 0.0
score += tail_score
end
if @branches < @@BRANCH_LIMIT
@branches += 1
alternate = raw_score(abbrev_idx,
index + 1,
score_idx,
first_char_matched)
#puts "#{' ' * @level}#{score}, #{alternate}"
score = [score, alternate].max
end
return score
end
end
module LustyE
# Abstract base class.
class Entry
attr_accessor :full_name, :short_name, :label
def initialize(full_name, short_name, label)
@full_name = full_name
@short_name = short_name
@label = label
end
# NOTE: very similar to BufferStack::shorten_paths()
def self.compute_buffer_entries()
buffer_entries = []
$le_buffer_stack.numbers.each do |n|
o = VIM::Buffer.obj_for_bufnr(n)
next if (o.nil? or not o.listed?)
buffer_entries << self.new(o, n)
end
# Put the current buffer at the end of the list.
buffer_entries << buffer_entries.shift
# Shorten each buffer name by removing all path elements which are not
# needed to differentiate a given name from other names. This usually
# results in only the basename shown, but if several buffers of the
# same basename are opened, there will be more.
# Group the buffers by common basename
common_base = Hash.new { |hash, k| hash[k] = [] }
buffer_entries.each do |entry|
if entry.full_name
basename = Pathname.new(entry.full_name).basename.to_s
common_base[basename] << entry
end
end
# Determine the longest common prefix for each basename group.
basename_to_prefix = {}
common_base.each do |base, entries|
if entries.length > 1
full_names = entries.map { |e| e.full_name }
basename_to_prefix[base] = LustyE::longest_common_prefix(full_names)
end
end
# Compute shortened buffer names by removing prefix, if possible.
buffer_entries.each do |entry|
full_name = entry.full_name
short_name = if full_name.nil?
'[No Name]'
elsif LustyE::starts_with?(full_name, "scp://")
full_name
else
base = Pathname.new(full_name).basename.to_s
prefix = basename_to_prefix[base]
prefix ? full_name[prefix.length..-1] \
: base
end
entry.short_name = short_name
end
buffer_entries
end
end
# Used in FilesystemExplorer
class FilesystemEntry < Entry
attr_accessor :current_score
def initialize(label)
super("::UNSET::", "::UNSET::", label)
@current_score = 0.0
end
end
# Used in BufferExplorer
class BufferEntry < Entry
attr_accessor :vim_buffer, :mru_placement, :current_score
def initialize(vim_buffer, mru_placement)
super(vim_buffer.name, "::UNSET::", "::UNSET::")
@vim_buffer = vim_buffer
@mru_placement = mru_placement
@current_score = 0.0
end
end
# Used in BufferGrep
class GrepEntry < Entry
attr_accessor :vim_buffer, :mru_placement, :line_number
def initialize(vim_buffer, mru_placement)
super(vim_buffer.name, "::UNSET::", "::UNSET::")
@vim_buffer = vim_buffer
@mru_placement = mru_placement
@line_number = 0
end
end
end
# Abstract base class; extended as BufferExplorer, FilesystemExplorer
module LustyE
class Explorer
public
def initialize
@settings = SavedSettings.new
@display = Display.new title()
@prompt = nil
@current_sorted_matches = []
@running = false
end
def run
return if @running
@settings.save
@running = true
@calling_window = $curwin
@saved_alternate_bufnum = if VIM::evaluate_bool("expand('#') == ''")
nil
else
VIM::evaluate("bufnr(expand('#'))")
end
create_explorer_window()
refresh(:full)
end
def key_pressed()
# Grab argument from the Vim function.
i = VIM::evaluate("a:code_arg").to_i
refresh_mode = :full
case i
when 32..126 # Printable characters
c = i.chr
@prompt.add! c
@selected_index = 0
when 8 # Backspace/Del/C-h
@prompt.backspace!
@selected_index = 0
when 9, 13 # Tab and Enter
choose(:current_tab)
when 23 # C-w (delete 1 dir backward)
@prompt.up_one_dir!
@selected_index = 0
when 14 # C-n (select next)
@selected_index = \
if @current_sorted_matches.size.zero?
0
else
(@selected_index + 1) % @current_sorted_matches.size
end
refresh_mode = :no_recompute
when 16 # C-p (select previous)
@selected_index = \
if @current_sorted_matches.size.zero?
0
else
(@selected_index - 1) % @current_sorted_matches.size
end
refresh_mode = :no_recompute
when 6 # C-f (select right)
@selected_index = \
if @row_count.nil? || @row_count.zero?
0
else
columns = \
(@current_sorted_matches.size.to_f / @row_count.to_f).ceil
cur_column = @selected_index / @row_count
cur_row = @selected_index % @row_count
new_column = (cur_column + 1) % columns
if (new_column + 1) * (cur_row + 1) > @current_sorted_matches.size
new_column = 0
end
new_column * @row_count + cur_row
end
refresh_mode = :no_recompute
when 2 # C-b (select left)
@selected_index = \
if @row_count.nil? || @row_count.zero?
0
else
columns = \
(@current_sorted_matches.size.to_f / @row_count.to_f).ceil
cur_column = @selected_index / @row_count
cur_row = @selected_index % @row_count
new_column = (cur_column - 1) % columns
if (new_column + 1) * (cur_row + 1) > @current_sorted_matches.size
new_column = columns - 2
end
new_column * @row_count + cur_row
end
refresh_mode = :no_recompute
when 15 # C-o choose in new horizontal split
choose(:new_split)
when 20 # C-t choose in new tab
choose(:new_tab)
when 21 # C-u clear prompt
@prompt.clear!
@selected_index = 0
when 22 # C-v choose in new vertical split
choose(:new_vsplit)
end
refresh(refresh_mode)
end
def cancel
if @running
cleanup()
# fix alternate file
if @saved_alternate_bufnum
cur = $curbuf
VIM::command "silent b #{@saved_alternate_bufnum}"
VIM::command "silent b #{cur.number}"
end
if $LUSTY_PROFILING
outfile = File.new('lusty-explorer-rbprof.html', 'a')
#RubyProf::CallTreePrinter.new(RubyProf.stop).print(outfile)
RubyProf::GraphHtmlPrinter.new(RubyProf.stop).print(outfile)
end
end
end
private
def refresh(mode)
return if not @running
if mode == :full
@current_sorted_matches = compute_sorted_matches()
end
on_refresh()
highlight_selected_index() if VIM::has_syntax?
@row_count = @display.print @current_sorted_matches.map { |x| x.label }
@prompt.print Display.max_width
end
def create_explorer_window
# Trim out the "::" in "LustyE::FooExplorer"
key_binding_prefix = 'Lusty' + self.class.to_s.sub(/.*::/,'')
@display.create(key_binding_prefix)
set_syntax_matching()
end
def highlight_selected_index
# Note: overridden by BufferGrep
VIM::command 'syn clear LustySelected'
entry = @current_sorted_matches[@selected_index]
return if entry.nil?
escaped = VIM::regex_escape(entry.label)
label_match_string = Display.entry_syntaxify(escaped, false)
VIM::command "syn match LustySelected \"#{label_match_string}\" " \
'contains=LustyGrepMatch'
end
def choose(open_mode)
entry = @current_sorted_matches[@selected_index]
return if entry.nil?
open_entry(entry, open_mode)
end
def cleanup
@display.close
Window.select @calling_window
@settings.restore
@running = false
VIM::message ""
LustyE::assert(@calling_window == $curwin)
end
# Pure virtual methods
# - set_syntax_matching
# - on_refresh
# - open_entry
# - compute_sorted_matches
end
end
module LustyE
class BufferExplorer < Explorer
public
def initialize
super
@prompt = Prompt.new
@buffer_entries = []
end
def run