/
nrrwrgn.vim
executable file
·1202 lines (1137 loc) · 34.1 KB
/
nrrwrgn.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
" nrrwrgn.vim - Narrow Region plugin for Vim
" -------------------------------------------------------------
" Version: 0.31
" Maintainer: Christian Brabandt <cb@256bit.org>
" Last Change: Sat, 16 Feb 2013 22:28:31 +0100
"
" Script: http://www.vim.org/scripts/script.php?script_id=3075
" Copyright: (c) 2009, 2010, 2011, 2012, 2013 by Christian Brabandt
" The VIM LICENSE applies to NrrwRgn.vim
" (see |copyright|) except use "NrrwRgn.vim"
" instead of "Vim".
" No warranty, express or implied.
" *** *** Use At-Your-Own-Risk! *** ***
" GetLatestVimScripts: 3075 31 :AutoInstall: NrrwRgn.vim
"
" Functions:
fun! <sid>WarningMsg(msg) "{{{1
let msg = "NarrowRegion: ". a:msg
echohl WarningMsg
if exists(":unsilent") == 2
unsilent echomsg msg
else
echomsg msg
endif
sleep 1
echohl Normal
let v:errmsg = msg
endfun
fun! <sid>Init() "{{{1
if !exists("s:opts")
" init once
let s:opts = []
endif
if !exists("s:instn")
let s:instn=1
if !exists("g:nrrw_custom_options") || empty(g:nrrw_custom_options)
let s:opts=<sid>Options('local to buffer')
endif
else
" Prevent accidently overwriting windows with instn_id set
" back to an already existing instn_id
let s:instn = (s:instn==0 ? 1 : s:instn)
while (has_key(s:nrrw_rgn_lines, s:instn))
let s:instn+=1
endw
endif
let s:nrrw_aucmd = {}
if exists("b:nrrw_aucmd_create")
let s:nrrw_aucmd["create"] = b:nrrw_aucmd_create
endif
if exists("b:nrrw_aucmd_close")
let s:nrrw_aucmd["close"] = b:nrrw_aucmd_close
endif
if !exists("s:nrrw_rgn_lines")
let s:nrrw_rgn_lines = {}
endif
let s:nrrw_rgn_lines[s:instn] = {}
" show some debugging messages
let s:nrrw_winname='Narrow_Region'
" Customization
let s:nrrw_rgn_vert = (exists("g:nrrw_rgn_vert") ? g:nrrw_rgn_vert : 0)
let s:nrrw_rgn_wdth = (exists("g:nrrw_rgn_wdth") ? g:nrrw_rgn_wdth : 20)
let s:nrrw_rgn_hl = (exists("g:nrrw_rgn_hl") ? g:nrrw_rgn_hl :
\ "WildMenu")
let s:nrrw_rgn_nohl = (exists("g:nrrw_rgn_nohl") ? g:nrrw_rgn_nohl : 0)
let s:debug = (exists("s:debug") ? s:debug : 0)
endfun
fun! <sid>NrrwRgnWin(bang) "{{{1
let local_options = <sid>GetOptions(s:opts)
let nrrw_winname = s:nrrw_winname. '_'. s:instn
let nrrw_win = bufwinnr('^'.nrrw_winname.'$')
if nrrw_win != -1
exe ":noa ". nrrw_win. 'wincmd w'
" just in case, a global nomodifiable was set
" disable this for the narrowed window
setl ma
silent %d _
else
if !exists('g:nrrw_topbot_leftright')
let g:nrrw_topbot_leftright = 'topleft'
endif
if !a:bang
exe g:nrrw_topbot_leftright s:nrrw_rgn_wdth.
\(s:nrrw_rgn_vert?'v':''). "sp ". nrrw_winname
else
try
" if hidden is set, set the original buffer to be modified, so
" that :q won't accidently quit vim
if &hid
setl modified
endif
enew
if bufexists(s:nrrw_winname. '_'. s:instn)
" avoid E95
exe 'bw' s:nrrw_winname. '_'. s:instn
endif
exe 'f' s:nrrw_winname. '_'. s:instn
catch /^Vim\%((\a\+)\)\=:E37/ " catch error E37
" Fall back and use a new window
exe g:nrrw_topbot_leftright s:nrrw_rgn_wdth.
\(s:nrrw_rgn_vert?'v':''). "sp ". nrrw_winname
endtry
endif
" just in case, a global nomodifiable was set
" disable this for the narrowed window
setl ma
" Just in case
silent %d _
" Set up some options like 'bufhidden', 'noswapfile',
" 'buftype', 'bufhidden', when enabling Narrowing.
call <sid>NrrwSettings(1)
let nrrw_win = bufwinnr("")
endif
call <sid>SetOptions(local_options)
" We are in the narrowed buffer now!
return nrrw_win
endfun
fun! <sid>CleanRegions() "{{{1
let s:nrrw_rgn_line=[]
unlet! s:nrrw_rgn_last
unlet! s:nrrw_rgn_buf
endfun
fun! <sid>CompareNumbers(a1,a2) "{{{1
return (a:a1+0) == (a:a2+0) ? 0
\ : (a:a1+0) > (a:a2+0) ? 1
\ : -1
endfun
fun! <sid>ParseList(list) "{{{1
" for a given list of line numbers, return those line numbers
" in a format start:end for continous items, else [start, next]
let result={}
let start=0
let temp=0
let i=1
for item in sort(a:list, "<sid>CompareNumbers")
if start==0
let start=item
elseif temp!=item-1
let result[i]=[start,temp]
let start=item
let i+=1
endif
let temp=item
endfor
if empty(result)
" add all items from the list to the result
" list consists only of consecutive items
let result[i] = [a:list[0], a:list[-1]]
endif
" Make sure the last item is included in the selection
if get(result, (i-1), 0)[0] && result[i-1][1] != item
let result[i]=[start,item]
endif
return result
endfun
fun! <sid>WriteNrrwRgn(...) "{{{1
" if argument is given, write narrowed buffer back
" else destroy the narrowed window
let nrrw_instn = exists("b:nrrw_instn") ? b:nrrw_instn : s:instn
if exists("b:orig_buf") && (bufwinnr(b:orig_buf) == -1) &&
\ !<sid>BufInTab(b:orig_buf) &&
\ !bufexists(b:orig_buf)
call s:WarningMsg("Original buffer does no longer exist! Aborting!")
return
endif
if &l:mod && exists("a:1") && a:1
" Write the buffer back to the original buffer
setl nomod
exe ":WidenRegion"
if bufname('') !~# 'Narrow_Region' && bufwinnr(s:nrrw_winname. '_'. s:instn) > 0
exe ':noa'. bufwinnr(s:nrrw_winname. '_'. s:instn). 'wincmd w'
endif
else
call <sid>StoreLastNrrwRgn(nrrw_instn)
let winnr = bufwinnr(b:orig_buf)
" Best guess
if bufname('') =~# 'Narrow_Region' && winnr > 0
exe ':noa'. winnr. 'wincmd w'
endif
if !exists("a:1")
" close narrowed buffer
call <sid>NrrwRgnAuCmd(nrrw_instn)
endif
endif
endfun
fun! <sid>SaveRestoreRegister(values) "{{{1
if empty(a:values)
" Save
let reg = ['a', getreg('a'), getregtype('a') ]
let fold = [ &fen, &l:fdm ]
if &fen
setl nofoldenable
endif
let visual = [getpos("'<"), getpos("'>")]
return [ reg, fold, visual ]
else
" Restore
if empty(a:values)
call <sid>WarningMsg("Error setting options back!")
return
endif
call call('setreg', a:values[0])
if a:values[1][0]
setl foldenable
let &l:fdm=a:values[1][1]
endif
if v:version > 703 || (v:version == 703 && has("patch590"))
" settable '< and '> marks
call setpos("'<", a:values[2][0])
call setpos("'>", a:values[2][1])
endif
endif
endfun!
fun! <sid>NrrwRgnAuCmd(instn) "{{{1
" If a:instn==0, then enable auto commands
" else disable auto commands for a:instn
if !a:instn
exe "aug NrrwRgn". b:nrrw_instn
au!
au BufWriteCmd <buffer> nested :call s:WriteNrrwRgn(1)
au BufWinLeave,BufWipeout,BufDelete <buffer> nested
\ :call s:WriteNrrwRgn()
aug end
else
exe "aug NrrwRgn". a:instn
au!
aug end
exe "aug! NrrwRgn". a:instn
if !has_key(s:nrrw_rgn_lines, a:instn)
" narrowed buffer was already cleaned up
call <sid>DeleteMatches(a:instn)
call s:WarningMsg("Window was already cleaned up. Nothing to do.")
return
endif
" make the original buffer modifiable, if possible
let buf = s:nrrw_rgn_lines[a:instn].orig_buf
if !getbufvar(buf, '&l:ma') && !getbufvar(buf, 'orig_buf_ro')
call setbufvar(s:nrrw_rgn_lines[a:instn].orig_buf, '&ma', 1)
endif
if s:debug
echo printf("bufnr: %d a:instn: %d\n", bufnr(''), a:instn)
echo "bwipe " s:nrrw_winname. '_'. a:instn
endif
if (has_key(s:nrrw_rgn_lines[a:instn], 'disable') &&
\ !s:nrrw_rgn_lines[a:instn].disable ) ||
\ !has_key(s:nrrw_rgn_lines[a:instn], 'disable')
call <sid>DeleteMatches(a:instn)
" bwipe! throws E855 (catching does not work)
" but because of 'bufhidden' wipeing will happen anyways
"exe "bwipe! " bufnr(s:nrrw_winname. '_'. a:instn)
" if has_key(s:nrrw_rgn_lines[a:instn], 'single') &&
" \ s:nrrw_rgn_lines[a:instn].single
" If there is only a single window open don't clean up now
" because we can't put the narrowed lines back, so do not
" clean up now. We need to clean up then later. But how?
" return
" endif
call <sid>CleanUpInstn(a:instn)
endif
endif
endfun
fun! <sid>CleanUpInstn(instn) "{{{1
if s:instn>=1 && has_key(s:nrrw_rgn_lines, a:instn)
unlet s:nrrw_rgn_lines[a:instn]
let s:instn-=1
endif
endfu
fun! <sid>StoreLastNrrwRgn(instn) "{{{1
" Only store the last region, when the narrowed instance is still valid
if !has_key(s:nrrw_rgn_lines, a:instn)
call <sid>WarningMsg("Error storing the last Narrowed Window,".
\ "it's invalid!")
return
endif
let s:nrrw_rgn_lines['last'] = []
if !exists("b:orig_buf")
let orig_buf = s:nrrw_rgn_lines[a:instn].orig_buf
else
let orig_buf = b:orig_buf
endif
if has_key(s:nrrw_rgn_lines[a:instn], 'multi')
call add(s:nrrw_rgn_lines['last'], [ orig_buf,
\ s:nrrw_rgn_lines[a:instn]['multi']])
else
" Linewise narrowed region, pretend it was done like a visual
" narrowed region
let s:nrrw_rgn_lines['last'] = [ [ orig_buf,
\ s:nrrw_rgn_lines[a:instn].start[1:]],
\ [ orig_buf, s:nrrw_rgn_lines[a:instn].end[1:]]]
call add(s:nrrw_rgn_lines['last'],
\ has_key(s:nrrw_rgn_lines[a:instn], 'vmode') ?
\ s:nrrw_rgn_lines[a:instn].vmode : 'V')
endif
endfu
fun! <sid>RetVisRegionPos() "{{{1
if v:version > 703 || (v:version == 703 && has("patch590"))
return [ getpos("'<"), getpos("'>") ]
else
return [ getpos("'<")[0:1] + [virtcol("'<"), 0],
\ getpos("'>")[0:1] + [virtcol("'>"), 0] ]
endif
endfun
fun! <sid>GeneratePattern(startl, endl, mode, ...) "{{{1
if exists("a:1") && a:1
let block = 0
else
let block = 1
endif
" This is just a best guess, the highlighted block could still be wrong
" (a " rectangle has been selected, but the complete lines are
" highlighted
if a:mode ==# '' && a:startl[0] > 0 && a:startl[1] > 0 && block
return '\%>'. (a:startl[0]-1). 'l\&\%>'. (a:startl[1]-1).
\ 'v\&\%<'. (a:endl[0]+1). 'l'
elseif a:mode ==# '' && a:startl[0] > 0 && a:startl[1] > 0
return '\%>'. (a:startl[0]-1). 'l\&\%>'. (a:startl[1]-1).
\ 'v\&\%<'. (a:endl[0]+1). 'l\&\%<'. (a:endl[1]+1). 'v'
elseif a:mode ==# 'v' && a:startl[0] > 0 && a:startl[1] > 0
return '\%>'. (a:startl[0]-1). 'l\&\%>'. (a:startl[1]-1).
\ 'v\_.*\%<'. (a:endl[0]+1). 'l\&\%<'. (a:endl[1]+1). 'v'
elseif a:startl[0] > 0
return '\%>'. (a:startl[0]-1). 'l\&\%<'. (a:endl[0]+1). 'l'
else
return ''
endif
endfun
fun! <sid>Options(search) "{{{1
let c=[]
let buf=bufnr('')
try
" empty search pattern
if empty(a:search)
return c
endif
silent noa sview $VIMRUNTIME/doc/options.txt
" for whatever reasons $VIMRUNTIME/doc/options.txt
" does not exist, return empty list
if line('$') == 1
return c
endif
keepj 0
let reg_a=[]
call add(reg_a, 'a')
call add(reg_a,getreg('a'))
call add(reg_a, getregtype('a'))
let @a=''
exe "silent :g/". '\v'.escape(a:search, '\\/'). "/-y A"
let b=split(@a, "\n")
call call('setreg', reg_a)
"call setreg('a', reg_a[0], reg_a[1])
call filter(b, 'v:val =~ "^''"')
" the following options should be set
let filter_opt='\%(modifi\%(ed\|able\)\|readonly\|swapfile\|'.
\ 'buftype\|bufhidden\|foldcolumn\|buflisted\)'
call filter(b, 'v:val !~ "^''".filter_opt."''"')
for item in b
let item=substitute(item, '''', '', 'g')
call add(c, split(item, '\s\+')[0])
endfor
finally
if fnamemodify(bufname(''),':p') ==
\expand("$VIMRUNTIME/doc/options.txt")
noa bwipe
endif
exe "noa " bufwinnr(buf) "wincmd w"
return c
endtry
endfun
fun! <sid>GetOptions(opt) "{{{1
if exists("g:nrrw_custom_options") && !empty(g:nrrw_custom_options)
let result = g:nrrw_custom_options
else
let result={}
for item in a:opt
try
exe "let result[item]=&l:".item
catch
endtry
endfor
endif
return result
endfun
fun! <sid>SetOptions(opt) "{{{1
if type(a:opt) == type({})
for [option, result] in items(a:opt)
exe "let &l:". option " = " string(result)
endfor
endif
setl nomod noro
endfun
fun! <sid>CheckProtected() "{{{1
" Protect the original window, unless the user explicitly defines not to
" protect it
if exists("g:nrrw_rgn_protect") && g:nrrw_rgn_protect =~? 'n'
return
endif
let b:orig_buf_ro=0
if !&l:ma || &l:ro
let b:orig_buf_ro=1
call s:WarningMsg("Buffer is protected, won't be able to write".
\ "the changes back!")
else
" Protect the original buffer,
" so you won't accidentally modify those lines,
" that might later be overwritten
setl noma
endif
endfun
fun! <sid>DeleteMatches(instn) "{{{1
" Make sure, we are in the correct buffer
" Not needed, prevents recursively narrowing
" if bufname('') =~# 'Narrow_Region'
" exe ':noa'. bufwinnr(b:orig_buf). 'wincmd w'
" endif
if exists("s:nrrw_rgn_lines[a:instn].matchid")
" if you call :NarrowRegion several times, without widening
" the previous region, b:matchid might already be defined so
" make sure, the previous highlighting is removed.
for item in s:nrrw_rgn_lines[a:instn].matchid
if item > 0
" If the match has been deleted, discard the error
exe (s:debug ? "" : "silent!") "call matchdelete(item)"
endif
endfor
let s:nrrw_rgn_lines[a:instn].matchid=[]
endif
endfun
fun! <sid>HideNrrwRgnLines() "{{{1
let cnc = has("Conceal")
let cmd='syn match NrrwRgnStart "^# Start NrrwRgn\d\+$" '.
\ (cnc ? 'conceal' : '')
exe cmd
let cmd='syn match NrrwRgnEnd "^# End NrrwRgn\d\+$" '.
\ (cnc ? 'conceal' : '')
exe cmd
syn region NrrwRgn start="^# Start NrrwRgn\z(\d\+\).*$"
\ end="^# End NrrwRgn\z1$" fold transparent
if cnc
setl conceallevel=3
endif
setl fdm=syntax
endfun
fun! <sid>ReturnCommentFT() "{{{1
" Vim
if &l:ft=="vim"
return '"'
" Perl, PHP, Ruby, Python, Sh
elseif &l:ft=~'^\(perl\|php\|ruby\|python\|sh\)$'
return '#'
" C, C++
elseif &l:ft=~'^\(c\%(pp\)\?\|java\)'
return '/* */'
" HTML, XML
elseif &l:ft=~'^\(ht\|x\)ml\?$'
return '<!-- -->'
" LaTex
elseif &l:ft=~'^\(la\)tex'
return '%'
else
" Fallback
return '#'
endif
endfun
fun! <sid>CheckRectangularRegion(reg) "{{{1
" Check whether the region that was pasted into
" register a:reg has always the same length
" This is needed, to be able to select the correct region
" when writing back the changes.
let result={}
let list=split(a:reg, "\n")
call map(list, 'substitute(v:val, ".", "x", "g")')
let llen = len(list)/2
call map(list, 'len(v:val)')
for item in list
if has_key(result, item)
let result[item] += 1
else
let result[item] = 1
endif
endfor
for [key, value] in items(result)
if value > llen
return 1
endif
endfor
return 0
endfu
fun! <sid>WidenRegionMulti(content, instn) "{{{1
" for single narrowed windows, the original narrowed buffer will be closed,
" so don't renew the highlighting and clean up (later in
" nrrwrgn#WidenRegion)
if empty(s:nrrw_rgn_lines[a:instn].multi)
return
endif
let output= []
let list = []
let [c_s, c_e] = <sid>ReturnComments()
let lastline = line('$')
" We must put the regions back from top to bottom,
" otherwise, changing lines in between messes up the list of lines that
" still need to put back from the narrowed buffer to the original buffer
for key in sort(keys(s:nrrw_rgn_lines[a:instn].multi),
\ "<sid>CompareNumbers")
let adjust = line('$') - lastline
let range = s:nrrw_rgn_lines[a:instn].multi[key]
let last = (len(range)==2) ? range[1] : range[0]
let first = range[0]
let indexs = index(a:content, c_s.' Start NrrwRgn'.key.c_e) + 1
let indexe = index(a:content, c_s.' End NrrwRgn'.key.c_e) - 1
if indexs <= 0 || indexe < -1
call s:WarningMsg("Skipping Region ". key)
continue
endif
" Adjust line numbers. Changing the original buffer, might also
" change the regions we have remembered. So we must adjust these
" numbers.
" This only works, if we put the regions from top to bottom!
let first += adjust
let last += adjust
if last == line('$') && first == 1
let delete_last_line=1
else
let delete_last_line=0
endif
exe ':silent :'. first. ','. last. 'd _'
call append((first-1), a:content[indexs : indexe])
" Recalculate the start and end positions of the narrowed window
" so subsequent calls will adjust the region accordingly
let last = first + len(a:content[indexs : indexe]) - 1
if last > line('$')
let last = line('$')
endif
if !has_key(s:nrrw_rgn_lines[a:instn].multi, 'single')
" original narrowed buffer is going to be closed
" so don't renew the matches
call <sid>AddMatches(<sid>GeneratePattern([first, 0 ],
\ [last, 0], 'V'), a:instn)
endif
if delete_last_line
silent! $d _
endif
endfor
endfun
fun! <sid>AddMatches(pattern, instn) "{{{1
if !s:nrrw_rgn_nohl || empty(a:pattern)
if !exists("s:nrrw_rgn_lines[a:instn].matchid")
let s:nrrw_rgn_lines[a:instn].matchid=[]
endif
call add(s:nrrw_rgn_lines[a:instn].matchid,
\matchadd(s:nrrw_rgn_hl, a:pattern))
endif
endfun
fun! <sid>BufInTab(bufnr) "{{{1
" returns tabpage of buffer a:bufnr
for tab in range(1,tabpagenr('$'))
if !empty(filter(tabpagebuflist(tab), 'v:val == a:bufnr'))
return tab
endif
endfor
return 0
endfun
fun! <sid>JumpToBufinTab(tab,buf) "{{{1
if a:tab
exe "noa tabn" a:tab
endif
let win = bufwinnr(a:buf)
if win > 0
exe ':noa '. bufwinnr(a:buf). 'wincmd w'
endif
endfun
fun! <sid>RecalculateLineNumbers(instn, adjust) "{{{1
" This only matters, if the original window isn't protected
if !exists("g:nrrw_rgn_protect") || g:nrrw_rgn_protect !~# 'n'
return
endif
for instn in filter(keys(s:nrrw_rgn_lines), 'v:val != a:instn')
" Skip narrowed instances, when they are before
" the region, we are currently putting back
if s:nrrw_rgn_lines[instn].start[1] <=
\ s:nrrw_rgn_lines[a:instn].start[1]
" Skip this instn
continue
else
let s:nrrw_rgn_lines[instn].start[1] += a:adjust
let s:nrrw_rgn_lines[instn].end[1] += a:adjust
if s:nrrw_rgn_lines[instn].start[1] < 1
let s:nrrw_rgn_lines[instn].start[1] = 1
endif
if s:nrrw_rgn_lines[instn].end[1] < 1
let s:nrrw_rgn_lines[instn].end[1] = 1
endif
call <sid>DeleteMatches(instn)
call <sid>AddMatches(<sid>GeneratePattern(
\s:nrrw_rgn_lines[instn].start[1:2],
\s:nrrw_rgn_lines[instn].end[1:2],
\'V'), instn)
endif
endfor
endfun
fun! <sid>NrrwSettings(on) "{{{1
if a:on
setl noswapfile buftype=acwrite foldcolumn=0
setl nobuflisted
let instn = matchstr(bufname(''), '_\zs\d\+')+0
if !&hidden && !has_key(s:nrrw_rgn_lines[instn], "single")
setl bufhidden=wipe
else
setl bufhidden=hide
endif
else
setl swapfile buftype= bufhidden= buflisted
endif
endfun
fun! <sid>SetupBufLocalCommands() "{{{1
com! -buffer -bang WidenRegion :call nrrwrgn#WidenRegion(<bang>0)
com! -buffer NRSyncOnWrite :call nrrwrgn#ToggleSyncWrite(1)
com! -buffer NRNoSyncOnWrite :call nrrwrgn#ToggleSyncWrite(0)
endfun
fun! <sid>ReturnComments() "{{{1
let cmt = <sid>ReturnCommentFT()
let c_s = split(cmt)[0]
let c_e = (len(split(cmt)) == 1 ? "" : " ". split(cmt)[1])
return [c_s, c_e]
endfun
fun! nrrwrgn#NrrwRgnDoPrepare(...) "{{{1
let bang = (a:0 > 0 && !empty(a:1))
if !exists("s:nrrw_rgn_line")
call <sid>WarningMsg("You need to first select the lines to".
\ " narrow using :NRP!")
return
endif
if empty(s:nrrw_rgn_line) && !exists("s:nrrw_rgn_buf")
call <sid>WarningMsg("No lines selected from :NRP, aborting!")
return
endif
if !exists("s:nrrw_rgn_buf")
let s:nrrw_rgn_buf = <sid>ParseList(s:nrrw_rgn_line)
endif
if empty(s:nrrw_rgn_buf)
call <sid>WarningMsg("An error occured when selecting all lines. Please report as bug")
unlet s:nrrw_rgn_buf
return
endif
let o_lz = &lz
let s:o_s = @/
set lz
let orig_buf=bufnr('')
" initialize Variables
call <sid>Init()
call <sid>CheckProtected()
let s:nrrw_rgn_lines[s:instn].start = []
let s:nrrw_rgn_lines[s:instn].end = []
let s:nrrw_rgn_lines[s:instn].multi = s:nrrw_rgn_buf
let s:nrrw_rgn_lines[s:instn].orig_buf = orig_buf
call <sid>DeleteMatches(s:instn)
let nr=0
let lines=[]
let buffer=[]
let keys = keys(s:nrrw_rgn_buf)
call sort(keys,"<sid>CompareNumbers")
"for [ nr,lines] in items(s:nrrw_rgn_buf)
let [c_s, c_e] = <sid>ReturnComments()
for nr in keys
let lines = s:nrrw_rgn_buf[nr]
let start = lines[0]
let end = len(lines)==2 ? lines[1] : lines[0]
if !bang
call <sid>AddMatches(<sid>GeneratePattern([start,0], [end,0], 'V'),
\s:instn)
endif
call add(buffer, c_s.' Start NrrwRgn'.nr.c_e)
let buffer = buffer +
\ getline(start,end) +
\ [c_s.' End NrrwRgn'.nr.c_e, '']
endfor
let win=<sid>NrrwRgnWin(bang)
if bang
let s:nrrw_rgn_lines[s:instn].single = 1
endif
let b:orig_buf = orig_buf
call setline(1, buffer)
setl nomod
let b:nrrw_instn = s:instn
call <sid>SetupBufLocalCommands()
call <sid>NrrwRgnAuCmd(0)
call <sid>CleanRegions()
call <sid>HideNrrwRgnLines()
" restore settings
let &lz = o_lz
endfun
fun! nrrwrgn#NrrwRgn(...) range "{{{1
let o_lz = &lz
let s:o_s = @/
set lz
let orig_buf=bufnr('')
let bang = (a:0 > 0 && !empty(a:1))
" initialize Variables
call <sid>Init()
call <sid>CheckProtected()
let first = a:firstline
let last = a:lastline
" If first line is in a closed fold,
" include complete fold in Narrowed window
if first == last && foldclosed(first) != -1
let first = foldclosed(first)
let last = foldclosedend(last)
endif
let s:nrrw_rgn_lines[s:instn].start = [ 0, first, 0, 0 ]
let s:nrrw_rgn_lines[s:instn].end = [ 0, last , 0, 0 ]
let s:nrrw_rgn_lines[s:instn].orig_buf = orig_buf
let a=getline(
\s:nrrw_rgn_lines[s:instn].start[1],
\s:nrrw_rgn_lines[s:instn].end[1])
call <sid>DeleteMatches(s:instn)
let win=<sid>NrrwRgnWin(bang)
if bang
let s:nrrw_rgn_lines[s:instn].single = 1
else
noa wincmd p
" Set highlighting in original window
call <sid>AddMatches(<sid>GeneratePattern(
\s:nrrw_rgn_lines[s:instn].start[1:2],
\s:nrrw_rgn_lines[s:instn].end[1:2],
\'V'), s:instn)
" move back to narrowed window
noa wincmd p
endif
let b:orig_buf = orig_buf
call setline(1, a)
setl nomod
let b:nrrw_instn = s:instn
call <sid>SetupBufLocalCommands()
call <sid>NrrwRgnAuCmd(0)
if has_key(s:nrrw_aucmd, "create")
exe s:nrrw_aucmd["create"]
endif
if has_key(s:nrrw_aucmd, "close")
let b:nrrw_aucmd_close = s:nrrw_aucmd["close"]
endif
" restore settings
let &lz = o_lz
endfun
fun! nrrwrgn#Prepare() "{{{1
let ltime = localtime()
if (!exists("s:nrrw_rgn_last") || s:nrrw_rgn_last + 10 < ltime)
let s:nrrw_rgn_last = ltime
let s:nrrw_rgn_line = []
endif
if !exists("s:nrrw_rgn_line") | let s:nrrw_rgn_line=[] | endif
call add(s:nrrw_rgn_line, line('.'))
endfun
fun! nrrwrgn#WidenRegion(force) "{{{1
" a:close: original narrowed window is going to be closed
" so, clean up, don't renew highlighting, etc.
let nrw_buf = bufnr('')
let orig_buf = b:orig_buf
let orig_tab = tabpagenr()
let instn = b:nrrw_instn
let close = has_key(s:nrrw_rgn_lines[instn], 'single')
let vmode = has_key(s:nrrw_rgn_lines[instn], 'vmode')
" Execute autocommands
if has_key(s:nrrw_aucmd, "close")
exe s:nrrw_aucmd["close"]
endif
let cont = getline(1,'$')
let tab=<sid>BufInTab(orig_buf)
if tab != tabpagenr() && tab > 0
exe "noa tabn" tab
endif
let orig_win = bufwinnr(orig_buf)
" Should be in the right tab now!
if (orig_win == -1)
if bufexists(orig_buf)
" buffer not in current window, switch to it!
exe "noa" orig_buf "b!"
" Make sure highlighting will be removed
let close = (&g:hid ? 0 : 1)
else
call s:WarningMsg("Original buffer does no longer exist!".
\ " Aborting!")
return
endif
else
exe ':noa'. orig_win. 'wincmd w'
endif
let _opts = <sid>SaveRestoreRegister([])
let wsv=winsaveview()
call <sid>DeleteMatches(instn)
if exists("b:orig_buf_ro") && b:orig_buf_ro && !a:force
call s:WarningMsg("Original buffer protected. Can't write changes!")
call <sid>JumpToBufinTab(orig_tab, nrw_buf)
return
endif
if !&l:ma && !( exists("b:orig_buf_ro") && b:orig_buf_ro)
setl ma
endif
" This is needed to adjust all other narrowed regions
" in case we have several narrowed regions within the same buffer
if exists("g:nrrw_rgn_protect") && g:nrrw_rgn_protect =~? 'n'
let adjust_line_numbers = len(cont) - 1 - (
\s:nrrw_rgn_lines[instn].end[1] -
\s:nrrw_rgn_lines[instn].start[1])
endif
" Make sure the narrowed buffer is still valid (happens, when 2 split
" window of the narrowed buffer is opened.
if !has_key(s:nrrw_rgn_lines, instn)
call <sid>WarningMsg("Error writing changes back,".
\ "Narrowed Window invalid!")
return
endif
" Now copy the content back into the original buffer
" 1) Check: Multiselection
if has_key(s:nrrw_rgn_lines[instn], 'multi')
call <sid>WidenRegionMulti(cont, instn)
" 2) Visual Selection
elseif vmode
"charwise, linewise or blockwise selection
call setreg('a', join(cont, "\n"). "\n",
\ s:nrrw_rgn_lines[instn].vmode)
if s:nrrw_rgn_lines[instn].vmode == 'v' &&
\ s:nrrw_rgn_lines[instn].end[1] -
\ s:nrrw_rgn_lines[instn].start[1] + 1 == len(cont) + 1
" in characterwise selection, remove trailing \n
call setreg('a', substitute(@a, '\n$', '', ''),
\ s:nrrw_rgn_lines[instn].vmode)
endif
if v:version > 703 || (v:version == 703 && has("patch590"))
" settable '< and '> marks
let _v = []
" store actual values
let _v = [getpos("'<"), getpos("'>"), [visualmode(1)]]
" set the mode for the gv command
exe "norm! ". s:nrrw_rgn_lines[instn].vmode."\<ESC>"
call setpos("'<", s:nrrw_rgn_lines[instn].start)
call setpos("'>", s:nrrw_rgn_lines[instn].end)
exe 'norm! gv"aP'
if !empty(_v[2][0]) && (_v[2][0] != visualmode())
exe 'norm!' _v[2][0]. "\<ESC>"
call setpos("'<", _v[0])
call setpos("'>", _v[1])
endif
else
exe "keepj" s:nrrw_rgn_lines[instn].start[1]
exe "keepj norm!" s:nrrw_rgn_lines[instn].start[2]. '|'
exe "keepj norm!" s:nrrw_rgn_lines[instn].vmode
exe "keepj" s:nrrw_rgn_lines[instn].end[1]
if s:nrrw_rgn_lines[instn].blockmode
exe "keepj norm!" s:nrrw_rgn_lines[instn].end[2]. '|'
else
keepj norm! $
endif
" overwrite the visually selected region with the contents from
" the narrowed buffer
norm! "aP
endif
" Recalculate the start and end positions of the narrowed window
" so subsequent calls will adjust the region accordingly
let [ s:nrrw_rgn_lines[instn].start,
\s:nrrw_rgn_lines[instn].end ] = <sid>RetVisRegionPos()
" make sure the visual selected lines did not add a new linebreak,
" this messes up the characterwise selected regions and removes lines
" on further writings
if s:nrrw_rgn_lines[instn].end[1] - s:nrrw_rgn_lines[instn].start[1]
\ + 1 > len(cont) && s:nrrw_rgn_lines[instn].vmode == 'v'
let s:nrrw_rgn_lines[instn].end[1] =
\ s:nrrw_rgn_lines[instn].end[1] - 1
let s:nrrw_rgn_lines[instn].end[2] = virtcol('$')
endif
" also, renew the highlighted region
if !has_key(s:nrrw_rgn_lines[instn], 'single')
call <sid>AddMatches(<sid>GeneratePattern(
\ s:nrrw_rgn_lines[instn].start[1:2],
\ s:nrrw_rgn_lines[instn].end[1:2],
\ s:nrrw_rgn_lines[instn].vmode),
\ instn)
else
noa b #
endif
" 3) :NR started selection
else
" linewise selection because we started the NarrowRegion with the
" command NarrowRegion(0)
"
" if the endposition of the narrowed buffer is also the last line of
" the buffer, the append will add an extra newline that needs to be
" cleared.
if s:nrrw_rgn_lines[instn].end[1]==line('$') &&
\ s:nrrw_rgn_lines[instn].start[1] == 1
let delete_last_line=1
else
let delete_last_line=0
endif
exe ':silent :'.s:nrrw_rgn_lines[instn].start[1].','
\.s:nrrw_rgn_lines[instn].end[1].'d _'
call append((s:nrrw_rgn_lines[instn].start[1]-1),cont)
" Recalculate the start and end positions of the narrowed window
" so subsequent calls will adjust the region accordingly
" so subsequent calls will adjust the region accordingly
let s:nrrw_rgn_lines[instn].end[1] =
\ s:nrrw_rgn_lines[instn].start[1] + len(cont) -1
if s:nrrw_rgn_lines[instn].end[1] > line('$')
let s:nrrw_rgn_lines[instn].end[1] = line('$')
endif
if !has_key(s:nrrw_rgn_lines[instn], 'single')
call <sid>AddMatches(<sid>GeneratePattern(
\s:nrrw_rgn_lines[instn].start[1:2],
\s:nrrw_rgn_lines[instn].end[1:2],
\'V'),
\instn)
endif
if delete_last_line
silent! $d _
endif
endif
" Recalculate start- and endline numbers for all other Narrowed Windows.
" This matters, if you narrow different regions of the same file and
" write your changes back.
if exists("g:nrrw_rgn_protect") && g:nrrw_rgn_protect =~? 'n'
call <sid>RecalculateLineNumbers(instn, adjust_line_numbers)
endif
" if close && !has_key(s:nrrw_rgn_lines[instn], 'single')
" For narrowed windows that have been created using !,
" don't clean up yet, or else we loose all data and can't write
" it back later.
" (e.g. :NR! createas a new single window, do :sp
" and you can only write one of the windows back, the other will
" become invalid, if CleanUp is executed)
" endif
call <sid>SaveRestoreRegister(_opts)
let @/=s:o_s
call winrestview(wsv)
if !close && has_key(s:nrrw_rgn_lines[instn], 'single')
" move back to narrowed buffer
noa b #
elseif close
call <sid>CleanUpInstn(instn)
endif
" jump back to narrowed window
call <sid>JumpToBufinTab(orig_tab, nrw_buf)
setl nomod
if a:force
" trigger auto command
bw