forked from jeetsukumaran/vim-buffersaurus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffersaurus.vim
More file actions
2207 lines (2011 loc) * 90.6 KB
/
buffersaurus.vim
File metadata and controls
2207 lines (2011 loc) * 90.6 KB
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
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"" Buffersaurus
""
"" Vim document buffer indexing and navigation utility
""
"" Copyright 2010 Jeet Sukumaran.
""
"" This program is free software; you can redistribute it and/or modify
"" it under the terms of the GNU General Public License as published by
"" the Free Software Foundation; either version 3 of the License, or
"" (at your option) any later version.
""
"" This program is distributed in the hope that it will be useful,
"" but WITHOUT ANY WARRANTY; without even the implied warranty of
"" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"" GNU General Public License
"" for more details.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Reload and Compatibility Guard {{{1
" ============================================================================
" Reload protection.
if (exists('g:did_buffersaurus') && g:did_buffersaurus) || &cp || version < 700
finish
endif
let g:did_buffersaurus = 1
" avoid line continuation issues (see ':help user_41.txt')
let s:save_cpo = &cpo
set cpo&vim
" 1}}}
" Global Plugin Options {{{1
" =============================================================================
if !exists("g:buffersaurus_autodismiss_on_select")
let g:buffersaurus_autodismiss_on_select = 1
endif
if !exists("g:buffersaurus_sort_regime")
let g:buffersaurus_sort_regime = 'fl'
endif
if !exists("g:buffersaurus_show_context")
let g:buffersaurus_show_context = 0
endif
if !exists("g:buffersaurus_context_size")
let g:buffersaurus_context_size = [4, 4]
endif
if !exists("g:buffersaurus_viewport_split_policy")
let g:buffersaurus_viewport_split_policy = "B"
endif
if !exists("g:buffersaurus_move_wrap")
let g:buffersaurus_move_wrap = 1
endif
if !exists("g:buffersaurus_flash_jumped_line")
let g:buffersaurus_flash_jumped_line = 1
endif
" 1}}}
" Script Data and Variables {{{1
" =============================================================================
" Display column sizes {{{2
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
" Display columns.
let s:buffersaurus_lnum_field_width = 6
let s:buffersaurus_entry_label_field_width = 4
" TODO: populate the following based on user setting, as well as allow
" abstraction from the actual Vim command (e.g., option "top" => "zt")
let s:buffersaurus_post_move_cmd = "normal! zz"
" 2}}}
" Split Modes {{{2
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
" Split modes are indicated by a single letter. Upper-case letters indicate
" that the SCREEN (i.e., the entire application "window" from the operating
" system's perspective) should be split, while lower-case letters indicate
" that the VIEWPORT (i.e., the "window" in Vim's terminology, referring to the
" various subpanels or splits within Vim) should be split.
" Split policy indicators and their corresponding modes are:
" ``/`d`/`D' : use default splitting mode
" `n`/`N` : NO split, use existing window.
" `L` : split SCREEN vertically, with new split on the left
" `l` : split VIEWPORT vertically, with new split on the left
" `R` : split SCREEN vertically, with new split on the right
" `r` : split VIEWPORT vertically, with new split on the right
" `T` : split SCREEN horizontally, with new split on the top
" `t` : split VIEWPORT horizontally, with new split on the top
" `B` : split SCREEN horizontally, with new split on the bottom
" `b` : split VIEWPORT horizontally, with new split on the bottom
let s:buffersaurus_viewport_split_modes = {
\ "d" : "sp",
\ "D" : "sp",
\ "N" : "buffer",
\ "n" : "buffer",
\ "L" : "topleft vert sbuffer",
\ "l" : "leftabove vert sbuffer",
\ "R" : "botright vert sbuffer",
\ "r" : "rightbelow vert sbuffer",
\ "T" : "topleft sbuffer",
\ "t" : "leftabove sbuffer",
\ "B" : "botright sbuffer",
\ "b" : "rightbelow sbuffer",
\ }
" 2}}}
" Catalog Sort Regimes {{{2
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let s:buffersaurus_catalog_sort_regimes = ['fl', 'fa', 'a']
let s:buffersaurus_catalog_sort_regime_desc = {
\ 'fl' : ["F(L#)", "by filepath, then by line number"],
\ 'fa' : ["F(A-Z)", "by filepath, then by line text"],
\ 'a' : ["A-Z", "by line text"],
\ 'pl' : ["P(L#)", "by priority, then by line number"],
\ }
" 2}}}
" 1}}}
" Utilities {{{1
" ==============================================================================
" Text Formatting {{{2
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function! s:Format_AlignLeft(text, width, fill_char)
let l:fill = repeat(a:fill_char, a:width-len(a:text))
return a:text . l:fill
endfunction
function! s:Format_AlignRight(text, width, fill_char)
let l:fill = repeat(a:fill_char, a:width-len(a:text))
return l:fill . a:text
endfunction
function! s:Format_Time(secs)
if exists("*strftime")
return strftime("%Y-%m-%d %H:%M:%S", a:secs)
else
return (localtime() - a:secs) . " secs ago"
endif
endfunction
function! s:Format_EscapedFilename(file)
if exists('*fnameescape')
return fnameescape(a:file)
else
return escape(a:file," \t\n*?[{`$\\%#'\"|!<")
endif
endfunction
" trunc: -1 = truncate left, 0 = no truncate, +1 = truncate right
function! s:Format_Truncate(str, max_len, trunc)
if len(a:str) > a:max_len
if a:trunc > 0
return strpart(a:str, a:max_len - 4) . " ..."
elseif a:trunc < 0
return '... ' . strpart(a:str, len(a:str) - a:max_len + 4)
endif
else
return a:str
endif
endfunction
" Pads/truncates text to fit a given width.
" align: -1/0 = align left, 0 = no align, 1 = align right
" trunc: -1 = truncate left, 0 = no truncate, +1 = truncate right
function! s:Format_Fill(str, width, align, trunc)
let l:prepped = a:str
if a:trunc != 0
let l:prepped = s:Format_Truncate(a:str, a:width, a:trunc)
endif
if len(l:prepped) < a:width
if a:align > 0
let l:prepped = s:Format_AlignRight(l:prepped, a:width, " ")
elseif a:align < 0
let l:prepped = s:Format_AlignLeft(l:prepped, a:width, " ")
endif
endif
return l:prepped
endfunction
" 2}}}
" Messaging {{{2
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function! s:NewMessenger(name)
" allocate a new pseudo-object
let l:messenger = {}
let l:messenger["name"] = a:name
if empty(a:name)
let l:messenger["title"] = "buffersaurus"
else
let l:messenger["title"] = "buffersaurus (" . l:messenger["name"] . ")"
endif
function! l:messenger.format_message(leader, msg) dict
return self.title . ": " . a:leader.a:msg
endfunction
function! l:messenger.format_exception( msg) dict
return a:msg
endfunction
function! l:messenger.send_error(msg) dict
redraw
echohl ErrorMsg
echomsg self.format_message("[ERROR] ", a:msg)
echohl None
endfunction
function! l:messenger.send_warning(msg) dict
redraw
echohl WarningMsg
echomsg self.format_message("[WARNING] ", a:msg)
echohl None
endfunction
function! l:messenger.send_status(msg) dict
redraw
echohl None
echomsg self.format_message("", a:msg)
endfunction
function! l:messenger.send_info(msg) dict
redraw
echohl None
echo self.format_message("", a:msg)
endfunction
return l:messenger
endfunction
" 2}}}
" 1}}}
" BufferManager {{{1
" ==============================================================================
" Creates the script-wide buffer/window manager.
function! s:NewBufferManager()
" initialize
let l:buffer_manager = {}
" Returns a list of all existing buffer numbers, excluding unlisted ones
" unless `include_unlisted` is non-empty.
function! l:buffer_manager.get_buf_nums(include_unlisted)
let l:buf_num_list = []
for l:idx in range(1, bufnr("$"))
if bufexists(l:idx) && (empty(a:include_unlisted) || buflisted(l:idx))
call add(l:buf_num_list, l:idx)
endif
endfor
return l:buf_num_list
endfunction
" Returns a list of all existing buffer names, excluding unlisted ones
" unless `include_unlisted` is non-empty.
function! l:buffer_manager.get_buf_names(include_unlisted, expand_modifiers)
let l:buf_name_list = []
for l:idx in range(1, bufnr("$"))
if bufexists(l:idx) && (empty(!a:include_unlisted) || buflisted(l:idx))
call add(l:buf_name_list, expand(bufname(l:idx).a:expand_modifiers))
endif
endfor
return l:buf_name_list
endfunction
" Searches for all windows that have a window-scoped variable `varname`
" with value that matches the expression `expr`. Returns list of window
" numbers that meet the criterion.
function! l:buffer_manager.find_windows_with_var(varname, expr)
let l:results = []
for l:wni in range(1, winnr("$"))
let l:wvar = getwinvar(l:wni, "")
if empty(a:varname)
call add(l:results, l:wni)
elseif has_key(l:wvar, a:varname) && l:wvar[a:varname] =~ a:expr
call add(l:results, l:wni)
endif
endfor
return l:results
endfunction
" Searches for all buffers that have a buffer-scoped variable `varname`
" with value that matches the expression `expr`. Returns list of buffer
" numbers that meet the criterion.
function! l:buffer_manager.find_buffers_with_var(varname, expr)
let l:results = []
for l:bni in range(1, bufnr("$"))
if !bufexists(l:bni)
continue
endif
let l:bvar = getbufvar(l:bni, "")
if empty(a:varname)
call add(l:results, l:bni)
elseif has_key(l:bvar, a:varname) && l:bvar[a:varname] =~ a:expr
call add(l:results, l:bni)
endif
endfor
return l:results
endfunction
" Returns a dictionary with the buffer number as keys (if `key` is empty)
" and the parsed information regarding each buffer as values. If `key` is
" given (e.g. key='num'; key='name', key='filepath') then that field will
" be used as the dictionary keys instead.
function! l:buffer_manager.get_buffers_info(key) dict
if empty(a:key)
let l:key = "num"
else
let l:key = a:key
endif
redir => buffers_output
execute('silent ls')
redir END
let l:buffers_info = {}
let l:buffers_output_rows = split(l:buffers_output, "\n")
for l:buffers_output_row in l:buffers_output_rows
let l:parts = matchlist(l:buffers_output_row, '^\s*\(\d\+\)\(.....\) "\(.*\)"\s\+line \d\+$')
let l:info = {}
let l:info["num"] = l:parts[1] + 0
if l:parts[2][0] == "u"
let l:info["is_unlisted"] = 1
let l:info["is_listed"] = 0
else
let l:info["is_unlisted"] = 0
let l:info["is_listed"] = 1
endif
if l:parts[2][1] == "%"
let l:info["is_current"] = 1
let l:info["is_alternate"] = 0
elseif l:parts[2][1] == "#"
let l:info["is_current"] = 0
let l:info["is_alternate"] = 1
else
let l:info["is_current"] = 0
let l:info["is_alternate"] = 0
endif
if l:parts[2][2] == "a"
let l:info["is_active"] = 1
let l:info["is_loaded"] = 1
let l:info["is_visible"] = 1
elseif l:parts[2][2] == "h"
let l:info["is_active"] = 0
let l:info["is_loaded"] = 1
let l:info["is_visible"] = 0
else
let l:info["is_active"] = 0
let l:info["is_loaded"] = 0
let l:info["is_visible"] = 0
endif
if l:parts[2][3] == "-"
let l:info["is_modifiable"] = 0
let l:info["is_readonly"] = 0
elseif l:parts[2][3] == "="
let l:info["is_modifiable"] = 1
let l:info["is_readonly"] = 1
else
let l:info["is_modifiable"] = 1
let l:info["is_readonly"] = 0
endif
if l:parts[2][4] == "+"
let l:info["is_modified"] = 1
let l:info["is_readerror"] = 0
elseif l:parts[2][4] == "x"
let l:info["is_modified"] = 0
let l:info["is_readerror"] = 0
else
let l:info["is_modified"] = 0
let l:info["is_readerror"] = 0
endif
let l:info["name"] = parts[3]
let l:info["filepath"] = fnamemodify(l:info["name"], ":p")
if !has_key(l:info, l:key)
throw s:_buffersaurus_messenger.format_exception("Invalid key requested: '" . l:key . "'")
endif
let l:buffers_info[l:info[l:key]] = l:info
endfor
return l:buffers_info
endfunction
" Returns split mode to use for a new Buffersaurus viewport.
function! l:buffer_manager.get_split_mode() dict
if has_key(s:buffersaurus_viewport_split_modes, g:buffersaurus_viewport_split_policy)
return s:buffersaurus_viewport_split_modes[g:buffersaurus_viewport_split_policy]
else
call s:_buffersaurus_messenger.send_error("Unrecognized split mode specified by 'g:buffersaurus_viewport_split_policy': " . g:buffersaurus_viewport_split_policy)
endif
endfunction
" Detect filetype. From the 'taglist' plugin.
" Copyright (C) 2002-2007 Yegappan Lakshmanan
function! l:buffer_manager:detect_filetype(fname)
" Ignore the filetype autocommands
let old_eventignore = &eventignore
set eventignore=FileType
" Save the 'filetype', as this will be changed temporarily
let old_filetype = &filetype
" Run the filetypedetect group of autocommands to determine
" the filetype
exe 'doautocmd filetypedetect BufRead ' . a:fname
" Save the detected filetype
let ftype = &filetype
" Restore the previous state
let &filetype = old_filetype
let &eventignore = old_eventignore
return ftype
endfunction
return l:buffer_manager
endfunction
" 1}}}
" Indexer {{{1
" =============================================================================
" create and return the an Indexer pseudo-object, which is a Catalog factory
function! s:NewIndexer()
" create/clear
let l:indexer = {}
" set up filetype vocabulary
let l:indexer["filetype_term_map"] = {
\ 'bib' : '^@\w\+\s*{\s*\zs\S\{-}\ze\s*,'
\ , 'c' : '^[[:alnum:]#].*'
\ , 'cpp' : '^[[:alnum:]#].*'
\ , 'html' : '\(\|<\(html\|head\|body\|div\|script\|a\s\+name=\).\{-}>\|<.\{-}\\)'
\ , 'java' : '^\s*\(\(package\|import\|private\|public\|protected\|void\|int\|boolean\)\s\+\|\u\).*'
\ , 'javascript' : '^\(var\s\+.\{-}\|\s*\w\+\s*:\s*\S.\{-}[,{]\)\s*$'
\ , 'perl' : '^\([$%@]\|\s*\(use\|sub\)\>\).*'
\ , 'php' : '^\(\w\|\s*\(class\|function\|var\|require\w*\|include\w*\)\>\).*'
\ , 'python' : '^\s*\(import\|class\|def\)\s\+[A-Za-z_]\i\+(.*'
\ , 'ruby' : '\C^\(if\>\|\s*\(class\|module\|def\|require\|private\|public\|protected\|module_functon\|alias\|attr\(_reader\|_writer\|_accessor\)\?\)\>\|\s*[[:upper:]_]\+\s*=\).*'
\ , 'scheme' : '^\s*(define.*'
\ , 'sh' : '^\s*\(\(export\|function\|while\|case\|if\)\>\|\w\+\s*()\s*{\).*'
\ , 'tcl' : '^\s*\(source\|proc\)\>.*'
\ , 'tex' : '\C\\\(label\|\(sub\)*\(section\|paragraph\|part\)\)\>.*'
\ , 'vim' : '\C^\(fu\%[nction]\|com\%[mand]\|if\|wh\%[ile]\)\>.*'
\ }
if exists("g:buffersaurus_filetype_term_map")
" User-defined patterns have higher priority
call extend(l:indexer["filetype_term_map"], g:buffersaurus_filetype_term_map, 'force')
endif
" set up element vocabulary
let l:indexer["element_term_map"] = {
\ 'PyClass' : '^\s*class\s\+[A-Za-z_]\i\+(.*'
\ , 'PyDef' : '^\s*def\s\+[A-Za-z_]\i\+(.*'
\ , 'VimFunction' : '^\C[:[:space:]]*fu\%[nction]\>!\=\s*\S\+\s*('
\ , 'VimMapping' : '^\C[:[:space:]]*[nvxsoilc]\=\(\%(nore\|un\)\=map\>\|mapclear\)\>'
\ , 'VimCommand' : '^\C[:[:space:]]*com\%[mand]\>'
\ , 'CppClass' : '^\s*\(\(public\|private\|protected\)\s*:\)\=\s*\(class\|struct\)\s\+\w\+\>\(\s*;\)\@!'
\ , 'CppTypedef' : '^\s*\(\(public\|private\|protected\)\s*:\)\=\s*typedef\>'
\ , 'CppEnum' : '^\s*\(\(public\|private\|protected\)\s*:\)\=\s*enum\>'
\ , 'CppTemplate' : '^\s*template\($\|<\)'
\ , 'CppPreproc' : '^#'
\ }
if exists("g:buffersaurus_element_term_map")
" User-defined patterns have higher priority
call extend(l:indexer["element_term_map"], g:buffersaurus_element_term_map, 'force')
endif
" Indexes all files given by the list `filepaths` for the regular
" expression(s) defined in the element vocabulary for `term_id`. If
" `term_id` is empty, the default filetype pattern is used. If
" `filepaths` is empty, then all
" listed buffers are indexed.
function! l:indexer.index_terms(filepaths, term_id, sort_regime) dict
let l:old_hidden = &hidden
set hidden
let l:worklist = self.ensure_buffers(a:filepaths)
let l:desc = "Catalog of"
if !empty(a:term_id)
let l:desc .= "'" . a:term_id . "'"
endif
let l:desc .= " terms"
if empty(a:filepaths)
let l:desc .= " (in all buffers)"
elseif len(a:filepaths) == 1
let l:desc .= ' (in "' . expand(a:filepaths[0]) . '")'
else
let l:desc .= " (in multiple files)"
endif
let l:catalog = s:NewCatalog("term", l:desc, a:sort_regime)
for buf_ref in l:worklist
let l:pattern = self.get_buffer_term_pattern(buf_ref, a:term_id)
call l:catalog.map_buffer(buf_ref, l:pattern)
endfor
let &hidden=l:old_hidden
return l:catalog
endfunction
" Indexes all files given by the list `filepaths` for tags.
function! l:indexer.index_tags(filepaths) dict
let l:old_hidden = &hidden
set hidden
let l:worklist = self.ensure_buffers(a:filepaths)
let l:desc = "Catalog of tags"
if empty(a:filepaths)
let l:desc .= " (in all buffers)"
elseif len(a:filepaths) == 1
let l:desc .= ' (in "' . a:filepaths[0] . '")'
else
let l:desc .= " (in multiple files)"
endif
let l:catalog = s:NewTagCatalog("tag", l:desc)
for buf_ref in l:worklist
call l:catalog.map_buffer(buf_ref)
endfor
let &hidden=l:old_hidden
return l:catalog
endfunction
" Indexes all files given by the list `filepaths` for the regular
" expression given by `pattern`. If `filepaths` is empty, then all
" listed buffers are indexed.
function! l:indexer.index_pattern(filepaths, pattern, sort_regime) dict
let l:old_hidden = &hidden
set hidden
let l:worklist = self.ensure_buffers(a:filepaths)
let l:desc = "Catalog of pattern '" . a:pattern . "'"
if empty(a:filepaths)
let l:desc .= " (in all buffers)"
elseif len(a:filepaths) == 1
let l:desc .= ' (in "' . a:filepaths[0] . '")'
else
let l:desc .= " (in multiple files)"
endif
let l:catalog = s:NewCatalog("pattern", l:desc, a:sort_regime)
for buf_ref in l:worklist
call l:catalog.map_buffer(buf_ref, a:pattern)
endfor
let &hidden=l:old_hidden
return l:catalog
endfunction
" returns pattern to be used when indexing terms for a particular buffer
function! l:indexer.get_buffer_term_pattern(buf_num, term_id) dict
let l:pattern = ""
if !empty(a:term_id)
try
let l:term_id_matches = filter(keys(self.element_term_map),
\ "v:val =~ '" . a:term_id . ".*'")
catch /E15:/
throw s:_buffersaurus_messenger.format_exception("Invalid name: '" . a:term_id . "': ".v:exception)
endtry
if len(l:term_id_matches) > 1
throw s:_buffersaurus_messenger.format_exception("Multiple matches for index pattern name starting with '".a:term_id."': ".join(l:term_id_matches, ", "))
elseif len(l:term_id_matches) == 0
throw s:_buffersaurus_messenger.format_exception("Index pattern with name '" . a:term_id . "' not found")
end
let l:pattern = self.element_term_map[l:term_id_matches[0]]
else
let l:pattern = get(self.filetype_term_map, getbufvar(a:buf_num, "&filetype"), "")
if empty(l:pattern)
let l:pattern = '^\w.*'
endif
endif
return l:pattern
endfunction
" Given a list of buffer references, `buf_refs` this will ensure than
" all the files/buffers are loaded and return a list of the buffer names.
" If `buf_refs` is empty, then all listed buffers are loaded.
function! l:indexer.ensure_buffers(buf_refs)
let l:cur_pos = getpos(".")
let l:cur_buf_num = bufnr("%")
if empty(a:buf_refs)
let l:req_buf_list = s:_buffersaurus_buffer_manager.get_buf_nums(0)
else
let l:req_buf_list = []
for l:buf_ref in a:buf_refs
if type(l:buf_ref) == type(0)
let l:buf_num = l:buf_ref
else
let l:buf_num = bufnr(l:buf_ref)
endif
call add(l:req_buf_list, l:buf_num)
endfor
endif
let l:work_list = []
for l:buf_num in l:req_buf_list
if !bufexists(l:buf_num)
throw s:_buffersaurus_messenger.format_exception('Buffer does not exist: "' . l:buf_num . '"')
elseif !buflisted(l:buf_num)
call s:_buffersaurus_messenger.send_warning('Skipping unlisted buffer: [' . l:buf_num . '] "' . bufname(l:buf_num) . '"')
elseif !empty(getbufvar(l:buf_num, "is_buffersaurus_buffer"))
call s:_buffersaurus_messenger.send_warning('Skipping buffersaurus buffer: [' . l:buf_num . '] "' . bufname(l:buf_num) . '"')
else
call add(l:work_list, l:buf_num)
if !bufloaded(l:buf_num)
execute("silent keepjumps keepalt buffer " . l:buf_num)
endif
endif
endfor
" execute("silent keepjumps keepalt e ".l:cur_buf_name)
execute("silent keepjumps keepalt buffer ".l:cur_buf_num)
call setpos(".", l:cur_pos)
return l:work_list
endfunction
return l:indexer
endfunction
" 1}}}
" Catalog {{{1
" ==============================================================================
" The main workhorse pseudo-object is created here ...
function! s:NewCatalog(catalog_domain, catalog_desc, default_sort)
" increment catalog counter, creating it if it does not already exist
if !exists("s:buffersaurus_catalog_count")
let s:buffersaurus_catalog_count = 1
else
let s:buffersaurus_catalog_count += 1
endif
" initialize fields
let l:var_name = a:catalog_domain
let l:catalog = {
\ "catalog_id" : s:buffersaurus_catalog_count,
\ "catalog_domain" : a:catalog_domain,
\ "catalog_desc" : a:catalog_desc,
\ "show_context" : exists("g:buffersaurus_" . l:var_name . "_show_context") ? g:buffersaurus_{l:var_name}_show_context : g:buffersaurus_show_context,
\ "context_size" : exists("g:buffersaurus_" . l:var_name . "_context_size") ? g:buffersaurus_{l:var_name}_context_size : g:buffersaurus_context_size,
\ "search_profile" : [],
\ "matched_lines" : [],
\ "search_history" : [],
\ "searched_files" : {},
\ "last_search_time" : 0,
\ "last_search_hits" : 0,
\ "entry_indexes" : [],
\ "entry_labels" : {},
\ "last_compile_time" : 0,
\ "sort_regime" : empty(a:default_sort) ? g:buffersaurus_sort_regime : a:default_sort,
\}
" sets the display context
function! l:catalog.set_context_size(...) dict
let l:context = self.context_size
for l:carg in range(a:0)
if a:000[l:carg] == ""
return
endif
if a:000[l:carg] =~ '\d\+'
let l:context[0] = str2nr(a:000[l:carg])
let l:context[1] = str2nr(a:000[l:carg])
elseif a:000[l:carg] =~ '-\d\+'
let l:context[0] = str2nr(a:000[l:carg][1:])
elseif a:000[l:carg] =! '+\d\+'
let l:context[1] = str2nr(a:000[l:carg][1:])
else
call s:_buffersaurus_messenger.send_error("Invalid argument ".l:carg.": ".a:000[l:carg])
return
endif
endfor
let self.context_size = l:context
return self.context_size
endfunction
" determine whether or not context should be shown
function! l:catalog.is_show_context() dict
if !self.show_context
return 0
else
if self.context_size[0] == 0 && self.context_size[1] == 0
return 0
else
return 1
endif
endif
endfunction
" clears all items
function! l:catalog.clear() dict
let self.matched_lines = []
let self.search_history = []
let self.searched_files = {}
let self.last_search_time = 0
let self.last_search_hits = 0
let self.entry_indexes = []
let self.entry_labels = {}
let self.last_compile_time = 0
endfunction
" number of entries in the catalog
function! l:catalog.size() dict
return len(self.matched_lines)
endfunction
" carry out search given in the search profile
function l:catalog.build(...) dict
call self.clear()
if a:0 >= 1
let self.search_profile = a:1
endif
for l:search in self.search_profile
call self.map_buffer(l:search.filepath, l:search.pattern)
endfor
endfunction
" repeat last search
function l:catalog.rebuild() dict
if empty(self.search_history)
raise s:_buffersaurus_messenger.format_exception("Search history is empty")
endif
let self.search_profile = []
for search in self.search_history
call add(self.search_profile, search)
endfor
call self.clear()
call self.build()
call self.compile_entry_indexes()
endfunction
" index all occurrences of `pattern` in buffer `buf_ref`
function! l:catalog.map_buffer(buf_ref, pattern) dict
if type(a:buf_ref) == type(0)
let l:buf_num = a:buf_ref
let l:buf_name = bufname(l:buf_num)
else
let l:buf_name = expand(a:buf_ref)
let l:buf_num = bufnr(l:buf_name) + 0
endif
let l:filepath = fnamemodify(expand(l:buf_name), ":p")
let l:buf_search_log = {
\ "buf_name" : l:buf_name,
\ 'buf_num': l:buf_num,
\ "filepath" : l:filepath,
\ "pattern" : a:pattern,
\ "num_lines_searched" : 0,
\ "num_lines_matched" : 0,
\ "last_searched" : 0,
\ }
let self.last_search_hits = 0
let l:lnum = 1
while 1
let l:buf_lines = getbufline(l:buf_num, l:lnum)
if empty(l:buf_lines)
break
endif
let l:pos = match(l:buf_lines[0], a:pattern)
let l:buf_search_log["num_lines_searched"] += 1
if l:pos >= 0
let self.last_search_hits += 1
let l:search_order = len(self.matched_lines) + 1
call add(self.matched_lines, {
\ 'buf_name': l:buf_name,
\ 'buf_num': l:buf_num,
\ 'filepath' : l:filepath,
\ 'lnum': l:lnum,
\ 'col': l:pos + 1,
\ 'sort_text' : substitute(l:buf_lines[0], '^\s*', '', 'g'),
\ 'search_order' : l:search_order,
\ 'entry_label' : string(l:search_order),
\ })
let l:buf_search_log["num_lines_matched"] += 1
endif
let l:lnum += 1
endwhile
let l:buf_search_log["last_searched"] = localtime()
let self.last_search_time = l:buf_search_log["last_searched"]
call add(self.search_history, l:buf_search_log)
if has_key(self.searched_files, l:filepath)
let self.searched_files[l:filepath] += self.last_search_hits
else
let self.searched_files[l:filepath] = self.last_search_hits
endif
endfunction
" open the catalog for viewing
function! l:catalog.open() dict
if !has_key(self, "catalog_viewer") || empty(self.catalog_viewer)
let self["catalog_viewer"] = s:NewCatalogViewer(self, self.catalog_desc)
endif
call self.catalog_viewer.open()
return self.catalog_viewer
endfunction
" returns indexes of matched lines, compiling them if
" needed
function! l:catalog.get_index_groups() dict
if self.last_compile_time < self.last_search_time
call self.compile_entry_indexes()
endif
return self.entry_indexes
endfunction
" returns true if sort regime dictates that indexes are grouped
function! l:catalog.is_sort_grouped() dict
if self.sort_regime == 'a'
return 0
else
return 1
endif
endfunction
" apply a sort regime
function! l:catalog.apply_sort(regime) dict
if index(s:buffersaurus_catalog_sort_regimes, a:regime) == - 1
throw s:_buffersaurus_messenger.format_exception("Unrecognized sort regime: '" . a:regime . "'")
endif
let self.sort_regime = a:regime
return self.compile_entry_indexes()
endfunction
" cycle through sort regimes
function! l:catalog.cycle_sort_regime() dict
let l:cur_regime = index(s:buffersaurus_catalog_sort_regimes, self.sort_regime)
let l:cur_regime += 1
if l:cur_regime < 0 || l:cur_regime >= len(s:buffersaurus_catalog_sort_regimes)
let self.sort_regime = s:buffersaurus_catalog_sort_regimes[0]
else
let self.sort_regime = s:buffersaurus_catalog_sort_regimes[l:cur_regime]
endif
return self.compile_entry_indexes()
endfunction
" compiles matches into index
function! l:catalog.compile_entry_indexes() dict
let self.entry_indexes = []
let self.entry_labels = {}
if self.sort_regime == 'fl'
call sort(self.matched_lines, "s:compare_matched_lines_fl")
elseif self.sort_regime == 'fa'
call sort(self.matched_lines, "s:compare_matched_lines_fa")
elseif self.sort_regime == 'a'
call sort(self.matched_lines, "s:compare_matched_lines_a")
elseif self.sort_regime == 'pl'
call sort(self.matched_lines, "s:compare_matched_lines_pl")
else
throw s:_buffersaurus_messenger.format_exception("Unrecognized sort regime: '" . self.sort_regime . "'")
endif
if self.sort_regime == 'a'
call add(self.entry_indexes, ['', []])
for l:matched_line_idx in range(0, len(self.matched_lines) - 1)
call add(self.entry_indexes[-1][1], l:matched_line_idx)
let self.entry_labels[l:matched_line_idx] = self.matched_lines[l:matched_line_idx].entry_label
endfor
else
let l:cur_group = ""
for l:matched_line_idx in range(0, len(self.matched_lines) - 1)
if self.matched_lines[l:matched_line_idx].filepath != l:cur_group
let l:cur_group = self.matched_lines[l:matched_line_idx].filepath
call add(self.entry_indexes, [l:cur_group, []])
endif
call add(self.entry_indexes[-1][1], l:matched_line_idx)
let self.entry_labels[l:matched_line_idx] = self.matched_lines[l:matched_line_idx].entry_label
endfor
endif
let self.last_compile_time = localtime()
return self.entry_indexes
endfunction
" Describes catalog status.
function! l:catalog.describe() dict
call s:_buffersaurus_messenger.send_info(self.format_status_message() . " (sorted " . self.format_sort_status() . ")")
endfunction
" Describes catalog status in detail.
function! l:catalog.describe_detail() dict
echon self.format_status_message() . ":\n"
let l:rows = []
let l:header = self.format_describe_detail_row([
\ "#",
\ "File",
\ "Found",
\ "Total",
\ "Pattern",
\])
echohl Title
echo l:header "\n"
echohl None
for search_log in self.search_history
let l:row = self.format_describe_detail_row([
\ bufnr(search_log.filepath),
\ bufname(search_log.filepath),
\ string(search_log.num_lines_matched),
\ string(search_log.num_lines_searched),
\ search_log.pattern,
\])
call add(l:rows, row)
endfor
echon join(l:rows, "\n")
endfunction
" Formats a single row in the detail catalog description
function! l:catalog.format_describe_detail_row(fields)
let l:row = join([
\ s:Format_Fill(a:fields[0], 3, 2, 1),
\ s:Format_Fill(a:fields[1], ((&columns - 14) / 3), -1, -1),
\ s:Format_Fill(a:fields[2], 6, 1, 0),
\ s:Format_Fill(a:fields[3], 6, 1, 0),
\ a:fields[4],
\ ], " ")
return l:row
endfunction
" Composes message indicating size of catalog.
function! l:catalog.format_status_message() dict
let l:message = ""
let l:catalog_size = self.size()
let l:num_searched_files = len(self.searched_files)
if l:catalog_size == 0
let l:message .= "no entries"
elseif l:catalog_size == 1
let l:message .= "1 entry"
else
let l:message .= l:catalog_size . " entries"
endif
let l:message .= " in "
if l:num_searched_files == 0
let l:message .= "no files"
elseif l:num_searched_files == 1
let l:message .= "1 file"
else
let l:message .= l:num_searched_files . " files"
endif
return l:message
endfunction
" Composes message indicating sort regime of catalog.
function! l:catalog.format_sort_status() dict
let l:message = get(s:buffersaurus_catalog_sort_regime_desc, self.sort_regime, ["??", "in unspecified order"])[1]
return l:message
endfunction
" return pseudo-object
return l:catalog
endfunction
" comparison function used for sorting matched lines: sort first by
" filepath, then by line number
function! s:compare_matched_lines_fl(m1, m2)
if a:m1.filepath < a:m2.filepath
return -1
elseif a:m1.filepath > a:m2.filepath
return 1
else
if a:m1.lnum < a:m2.lnum
return -1
elseif a:m1.lnum > a:m2.lnum
return 1
else
return 0
endif
endif
endfunction
" comparison function used for sorting matched lines: sort first by
" priority, then by line number
function! s:compare_matched_lines_pl(m1, m2)
let l:pri = s:compare_matched_lines_p(a:m1, a:m2)
"echo l:pri
"
if l:pri != 0
return l:pri
else
if a:m1.lnum < a:m2.lnum
return -1
elseif a:m1.lnum > a:m2.lnum
return 1
else
return 0
endif
endif
endfunction
" comparison function used for sorting matched lines: sort first by
" filepath, then by text
function! s:compare_matched_lines_fa(m1, m2)
if a:m1.filepath < a:m2.filepath
return -1
elseif a:m1.filepath > a:m2.filepath
return 1
else
return s:compare_matched_lines_a(a:m1, a:m2)
endif
endfunction
" comparison function used for sorting matched lines: sort by
" text
function! s:compare_matched_lines_a(m1, m2)
if a:m1.sort_text < a:m2.sort_text
return -1
elseif a:m1.sort_text > a:m2.sort_text
return 1
else
return 0
endif