/
lusty-juggler.vim
1207 lines (1032 loc) · 32.4 KB
/
lusty-juggler.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) 2008-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-juggler.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-juggler.vim
" Description: Dynamic Buffer Switcher Vim Plugin
" Maintainer: Stephen Bach <this-file@sjbach.com>
" Contributors: Juan Frias, Bartosz Leper, Marco Barberis, Vincent Driessen,
" Martin Wache, Johannes Holzfuß, Adam Rutkowski, Carlo Teubner,
" lilydjwg, Leonid Shevtsov, Giuseppe Rota, Göran Gustafsson,
" Chris Lasher
"
" Release Date: February 24, 2012
" Version: 1.5
"
" Usage:
" <Leader>lj - Opens the buffer juggler.
"
" You can also use this command:
"
" ":LustyJuggler"
"
" To suppress the default mapping, set this option:
"
" let g:LustyJugglerDefaultMappings = 0
"
" When launched, the command bar at bottom is replaced with a
" new bar showing the names of currently-opened buffers in
" most-recently-used order.
"
" By default, LustyJuggler follows the QWERTY layout, and
" buffers are mapped to these keys:
"
" 1st|2nd|3rd|4th|5th|6th|7th|8th|9th|10th
" ----------------------------------------
" a s d f g h j k l ;
" 1 2 3 4 5 6 7 8 9 0
"
" So if you type "f" or "4", the fourth buffer name will be
" highlighted and the bar will shift to center it as necessary
" (and show more of the buffer names on the right).
"
" If you want to switch to that buffer, press "f" or "4" again
" or press "<ENTER>". Alternatively, press one of the other
" mapped keys to highlight another buffer. To open the buffer
" in a new split, press "b" for horizontal or "v" for vertical.
"
" To display the key with the name of the buffer, add one of
" the following lines to your .vimrc:
"
" let g:LustyJugglerShowKeys = 'a' (for alpha characters)
" let g:LustyJugglerShowKeys = 1 (for digits)
"
" To cancel the juggler, press any of "q", "<ESC>", "<C-c",
" "<BS>", "<Del>", or "<C-h>".
"
" LustyJuggler also supports the Dvorak keyboard layout. To
" enable this feature, place the following in your .vimrc:
"
" let g:LustyJugglerKeyboardLayout = "dvorak"
"
" With the layout set to "dvorak", the buffer mapping is as
" follows:
"
" 1st|2nd|3rd|4th|5th|6th|7th|8th|9th|10th
" ----------------------------------------
" a o e u i d h t n s
" 1 2 3 4 5 6 7 8 9 0
"
" LustyJuggler can act very much like <A-Tab> window switching.
" To enable this mode, add the following line to your .vimrc:
"
" let g:LustyJugglerAltTabMode = 1
"
" Then, given the following mapping:
"
" noremap <silent> <A-s> :LustyJuggler<CR>
"
" Pressing "<A-s>" will launch the LustyJuggler with the
" previous buffer highlighted. Typing "<A-s>" again will cycle
" to the next buffer (in most-recently used order), and
" "<ENTER>" will open the highlighted buffer. For example, the
" sequence "<A-s><Enter>" will open the previous buffer, and
" "<A-s><A-s><Enter>" will open the buffer used just before the
" previous buffer, and so on.
"
" Bonus: This plugin also includes the following command, which will
" immediately switch to your previously used buffer:
"
" ":LustyJugglePrevious"
"
" This is similar to the ":b#" command, but accounts for the
" common situation where the previously used buffer (#) has
" been killed and is thus inaccessible. In that case, it will
" instead switch to the buffer used before that one (and on down
" the line if that buffer has been killed too).
"
"
" 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, LustyJuggler requires ruby" warning. You can do so
" like this (in .vimrc):
"
" let g:LustyJugglerSuppressRubyWarning = 1
"
"
" Contributing:
"
" Patches and suggestions welcome. Note: lusty-juggler.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: 2050 1 :AutoInstall: lusty-juggler.vim
"
" TODO:
" - Add TAB recognition back.
" - Add option to open buffer immediately when mapping is pressed (but not
" release the juggler until the confirmation press).
" - Have the delimiter character settable.
" - have colours settable?
" Exit quickly when already loaded.
if exists("g:loaded_lustyjuggler")
finish
endif
if &compatible
echohl ErrorMsg
echo "LustyJuggler 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: LustyJuggler detects the presence of fuzzyfinder_textmate;"
echo "that plugin often interacts poorly with other Ruby plugins."
echo "If LustyJuggler 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")
if !exists("g:LustyExplorerSuppressRubyWarning") ||
\ g:LustyExplorerSuppressRubyWarning == "0"
if !exists("g:LustyJugglerSuppressRubyWarning") ||
\ g:LustyJugglerSuppressRubyWarning == "0"
echohl ErrorMsg
echon "Sorry, LustyJuggler 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\n"
echo "(If you just wish to stifle this message, set the following option:"
echo " let g:LustyJugglerSuppressRubyWarning = 1)"
echohl none
endif
endif
finish
endif
let g:loaded_lustyjuggler = "yep"
" Commands.
command LustyJuggler :call <SID>LustyJugglerStart()
command LustyJugglePrevious :call <SID>LustyJugglePreviousRun()
" Deprecated command names.
command JugglePrevious :call
\ <SID>deprecated('JugglePrevious', 'LustyJugglePrevious')
function! s:deprecated(old, new)
echohl WarningMsg
echo ":" . a:old . " is deprecated; use :" . a:new . " instead."
echohl none
endfunction
" Default mappings.
if !exists("g:LustyJugglerDefaultMappings")
let g:LustyJugglerDefaultMappings = 1
endif
if g:LustyJugglerDefaultMappings == 1
nmap <silent> <Leader>lj :LustyJuggler<CR>
endif
" Vim-to-ruby function calls.
function! s:LustyJugglerStart()
ruby LustyJ::profile() { $lusty_juggler.run }
endfunction
function! s:LustyJugglerKeyPressed(code_arg)
ruby LustyJ::profile() { $lusty_juggler.key_pressed }
endfunction
function! s:LustyJugglerCancel()
ruby LustyJ::profile() { $lusty_juggler.cleanup }
endfunction
function! s:LustyJugglePreviousRun()
ruby LustyJ::profile() { $lj_buffer_stack.juggle_previous }
endfunction
" Setup the autocommands that handle buffer MRU ordering.
augroup LustyJuggler
autocmd!
autocmd BufEnter * ruby LustyJ::profile() { $lj_buffer_stack.push }
autocmd BufDelete * ruby LustyJ::profile() { $lj_buffer_stack.pop }
autocmd BufWipeout * ruby LustyJ::profile() { $lj_buffer_stack.pop }
augroup End
" Used to work around a flaw in Vim's ruby bindings.
let s:maparg_holder = 0
let s:maparg_dict_holder = { }
ruby << EOF
require 'pathname'
$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
LustyJ::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 LustyJ
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
module LustyJ
class LustyJuggler
public
def initialize
@running = false
@last_pressed = nil
alpha_buffer_keys = [
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
";",
]
@name_bar = NameBar.new(alpha_buffer_keys)
@ALPHA_BUFFER_KEYS = Hash.new
alpha_buffer_keys.each_with_index {|x, i| @ALPHA_BUFFER_KEYS[x] = i + 1}
@NUMERIC_BUFFER_KEYS = {
"1" => 1,
"2" => 2,
"3" => 3,
"4" => 4,
"5" => 5,
"6" => 6,
"7" => 7,
"8" => 8,
"9" => 9,
"0" => 10
}
@BUFFER_KEYS = @ALPHA_BUFFER_KEYS.merge(@NUMERIC_BUFFER_KEYS)
@KEYPRESS_KEYS = {
# Can't use '<CR>' as an argument to :call func for some reason.
"<CR>" => "ENTER",
"<Tab>" => "TAB",
# Split opener keys
"v" => "v",
"b" => "b",
# Left and Right keys
"<Esc>OD" => "Left",
"<Esc>OC" => "Right",
"<Left>" => "Left",
"<Right>" => "Right",
}
@KEYPRESS_MAPPINGS = @BUFFER_KEYS.merge(@KEYPRESS_KEYS)
@CANCEL_MAPPINGS = [
"i",
"q",
"<Esc>",
"<C-c>",
"<BS>",
"<Del>",
"<C-h>",
]
end
def run
if $lj_buffer_stack.length <= 1
VIM::pretty_msg("PreProc", "No other buffers")
return
end
# If already running, highlight next buffer
if @running and LustyJuggler::alt_tab_mode_active?
@last_pressed = (@last_pressed % $lj_buffer_stack.length) + 1;
print_buffer_list(@last_pressed)
return
end
return if @running
@running = true
# Need to zero the timeout length or pressing 'g' will hang.
@ruler = VIM::evaluate_bool("&ruler")
@showcmd = VIM::evaluate_bool("&showcmd")
@showmode = VIM::evaluate_bool("&showmode")
@timeoutlen = VIM::evaluate("&timeoutlen")
VIM::set_option 'timeoutlen=0'
VIM::set_option 'noruler'
VIM::set_option 'noshowcmd'
VIM::set_option 'noshowmode'
@key_mappings_map = Hash.new { |hash, k| hash[k] = [] }
# Selection keys.
@KEYPRESS_MAPPINGS.keys.each do |c|
map_key(c, ":call <SID>LustyJugglerKeyPressed('#{c}')<CR>")
end
# Cancel keys.
@CANCEL_MAPPINGS.each do |c|
map_key(c, ":call <SID>LustyJugglerCancel()<CR>")
end
@last_pressed = 2 if LustyJuggler::alt_tab_mode_active?
print_buffer_list(@last_pressed)
end
def key_pressed()
c = VIM::evaluate("a:code_arg")
if @last_pressed.nil? and c == 'ENTER'
cleanup()
elsif @last_pressed and (@BUFFER_KEYS[c] == @last_pressed or c == 'ENTER')
choose(@last_pressed)
cleanup()
elsif @last_pressed and %w(v b).include?(c)
c=='v' ? vsplit(@last_pressed) : hsplit(@last_pressed)
cleanup()
elsif c == 'Left'
@last_pressed = (@last_pressed.nil?) ? 0 : (@last_pressed)
@last_pressed = (@last_pressed - 1) < 1 ? $lj_buffer_stack.length : (@last_pressed - 1)
print_buffer_list(@last_pressed)
elsif c == 'Right'
@last_pressed = (@last_pressed.nil?) ? 0 : (@last_pressed)
@last_pressed = (@last_pressed + 1) > $lj_buffer_stack.length ? 1 : (@last_pressed + 1)
print_buffer_list(@last_pressed)
else
@last_pressed = @BUFFER_KEYS[c]
print_buffer_list(@last_pressed)
end
end
# Restore settings, mostly.
def cleanup
@last_pressed = nil
VIM::set_option "timeoutlen=#{@timeoutlen}"
VIM::set_option "ruler" if @ruler
VIM::set_option "showcmd" if @showcmd
VIM::set_option "showmode" if @showmode
@KEYPRESS_MAPPINGS.keys.each do |c|
unmap_key(c)
end
@CANCEL_MAPPINGS.each do |c|
unmap_key(c)
end
@running = false
VIM::message ''
VIM::command 'redraw' # Prevents "Press ENTER to continue" message.
end
private
def self.alt_tab_mode_active?
return (VIM::exists?("g:LustyJugglerAltTabMode") and
VIM::evaluate("g:LustyJugglerAltTabMode").to_i != 0)
end
def print_buffer_list(highlighted_entry = nil)
# If the user pressed a key higher than the number of open buffers,
# highlight the highest (see also BufferStack.num_at_pos()).
@name_bar.selected_buffer = \
if highlighted_entry
# Correct for zero-based array.
[highlighted_entry, $lj_buffer_stack.length].min - 1
else
nil
end
@name_bar.print
end
def choose(i)
buf = $lj_buffer_stack.num_at_pos(i)
VIM::command "b #{buf}"
end
def vsplit(i)
buf = $lj_buffer_stack.num_at_pos(i)
VIM::command "vert sb #{buf}"
end
def hsplit(i)
buf = $lj_buffer_stack.num_at_pos(i)
VIM::command "sb #{buf}"
end
def map_key(key, action)
['n','s','x','o','i','c','l'].each do |mode|
VIM::command "let s:maparg_holder = maparg('#{key}', '#{mode}')"
if VIM::evaluate_bool("s:maparg_holder != ''")
orig_rhs = VIM::evaluate("s:maparg_holder")
if VIM::has_ext_maparg?
VIM::command "let s:maparg_dict_holder = maparg('#{key}', '#{mode}', 0, 1)"
nore = VIM::evaluate_bool("s:maparg_dict_holder['noremap']") ? 'nore' : ''
silent = VIM::evaluate_bool("s:maparg_dict_holder['silent']") ? ' <silent>' : ''
expr = VIM::evaluate_bool("s:maparg_dict_holder['expr']") ? ' <expr>' : ''
buffer = VIM::evaluate_bool("s:maparg_dict_holder['buffer']") ? ' <buffer>' : ''
restore_cmd = "#{mode}#{nore}map#{silent}#{expr}#{buffer} #{key} #{orig_rhs}"
else
nore = LustyJ::starts_with?(orig_rhs, '<Plug>') ? '' : 'nore'
restore_cmd = "#{mode}#{nore}map <silent> #{key} #{orig_rhs}"
end
@key_mappings_map[key] << [ mode, restore_cmd ]
end
VIM::command "#{mode}noremap <silent> #{key} #{action}"
end
end
def unmap_key(key)
#first, unmap lusty_juggler's maps
['n','s','x','o','i','c','l'].each do |mode|
VIM::command "#{mode}unmap <silent> #{key}"
end
if @key_mappings_map.has_key?(key)
@key_mappings_map[key].each do |a|
mode, restore_cmd = *a
# for mappings that have on the rhs \|, the \ is somehow stripped
restore_cmd.gsub!("|", "\\|")
VIM::command restore_cmd
end
end
end
end
class LustyJugglerDvorak < LustyJuggler
public
def initialize
super
alpha_buffer_keys = [
"a",
"o",
"e",
"u",
"i",
"d",
"h",
"t",
"n",
"s",
]
@name_bar = NameBar.new(alpha_buffer_keys)
@ALPHA_BUFFER_KEYS = Hash.new
alpha_buffer_keys.each_with_index {|x, i| @ALPHA_BUFFER_KEYS[x] = i + 1}
@BUFFER_KEYS = @ALPHA_BUFFER_KEYS.merge(@NUMERIC_BUFFER_KEYS)
@KEYPRESS_MAPPINGS = @BUFFER_KEYS.merge(@KEYPRESS_KEYS)
@CANCEL_MAPPINGS.delete("i")
@CANCEL_MAPPINGS.push("c")
end
end
end
# An item (delimiter/separator or buffer name) on the NameBar.
module LustyJ
class BarItem
def initialize(str, color)
@str = str
@color = color
end
def length
@str.length
end
def pretty_print_input
[@color, @str]
end
def [](*rest)
return BarItem.new(@str[*rest], @color)
end
def self.full_length(array)
if array
array.inject(0) { |sum, el| sum + el.length }
else
0
end
end
end
class BufferItem < BarItem
def initialize(str, highlighted)
@str = str
@highlighted = highlighted
destructure()
end
def [](*rest)
return BufferItem.new(@str[*rest], @highlighted)
end
def pretty_print_input
@array
end
private
@@BUFFER_COLOR = "PreProc"
#@@BUFFER_COLOR = "None"
@@DIR_COLOR = "Directory"
@@SLASH_COLOR = "Function"
@@HIGHLIGHTED_COLOR = "Question"
# Breakdown the string to colourize each part.
def destructure
if @highlighted
buf_color = @@HIGHLIGHTED_COLOR
dir_color = @@HIGHLIGHTED_COLOR
slash_color = @@HIGHLIGHTED_COLOR
else
buf_color = @@BUFFER_COLOR
dir_color = @@DIR_COLOR
slash_color = @@SLASH_COLOR
end
pieces = @str.split(File::SEPARATOR, -1)
@array = []
@array << dir_color
@array << pieces.shift
pieces.each { |piece|
@array << slash_color
@array << File::SEPARATOR
@array << dir_color
@array << piece
}
# Last piece is the actual name.
@array[-2] = buf_color
end
end
class SeparatorItem < BarItem
public
def initialize
super(@@TEXT, @@COLOR)
end
private
@@TEXT = "|"
#@@COLOR = "NonText"
@@COLOR = "None"
end
class LeftContinuerItem < BarItem
public
def initialize
super(@@TEXT, @@COLOR)
end
def self.length
@@TEXT.length
end
private
@@TEXT = "<"
@@COLOR = "NonText"
end
class RightContinuerItem < BarItem
public
def initialize
super(@@TEXT, @@COLOR)
end
def self.length
@@TEXT.length
end
private
@@TEXT = ">"
@@COLOR = "NonText"
end
end
# A one-line display of the open buffers, appearing in the command display.
module LustyJ
class NameBar
public
def initialize(letters)
@selected_buffer = nil
@LETTERS = letters
end
attr_writer :selected_buffer
def print
items = create_items()
selected_item = \
if @selected_buffer
# Account for the separators we've added.
[@selected_buffer * 2, (items.length - 1)].min
end
clipped = clip(items, selected_item)
NameBar.do_pretty_print(clipped)
end
def create_items
names = $lj_buffer_stack.names(10)
items = names.inject([]) { |array, name|
key = if VIM::exists?("g:LustyJugglerShowKeys")
case VIM::evaluate("g:LustyJugglerShowKeys").to_s
when /[[:alpha:]]/
@LETTERS[array.size / 2] + ":"
when /[[:digit:]]/
"#{((array.size / 2) + 1) % 10}:"
else
""
end
else
""
end
array << BufferItem.new("#{key}#{name}",
(@selected_buffer and \
name == names[@selected_buffer]))
array << SeparatorItem.new
}
items.pop # Remove last separator.
return items
end
# Clip the given array of items to the available display width.
def clip(items, selected)
# This function is pretty hard to follow...
# Note: Vim gives the annoying "Press ENTER to continue" message if we
# use the full width.
columns = VIM::columns() - 1
if BarItem.full_length(items) <= columns
return items
end
selected = 0 if selected.nil?
half_displayable_len = columns / 2
# The selected buffer is excluded since it's basically split between
# the sides.
left_len = BarItem.full_length items[0, selected - 1]
right_len = BarItem.full_length items[selected + 1, items.length - 1]
right_justify = (left_len > half_displayable_len) and \
(right_len < half_displayable_len)
selected_str_half_len = (items[selected].length / 2) + \
(items[selected].length % 2 == 0 ? 0 : 1)
if right_justify
# Right justify the bar.
first_layout = self.method :layout_right
second_layout = self.method :layout_left
first_adjustment = selected_str_half_len
second_adjustment = -selected_str_half_len