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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
|
" fugitive.vim - A Git wrapper so awesome, it should be illegal
" Maintainer: Tim Pope <http://tpo.pe/>
" Version: 2.1
" GetLatestVimScripts: 2975 1 :AutoInstall: fugitive.vim
if exists('g:loaded_fugitive') || &cp
finish
endif
let g:loaded_fugitive = 1
if !exists('g:fugitive_git_executable')
let g:fugitive_git_executable = 'git'
endif
" Section: Utility
function! s:function(name) abort
return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),''))
endfunction
function! s:sub(str,pat,rep) abort
return substitute(a:str,'\v\C'.a:pat,a:rep,'')
endfunction
function! s:gsub(str,pat,rep) abort
return substitute(a:str,'\v\C'.a:pat,a:rep,'g')
endfunction
function! s:winshell() abort
return &shell =~? 'cmd' || exists('+shellslash') && !&shellslash
endfunction
function! s:shellesc(arg) abort
if a:arg =~ '^[A-Za-z0-9_/.-]\+$'
return a:arg
elseif s:winshell()
return '"'.s:gsub(s:gsub(a:arg, '"', '""'), '\%', '"%"').'"'
else
return shellescape(a:arg)
endif
endfunction
function! s:fnameescape(file) abort
if exists('*fnameescape')
return fnameescape(a:file)
else
return escape(a:file," \t\n*?[{`$\\%#'\"|!<")
endif
endfunction
function! s:throw(string) abort
let v:errmsg = 'fugitive: '.a:string
throw v:errmsg
endfunction
function! s:warn(str) abort
echohl WarningMsg
echomsg a:str
echohl None
let v:warningmsg = a:str
endfunction
function! s:shellslash(path) abort
if s:winshell()
return s:gsub(a:path,'\\','/')
else
return a:path
endif
endfunction
let s:git_versions = {}
function! fugitive#git_version(...) abort
if !has_key(s:git_versions, g:fugitive_git_executable)
let s:git_versions[g:fugitive_git_executable] = matchstr(system(g:fugitive_git_executable.' --version'), "\\S\\+\n")
endif
return s:git_versions[g:fugitive_git_executable]
endfunction
function! s:recall() abort
let rev = s:sub(s:buffer().rev(), '^/', '')
if rev ==# ':'
return matchstr(getline('.'),'^#\t\%([[:alpha:] ]\+: *\)\=\zs.\{-\}\ze\%( ([^()[:digit:]]\+)\)\=$\|^\d\{6} \x\{40\} \d\t\zs.*')
elseif s:buffer().type('tree')
let file = matchstr(getline('.'), '\t\zs.*')
if empty(file) && line('.') > 2
let file = s:sub(getline('.'), '/$', '')
endif
if !empty(file) && rev !~# ':$'
return rev . '/' . file
else
return rev . file
endif
endif
return rev
endfunction
function! s:add_methods(namespace, method_names) abort
for name in a:method_names
let s:{a:namespace}_prototype[name] = s:function('s:'.a:namespace.'_'.name)
endfor
endfunction
let s:commands = []
function! s:command(definition) abort
let s:commands += [a:definition]
endfunction
function! s:define_commands() abort
for command in s:commands
exe 'command! -buffer '.command
endfor
endfunction
augroup fugitive_utility
autocmd!
autocmd User Fugitive call s:define_commands()
augroup END
let s:abstract_prototype = {}
" Section: Initialization
function! fugitive#is_git_dir(path) abort
let path = s:sub(a:path, '[\/]$', '') . '/'
return isdirectory(path.'objects') && isdirectory(path.'refs') && getfsize(path.'HEAD') > 10
endfunction
function! fugitive#extract_git_dir(path) abort
if s:shellslash(a:path) =~# '^fugitive://.*//'
return matchstr(s:shellslash(a:path), '\C^fugitive://\zs.\{-\}\ze//')
endif
let root = s:shellslash(simplify(fnamemodify(a:path, ':p:s?[\/]$??')))
let previous = ""
while root !=# previous
if root =~# '\v^//%([^/]+/?)?$'
" This is for accessing network shares from Cygwin Vim. There won't be
" any git directory called //.git or //serverName/.git so let's avoid
" checking for them since such checks are extremely slow.
break
endif
if index(split($GIT_CEILING_DIRECTORIES, ':'), root) >= 0
break
endif
if root ==# $GIT_WORK_TREE && fugitive#is_git_dir($GIT_DIR)
return $GIT_DIR
endif
let dir = s:sub(root, '[\/]$', '') . '/.git'
let type = getftype(dir)
if type ==# 'dir' && fugitive#is_git_dir(dir)
return dir
elseif type ==# 'link' && fugitive#is_git_dir(dir)
return resolve(dir)
elseif type !=# '' && filereadable(dir)
let line = get(readfile(dir, '', 1), 0, '')
if line =~# '^gitdir: \.' && fugitive#is_git_dir(root.'/'.line[8:-1])
return simplify(root.'/'.line[8:-1])
elseif line =~# '^gitdir: ' && fugitive#is_git_dir(line[8:-1])
return line[8:-1]
endif
elseif fugitive#is_git_dir(root)
return root
endif
let previous = root
let root = fnamemodify(root, ':h')
endwhile
return ''
endfunction
function! fugitive#detect(path) abort
if exists('b:git_dir') && (b:git_dir ==# '' || b:git_dir =~# '/$')
unlet b:git_dir
endif
if !exists('b:git_dir')
let dir = fugitive#extract_git_dir(a:path)
if dir !=# ''
let b:git_dir = dir
endif
endif
if exists('b:git_dir')
silent doautocmd User FugitiveBoot
cnoremap <buffer> <expr> <C-R><C-G> fnameescape(<SID>recall())
nnoremap <buffer> <silent> y<C-G> :call setreg(v:register, <SID>recall())<CR>
let buffer = fugitive#buffer()
if expand('%:p') =~# '//'
call buffer.setvar('&path', s:sub(buffer.getvar('&path'), '^\.%(,|$)', ''))
endif
if stridx(buffer.getvar('&tags'), escape(b:git_dir.'/tags', ', ')) == -1
call buffer.setvar('&tags', escape(b:git_dir.'/tags', ', ').','.buffer.getvar('&tags'))
if &filetype !=# ''
call buffer.setvar('&tags', escape(b:git_dir.'/'.&filetype.'.tags', ', ').','.buffer.getvar('&tags'))
endif
endif
silent doautocmd User Fugitive
endif
endfunction
augroup fugitive
autocmd!
autocmd BufNewFile,BufReadPost * call fugitive#detect(expand('<amatch>:p'))
autocmd FileType netrw call fugitive#detect(expand('%:p'))
autocmd User NERDTreeInit,NERDTreeNewRoot call fugitive#detect(b:NERDTreeRoot.path.str())
autocmd VimEnter * if expand('<amatch>')==''|call fugitive#detect(getcwd())|endif
autocmd CmdWinEnter * call fugitive#detect(expand('#:p'))
autocmd BufWinLeave * execute getwinvar(+bufwinnr(+expand('<abuf>')), 'fugitive_leave')
augroup END
" Section: Repository
let s:repo_prototype = {}
let s:repos = {}
function! s:repo(...) abort
let dir = a:0 ? a:1 : (exists('b:git_dir') && b:git_dir !=# '' ? b:git_dir : fugitive#extract_git_dir(expand('%:p')))
if dir !=# ''
if has_key(s:repos, dir)
let repo = get(s:repos, dir)
else
let repo = {'git_dir': dir}
let s:repos[dir] = repo
endif
return extend(extend(repo, s:repo_prototype, 'keep'), s:abstract_prototype, 'keep')
endif
call s:throw('not a git repository: '.expand('%:p'))
endfunction
function! fugitive#repo(...) abort
return call('s:repo', a:000)
endfunction
function! s:repo_dir(...) dict abort
return join([self.git_dir]+a:000,'/')
endfunction
function! s:repo_configured_tree() dict abort
if !has_key(self,'_tree')
let self._tree = ''
if filereadable(self.dir('config'))
let config = readfile(self.dir('config'),'',10)
call filter(config,'v:val =~# "^\\s*worktree *="')
if len(config) == 1
let self._tree = matchstr(config[0], '= *\zs.*')
endif
endif
endif
if self._tree =~# '^\.'
return simplify(self.dir(self._tree))
else
return self._tree
endif
endfunction
function! s:repo_tree(...) dict abort
if self.dir() =~# '/\.git$'
let dir = self.dir()[0:-6]
else
let dir = self.configured_tree()
endif
if dir ==# ''
call s:throw('no work tree')
else
return join([dir]+a:000,'/')
endif
endfunction
function! s:repo_bare() dict abort
if self.dir() =~# '/\.git$'
return 0
else
return self.configured_tree() ==# ''
endif
endfunction
function! s:repo_translate(spec) dict abort
if a:spec ==# '.' || a:spec ==# '/.'
return self.bare() ? self.dir() : self.tree()
elseif a:spec =~# '^/\=\.git$' && self.bare()
return self.dir()
elseif a:spec =~# '^/\=\.git/'
return self.dir(s:sub(a:spec, '^/=\.git/', ''))
elseif a:spec =~# '^/'
return self.tree().a:spec
elseif a:spec =~# '^:[0-3]:'
return 'fugitive://'.self.dir().'//'.a:spec[1].'/'.a:spec[3:-1]
elseif a:spec ==# ':'
if $GIT_INDEX_FILE =~# '/[^/]*index[^/]*\.lock$' && fnamemodify($GIT_INDEX_FILE,':p')[0:strlen(self.dir())] ==# self.dir('') && filereadable($GIT_INDEX_FILE)
return fnamemodify($GIT_INDEX_FILE,':p')
else
return self.dir('index')
endif
elseif a:spec =~# '^:/'
let ref = self.rev_parse(matchstr(a:spec,'.[^:]*'))
return 'fugitive://'.self.dir().'//'.ref
elseif a:spec =~# '^:'
return 'fugitive://'.self.dir().'//0/'.a:spec[1:-1]
elseif a:spec =~# 'HEAD\|^refs/' && a:spec !~ ':' && filereadable(self.dir(a:spec))
return self.dir(a:spec)
elseif filereadable(self.dir('refs/'.a:spec))
return self.dir('refs/'.a:spec)
elseif filereadable(self.dir('refs/tags/'.a:spec))
return self.dir('refs/tags/'.a:spec)
elseif filereadable(self.dir('refs/heads/'.a:spec))
return self.dir('refs/heads/'.a:spec)
elseif filereadable(self.dir('refs/remotes/'.a:spec))
return self.dir('refs/remotes/'.a:spec)
elseif filereadable(self.dir('refs/remotes/'.a:spec.'/HEAD'))
return self.dir('refs/remotes/'.a:spec,'/HEAD')
else
try
let ref = self.rev_parse(matchstr(a:spec,'[^:]*'))
let path = s:sub(matchstr(a:spec,':.*'),'^:','/')
return 'fugitive://'.self.dir().'//'.ref.path
catch /^fugitive:/
return self.tree(a:spec)
endtry
endif
endfunction
function! s:repo_head(...) dict abort
let head = s:repo().head_ref()
if head =~# '^ref: '
let branch = s:sub(head,'^ref: %(refs/%(heads/|remotes/|tags/)=)=','')
elseif head =~# '^\x\{40\}$'
" truncate hash to a:1 characters if we're in detached head mode
let len = a:0 ? a:1 : 0
let branch = len ? head[0:len-1] : ''
else
return ''
endif
return branch
endfunction
call s:add_methods('repo',['dir','configured_tree','tree','bare','translate','head'])
function! s:repo_git_command(...) dict abort
let git = g:fugitive_git_executable . ' --git-dir='.s:shellesc(self.git_dir)
return git.join(map(copy(a:000),'" ".s:shellesc(v:val)'),'')
endfunction
function! s:repo_git_chomp(...) dict abort
return s:sub(system(call(self.git_command,a:000,self)),'\n$','')
endfunction
function! s:repo_git_chomp_in_tree(...) dict abort
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd()
try
execute cd.'`=s:repo().tree()`'
return call(s:repo().git_chomp, a:000, s:repo())
finally
execute cd.'`=dir`'
endtry
endfunction
function! s:repo_rev_parse(rev) dict abort
let hash = self.git_chomp('rev-parse','--verify',a:rev)
if hash =~ '\<\x\{40\}$'
return matchstr(hash,'\<\x\{40\}$')
endif
call s:throw('rev-parse '.a:rev.': '.hash)
endfunction
call s:add_methods('repo',['git_command','git_chomp','git_chomp_in_tree','rev_parse'])
function! s:repo_dirglob(base) dict abort
let base = s:sub(a:base,'^/','')
let matches = split(glob(self.tree(s:gsub(base,'/','*&').'*/')),"\n")
call map(matches,'v:val[ strlen(self.tree())+(a:base !~ "^/") : -1 ]')
return matches
endfunction
function! s:repo_superglob(base) dict abort
if a:base =~# '^/' || a:base !~# ':'
let results = []
if a:base !~# '^/'
let heads = ["HEAD","ORIG_HEAD","FETCH_HEAD","MERGE_HEAD"]
let heads += sort(split(s:repo().git_chomp("rev-parse","--symbolic","--branches","--tags","--remotes"),"\n"))
call filter(heads,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base')
let results += heads
endif
if !self.bare()
let base = s:sub(a:base,'^/','')
let matches = split(glob(self.tree(s:gsub(base,'/','*&').'*')),"\n")
call map(matches,'s:shellslash(v:val)')
call map(matches,'v:val !~ "/$" && isdirectory(v:val) ? v:val."/" : v:val')
call map(matches,'v:val[ strlen(self.tree())+(a:base !~ "^/") : -1 ]')
let results += matches
endif
return results
elseif a:base =~# '^:'
let entries = split(self.git_chomp('ls-files','--stage'),"\n")
call map(entries,'s:sub(v:val,".*(\\d)\\t(.*)",":\\1:\\2")')
if a:base !~# '^:[0-3]\%(:\|$\)'
call filter(entries,'v:val[1] == "0"')
call map(entries,'v:val[2:-1]')
endif
call filter(entries,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base')
return entries
else
let tree = matchstr(a:base,'.*[:/]')
let entries = split(self.git_chomp('ls-tree',tree),"\n")
call map(entries,'s:sub(v:val,"^04.*\\zs$","/")')
call map(entries,'tree.s:sub(v:val,".*\t","")')
return filter(entries,'v:val[ 0 : strlen(a:base)-1 ] ==# a:base')
endif
endfunction
call s:add_methods('repo',['dirglob','superglob'])
function! s:repo_config(conf) dict abort
return matchstr(system(s:repo().git_command('config').' '.a:conf),"[^\r\n]*")
endfun
function! s:repo_user() dict abort
let username = s:repo().config('user.name')
let useremail = s:repo().config('user.email')
return username.' <'.useremail.'>'
endfun
function! s:repo_aliases() dict abort
if !has_key(self,'_aliases')
let self._aliases = {}
for line in split(self.git_chomp('config','--get-regexp','^alias[.]'),"\n")
let self._aliases[matchstr(line,'\.\zs\S\+')] = matchstr(line,' \zs.*')
endfor
endif
return self._aliases
endfunction
call s:add_methods('repo',['config', 'user', 'aliases'])
function! s:repo_keywordprg() dict abort
let args = ' --git-dir='.escape(self.dir(),"\\\"' ")
if has('gui_running') && !has('win32')
return g:fugitive_git_executable . ' --no-pager' . args . ' log -1'
else
return g:fugitive_git_executable . args . ' show'
endif
endfunction
call s:add_methods('repo',['keywordprg'])
" Section: Buffer
let s:buffer_prototype = {}
function! s:buffer(...) abort
let buffer = {'#': bufnr(a:0 ? a:1 : '%')}
call extend(extend(buffer,s:buffer_prototype,'keep'),s:abstract_prototype,'keep')
if buffer.getvar('git_dir') !=# ''
return buffer
endif
call s:throw('not a git repository: '.expand('%:p'))
endfunction
function! fugitive#buffer(...) abort
return s:buffer(a:0 ? a:1 : '%')
endfunction
function! s:buffer_getvar(var) dict abort
return getbufvar(self['#'],a:var)
endfunction
function! s:buffer_setvar(var,value) dict abort
return setbufvar(self['#'],a:var,a:value)
endfunction
function! s:buffer_getline(lnum) dict abort
return get(getbufline(self['#'], a:lnum), 0, '')
endfunction
function! s:buffer_repo() dict abort
return s:repo(self.getvar('git_dir'))
endfunction
function! s:buffer_type(...) dict abort
if self.getvar('fugitive_type') != ''
let type = self.getvar('fugitive_type')
elseif fnamemodify(self.spec(),':p') =~# '.\git/refs/\|\.git/\w*HEAD$'
let type = 'head'
elseif self.getline(1) =~ '^tree \x\{40\}$' && self.getline(2) == ''
let type = 'tree'
elseif self.getline(1) =~ '^\d\{6\} \w\{4\} \x\{40\}\>\t'
let type = 'tree'
elseif self.getline(1) =~ '^\d\{6\} \x\{40\}\> \d\t'
let type = 'index'
elseif isdirectory(self.spec())
let type = 'directory'
elseif self.spec() == ''
let type = 'null'
else
let type = 'file'
endif
if a:0
return !empty(filter(copy(a:000),'v:val ==# type'))
else
return type
endif
endfunction
if has('win32')
function! s:buffer_spec() dict abort
let bufname = bufname(self['#'])
let retval = ''
for i in split(bufname,'[^:]\zs\\')
let retval = fnamemodify((retval==''?'':retval.'\').i,':.')
endfor
return s:shellslash(fnamemodify(retval,':p'))
endfunction
else
function! s:buffer_spec() dict abort
let bufname = bufname(self['#'])
return s:shellslash(bufname == '' ? '' : fnamemodify(bufname,':p'))
endfunction
endif
function! s:buffer_name() dict abort
return self.spec()
endfunction
function! s:buffer_commit() dict abort
return matchstr(self.spec(),'^fugitive://.\{-\}//\zs\w*')
endfunction
function! s:buffer_path(...) dict abort
let rev = matchstr(self.spec(),'^fugitive://.\{-\}//\zs.*')
if rev != ''
let rev = s:sub(rev,'\w*','')
elseif self.spec()[0 : len(self.repo().dir())] ==# self.repo().dir() . '/'
let rev = '/.git'.self.spec()[strlen(self.repo().dir()) : -1]
elseif !self.repo().bare() && self.spec()[0 : len(self.repo().tree())] ==# self.repo().tree() . '/'
let rev = self.spec()[strlen(self.repo().tree()) : -1]
endif
return s:sub(s:sub(rev,'.\zs/$',''),'^/',a:0 ? a:1 : '')
endfunction
function! s:buffer_rev() dict abort
let rev = matchstr(self.spec(),'^fugitive://.\{-\}//\zs.*')
if rev =~ '^\x/'
return ':'.rev[0].':'.rev[2:-1]
elseif rev =~ '.'
return s:sub(rev,'/',':')
elseif self.spec() =~ '\.git/index$'
return ':'
elseif self.spec() =~ '\.git/refs/\|\.git/.*HEAD$'
return self.spec()[strlen(self.repo().dir())+1 : -1]
else
return self.path('/')
endif
endfunction
function! s:buffer_sha1() dict abort
if self.spec() =~ '^fugitive://' || self.spec() =~ '\.git/refs/\|\.git/.*HEAD$'
return self.repo().rev_parse(self.rev())
else
return ''
endif
endfunction
function! s:buffer_expand(rev) dict abort
if a:rev =~# '^:[0-3]$'
let file = a:rev.self.path(':')
elseif a:rev =~# '^[-:]/$'
let file = '/'.self.path()
elseif a:rev =~# '^-'
let file = 'HEAD^{}'.a:rev[1:-1].self.path(':')
elseif a:rev =~# '^@{'
let file = 'HEAD'.a:rev.self.path(':')
elseif a:rev =~# '^[~^]'
let commit = s:sub(self.commit(),'^\d=$','HEAD')
let file = commit.a:rev.self.path(':')
else
let file = a:rev
endif
return s:sub(s:sub(file,'\%$',self.path()),'\.\@<=/$','')
endfunction
function! s:buffer_containing_commit() dict abort
if self.commit() =~# '^\d$'
return ':'
elseif self.commit() =~# '.'
return self.commit()
else
return 'HEAD'
endif
endfunction
function! s:buffer_up(...) dict abort
let rev = self.rev()
let c = a:0 ? a:1 : 1
while c
if rev =~# '^[/:]$'
let rev = 'HEAD'
elseif rev =~# '^:'
let rev = ':'
elseif rev =~# '^refs/[^^~:]*$\|^[^^~:]*HEAD$'
let rev .= '^{}'
elseif rev =~# '^/\|:.*/'
let rev = s:sub(rev, '.*\zs/.*', '')
elseif rev =~# ':.'
let rev = matchstr(rev, '^[^:]*:')
elseif rev =~# ':$'
let rev = rev[0:-2]
else
return rev.'~'.c
endif
let c -= 1
endwhile
return rev
endfunction
call s:add_methods('buffer',['getvar','setvar','getline','repo','type','spec','name','commit','path','rev','sha1','expand','containing_commit','up'])
" Section: Git
call s:command("-bang -nargs=? -complete=customlist,s:GitComplete Git :execute s:Git(<bang>0,<q-args>)")
function! s:ExecuteInTree(cmd) abort
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd()
try
execute cd.'`=s:repo().tree()`'
execute a:cmd
finally
execute cd.'`=dir`'
endtry
endfunction
function! s:Git(bang, args) abort
if a:bang
return s:Edit('edit', 1, a:args)
endif
let git = g:fugitive_git_executable
if has('gui_running') && !has('win32')
let git .= ' --no-pager'
endif
let args = matchstr(a:args,'\v\C.{-}%($|\\@<!%(\\\\)*\|)@=')
call s:ExecuteInTree('!'.git.' '.args)
call fugitive#reload_status()
return matchstr(a:args, '\v\C\\@<!%(\\\\)*\|\zs.*')
endfunction
function! s:GitComplete(A,L,P) abort
if !exists('s:exec_path')
let s:exec_path = s:sub(system(g:fugitive_git_executable.' --exec-path'),'\n$','')
endif
let cmds = map(split(glob(s:exec_path.'/git-*'),"\n"),'s:sub(v:val[strlen(s:exec_path)+5 : -1],"\\.exe$","")')
if a:L =~ ' [[:alnum:]-]\+ '
return s:repo().superglob(a:A)
else
return filter(sort(cmds+keys(s:repo().aliases())), 'strpart(v:val, 0, strlen(a:A)) ==# a:A')
endif
endfunction
" Section: Gcd, Glcd
function! s:DirComplete(A,L,P) abort
let matches = s:repo().dirglob(a:A)
return matches
endfunction
call s:command("-bar -bang -nargs=? -complete=customlist,s:DirComplete Gcd :cd<bang> `=s:repo().bare() ? s:repo().dir(<q-args>) : s:repo().tree(<q-args>)`")
call s:command("-bar -bang -nargs=? -complete=customlist,s:DirComplete Glcd :lcd<bang> `=s:repo().bare() ? s:repo().dir(<q-args>) : s:repo().tree(<q-args>)`")
" Section: Gstatus
call s:command("-bar Gstatus :execute s:Status()")
augroup fugitive_status
autocmd!
if !has('win32')
autocmd FocusGained,ShellCmdPost * call fugitive#reload_status()
endif
augroup END
function! s:Status() abort
try
Gpedit :
wincmd P
setlocal foldmethod=syntax foldlevel=1
nnoremap <buffer> <silent> q :<C-U>bdelete<CR>
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
return ''
endfunction
function! fugitive#reload_status() abort
if exists('s:reloading_status')
return
endif
try
let s:reloading_status = 1
let mytab = tabpagenr()
for tab in [mytab] + range(1,tabpagenr('$'))
for winnr in range(1,tabpagewinnr(tab,'$'))
if getbufvar(tabpagebuflist(tab)[winnr-1],'fugitive_type') ==# 'index'
execute 'tabnext '.tab
if winnr != winnr()
execute winnr.'wincmd w'
let restorewinnr = 1
endif
try
if !&modified
call s:BufReadIndex()
endif
finally
if exists('restorewinnr')
wincmd p
endif
execute 'tabnext '.mytab
endtry
endif
endfor
endfor
finally
unlet! s:reloading_status
endtry
endfunction
function! s:stage_info(lnum) abort
let filename = matchstr(getline(a:lnum),'^#\t\zs.\{-\}\ze\%( ([^()[:digit:]]\+)\)\=$')
let lnum = a:lnum
if has('multi_byte_encoding')
let colon = '\%(:\|\%uff1a\)'
else
let colon = ':'
endif
while lnum && getline(lnum) !~# colon.'$'
let lnum -= 1
endwhile
if !lnum
return ['', '']
elseif (getline(lnum+1) =~# '^# .*\<git \%(reset\|rm --cached\) ' && getline(lnum+2) ==# '#') || getline(lnum) ==# '# Changes to be committed:'
return [matchstr(filename, colon.' *\zs.*'), 'staged']
elseif (getline(lnum+1) =~# '^# .*\<git add ' && getline(lnum+2) ==# '#' && getline(lnum+3) !~# colon.' ') || getline(lnum) ==# '# Untracked files:'
return [filename, 'untracked']
elseif getline(lnum+2) =~# '^# .*\<git checkout ' || getline(lnum) ==# '# Changes not staged for commit:'
return [matchstr(filename, colon.' *\zs.*'), 'unstaged']
elseif getline(lnum+2) =~# '^# .*\<git \%(add\|rm\)' || getline(lnum) ==# '# Unmerged paths:'
return [matchstr(filename, colon.' *\zs.*'), 'unmerged']
else
return ['', 'unknown']
endif
endfunction
function! s:StageNext(count) abort
for i in range(a:count)
call search('^#\t.*','W')
endfor
return '.'
endfunction
function! s:StagePrevious(count) abort
if line('.') == 1 && exists(':CtrlP') && get(g:, 'ctrl_p_map') =~? '^<c-p>$'
return 'CtrlP '.fnameescape(s:repo().tree())
else
for i in range(a:count)
call search('^#\t.*','Wbe')
endfor
return '.'
endif
endfunction
function! s:StageReloadSeek(target,lnum1,lnum2) abort
let jump = a:target
let f = matchstr(getline(a:lnum1-1),'^#\t\%([[:alpha:] ]\+: *\|.*\%uff1a *\)\=\zs.*')
if f !=# '' | let jump = f | endif
let f = matchstr(getline(a:lnum2+1),'^#\t\%([[:alpha:] ]\+: *\|.*\%uff1a *\)\=\zs.*')
if f !=# '' | let jump = f | endif
silent! edit!
1
redraw
call search('^#\t\%([[:alpha:] ]\+: *\|.*\%uff1a *\)\=\V'.jump.'\%( ([^()[:digit:]]\+)\)\=\$','W')
endfunction
function! s:StageUndo() abort
let [filename, section] = s:stage_info(line('.'))
if empty(filename)
return ''
endif
let repo = s:repo()
let hash = repo.git_chomp('hash-object', '-w', filename)
if !empty(hash)
if section ==# 'untracked'
call delete(s:repo().tree(filename))
elseif section ==# 'unstaged'
call repo.git_chomp('checkout', '--', filename)
else
call repo.git_chomp('checkout', 'HEAD', '--', filename)
endif
call s:StageReloadSeek(filename, line('.'), line('.'))
let @" = hash
return 'checktime|redraw|echomsg ' .
\ string('To restore, :Git cat-file blob '.hash[0:6].' > '.filename)
endif
endfunction
function! s:StageDiff(diff) abort
let [filename, section] = s:stage_info(line('.'))
if filename ==# '' && section ==# 'staged'
return 'Git! diff --no-ext-diff --cached'
elseif filename ==# ''
return 'Git! diff --no-ext-diff'
elseif filename =~# ' -> '
let [old, new] = split(filename,' -> ')
execute 'Gedit '.s:fnameescape(':0:'.new)
return a:diff.' HEAD:'.s:fnameescape(old)
elseif section ==# 'staged'
execute 'Gedit '.s:fnameescape(':0:'.filename)
return a:diff.' -'
else
execute 'Gedit '.s:fnameescape('/'.filename)
return a:diff
endif
endfunction
function! s:StageDiffEdit() abort
let [filename, section] = s:stage_info(line('.'))
let arg = (filename ==# '' ? '.' : filename)
if section ==# 'staged'
return 'Git! diff --no-ext-diff --cached '.s:shellesc(arg)
elseif section ==# 'untracked'
let repo = s:repo()
call repo.git_chomp_in_tree('add','--intent-to-add',arg)
if arg ==# '.'
silent! edit!
1
if !search('^# .*:\n#.*\n# .*"git checkout \|^# Changes not staged for commit:$','W')
call search('^# .*:$','W')
endif
else
call s:StageReloadSeek(arg,line('.'),line('.'))
endif
return ''
else
return 'Git! diff --no-ext-diff '.s:shellesc(arg)
endif
endfunction
function! s:StageToggle(lnum1,lnum2) abort
if a:lnum1 == 1 && a:lnum2 == 1
return 'Gedit /.git|call search("^index$", "wc")'
endif
try
let output = ''
for lnum in range(a:lnum1,a:lnum2)
let [filename, section] = s:stage_info(lnum)
let repo = s:repo()
if getline('.') =~# '^# .*:$'
if section ==# 'staged'
call repo.git_chomp_in_tree('reset','-q')
silent! edit!
1
if !search('^# .*:\n# .*"git add .*\n#\n\|^# Untracked files:$','W')
call search('^# .*:$','W')
endif
return ''
elseif section ==# 'unstaged'
call repo.git_chomp_in_tree('add','-u')
silent! edit!
1
if !search('^# .*:\n# .*"git add .*\n#\n\|^# Untracked files:$','W')
call search('^# .*:$','W')
endif
return ''
else
call repo.git_chomp_in_tree('add','.')
silent! edit!
1
call search('^# .*:$','W')
return ''
endif
endif
if filename ==# ''
continue
endif
execute lnum
if filename =~ ' -> '
let cmd = ['mv','--'] + reverse(split(filename,' -> '))
let filename = cmd[-1]
elseif section ==# 'staged'
let cmd = ['reset','-q','--',filename]
elseif getline(lnum) =~# '^#\tdeleted:'
let cmd = ['rm','--',filename]
elseif getline(lnum) =~# '^#\tmodified:'
let cmd = ['add','--',filename]
else
let cmd = ['add','-A','--',filename]
endif
if !exists('first_filename')
let first_filename = filename
endif
let output .= call(repo.git_chomp_in_tree,cmd,s:repo())."\n"
endfor
if exists('first_filename')
call s:StageReloadSeek(first_filename,a:lnum1,a:lnum2)
endif
echo s:sub(s:gsub(output,'\n+','\n'),'\n$','')
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
return 'checktime'
endfunction
function! s:StagePatch(lnum1,lnum2) abort
let add = []
let reset = []
for lnum in range(a:lnum1,a:lnum2)
let [filename, section] = s:stage_info(lnum)
if getline('.') =~# '^# .*:$' && section ==# 'staged'
return 'Git reset --patch'
elseif getline('.') =~# '^# .*:$' && section ==# 'unstaged'
return 'Git add --patch'
elseif getline('.') =~# '^# .*:$' && section ==# 'untracked'
return 'Git add -N .'
elseif filename ==# ''
continue
endif
if !exists('first_filename')
let first_filename = filename
endif
execute lnum
if filename =~ ' -> '
let reset += [split(filename,' -> ')[1]]
elseif section ==# 'staged'
let reset += [filename]
elseif getline(lnum) !~# '^#\tdeleted:'
let add += [filename]
endif
endfor
try
if !empty(add)
execute "Git add --patch -- ".join(map(add,'s:shellesc(v:val)'))
endif
if !empty(reset)
execute "Git reset --patch -- ".join(map(add,'s:shellesc(v:val)'))
endif
if exists('first_filename')
silent! edit!
1
redraw
call search('^#\t\%([[:alpha:] ]\+: *\)\=\V'.first_filename.'\%( ([^()[:digit:]]\+)\)\=\$','W')
endif
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
return 'checktime'
endfunction
" Section: Gcommit
call s:command("-nargs=? -complete=customlist,s:CommitComplete Gcommit :execute s:Commit(<q-args>)")
function! s:Commit(args) abort
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd()
let msgfile = s:repo().dir('COMMIT_EDITMSG')
let outfile = tempname()
let errorfile = tempname()
try
try
execute cd.s:fnameescape(s:repo().tree())
if s:winshell()
let command = ''
let old_editor = $GIT_EDITOR
let $GIT_EDITOR = 'false'
else
let command = 'env GIT_EDITOR=false '
endif
let command .= s:repo().git_command('commit').' '.a:args
if &shell =~# 'csh'
noautocmd silent execute '!('.command.' > '.outfile.') >& '.errorfile
elseif a:args =~# '\%(^\| \)-\%(-interactive\|p\|-patch\)\>'
noautocmd execute '!'.command.' 2> '.errorfile
else
noautocmd silent execute '!'.command.' > '.outfile.' 2> '.errorfile
endif
finally
execute cd.'`=dir`'
endtry
if !has('gui_running')
redraw!
endif
if !v:shell_error
if filereadable(outfile)
for line in readfile(outfile)
echo line
endfor
endif
return ''
else
let errors = readfile(errorfile)
let error = get(errors,-2,get(errors,-1,'!'))
if error =~# 'false''\=\.$'
let args = a:args
let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-[esp]|--edit|--interactive|patch|--signoff)%($| )','')
let args = s:gsub(args,'%(%(^| )-- )@<!%(^| )@<=%(-c|--reedit-message|--reuse-message|-F|--file|-m|--message)%(\s+|\=)%(''[^'']*''|"%(\\.|[^"])*"|\\.|\S)*','')
let args = s:gsub(args,'%(^| )@<=[%#]%(:\w)*','\=expand(submatch(0))')
let args = '-F '.s:shellesc(msgfile).' '.args
if args !~# '\%(^\| \)--cleanup\>'
let args = '--cleanup=strip '.args
endif
if bufname('%') == '' && line('$') == 1 && getline(1) == '' && !&mod
execute 'keepalt edit '.s:fnameescape(msgfile)
elseif s:buffer().type() ==# 'index'
execute 'keepalt edit '.s:fnameescape(msgfile)
execute (search('^#','n')+1).'wincmd+'
setlocal nopreviewwindow
else
execute 'keepalt split '.s:fnameescape(msgfile)
endif
let b:fugitive_commit_arguments = args
setlocal bufhidden=wipe filetype=gitcommit
return '1'
elseif error ==# '!'
return s:Status()
else
call s:throw(error)
endif
endif
catch /^fugitive:/
return 'echoerr v:errmsg'
finally
if exists('old_editor')
let $GIT_EDITOR = old_editor
endif
call delete(outfile)
call delete(errorfile)
call fugitive#reload_status()
endtry
endfunction
function! s:CommitComplete(A,L,P) abort
if a:A =~ '^-' || type(a:A) == type(0) " a:A is 0 on :Gcommit -<Tab>
let args = ['-C', '-F', '-a', '-c', '-e', '-i', '-m', '-n', '-o', '-q', '-s', '-t', '-u', '-v', '--all', '--allow-empty', '--amend', '--author=', '--cleanup=', '--dry-run', '--edit', '--file=', '--include', '--interactive', '--message=', '--no-verify', '--only', '--quiet', '--reedit-message=', '--reuse-message=', '--signoff', '--template=', '--untracked-files', '--verbose']
return filter(args,'v:val[0 : strlen(a:A)-1] ==# a:A')
else
return s:repo().superglob(a:A)
endif
endfunction
function! s:FinishCommit() abort
let args = getbufvar(+expand('<abuf>'),'fugitive_commit_arguments')
if !empty(args)
call setbufvar(+expand('<abuf>'),'fugitive_commit_arguments','')
return s:Commit(args)
endif
return ''
endfunction
" Section: Ggrep, Glog
if !exists('g:fugitive_summary_format')
let g:fugitive_summary_format = '%s'
endif
call s:command("-bang -nargs=? -complete=customlist,s:EditComplete Ggrep :execute s:Grep('grep',<bang>0,<q-args>)")
call s:command("-bang -nargs=? -complete=customlist,s:EditComplete Glgrep :execute s:Grep('lgrep',<bang>0,<q-args>)")
call s:command("-bar -bang -nargs=* -range=0 -complete=customlist,s:EditComplete Glog :call s:Log('grep<bang>',<count>,<f-args>)")
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditComplete Gllog :call s:Log('lgrep<bang>',<count>,<f-args>)")
function! s:Grep(cmd,bang,arg) abort
let grepprg = &grepprg
let grepformat = &grepformat
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd()
try
execute cd.'`=s:repo().tree()`'
let &grepprg = s:repo().git_command('--no-pager', 'grep', '-n')
let &grepformat = '%f:%l:%m'
exe a:cmd.'! '.escape(matchstr(a:arg,'\v\C.{-}%($|[''" ]\@=\|)@='),'|')
let list = a:cmd =~# '^l' ? getloclist(0) : getqflist()
for entry in list
if bufname(entry.bufnr) =~ ':'
let entry.filename = s:repo().translate(bufname(entry.bufnr))
unlet! entry.bufnr
let changed = 1
elseif a:arg =~# '\%(^\| \)--cached\>'
let entry.filename = s:repo().translate(':0:'.bufname(entry.bufnr))
unlet! entry.bufnr
let changed = 1
endif
endfor
if a:cmd =~# '^l' && exists('changed')
call setloclist(0, list, 'r')
elseif exists('changed')
call setqflist(list, 'r')
endif
if !a:bang && !empty(list)
return (a:cmd =~# '^l' ? 'l' : 'c').'first'.matchstr(a:arg,'\v\C[''" ]\zs\|.*')
else
return matchstr(a:arg,'\v\C[''" ]\|\zs.*')
endif
finally
let &grepprg = grepprg
let &grepformat = grepformat
execute cd.'`=dir`'
endtry
endfunction
function! s:Log(cmd, count, ...) abort
let path = s:buffer().path('/')
if path =~# '^/\.git\%(/\|$\)' || index(a:000,'--') != -1
let path = ''
endif
let cmd = ['--no-pager', 'log', '--no-color']
let cmd += ['--pretty=format:fugitive://'.s:repo().dir().'//%H'.path.':'.(a:count ? a:count : '').'::'.g:fugitive_summary_format]
if empty(filter(a:000[0 : index(a:000,'--')],'v:val !~# "^-"'))
if s:buffer().commit() =~# '\x\{40\}'
let cmd += [s:buffer().commit()]
elseif s:buffer().path() =~# '^\.git/refs/\|^\.git/.*HEAD$'
let cmd += [s:buffer().path()[5:-1]]
endif
end
let cmd += map(copy(a:000),'s:sub(v:val,"^\\%(%(:\\w)*)","\\=fnamemodify(s:buffer().path(),submatch(1))")')
if path =~# '/.'
let cmd += ['--',path[1:-1]]
endif
let grepformat = &grepformat
let grepprg = &grepprg
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd()
try
execute cd.'`=s:repo().tree()`'
let &grepprg = escape(call(s:repo().git_command,cmd,s:repo()),'%#')
let &grepformat = '%f:%l::%m,%f:::%m'
exe a:cmd
finally
let &grepformat = grepformat
let &grepprg = grepprg
execute cd.'`=dir`'
endtry
endfunction
" Section: Gedit, Gpedit, Gsplit, Gvsplit, Gtabedit, Gread
function! s:Edit(cmd,bang,...) abort
let buffer = s:buffer()
if a:cmd !~# 'read'
if &previewwindow && getbufvar('','fugitive_type') ==# 'index'
wincmd p
if &diff
let mywinnr = winnr()
for winnr in range(winnr('$'),1,-1)
if winnr != mywinnr && getwinvar(winnr,'&diff')
execute winnr.'wincmd w'
close
if winnr('$') > 1
wincmd p
endif
endif
endfor
endif
endif
endif
if a:bang
let arglist = map(copy(a:000), 's:gsub(v:val, ''\\@<!%(\\\\)*\zs[%#]'', ''\=s:buffer().expand(submatch(0))'')')
let args = join(arglist, ' ')
if a:cmd =~# 'read'
let git = buffer.repo().git_command()
let last = line('$')
silent call s:ExecuteInTree((a:cmd ==# 'read' ? '$read' : a:cmd).'!'.git.' --no-pager '.args)
if a:cmd ==# 'read'
silent execute '1,'.last.'delete_'
endif
call fugitive#reload_status()
diffupdate
return 'redraw|echo '.string(':!'.git.' '.args)
else
let temp = resolve(tempname())
let s:temp_files[tolower(temp)] = { 'dir': buffer.repo().dir(), 'args': arglist }
silent execute a:cmd.' '.temp
if a:cmd =~# 'pedit'
wincmd P
endif
let echo = s:Edit('read',1,args)
silent write!
setlocal buftype=nowrite nomodified filetype=git foldmarker=<<<<<<<,>>>>>>>
if getline(1) !~# '^diff '
setlocal readonly nomodifiable
endif
if a:cmd =~# 'pedit'
wincmd p
endif
return echo
endif
return ''
endif
if a:0 && a:1 == ''
return ''
elseif a:0
let file = buffer.expand(join(a:000, ' '))
elseif expand('%') ==# ''
let file = ':'
elseif buffer.commit() ==# '' && buffer.path('/') !~# '^/.git\>'
let file = buffer.path(':')
else
let file = buffer.path('/')
endif
try
let file = buffer.repo().translate(file)
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
if a:cmd ==# 'read'
return 'silent %delete_|read '.s:fnameescape(file).'|silent 1delete_|diffupdate|'.line('.')
else
return a:cmd.' '.s:fnameescape(file)
endif
endfunction
function! s:EditComplete(A,L,P) abort
return map(s:repo().superglob(a:A), 'fnameescape(v:val)')
endfunction
function! s:EditRunComplete(A,L,P) abort
if a:L =~# '^\w\+!'
return s:GitComplete(a:A,a:L,a:P)
else
return s:repo().superglob(a:A)
endif
endfunction
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditComplete Ge :execute s:Edit('edit<bang>',0,<f-args>)")
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditComplete Gedit :execute s:Edit('edit<bang>',0,<f-args>)")
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditRunComplete Gpedit :execute s:Edit('pedit',<bang>0,<f-args>)")
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditRunComplete Gsplit :execute s:Edit('split',<bang>0,<f-args>)")
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditRunComplete Gvsplit :execute s:Edit('vsplit',<bang>0,<f-args>)")
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditRunComplete Gtabedit :execute s:Edit('tabedit',<bang>0,<f-args>)")
call s:command("-bar -bang -nargs=* -count -complete=customlist,s:EditRunComplete Gread :execute s:Edit((!<count> && <line1> ? '' : <count>).'read',<bang>0,<f-args>)")
" Section: Gwrite, Gwq
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditComplete Gwrite :execute s:Write(<bang>0,<f-args>)")
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditComplete Gw :execute s:Write(<bang>0,<f-args>)")
call s:command("-bar -bang -nargs=* -complete=customlist,s:EditComplete Gwq :execute s:Wq(<bang>0,<f-args>)")
function! s:Write(force,...) abort
if exists('b:fugitive_commit_arguments')
return 'write|bdelete'
elseif expand('%:t') == 'COMMIT_EDITMSG' && $GIT_INDEX_FILE != ''
return 'wq'
elseif s:buffer().type() == 'index'
return 'Gcommit'
elseif s:buffer().path() ==# '' && getline(4) =~# '^+++ '
let filename = getline(4)[6:-1]
setlocal buftype=
silent write
setlocal buftype=nowrite
if matchstr(getline(2),'index [[:xdigit:]]\+\.\.\zs[[:xdigit:]]\{7\}') ==# s:repo().rev_parse(':0:'.filename)[0:6]
let err = s:repo().git_chomp('apply','--cached','--reverse',s:buffer().spec())
else
let err = s:repo().git_chomp('apply','--cached',s:buffer().spec())
endif
if err !=# ''
let v:errmsg = split(err,"\n")[0]
return 'echoerr v:errmsg'
elseif a:force
return 'bdelete'
else
return 'Gedit '.fnameescape(filename)
endif
endif
let mytab = tabpagenr()
let mybufnr = bufnr('')
let path = a:0 ? join(a:000, ' ') : s:buffer().path()
if path =~# '^:\d\>'
return 'write'.(a:force ? '! ' : ' ').s:fnameescape(s:repo().translate(s:buffer().expand(path)))
endif
let always_permitted = (s:buffer().path() ==# path && s:buffer().commit() =~# '^0\=$')
if !always_permitted && !a:force && s:repo().git_chomp_in_tree('diff','--name-status','HEAD','--',path) . s:repo().git_chomp_in_tree('ls-files','--others','--',path) !=# ''
let v:errmsg = 'fugitive: file has uncommitted changes (use ! to override)'
return 'echoerr v:errmsg'
endif
let file = s:repo().translate(path)
let treebufnr = 0
for nr in range(1,bufnr('$'))
if fnamemodify(bufname(nr),':p') ==# file
let treebufnr = nr
endif
endfor
if treebufnr > 0 && treebufnr != bufnr('')
let temp = tempname()
silent execute '%write '.temp
for tab in [mytab] + range(1,tabpagenr('$'))
for winnr in range(1,tabpagewinnr(tab,'$'))
if tabpagebuflist(tab)[winnr-1] == treebufnr
execute 'tabnext '.tab
if winnr != winnr()
execute winnr.'wincmd w'
let restorewinnr = 1
endif
try
let lnum = line('.')
let last = line('$')
silent execute '$read '.temp
silent execute '1,'.last.'delete_'
silent write!
silent execute lnum
let did = 1
finally
if exists('restorewinnr')
wincmd p
endif
execute 'tabnext '.mytab
endtry
endif
endfor
endfor
if !exists('did')
call writefile(readfile(temp,'b'),file,'b')
endif
else
execute 'write! '.s:fnameescape(s:repo().translate(path))
endif
if a:force
let error = s:repo().git_chomp_in_tree('add', '--force', '--', path)
else
let error = s:repo().git_chomp_in_tree('add', '--', path)
endif
if v:shell_error
let v:errmsg = 'fugitive: '.error
return 'echoerr v:errmsg'
endif
if s:buffer().path() ==# path && s:buffer().commit() =~# '^\d$'
set nomodified
endif
let one = s:repo().translate(':1:'.path)
let two = s:repo().translate(':2:'.path)
let three = s:repo().translate(':3:'.path)
for nr in range(1,bufnr('$'))
let name = fnamemodify(bufname(nr), ':p')
if bufloaded(nr) && !getbufvar(nr,'&modified') && (name ==# one || name ==# two || name ==# three)
execute nr.'bdelete'
endif
endfor
unlet! restorewinnr
let zero = s:repo().translate(':0:'.path)
for tab in range(1,tabpagenr('$'))
for winnr in range(1,tabpagewinnr(tab,'$'))
let bufnr = tabpagebuflist(tab)[winnr-1]
let bufname = fnamemodify(bufname(bufnr), ':p')
if bufname ==# zero && bufnr != mybufnr
execute 'tabnext '.tab
if winnr != winnr()
execute winnr.'wincmd w'
let restorewinnr = 1
endif
try
let lnum = line('.')
let last = line('$')
silent execute '$read '.s:fnameescape(file)
silent execute '1,'.last.'delete_'
silent execute lnum
set nomodified
diffupdate
finally
if exists('restorewinnr')
wincmd p
endif
execute 'tabnext '.mytab
endtry
break
endif
endfor
endfor
call fugitive#reload_status()
return 'checktime'
endfunction
function! s:Wq(force,...) abort
let bang = a:force ? '!' : ''
if exists('b:fugitive_commit_arguments')
return 'wq'.bang
endif
let result = call(s:function('s:Write'),[a:force]+a:000)
if result =~# '^\%(write\|wq\|echoerr\)'
return s:sub(result,'^write','wq')
else
return result.'|quit'.bang
endif
endfunction
augroup fugitive_commit
autocmd!
autocmd VimLeavePre,BufDelete COMMIT_EDITMSG execute s:sub(s:FinishCommit(), '^echoerr (.*)', 'echohl ErrorMsg|echo \1|echohl NONE')
augroup END
" Section: Gdiff
call s:command("-bang -bar -nargs=* -complete=customlist,s:EditComplete Gdiff :execute s:Diff('',<f-args>)")
call s:command("-bar -nargs=* -complete=customlist,s:EditComplete Gvdiff :execute s:Diff('keepalt vert ',<f-args>)")
call s:command("-bar -nargs=* -complete=customlist,s:EditComplete Gsdiff :execute s:Diff('keepalt ',<f-args>)")
augroup fugitive_diff
autocmd!
autocmd BufWinLeave *
\ if s:can_diffoff(+expand('<abuf>')) && s:diff_window_count() == 2 |
\ call s:diffoff_all(getbufvar(+expand('<abuf>'), 'git_dir')) |
\ endif
autocmd BufWinEnter *
\ if s:can_diffoff(+expand('<abuf>')) && s:diff_window_count() == 1 |
\ call s:diffoff() |
\ endif
augroup END
function! s:can_diffoff(buf) abort
return getwinvar(bufwinnr(a:buf), '&diff') &&
\ !empty(getbufvar(a:buf, 'git_dir')) &&
\ !empty(getwinvar(bufwinnr(a:buf), 'fugitive_diff_restore'))
endfunction
function! fugitive#can_diffoff(buf) abort
return s:can_diffoff(a:buf)
endfunction
function! s:diff_modifier(count) abort
let fdc = matchstr(&diffopt, 'foldcolumn:\zs\d\+')
if &diffopt =~# 'horizontal' && &diffopt !~# 'vertical'
return 'keepalt '
elseif &diffopt =~# 'vertical'
return 'keepalt vert '
elseif winwidth(0) <= a:count * ((&tw ? &tw : 80) + (empty(fdc) ? 2 : fdc))
return 'keepalt '
else
return 'keepalt vert '
endif
endfunction
function! s:diff_window_count() abort
let c = 0
for nr in range(1,winnr('$'))
let c += getwinvar(nr,'&diff')
endfor
return c
endfunction
function! s:diff_restore() abort
let restore = 'setlocal nodiff noscrollbind'
\ . ' scrollopt=' . &l:scrollopt
\ . (&l:wrap ? ' wrap' : ' nowrap')
\ . ' foldlevel=999'
\ . ' foldmethod=' . &l:foldmethod
\ . ' foldcolumn=' . &l:foldcolumn
\ . ' foldlevel=' . &l:foldlevel
\ . (&l:foldenable ? ' foldenable' : ' nofoldenable')
if has('cursorbind')
let restore .= (&l:cursorbind ? ' ' : ' no') . 'cursorbind'
endif
return restore
endfunction
function! s:diffthis() abort
if !&diff
let w:fugitive_diff_restore = s:diff_restore()
diffthis
endif
endfunction
function! s:diffoff() abort
if exists('w:fugitive_diff_restore')
execute w:fugitive_diff_restore
unlet w:fugitive_diff_restore
else
diffoff
endif
endfunction
function! s:diffoff_all(dir) abort
for nr in range(1,winnr('$'))
if getwinvar(nr,'&diff')
if nr != winnr()
execute nr.'wincmd w'
let restorewinnr = 1
endif
if exists('b:git_dir') && b:git_dir ==# a:dir
call s:diffoff()
endif
endif
endfor
endfunction
function! s:buffer_compare_age(commit) dict abort
let scores = {':0': 1, ':1': 2, ':2': 3, ':': 4, ':3': 5}
let my_score = get(scores,':'.self.commit(),0)
let their_score = get(scores,':'.a:commit,0)
if my_score || their_score
return my_score < their_score ? -1 : my_score != their_score
elseif self.commit() ==# a:commit
return 0
endif
let base = self.repo().git_chomp('merge-base',self.commit(),a:commit)
if base ==# self.commit()
return -1
elseif base ==# a:commit
return 1
endif
let my_time = +self.repo().git_chomp('log','--max-count=1','--pretty=format:%at',self.commit())
let their_time = +self.repo().git_chomp('log','--max-count=1','--pretty=format:%at',a:commit)
return my_time < their_time ? -1 : my_time != their_time
endfunction
call s:add_methods('buffer',['compare_age'])
function! s:Diff(vert,...) abort
let vert = empty(a:vert) ? s:diff_modifier(2) : a:vert
if exists(':DiffGitCached')
return 'DiffGitCached'
elseif (!a:0 || a:1 == ':') && s:buffer().commit() =~# '^[0-1]\=$' && s:repo().git_chomp_in_tree('ls-files', '--unmerged', '--', s:buffer().path()) !=# ''
let vert = empty(a:vert) ? s:diff_modifier(3) : a:vert
let nr = bufnr('')
execute 'leftabove '.vert.'split `=fugitive#buffer().repo().translate(s:buffer().expand('':2''))`'
execute 'nnoremap <buffer> <silent> dp :diffput '.nr.'<Bar>diffupdate<CR>'
call s:diffthis()
wincmd p
execute 'rightbelow '.vert.'split `=fugitive#buffer().repo().translate(s:buffer().expand('':3''))`'
execute 'nnoremap <buffer> <silent> dp :diffput '.nr.'<Bar>diffupdate<CR>'
call s:diffthis()
wincmd p
call s:diffthis()
return ''
elseif a:0
let arg = join(a:000, ' ')
if arg ==# ''
return ''
elseif arg ==# '/'
let file = s:buffer().path('/')
elseif arg ==# ':'
let file = s:buffer().path(':0:')
elseif arg =~# '^:/.'
try
let file = s:repo().rev_parse(arg).s:buffer().path(':')
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
else
let file = s:buffer().expand(arg)
endif
if file !~# ':' && file !~# '^/' && s:repo().git_chomp('cat-file','-t',file) =~# '^\%(tag\|commit\)$'
let file = file.s:buffer().path(':')
endif
else
let file = s:buffer().path(s:buffer().commit() == '' ? ':0:' : '/')
endif
try
let spec = s:repo().translate(file)
let commit = matchstr(spec,'\C[^:/]//\zs\x\+')
let restore = s:diff_restore()
if exists('+cursorbind')
setlocal cursorbind
endif
let w:fugitive_diff_restore = restore
if s:buffer().compare_age(commit) < 0
execute 'rightbelow '.vert.'diffsplit '.s:fnameescape(spec)
else
execute 'leftabove '.vert.'diffsplit '.s:fnameescape(spec)
endif
let w:fugitive_diff_restore = restore
let winnr = winnr()
if getwinvar('#', '&diff')
wincmd p
call feedkeys("\<C-W>p", 'n')
endif
return ''
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
endfunction
" Section: Gmove, Gremove
function! s:Move(force,destination) abort
if a:destination =~# '^/'
let destination = a:destination[1:-1]
else
let destination = s:shellslash(fnamemodify(s:sub(a:destination,'[%#]%(:\w)*','\=expand(submatch(0))'),':p'))
if destination[0:strlen(s:repo().tree())] ==# s:repo().tree('')
let destination = destination[strlen(s:repo().tree('')):-1]
endif
endif
if isdirectory(s:buffer().spec())
" Work around Vim parser idiosyncrasy
let discarded = s:buffer().setvar('&swapfile',0)
endif
let message = call(s:repo().git_chomp_in_tree,['mv']+(a:force ? ['-f'] : [])+['--', s:buffer().path(), destination], s:repo())
if v:shell_error
let v:errmsg = 'fugitive: '.message
return 'echoerr v:errmsg'
endif
let destination = s:repo().tree(destination)
if isdirectory(destination)
let destination = fnamemodify(s:sub(destination,'/$','').'/'.expand('%:t'),':.')
endif
call fugitive#reload_status()
if s:buffer().commit() == ''
if isdirectory(destination)
return 'keepalt edit '.s:fnameescape(destination)
else
return 'keepalt saveas! '.s:fnameescape(destination)
endif
else
return 'file '.s:fnameescape(s:repo().translate(':0:'.destination))
endif
endfunction
function! s:MoveComplete(A,L,P) abort
if a:A =~ '^/'
return s:repo().superglob(a:A)
else
let matches = split(glob(a:A.'*'),"\n")
call map(matches,'v:val !~ "/$" && isdirectory(v:val) ? v:val."/" : v:val')
return matches
endif
endfunction
function! s:Remove(force) abort
if s:buffer().commit() ==# ''
let cmd = ['rm']
elseif s:buffer().commit() ==# '0'
let cmd = ['rm','--cached']
else
let v:errmsg = 'fugitive: rm not supported here'
return 'echoerr v:errmsg'
endif
if a:force
let cmd += ['--force']
endif
let message = call(s:repo().git_chomp_in_tree,cmd+['--',s:buffer().path()],s:repo())
if v:shell_error
let v:errmsg = 'fugitive: '.s:sub(message,'error:.*\zs\n\(.*-f.*',' (add ! to force)')
return 'echoerr '.string(v:errmsg)
else
call fugitive#reload_status()
return 'bdelete'.(a:force ? '!' : '')
endif
endfunction
augroup fugitive_remove
autocmd!
autocmd User Fugitive if s:buffer().commit() =~# '^0\=$' |
\ exe "command! -buffer -bar -bang -nargs=1 -complete=customlist,s:MoveComplete Gmove :execute s:Move(<bang>0,<q-args>)" |
\ exe "command! -buffer -bar -bang Gremove :execute s:Remove(<bang>0)" |
\ endif
augroup END
" Section: Gblame
augroup fugitive_blame
autocmd!
autocmd BufReadPost *.fugitiveblame setfiletype fugitiveblame
autocmd FileType fugitiveblame setlocal nomodeline | if exists('b:git_dir') | let &l:keywordprg = s:repo().keywordprg() | endif
autocmd Syntax fugitiveblame call s:BlameSyntax()
autocmd User Fugitive if s:buffer().type('file', 'blob') | exe "command! -buffer -bar -bang -range=0 -nargs=* Gblame :execute s:Blame(<bang>0,<line1>,<line2>,<count>,[<f-args>])" | endif
augroup END
function! s:linechars(pattern) abort
let chars = strlen(s:gsub(matchstr(getline('.'), a:pattern), '.', '.'))
if exists('*synconcealed') && &conceallevel > 1
for col in range(1, chars)
let chars -= synconcealed(line('.'), col)[0]
endfor
endif
return chars
endfunction
function! s:Blame(bang,line1,line2,count,args) abort
try
if s:buffer().path() == ''
call s:throw('file or blob required')
endif
if filter(copy(a:args),'v:val !~# "^\\%(--root\|--show-name\\|-\\=\\%([ltfnsew]\\|[MC]\\d*\\)\\+\\)$"') != []
call s:throw('unsupported option')
endif
call map(a:args,'s:sub(v:val,"^\\ze[^-]","-")')
let cmd = ['--no-pager', 'blame', '--show-number'] + a:args
if s:buffer().commit() =~# '\D\|..'
let cmd += [s:buffer().commit()]
else
let cmd += ['--contents', '-']
endif
let cmd += ['--', s:buffer().path()]
let basecmd = escape(call(s:repo().git_command,cmd,s:repo()),'!')
try
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
if !s:repo().bare()
let dir = getcwd()
execute cd.'`=s:repo().tree()`'
endif
if a:count
execute 'write !'.substitute(basecmd,' blame ',' blame -L '.a:line1.','.a:line2.' ','g')
else
let error = resolve(tempname())
let temp = error.'.fugitiveblame'
if &shell =~# 'csh'
silent! execute '%write !('.basecmd.' > '.temp.') >& '.error
else
silent! execute '%write !'.basecmd.' > '.temp.' 2> '.error
endif
if exists('l:dir')
execute cd.'`=dir`'
unlet dir
endif
if v:shell_error
call s:throw(join(readfile(error),"\n"))
endif
for winnr in range(winnr('$'),1,-1)
call setwinvar(winnr, '&scrollbind', 0)
if getbufvar(winbufnr(winnr), 'fugitive_blamed_bufnr')
execute winbufnr(winnr).'bdelete'
endif
endfor
let bufnr = bufnr('')
let restore = 'call setwinvar(bufwinnr('.bufnr.'),"&scrollbind",0)'
if &l:wrap
let restore .= '|call setwinvar(bufwinnr('.bufnr.'),"&wrap",1)'
endif
if &l:foldenable
let restore .= '|call setwinvar(bufwinnr('.bufnr.'),"&foldenable",1)'
endif
setlocal scrollbind nowrap nofoldenable
let top = line('w0') + &scrolloff
let current = line('.')
let s:temp_files[tolower(temp)] = { 'dir': s:repo().dir(), 'args': cmd }
exe 'keepalt leftabove vsplit '.temp
let b:fugitive_blamed_bufnr = bufnr
let w:fugitive_leave = restore
let b:fugitive_blame_arguments = join(a:args,' ')
execute top
normal! zt
execute current
setlocal nomodified nomodifiable nonumber scrollbind nowrap foldcolumn=0 nofoldenable winfixwidth filetype=fugitiveblame
if exists('+concealcursor')
setlocal concealcursor=nc conceallevel=2
endif
if exists('+relativenumber')
setlocal norelativenumber
endif
execute "vertical resize ".(s:linechars('.\{-\}\ze\s\+\d\+)')+1)
nnoremap <buffer> <silent> <F1> :help fugitive-:Gblame<CR>
nnoremap <buffer> <silent> g? :help fugitive-:Gblame<CR>
nnoremap <buffer> <silent> q :exe substitute(bufwinnr(b:fugitive_blamed_bufnr).' wincmd w<Bar>'.bufnr('').'bdelete','^-1','','')<CR>
nnoremap <buffer> <silent> gq :exe substitute(bufwinnr(b:fugitive_blamed_bufnr).' wincmd w<Bar>'.bufnr('').'bdelete<Bar>if expand("%:p") =~# "^fugitive:[\\/][\\/]"<Bar>Gedit<Bar>endif','^-1','','')<CR>
nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>BlameCommit("exe 'norm q'<Bar>edit")<CR>
nnoremap <buffer> <silent> - :<C-U>exe <SID>BlameJump('')<CR>
nnoremap <buffer> <silent> P :<C-U>exe <SID>BlameJump('^'.v:count1)<CR>
nnoremap <buffer> <silent> ~ :<C-U>exe <SID>BlameJump('~'.v:count1)<CR>
nnoremap <buffer> <silent> i :<C-U>exe <SID>BlameCommit("exe 'norm q'<Bar>edit")<CR>
nnoremap <buffer> <silent> o :<C-U>exe <SID>BlameCommit((&splitbelow ? "botright" : "topleft")." split")<CR>
nnoremap <buffer> <silent> O :<C-U>exe <SID>BlameCommit("tabedit")<CR>
nnoremap <buffer> <silent> A :<C-u>exe "vertical resize ".(<SID>linechars('.\{-\}\ze [0-9:/+-][0-9:/+ -]* \d\+)')+1+v:count)<CR>
nnoremap <buffer> <silent> C :<C-u>exe "vertical resize ".(<SID>linechars('^\S\+')+1+v:count)<CR>
nnoremap <buffer> <silent> D :<C-u>exe "vertical resize ".(<SID>linechars('.\{-\}\ze\d\ze\s\+\d\+)')+1-v:count)<CR>
redraw
syncbind
endif
finally
if exists('l:dir')
execute cd.'`=dir`'
endif
endtry
return ''
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
endfunction
function! s:BlameCommit(cmd) abort
let cmd = s:Edit(a:cmd, 0, matchstr(getline('.'),'\x\+'))
if cmd =~# '^echoerr'
return cmd
endif
let lnum = matchstr(getline('.'),' \zs\d\+\ze\s\+[([:digit:]]')
let path = matchstr(getline('.'),'^\^\=\x\+\s\+\zs.\{-\}\ze\s*\d\+ ')
if path ==# ''
let path = s:buffer(b:fugitive_blamed_bufnr).path()
endif
execute cmd
if search('^diff .* b/\M'.escape(path,'\').'$','W')
call search('^+++')
let head = line('.')
while search('^@@ \|^diff ') && getline('.') =~# '^@@ '
let top = +matchstr(getline('.'),' +\zs\d\+')
let len = +matchstr(getline('.'),' +\d\+,\zs\d\+')
if lnum >= top && lnum <= top + len
let offset = lnum - top
if &scrolloff
+
normal! zt
else
normal! zt
+
endif
while offset > 0 && line('.') < line('$')
+
if getline('.') =~# '^[ +]'
let offset -= 1
endif
endwhile
return 'normal! zv'
endif
endwhile
execute head
normal! zt
endif
return ''
endfunction
function! s:BlameJump(suffix) abort
let commit = matchstr(getline('.'),'^\^\=\zs\x\+')
if commit =~# '^0\+$'
let commit = ':0'
endif
let lnum = matchstr(getline('.'),' \zs\d\+\ze\s\+[([:digit:]]')
let path = matchstr(getline('.'),'^\^\=\x\+\s\+\zs.\{-\}\ze\s*\d\+ ')
if path ==# ''
let path = s:buffer(b:fugitive_blamed_bufnr).path()
endif
let args = b:fugitive_blame_arguments
let offset = line('.') - line('w0')
let bufnr = bufnr('%')
let winnr = bufwinnr(b:fugitive_blamed_bufnr)
if winnr > 0
exe winnr.'wincmd w'
endif
execute s:Edit('edit', 0, commit.a:suffix.':'.path)
execute lnum
if winnr > 0
exe bufnr.'bdelete'
endif
execute 'Gblame '.args
execute lnum
let delta = line('.') - line('w0') - offset
if delta > 0
execute 'normal! '.delta."\<C-E>"
elseif delta < 0
execute 'normal! '.(-delta)."\<C-Y>"
endif
syncbind
return ''
endfunction
function! s:BlameSyntax() abort
let b:current_syntax = 'fugitiveblame'
let conceal = has('conceal') ? ' conceal' : ''
let arg = exists('b:fugitive_blame_arguments') ? b:fugitive_blame_arguments : ''
syn match FugitiveblameBoundary "^\^"
syn match FugitiveblameBlank "^\s\+\s\@=" nextgroup=FugitiveblameAnnotation,fugitiveblameOriginalFile,FugitiveblameOriginalLineNumber skipwhite
syn match FugitiveblameHash "\%(^\^\=\)\@<=\x\{7,40\}\>" nextgroup=FugitiveblameAnnotation,FugitiveblameOriginalLineNumber,fugitiveblameOriginalFile skipwhite
syn match FugitiveblameUncommitted "\%(^\^\=\)\@<=0\{7,40\}\>" nextgroup=FugitiveblameAnnotation,FugitiveblameOriginalLineNumber,fugitiveblameOriginalFile skipwhite
syn region FugitiveblameAnnotation matchgroup=FugitiveblameDelimiter start="(" end="\%( \d\+\)\@<=)" contained keepend oneline
syn match FugitiveblameTime "[0-9:/+-][0-9:/+ -]*[0-9:/+-]\%( \+\d\+)\)\@=" contained containedin=FugitiveblameAnnotation
exec 'syn match FugitiveblameLineNumber " *\d\+)\@=" contained containedin=FugitiveblameAnnotation'.conceal
exec 'syn match FugitiveblameOriginalFile " \%(\f\+\D\@<=\|\D\@=\f\+\)\%(\%(\s\+\d\+\)\=\s\%((\|\s*\d\+)\)\)\@=" contained nextgroup=FugitiveblameOriginalLineNumber,FugitiveblameAnnotation skipwhite'.(arg =~# 'f' ? '' : conceal)
exec 'syn match FugitiveblameOriginalLineNumber " *\d\+\%(\s(\)\@=" contained nextgroup=FugitiveblameAnnotation skipwhite'.(arg =~# 'n' ? '' : conceal)
exec 'syn match FugitiveblameOriginalLineNumber " *\d\+\%(\s\+\d\+)\)\@=" contained nextgroup=FugitiveblameShort skipwhite'.(arg =~# 'n' ? '' : conceal)
syn match FugitiveblameShort " \d\+)" contained contains=FugitiveblameLineNumber
syn match FugitiveblameNotCommittedYet "(\@<=Not Committed Yet\>" contained containedin=FugitiveblameAnnotation
hi def link FugitiveblameBoundary Keyword
hi def link FugitiveblameHash Identifier
hi def link FugitiveblameUncommitted Function
hi def link FugitiveblameTime PreProc
hi def link FugitiveblameLineNumber Number
hi def link FugitiveblameOriginalFile String
hi def link FugitiveblameOriginalLineNumber Float
hi def link FugitiveblameShort FugitiveblameDelimiter
hi def link FugitiveblameDelimiter Delimiter
hi def link FugitiveblameNotCommittedYet Comment
endfunction
" Section: Gbrowse
call s:command("-bar -bang -range -nargs=* -complete=customlist,s:EditComplete Gbrowse :execute s:Browse(<bang>0,<line1>,<count>,<f-args>)")
function! s:Browse(bang,line1,count,...) abort
try
let rev = a:0 ? substitute(join(a:000, ' '),'@[[:alnum:]_-]*\%(://.\{-\}\)\=$','','') : ''
if rev ==# ''
let expanded = s:buffer().rev()
elseif rev ==# ':'
let expanded = s:buffer().path('/')
else
let expanded = s:buffer().expand(rev)
endif
let full = s:repo().translate(expanded)
let commit = ''
if full =~# '^fugitive://'
let commit = matchstr(full,'://.*//\zs\w\+')
let path = matchstr(full,'://.*//\w\+\zs/.*')
if commit =~ '..'
let type = s:repo().git_chomp('cat-file','-t',commit.s:sub(path,'^/',':'))
else
let type = 'blob'
endif
let path = path[1:-1]
elseif s:repo().bare()
let path = '.git/' . full[strlen(s:repo().dir())+1:-1]
let type = ''
else
let path = full[strlen(s:repo().tree())+1:-1]
if path =~# '^\.git/'
let type = ''
elseif isdirectory(full)
let type = 'tree'
else
let type = 'blob'
endif
endif
if path =~# '^\.git/.*HEAD' && filereadable(s:repo().dir(path[5:-1]))
let body = readfile(s:repo().dir(path[5:-1]))[0]
if body =~# '^\x\{40\}$'
let commit = body
let type = 'commit'
let path = ''
elseif body =~# '^ref: refs/'
let path = '.git/' . matchstr(body,'ref: \zs.*')
endif
endif
if a:0 && join(a:000, ' ') =~# '@[[:alnum:]_-]*\%(://.\{-\}\)\=$'
let remote = matchstr(join(a:000, ' '),'@\zs[[:alnum:]_-]\+\%(://.\{-\}\)\=$')
elseif path =~# '^\.git/refs/remotes/.'
let remote = matchstr(path,'^\.git/refs/remotes/\zs[^/]\+')
else
let remote = 'origin'
let branch = matchstr(rev,'^[[:alnum:]/._-]\+\ze[:^~@]')
if branch ==# '' && path =~# '^\.git/refs/\w\+/'
let branch = s:sub(path,'^\.git/refs/\w+/','')
endif
if filereadable(s:repo().dir('refs/remotes/'.branch))
let remote = matchstr(branch,'[^/]\+')
let rev = rev[strlen(remote)+1:-1]
else
if branch ==# ''
let branch = matchstr(s:repo().head_ref(),'\<refs/heads/\zs.*')
endif
if branch != ''
let remote = s:repo().git_chomp('config','branch.'.branch.'.remote')
if remote =~# '^\.\=$'
let remote = 'origin'
elseif rev[0:strlen(branch)-1] ==# branch && rev[strlen(branch)] =~# '[:^~@]'
let rev = s:repo().git_chomp('config','branch.'.branch.'.merge')[11:-1] . rev[strlen(branch):-1]
endif
endif
endif
endif
let raw = s:repo().git_chomp('config','remote.'.remote.'.url')
if raw ==# ''
let raw = remote
endif
let url = s:github_url(s:repo(),raw,rev,commit,path,type,a:line1,a:count)
if url == ''
let url = s:instaweb_url(s:repo(),rev,commit,path,type,a:count > 0 ? a:line1 : 0)
endif
if url == ''
call s:throw("Instaweb failed to start and '".remote."' is not a GitHub remote")
endif
if a:bang
let @* = url
return 'echomsg '.string(url)
else
return 'echomsg '.string(url).'|call netrw#NetrwBrowseX('.string(url).', 0)'
endif
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
endfunction
function! s:github_url(repo,url,rev,commit,path,type,line1,line2) abort
let path = a:path
let domain_pattern = 'github\.com'
let domains = exists('g:fugitive_github_domains') ? g:fugitive_github_domains : []
for domain in domains
let domain_pattern .= '\|' . escape(split(domain, '://')[-1], '.')
endfor
let repo = matchstr(a:url,'^\%(https\=://\|git://\|git@\)\=\zs\('.domain_pattern.'\)[/:].\{-\}\ze\%(\.git\)\=$')
if repo ==# ''
return ''
endif
if index(domains, 'http://' . matchstr(repo, '^[^:/]*')) >= 0
let root = 'http://' . s:sub(repo,':','/')
else
let root = 'https://' . s:sub(repo,':','/')
endif
if path =~# '^\.git/refs/heads/'
let branch = a:repo.git_chomp('config','branch.'.path[16:-1].'.merge')[11:-1]
if branch ==# ''
return root . '/commits/' . path[16:-1]
else
return root . '/commits/' . branch
endif
elseif path =~# '^\.git/refs/.'
return root . '/commits/' . matchstr(path,'[^/]\+$')
elseif path =~# '.git/\%(config$\|hooks\>\)'
return root . '/admin'
elseif path =~# '^\.git\>'
return root
endif
if a:rev =~# '^[[:alnum:]._-]\+:'
let commit = matchstr(a:rev,'^[^:]*')
elseif a:commit =~# '^\d\=$'
let local = matchstr(a:repo.head_ref(),'\<refs/heads/\zs.*')
let commit = a:repo.git_chomp('config','branch.'.local.'.merge')[11:-1]
if commit ==# ''
let commit = local
endif
else
let commit = a:commit
endif
if a:type == 'tree'
let url = s:sub(root . '/tree/' . commit . '/' . path,'/$','')
elseif a:type == 'blob'
let url = root . '/blob/' . commit . '/' . path
if a:line2 > 0 && a:line1 == a:line2
let url .= '#L' . a:line1
elseif a:line2 > 0
let url .= '#L' . a:line1 . '-' . a:line2
endif
elseif a:type == 'tag'
let commit = matchstr(getline(3),'^tag \zs.*')
let url = root . '/tree/' . commit
else
let url = root . '/commit/' . commit
endif
return url
endfunction
function! s:instaweb_url(repo,rev,commit,path,type,...) abort
let output = a:repo.git_chomp('instaweb','-b','unknown')
if output =~# 'http://'
let root = matchstr(output,'http://.*').'/?p='.fnamemodify(a:repo.dir(),':t')
else
return ''
endif
if a:path =~# '^\.git/refs/.'
return root . ';a=shortlog;h=' . matchstr(a:path,'^\.git/\zs.*')
elseif a:path =~# '^\.git\>'
return root
endif
let url = root
if a:commit =~# '^\x\{40\}$'
if a:type ==# 'commit'
let url .= ';a=commit'
endif
let url .= ';h=' . a:repo.rev_parse(a:commit . (a:path == '' ? '' : ':' . a:path))
else
if a:type ==# 'blob'
let tmp = tempname()
silent execute 'write !'.a:repo.git_command('hash-object','-w','--stdin').' > '.tmp
let url .= ';h=' . readfile(tmp)[0]
else
try
let url .= ';h=' . a:repo.rev_parse((a:commit == '' ? 'HEAD' : ':' . a:commit) . ':' . a:path)
catch /^fugitive:/
call s:throw('fugitive: cannot browse uncommitted file')
endtry
endif
let root .= ';hb=' . matchstr(a:repo.head_ref(),'[^ ]\+$')
endif
if a:path !=# ''
let url .= ';f=' . a:path
endif
if a:0 && a:1
let url .= '#l' . a:1
endif
return url
endfunction
" Section: File access
function! s:ReplaceCmd(cmd,...) abort
let fn = expand('%:p')
let tmp = tempname()
let prefix = ''
try
if a:0 && a:1 != ''
if s:winshell()
let old_index = $GIT_INDEX_FILE
let $GIT_INDEX_FILE = a:1
else
let prefix = 'env GIT_INDEX_FILE='.s:shellesc(a:1).' '
endif
endif
if s:winshell()
let cmd_escape_char = &shellxquote == '(' ? '^' : '^^^'
call system('cmd /c "'.prefix.s:gsub(a:cmd,'[<>]', cmd_escape_char.'&').' > '.tmp.'"')
else
call system(' ('.prefix.a:cmd.' > '.tmp.') ')
endif
finally
if exists('old_index')
let $GIT_INDEX_FILE = old_index
endif
endtry
silent exe 'keepalt file '.tmp
try
silent edit!
finally
try
silent exe 'keepalt file '.s:fnameescape(fn)
catch /^Vim\%((\a\+)\)\=:E302/
endtry
call delete(tmp)
if fnamemodify(bufname('$'), ':p') ==# tmp
silent execute 'bwipeout '.bufnr('$')
endif
silent exe 'doau BufReadPost '.s:fnameescape(fn)
endtry
endfunction
function! s:BufReadIndex() abort
if !exists('b:fugitive_display_format')
let b:fugitive_display_format = filereadable(expand('%').'.lock')
endif
let b:fugitive_display_format = b:fugitive_display_format % 2
let b:fugitive_type = 'index'
try
let b:git_dir = s:repo().dir()
setlocal noro ma nomodeline
if fnamemodify($GIT_INDEX_FILE !=# '' ? $GIT_INDEX_FILE : b:git_dir . '/index', ':p') ==# expand('%:p')
let index = ''
else
let index = expand('%:p')
endif
if b:fugitive_display_format
call s:ReplaceCmd(s:repo().git_command('ls-files','--stage'),index)
set ft=git nospell
else
let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
let dir = getcwd()
if fugitive#git_version() =~# '^0\|^1\.[1-7]\.'
let cmd = s:repo().git_command('status')
else
let cmd = s:repo().git_command(
\ '-c', 'status.displayCommentPrefix=true',
\ '-c', 'color.status=false',
\ '-c', 'status.short=false',
\ 'status')
endif
try
execute cd.'`=s:repo().tree()`'
call s:ReplaceCmd(cmd, index)
finally
execute cd.'`=dir`'
endtry
set ft=gitcommit
set foldtext=fugitive#foldtext()
endif
setlocal ro noma nomod noswapfile
if &bufhidden ==# ''
setlocal bufhidden=delete
endif
call s:JumpInit()
nunmap <buffer> P
nunmap <buffer> ~
nnoremap <buffer> <silent> <C-N> :<C-U>execute <SID>StageNext(v:count1)<CR>
nnoremap <buffer> <silent> <C-P> :<C-U>execute <SID>StagePrevious(v:count1)<CR>
nnoremap <buffer> <silent> - :<C-U>silent execute <SID>StageToggle(line('.'),line('.')+v:count1-1)<CR>
xnoremap <buffer> <silent> - :<C-U>silent execute <SID>StageToggle(line("'<"),line("'>"))<CR>
nnoremap <buffer> <silent> a :<C-U>let b:fugitive_display_format += 1<Bar>exe <SID>BufReadIndex()<CR>
nnoremap <buffer> <silent> i :<C-U>let b:fugitive_display_format -= 1<Bar>exe <SID>BufReadIndex()<CR>
nnoremap <buffer> <silent> C :<C-U>Gcommit<CR>
nnoremap <buffer> <silent> cA :<C-U>Gcommit --amend --reuse-message=HEAD<CR>
nnoremap <buffer> <silent> ca :<C-U>Gcommit --amend<CR>
nnoremap <buffer> <silent> cc :<C-U>Gcommit<CR>
nnoremap <buffer> <silent> cva :<C-U>Gcommit --amend --verbose<CR>
nnoremap <buffer> <silent> cvc :<C-U>Gcommit --verbose<CR>
nnoremap <buffer> <silent> D :<C-U>execute <SID>StageDiff('Gdiff')<CR>
nnoremap <buffer> <silent> dd :<C-U>execute <SID>StageDiff('Gdiff')<CR>
nnoremap <buffer> <silent> dh :<C-U>execute <SID>StageDiff('Gsdiff')<CR>
nnoremap <buffer> <silent> ds :<C-U>execute <SID>StageDiff('Gsdiff')<CR>
nnoremap <buffer> <silent> dp :<C-U>execute <SID>StageDiffEdit()<CR>
nnoremap <buffer> <silent> dv :<C-U>execute <SID>StageDiff('Gvdiff')<CR>
nnoremap <buffer> <silent> p :<C-U>execute <SID>StagePatch(line('.'),line('.')+v:count1-1)<CR>
xnoremap <buffer> <silent> p :<C-U>execute <SID>StagePatch(line("'<"),line("'>"))<CR>
nnoremap <buffer> <silent> q :<C-U>if bufnr('$') == 1<Bar>quit<Bar>else<Bar>bdelete<Bar>endif<CR>
nnoremap <buffer> <silent> r :<C-U>edit<CR>
nnoremap <buffer> <silent> R :<C-U>edit<CR>
nnoremap <buffer> <silent> U :<C-U>execute <SID>StageUndo()<CR>
nnoremap <buffer> <silent> g? :help fugitive-:Gstatus<CR>
nnoremap <buffer> <silent> <F1> :help fugitive-:Gstatus<CR>
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
endfunction
function! s:FileRead() abort
try
let repo = s:repo(fugitive#extract_git_dir(expand('<amatch>')))
let path = s:sub(s:sub(matchstr(expand('<amatch>'),'fugitive://.\{-\}//\zs.*'),'/',':'),'^\d:',':&')
let hash = repo.rev_parse(path)
if path =~ '^:'
let type = 'blob'
else
let type = repo.git_chomp('cat-file','-t',hash)
endif
" TODO: use count, if possible
return "read !".escape(repo.git_command('cat-file',type,hash),'%#\')
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
endfunction
function! s:BufReadIndexFile() abort
try
let b:fugitive_type = 'blob'
let b:git_dir = s:repo().dir()
try
call s:ReplaceCmd(s:repo().git_command('cat-file','blob',s:buffer().sha1()))
finally
if &bufhidden ==# ''
setlocal bufhidden=delete
endif
setlocal noswapfile
endtry
return ''
catch /^fugitive: rev-parse/
silent exe 'doau BufNewFile '.s:fnameescape(expand('%:p'))
return ''
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
endfunction
function! s:BufWriteIndexFile() abort
let tmp = tempname()
try
let path = matchstr(expand('<amatch>'),'//\d/\zs.*')
let stage = matchstr(expand('<amatch>'),'//\zs\d')
silent execute 'write !'.s:repo().git_command('hash-object','-w','--stdin').' > '.tmp
let sha1 = readfile(tmp)[0]
let old_mode = matchstr(s:repo().git_chomp('ls-files','--stage',path),'^\d\+')
if old_mode == ''
let old_mode = executable(s:repo().tree(path)) ? '100755' : '100644'
endif
let info = old_mode.' '.sha1.' '.stage."\t".path
call writefile([info],tmp)
if s:winshell()
let error = system('type '.s:gsub(tmp,'/','\\').'|'.s:repo().git_command('update-index','--index-info'))
else
let error = system(s:repo().git_command('update-index','--index-info').' < '.tmp)
endif
if v:shell_error == 0
setlocal nomodified
silent execute 'doautocmd BufWritePost '.s:fnameescape(expand('%:p'))
call fugitive#reload_status()
return ''
else
return 'echoerr '.string('fugitive: '.error)
endif
finally
call delete(tmp)
endtry
endfunction
function! s:BufReadObject() abort
try
setlocal noro ma
let b:git_dir = s:repo().dir()
let hash = s:buffer().sha1()
if !exists("b:fugitive_type")
let b:fugitive_type = s:repo().git_chomp('cat-file','-t',hash)
endif
if b:fugitive_type !~# '^\%(tag\|commit\|tree\|blob\)$'
return "echoerr 'fugitive: unrecognized git type'"
endif
let firstline = getline('.')
if !exists('b:fugitive_display_format') && b:fugitive_type != 'blob'
let b:fugitive_display_format = +getbufvar('#','fugitive_display_format')
endif
if b:fugitive_type !=# 'blob'
setlocal nomodeline
endif
let pos = getpos('.')
silent keepjumps %delete_
setlocal endofline
try
if b:fugitive_type ==# 'tree'
let b:fugitive_display_format = b:fugitive_display_format % 2
if b:fugitive_display_format
call s:ReplaceCmd(s:repo().git_command('ls-tree',hash))
else
call s:ReplaceCmd(s:repo().git_command('show','--no-color',hash))
endif
elseif b:fugitive_type ==# 'tag'
let b:fugitive_display_format = b:fugitive_display_format % 2
if b:fugitive_display_format
call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash))
else
call s:ReplaceCmd(s:repo().git_command('cat-file','-p',hash))
endif
elseif b:fugitive_type ==# 'commit'
let b:fugitive_display_format = b:fugitive_display_format % 2
if b:fugitive_display_format
call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash))
else
call s:ReplaceCmd(s:repo().git_command('show','--no-color','--pretty=format:tree %T%nparent %P%nauthor %an <%ae> %ad%ncommitter %cn <%ce> %cd%nencoding %e%n%n%s%n%n%b',hash))
keepjumps call search('^parent ')
if getline('.') ==# 'parent '
silent keepjumps delete_
else
silent keepjumps s/\%(^parent\)\@<! /\rparent /ge
endif
keepjumps let lnum = search('^encoding \%(<unknown>\)\=$','W',line('.')+3)
if lnum
silent keepjumps delete_
end
keepjumps 1
endif
elseif b:fugitive_type ==# 'blob'
call s:ReplaceCmd(s:repo().git_command('cat-file',b:fugitive_type,hash))
setlocal nomodeline
endif
finally
keepjumps call setpos('.',pos)
setlocal ro noma nomod noswapfile
if &bufhidden ==# ''
setlocal bufhidden=delete
endif
if b:fugitive_type !=# 'blob'
setlocal filetype=git foldmethod=syntax
nnoremap <buffer> <silent> a :<C-U>let b:fugitive_display_format += v:count1<Bar>exe <SID>BufReadObject()<CR>
nnoremap <buffer> <silent> i :<C-U>let b:fugitive_display_format -= v:count1<Bar>exe <SID>BufReadObject()<CR>
else
call s:JumpInit()
endif
endtry
return ''
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
endfunction
augroup fugitive_files
autocmd!
autocmd BufReadCmd index{,.lock}
\ if fugitive#is_git_dir(expand('<amatch>:p:h')) |
\ exe s:BufReadIndex() |
\ elseif filereadable(expand('<amatch>')) |
\ read <amatch> |
\ 1delete |
\ endif
autocmd FileReadCmd fugitive://**//[0-3]/** exe s:FileRead()
autocmd BufReadCmd fugitive://**//[0-3]/** exe s:BufReadIndexFile()
autocmd BufWriteCmd fugitive://**//[0-3]/** exe s:BufWriteIndexFile()
autocmd BufReadCmd fugitive://**//[0-9a-f][0-9a-f]* exe s:BufReadObject()
autocmd FileReadCmd fugitive://**//[0-9a-f][0-9a-f]* exe s:FileRead()
autocmd FileType git
\ if exists('b:git_dir') |
\ call s:JumpInit() |
\ endif
augroup END
" Section: Temp files
if !exists('s:temp_files')
let s:temp_files = {}
endif
augroup fugitive_temp
autocmd!
autocmd BufNewFile,BufReadPost *
\ if has_key(s:temp_files,tolower(expand('<afile>:p'))) |
\ let b:git_dir = s:temp_files[tolower(expand('<afile>:p'))].dir |
\ let b:git_type = 'temp' |
\ let b:git_args = s:temp_files[tolower(expand('<afile>:p'))].args |
\ call fugitive#detect(expand('<afile>:p')) |
\ setlocal bufhidden=delete |
\ nnoremap <buffer> <silent> q :<C-U>bdelete<CR>|
\ endif
augroup END
" Section: Go to file
function! s:JumpInit() abort
nnoremap <buffer> <silent> <CR> :<C-U>exe <SID>GF("edit")<CR>
if !&modifiable
nnoremap <buffer> <silent> o :<C-U>exe <SID>GF("split")<CR>
nnoremap <buffer> <silent> S :<C-U>exe <SID>GF("vsplit")<CR>
nnoremap <buffer> <silent> O :<C-U>exe <SID>GF("tabedit")<CR>
nnoremap <buffer> <silent> - :<C-U>exe <SID>Edit('edit',0,<SID>buffer().up(v:count1))<Bar> if fugitive#buffer().type('tree')<Bar>call search('^'.escape(expand('#:t'),'.*[]~\').'/\=$','wc')<Bar>endif<CR>
nnoremap <buffer> <silent> P :<C-U>exe <SID>Edit('edit',0,<SID>buffer().commit().'^'.v:count1.<SID>buffer().path(':'))<CR>
nnoremap <buffer> <silent> ~ :<C-U>exe <SID>Edit('edit',0,<SID>buffer().commit().'~'.v:count1.<SID>buffer().path(':'))<CR>
nnoremap <buffer> <silent> C :<C-U>exe <SID>Edit('edit',0,<SID>buffer().containing_commit())<CR>
nnoremap <buffer> <silent> cc :<C-U>exe <SID>Edit('edit',0,<SID>buffer().containing_commit())<CR>
nnoremap <buffer> <silent> co :<C-U>exe <SID>Edit('split',0,<SID>buffer().containing_commit())<CR>
nnoremap <buffer> <silent> cS :<C-U>exe <SID>Edit('vsplit',0,<SID>buffer().containing_commit())<CR>
nnoremap <buffer> <silent> cO :<C-U>exe <SID>Edit('tabedit',0,<SID>buffer().containing_commit())<CR>
nnoremap <buffer> <silent> cP :<C-U>exe <SID>Edit('pedit',0,<SID>buffer().containing_commit())<CR>
nnoremap <buffer> . : <C-R>=fnameescape(<SID>recall())<CR><Home>
endif
endfunction
function! s:GF(mode) abort
try
let buffer = s:buffer()
let myhash = buffer.sha1()
if myhash ==# '' && getline(1) =~# '^\%(commit\|tag\) \w'
let myhash = matchstr(getline(1),'^\w\+ \zs\S\+')
endif
if buffer.type('tree')
let showtree = (getline(1) =~# '^tree ' && getline(2) == "")
if showtree && line('.') == 1
return ""
elseif showtree && line('.') > 2
return s:Edit(a:mode,0,buffer.commit().':'.s:buffer().path().(buffer.path() =~# '^$\|/$' ? '' : '/').s:sub(getline('.'),'/$',''))
elseif getline('.') =~# '^\d\{6\} \l\{3,8\} \x\{40\}\t'
return s:Edit(a:mode,0,buffer.commit().':'.s:buffer().path().(buffer.path() =~# '^$\|/$' ? '' : '/').s:sub(matchstr(getline('.'),'\t\zs.*'),'/$',''))
endif
elseif buffer.type('blob')
let ref = expand("<cfile>")
try
let sha1 = buffer.repo().rev_parse(ref)
catch /^fugitive:/
endtry
if exists('sha1')
return s:Edit(a:mode,0,ref)
endif
else
" Index
if getline('.') =~# '^\d\{6\} \x\{40\} \d\t'
let ref = matchstr(getline('.'),'\x\{40\}')
let file = ':'.s:sub(matchstr(getline('.'),'\d\t.*'),'\t',':')
return s:Edit(a:mode,0,file)
elseif getline('.') =~# '^#\trenamed:.* -> '
let file = '/'.matchstr(getline('.'),' -> \zs.*')
return s:Edit(a:mode,0,file)
elseif getline('.') =~# '^#\t[[:alpha:] ]\+: *.'
let file = '/'.matchstr(getline('.'),': *\zs.\{-\}\ze\%( ([^()[:digit:]]\+)\)\=$')
return s:Edit(a:mode,0,file)
elseif getline('.') =~# '^#\t.'
let file = '/'.matchstr(getline('.'),'#\t\zs.*')
return s:Edit(a:mode,0,file)
elseif getline('.') =~# ': needs merge$'
let file = '/'.matchstr(getline('.'),'.*\ze: needs merge$')
return s:Edit(a:mode,0,file).'|Gdiff'
elseif getline('.') ==# '# Not currently on any branch.'
return s:Edit(a:mode,0,'HEAD')
elseif getline('.') =~# '^# On branch '
let file = 'refs/heads/'.getline('.')[12:]
return s:Edit(a:mode,0,file)
elseif getline('.') =~# "^# Your branch .*'"
let file = matchstr(getline('.'),"'\\zs\\S\\+\\ze'")
return s:Edit(a:mode,0,file)
endif
let showtree = (getline(1) =~# '^tree ' && getline(2) == "")
if getline('.') =~# '^ref: '
let ref = strpart(getline('.'),5)
elseif getline('.') =~# '^commit \x\{40\}\>'
let ref = matchstr(getline('.'),'\x\{40\}')
return s:Edit(a:mode,0,ref)
elseif getline('.') =~# '^parent \x\{40\}\>'
let ref = matchstr(getline('.'),'\x\{40\}')
let line = line('.')
let parent = 0
while getline(line) =~# '^parent '
let parent += 1
let line -= 1
endwhile
return s:Edit(a:mode,0,ref)
elseif getline('.') =~ '^tree \x\{40\}$'
let ref = matchstr(getline('.'),'\x\{40\}')
if s:repo().rev_parse(myhash.':') == ref
let ref = myhash.':'
endif
return s:Edit(a:mode,0,ref)
elseif getline('.') =~# '^object \x\{40\}$' && getline(line('.')+1) =~ '^type \%(commit\|tree\|blob\)$'
let ref = matchstr(getline('.'),'\x\{40\}')
let type = matchstr(getline(line('.')+1),'type \zs.*')
elseif getline('.') =~# '^\l\{3,8\} '.myhash.'$'
return ''
elseif getline('.') =~# '^\l\{3,8\} \x\{40\}\>'
let ref = matchstr(getline('.'),'\x\{40\}')
echoerr "warning: unknown context ".matchstr(getline('.'),'^\l*')
elseif getline('.') =~# '^[+-]\{3\} [ab/]'
let ref = getline('.')[4:]
elseif getline('.') =~# '^[+-]' && search('^@@ -\d\+,\d\+ +\d\+,','bnW')
let type = getline('.')[0]
let lnum = line('.') - 1
let offset = -1
while getline(lnum) !~# '^@@ -\d\+,\d\+ +\d\+,'
if getline(lnum) =~# '^[ '.type.']'
let offset += 1
endif
let lnum -= 1
endwhile
let offset += matchstr(getline(lnum), type.'\zs\d\+')
let ref = getline(search('^'.type.'\{3\} [ab]/','bnW'))[4:-1]
let dcmd = '+'.offset.'|normal! zv'
let dref = ''
elseif getline('.') =~# '^rename from '
let ref = 'a/'.getline('.')[12:]
elseif getline('.') =~# '^rename to '
let ref = 'b/'.getline('.')[10:]
elseif getline('.') =~# '^diff --git \%(a/.*\|/dev/null\) \%(b/.*\|/dev/null\)'
let dref = matchstr(getline('.'),'\Cdiff --git \zs\%(a/.*\|/dev/null\)\ze \%(b/.*\|/dev/null\)')
let ref = matchstr(getline('.'),'\Cdiff --git \%(a/.*\|/dev/null\) \zs\%(b/.*\|/dev/null\)')
let dcmd = 'Gdiff'
elseif getline('.') =~# '^index ' && getline(line('.')-1) =~# '^diff --git \%(a/.*\|/dev/null\) \%(b/.*\|/dev/null\)'
let line = getline(line('.')-1)
let dref = matchstr(line,'\Cdiff --git \zs\%(a/.*\|/dev/null\)\ze \%(b/.*\|/dev/null\)')
let ref = matchstr(line,'\Cdiff --git \%(a/.*\|/dev/null\) \zs\%(b/.*\|/dev/null\)')
let dcmd = 'Gdiff!'
elseif line('$') == 1 && getline('.') =~ '^\x\{40\}$'
let ref = getline('.')
elseif expand('<cword>') =~# '^\x\{7,40\}\>'
return s:Edit(a:mode,0,expand('<cword>'))
else
let ref = ''
endif
if myhash ==# ''
let ref = s:sub(ref,'^a/','HEAD:')
let ref = s:sub(ref,'^b/',':0:')
if exists('dref')
let dref = s:sub(dref,'^a/','HEAD:')
endif
else
let ref = s:sub(ref,'^a/',myhash.'^:')
let ref = s:sub(ref,'^b/',myhash.':')
if exists('dref')
let dref = s:sub(dref,'^a/',myhash.'^:')
endif
endif
if ref ==# '/dev/null'
" Empty blob
let ref = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391'
endif
if exists('dref')
return s:Edit(a:mode,0,ref) . '|'.dcmd.' '.s:fnameescape(dref)
elseif ref != ""
return s:Edit(a:mode,0,ref)
endif
endif
return ''
catch /^fugitive:/
return 'echoerr v:errmsg'
endtry
endfunction
" Section: Statusline
function! s:repo_head_ref() dict abort
if !filereadable(self.dir('HEAD'))
return ''
endif
return readfile(self.dir('HEAD'))[0]
endfunction
call s:add_methods('repo',['head_ref'])
function! fugitive#statusline(...) abort
if !exists('b:git_dir')
return ''
endif
let status = ''
if s:buffer().commit() != ''
let status .= ':' . s:buffer().commit()[0:7]
endif
let status .= '('.fugitive#head(7).')'
if &statusline =~# '%[MRHWY]' && &statusline !~# '%[mrhwy]'
return ',GIT'.status
else
return '[Git'.status.']'
endif
endfunction
function! fugitive#head(...) abort
if !exists('b:git_dir')
return ''
endif
return s:repo().head(a:0 ? a:1 : 0)
endfunction
" Section: Folding
function! fugitive#foldtext() abort
if &foldmethod !=# 'syntax'
return foldtext()
elseif getline(v:foldstart) =~# '^diff '
let [add, remove] = [-1, -1]
let filename = ''
for lnum in range(v:foldstart, v:foldend)
if filename ==# '' && getline(lnum) =~# '^[+-]\{3\} [abciow12]/'
let filename = getline(lnum)[6:-1]
endif
if getline(lnum) =~# '^+'
let add += 1
elseif getline(lnum) =~# '^-'
let remove += 1
elseif getline(lnum) =~# '^Binary '
let binary = 1
endif
endfor
if filename ==# ''
let filename = matchstr(getline(v:foldstart), '^diff .\{-\} a/\zs.*\ze b/')
endif
if filename ==# ''
let filename = getline(v:foldstart)[5:-1]
endif
if exists('binary')
return 'Binary: '.filename
else
return (add<10&&remove<100?' ':'') . add . '+ ' . (remove<10&&add<100?' ':'') . remove . '- ' . filename
endif
elseif getline(v:foldstart) =~# '^# .*:$'
let lines = getline(v:foldstart, v:foldend)
call filter(lines, 'v:val =~# "^#\t"')
cal map(lines,'s:sub(v:val, "^#\t%(modified: +|renamed: +)=", "")')
cal map(lines,'s:sub(v:val, "^([[:alpha:] ]+): +(.*)", "\\2 (\\1)")')
return getline(v:foldstart).' '.join(lines, ', ')
endif
return foldtext()
endfunction
augroup fugitive_foldtext
autocmd!
autocmd User Fugitive
\ if &filetype =~# '^git\%(commit\)\=$' && &foldtext ==# 'foldtext()' |
\ set foldtext=fugitive#foldtext() |
\ endif
augroup END
|