Shougo's vimrc

raw delete

Vim muscle: 2320 - Power user

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
"---------------------------------------------------------------------------
" Shougo's .vimrc
"---------------------------------------------------------------------------
" Initialize:"{{{
"

if !exists('g:loaded_vimrc')
  let g:loaded_vimrc = 0
endif

" 文字化けするので、インターフェースに英語を使用する
if has('win32') || has('win64')
    " For Windows.
    language en
else
    " For Linux.
    language mes C
endif

" \の代わりに'm'を使えるようにする
" ','より押しやすい。
" プラグイン用設定の前に設定しないとうまくマッピングされない。
let mapleader = 'm'
" グローバルプラグインでは <Leader> を使用
let g:mapleader = 'm'
" ファイルタイププラグインでは <LocalLeader> を使用
" 'm'の隣だから','を使用する。
let g:maplocalleader = ','

" plug-inのためにキーマップを解放する
nnoremap ;  <Nop>
xnoremap ;  <Nop>
nnoremap m  <Nop>
xnoremap m  <Nop>
nnoremap ,  <Nop>
xnoremap ,  <Nop>

if has('win32') || has('win64') 
    " Exchange path separator.
    set shellslash
endif

" Windows/Linuxにおいて、.vimと$VIM/vimfilesの違いを吸収する
if has('win32') || has('win64')
    let $DOTVIM = $VIM."/vimfiles"
else
    let $DOTVIM = $HOME."/.vim"
endif

" コンソールでは$MYGVIMRCに値がセットされていないのでセットする
if !exists($MYGVIMRC)
    if has('win32') || has('win64')
        let $MYGVIMRC = $VIM."/.gvimrc"
    else
        let $MYGVIMRC = $HOME."/.gvimrc"
    endif
endif

" Anywhere SID.
function! s:SID_PREFIX()
    return matchstr(expand('<sfile>'), '<SNR>\d\+_')
endfunction

function! s:set_default(var, val)
    if !exists(a:var) || type({a:var}) != type(a:val)
        let {a:var} = a:val
    endif
endfunction

" 最初に処理して、設定を上書きする
filetype plugin on
filetype indent on 

" Set augroup.
augroup MyAutoCmd
    autocmd!
augroup END

source ~/.secret_vimrc
"}}}

"---------------------------------------------------------------------------
" Encoding:"{{{
"
" The automatic recognition of the character code.

" Setting of the encoding to use for a save and reading.
" Make it normal in UTF-8 in Unix. 
set encoding=utf-8

" Setting of terminal encoding."{{{
if !has('gui_running')
    if &term == 'win32' || &term == 'win64'
        " Setting when use the non-GUI Japanese console.

        " Garbled unless set this.
        set termencoding=cp932
        " Japanese input changes itself unless set this.
        " Be careful because the automatic recognition of the character code is not possible!
        set encoding=japan
    else
        if $ENV_ACCESS ==# 'cygwin'
            set termencoding=cp932
        elseif $ENV_ACCESS ==# 'linux'
            set termencoding=euc-jp
        elseif $ENV_ACCESS ==# 'colinux'
            set termencoding=utf-8
        else  " fallback
            set termencoding=  " same as 'encoding'
        endif
    endif
endif
"}}}

" The automatic recognition of the character code."{{{
if !exists('did_encoding_settings') && has('iconv')
    let s:enc_euc = 'euc-jp'
    let s:enc_jis = 'iso-2022-jp'

    " Does iconv support JIS X 0213?
    if iconv("\x87\x64\x87\x6a", 'cp932', 'euc-jisx0213') ==# "\xad\xc5\xad\xcb"
        let s:enc_euc = 'euc-jisx0213,euc-jp'
        let s:enc_jis = 'iso-2022-jp-3'
    endif
 
    " Build encodings.
    let &fileencodings = 'ucs-bom'
    if &encoding !=# 'utf-8'
        let &fileencodings = &fileencodings . ',' . 'ucs-2le'
        let &fileencodings = &fileencodings . ',' . 'ucs-2'
    endif
    let &fileencodings = &fileencodings . ',' . s:enc_jis

    if &encoding ==# 'utf-8'
        let &fileencodings = &fileencodings . ',' . s:enc_euc
        let &fileencodings = &fileencodings . ',' . 'cp932'
    elseif &encoding =~# '^euc-\%(jp\|jisx0213\)$'
        let &encoding = s:enc_euc
        let &fileencodings = &fileencodings . ',' . 'utf-8'
        let &fileencodings = &fileencodings . ',' . 'cp932'
    else  " cp932
        let &fileencodings = &fileencodings . ',' . 'utf-8'
        let &fileencodings = &fileencodings . ',' . s:enc_euc
    endif
    let &fileencodings = &fileencodings . ',' . &encoding

    unlet s:enc_euc
    unlet s:enc_jis

    let did_encoding_settings = 1
endif
"}}}

" When do not include Japanese, use encoding for fileencoding.
function! AU_ReCheck_FENC()
    if &fileencoding =~# 'iso-2022-jp' && search("[^\x01-\x7e]", 'n') == 0
        let &fileencoding=&encoding
    endif
endfunction

autocmd MyAutoCmd BufReadPost * call AU_ReCheck_FENC()

" Default fileformat.
set fileformat=unix
" Automatic recognition of a new line cord.
set fileformats=unix,dos,mac
" A fullwidth character is displayed in vim properly.
set ambiwidth=double

" Command group opening with a specific character code again."{{{
" In particular effective when I am garbled in a terminal.
" Open in UTF-8 again.
command! -bang -bar -complete=file -nargs=? Utf8 edit<bang> ++enc=utf-8 <args>
" Open in iso-2022-jp again.
command! -bang -bar -complete=file -nargs=? Iso2022jp edit<bang> ++enc=iso-2022-jp <args>
" Open in Shift_JIS again.
command! -bang -bar -complete=file -nargs=? Cp932 edit<bang> ++enc=cp932 <args>
" Open in EUC-jp again.
command! -bang -bar -complete=file -nargs=? Euc edit<bang> ++enc=euc-jp <args>
" Open in UTF-16 again.
command! -bang -bar -complete=file -nargs=? Utf16 edit<bang> ++enc=ucs-2le <args>
" Open in UTF-16BE again.
command! -bang -bar -complete=file -nargs=? Utf16be edit<bang> ++enc=ucs-2 <args>

" Aliases.
command! -bang -bar -complete=file -nargs=? Jis  Iso2022jp<bang> <args>
command! -bang -bar -complete=file -nargs=? Sjis  Cp932<bang> <args>
command! -bang -bar -complete=file -nargs=? Unicode Utf16<bang> <args>
"}}}

" Tried to make a file note version."{{{
" Don't save it because dangerous.
command! WUtf8 setlocal fenc=utf-8
command! WIso2022jp setlocal fenc=iso-2022-jp
command! WCp932 setlocal fenc=cp932
command! WEuc setlocal fenc=euc-jp
command! WUtf16 setlocal fenc=ucs-2le
command! WUtf16be setlocal fenc=ucs-2
" Aliases.
command! WJis  WIso2022jp
command! WSjis  WCp932
command! WUnicode WUtf16
"}}}

" Handle it in nkf and open.
command! Nkf !nkf -g %

" Appoint a line feed."{{{
command! -bang -bar -complete=file -nargs=? Unix edit<bang> ++fileformat=unix <args>
command! -bang -bar -complete=file -nargs=? Mac edit<bang> ++fileformat=mac <args>
command! -bang -bar -complete=file -nargs=? Dos edit<bang> ++fileformat=dos <args>
command! -bang -complete=file -nargs=? WUnix write<bang> ++fileformat=unix <args> | edit <args>
command! -bang -complete=file -nargs=? WMac write<bang> ++fileformat=mac <args> | edit <args>
command! -bang -complete=file -nargs=? WDos write<bang> ++fileformat=dos <args> | edit <args>
"}}}"}}}

"---------------------------------------------------------------------------
" Search:"{{{
"
" Ignore the case of normal letters. 
set ignorecase
" If the search pattern contains upper case characters, override ignorecase option.
set smartcase

" Enable incremental search.
set incsearch
" Don't highlight search result.
set nohlsearch

" Searches wrap around the end of the file.
set wrapscan
"}}}

"---------------------------------------------------------------------------
" Input Japanese:"{{{
"
if has('multi_byte_ime')
    " Settings of default ime condition.
    set iminsert=0 imsearch=0
    " Don't save ime condition.
    autocmd MyAutoCmd InsertLeave * set iminsert=0 imsearch=0
    nnoremap / :<C-u>set imsearch=0<CR>/
    xnoremap / :<C-u>set imsearch=0<CR>/
    nnoremap ? :<C-u>set imsearch=0<CR>?
    xnoremap ? :<C-u>set imsearch=0<CR>?
endif
"}}}

"---------------------------------------------------------------------------
" Edit:"{{{
"
" Enable no Vi compatible commands.
set nocompatible

" Smart insert tab setting.
set smarttab
" Exchange tab to spaces.
set expandtab
" ファイルの<Tab>が対応する空白の数
set tabstop=8
" <Tab>の代わりに挿入する空白の数
set softtabstop=4
" 自動インデントに使われる空白の数
set shiftwidth=4
" インデントをshiftwidthの倍数に丸める
set shiftround

" Enable modeline.
set modeline

" Use clipboard register.
set clipboard& clipboard+=unnamed

" Disable auto wrap.
autocmd MyAutoCmd FileType * set textwidth=0

" Enable backspace delete indent and newline.
set backspace=indent,eol,start

" 括弧入力時に対応する括弧を表示
set showmatch
" 移動キーを押しても括弧の強調を有効にする
set cpoptions-=m
set matchtime=3
" <>にもマッチするようにする
set matchpairs+=<:>

" 保存していなくても別のファイルを表示できるようにする
set hidden

" Auto reload if file is changed.
"set autoread

" Ignore case on insert completion.
set infercase

" Search home directory path on cd.
" But can't complete.
set cdpath+=~

" Save fold settings.
" 無名バッファを開くときにエラーになる問題に対応。
" *.*と違って、拡張子がないファイルにも対応した。
autocmd MyAutoCmd BufWritePost * if expand('%') != '' && &buftype !~ 'nofile' | mkview | endif
autocmd MyAutoCmd BufRead * if expand('%') != '' && &buftype !~ 'nofile' | silent loadview | endif
" Don't save options.
set viewoptions-=options

" Enable folding.
set foldenable
" 折りたたみ方法は分かりやすいマーカーにする。
set foldmethod=marker
" Show folding level.
set foldcolumn=3

" GrepをVim標準のGrepにする
set grepprg=internal

" = をファイル名の一部と認識しない
set isfname-==

" 編集したら、自動的に.vimrc, .gvimrcをリロードする
" GUIの場合、.vimrcを編集したら.gvimrcもロードする。
if !has('gui_running') && !(has('win32') || has('win64'))
    " .vimrcの再読込時にも色が変化するようにする
    autocmd MyAutoCmd BufWritePost .vimrc nested source $MYVIMRC | echo "source $MYVIMRC"
else
    " .vimrcの再読込時にも色が変化するようにする
    autocmd MyAutoCmd BufWritePost .vimrc source $MYVIMRC | 
                \if has('gui_running') | source $MYGVIMRC | echo "source $MYVIMRC"
    autocmd MyAutoCmd BufWritePost .gvimrc if has('gui_running') | source $MYGVIMRC | echo "source $MYGVIMRC"
endif

" Keymapping timeout.
set timeout timeoutlen=2500 ttimeoutlen=50

" CursorHold time.
set updatetime=3000

" Set swap directory.
set directory-=.

" Set tags file.
" Don't search tags file in current directory. And search upward.
set tags& tags-=tags tags+=./tags;

" Enable virtualedit in visual block mode.
set virtualedit=block

" Set keyword help.
set keywordprg=:help

"}}}

"---------------------------------------------------------------------------
" View:"{{{
"
" Show line number.
set number
" Show cursor position.
set ruler
" タブや改行を表示
set list
" どの文字でタブや改行を表示するかを設定
set listchars=tab:>-,extends:>,precedes:<
" Wrap long line.
set wrap
" Wrap conditions.
set whichwrap+=h,l,<,>,[,],b,s,~
" Always display statusline.
set laststatus=2
" Height of command line.
set cmdheight=2
" Show command on statusline.
set showcmd
" Show title.
set title
" Title length.
set titlelen=95
" Title string.
set titlestring=%f%(\ %M%)%(\ (%{getcwd()})%)%(\ %a%)

" Set tabline.
function! s:my_tabline()  "{{{
      let l:s = ''
       
      for l:i in range(1, tabpagenr('$'))
          let l:bufnrs = tabpagebuflist(i)
          let l:curbufnr = l:bufnrs[tabpagewinnr(l:i) - 1]  " first window, first appears

          let l:no = (l:i <= 10 ? l:i-1 : '#')  " display 0-origin tabpagenr.
          let l:mod = len(filter(l:bufnrs, 'getbufvar(v:val, "&modified")')) ? '!' : ' '
          let l:title = gettabwinvar(l:i, tabpagewinnr(l:i), 'title')
          if l:title == ''
              let l:title = fnamemodify(gettabwinvar(l:i, tabpagewinnr(l:i), 'cwd'), ':t')
              if l:title == ''
                  let l:title = fnamemodify(bufname(l:curbufnr),':t')
                  if l:title == ''
                      let l:title = '[No Name]'
                  endif
              endif
          endif

          let l:s .= '%'.l:i.'T'
          let l:s .= '%#' . (l:i == tabpagenr() ? 'TabLineSel' : 'TabLine') . '#'
          let l:s .= l:no . ':' . l:title . l:mod
          let l:s .= '%#TabLineFill#  '
      endfor

      let l:s .= '%#TabLineFill#%T%=%#TabLine#|%999X %X'
      return l:s
endfunction "}}}
"let &tabline = '%!'. s:SID_PREFIX() . 'my_tabline()'
set showtabline=2

" 画面に収まりきる最後の文字ではなく、オプション 'breakat'
" に指定された文字のところで、長い行を折り返す
set linebreak
set showbreak=>\ 
set breakat=\ \ ;:,!?

" Do not display greetings message at the time of Vim start.
set shortmess=aTI

" Don't create backup.
set nowritebackup
set nobackup

" Disable bell.
set visualbell
set vb t_vb=

" Display candidate supplement.
set nowildmenu
set wildmode=list:longest,full
" Increase history amount.
set history=200
" Display all the information of the tag by the supplement of the Insert mode.
set showfulltag
" Can supplement a tag in a command-line.
set wildoptions=tagfile

" Enable spell check.
"set spell spelllang=en_us

" Completion setting.
set completeopt=menuone,preview
" Don't complete from other buffer.
set complete=.
"set complete=.,w,b,i,t
" Set popup menu max height.
set pumheight=20

" Report changes.
set report=0

" Maintain a current line at the time of movement as much as possible.
set nostartofline

" Splitting a window will put the new window below the current one.
set splitbelow
" Splitting a window will put the new window right the current one.
set splitright
" Set minimal width for current window.
set winwidth=60
" Set minimal height for current window.
set winheight=20

" Adjust window size of preview and help.
set previewheight=3
set helpheight=12

" Don't redraw while macro executing.
set lazyredraw

" Store window size as a session.
set sessionoptions+=resize

" Enable menu in console.
if !has('gui_running')
    source $VIMRUNTIME/menu.vim
    set cpo-=<
    set wcm=<C-z>
    noremap <F2> :emenu <C-z>
endif

" When a line is long, do not omit it in @.
set display=lastline
" Display an invisible letter with hex format.
"set display+=uhex

" Set cursor line in current window.
augroup vimrc-auto-cursorline"{{{
  autocmd!
  autocmd CursorMoved,CursorMovedI * call s:auto_cursorline('CursorMoved')
  autocmd CursorHold,CursorHoldI * call s:auto_cursorline('CursorHold')
  autocmd WinEnter * call s:auto_cursorline('WinEnter')
  autocmd WinLeave * call s:auto_cursorline('WinLeave')

  let s:cursorline_lock = 0
  function! s:auto_cursorline(event)
    if a:event ==# 'WinEnter'
      setlocal cursorline
      let s:cursorline_lock = 2
    elseif a:event ==# 'WinLeave'
      setlocal nocursorline
    elseif a:event ==# 'CursorMoved'
      if s:cursorline_lock
        if 1 < s:cursorline_lock
          let s:cursorline_lock = 1
        else
          setlocal nocursorline
          let s:cursorline_lock = 0
        endif
      endif
    elseif a:event ==# 'CursorHold'
      setlocal cursorline
      let s:cursorline_lock = 1
    endif
  endfunction
augroup END"}}}

" Disable automatically insert comment.
autocmd MyAutoCmd FileType * set formatoptions-=ro

"}}}

"---------------------------------------------------------------------------
" Syntax:"{{{
"
" Enable syntax color.
syntax enable

" Enable smart indent.
set autoindent smartindent

augroup MyAutoCmd"{{{
    " Enable gauche syntax.
    autocmd FileType scheme nested let b:is_gauche=1 | setlocal lispwords=define | 
                \let b:current_syntax='' | syntax enable

    " Easily load VimScript.
    autocmd FileType vim nnoremap <silent><buffer> [Space]so :write \| source % \| echo "source " . bufname('%')<CR>

    " Auto reload VimScript.
    autocmd BufWritePost,FileWritePost *.vim if &autoread | source <afile> | echo "source " . bufname('%') | endif

    " netrwでは<C-h>で上のディレクトリへ移動
    autocmd FileType netrw nmap <buffer> <C-h> -

    " Manage long Rakefile easily
    autocmd BufNewfile,BufRead Rakefile foldmethod=syntax foldnestmax=1

    " Close help and git window by pressing q.
    autocmd FileType help,git-status,git-log,qf nnoremap <buffer> q <C-w>c

    " Enable omni completion."{{{
    autocmd FileType ada setlocal omnifunc=adacomplete#Complete
    autocmd FileType c setlocal omnifunc=ccomplete#Complete
    autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
    autocmd FileType html setlocal omnifunc=htmlcomplete#CompleteTags
    autocmd FileType java setlocal omnifunc=javacomplete#Complete
    autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
    autocmd FileType php setlocal omnifunc=phpcomplete#CompletePHP
    autocmd FileType python setlocal omnifunc=pythoncomplete#Complete
    autocmd FileType ruby setlocal omnifunc=rubycomplete#Complete
    "autocmd FileType sql setlocal omnifunc=sqlcomplete#Complete
    autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags
    " default omnifunc.
    "autocmd Filetype * if &l:omnifunc == "" | setlocal omnifunc=syntaxcomplete#Complete | endif
    "}}}

augroup END
"}}}

" Java
let g:java_highlight_functions = 'style'
let g:java_highlight_all = 1
let g:java_allow_cpp_keywords = 1

" PHP
let g:php_folding = 1

" Python
let g:python_highlight_all = 1

" XML
let g:xml_syntax_folding = 1

" Vim
let g:vimsyntax_noerror = 1
"let g:vim_indent_cont = 0

"}}}"}}}

"---------------------------------------------------------------------------
" Plugin:"{{{
"

" yanktmp.vim"{{{
" Because I don't use it that much, I demote it to Sy.
nnoremap S    <Nop>
xnoremap S    <Nop>
nmap <silent> Sy    <Plug>(yanktmp_yank)
xmap <silent> Sy    <Plug>(yanktmp_yank)
nmap <silent> Sp    <Plug>(yanktmp_paste_p)
xmap <silent> Sp    <Plug>(yanktmp_paste_p)
nmap <silent> SP    <Plug>(yanktmp_paste_P)
xmap <silent> SP    <Plug>(yanktmp_paste_P)
"}}}

" bufstatus.vim"{{{
" Right tabline information.
let g:BufStatus_RightStatus = ''
" Set margin.
let g:BufStatus_SideMargin = 0
" Set statusline.
let &statusline = '%f%=%m%y%{"[".(&fenc!=""?&fenc:&enc).",".&ff."]"}%{"[".neocomplcache#caching_percent()."%]"} %3p%%'
"}}}

" neocomplcache.vim"{{{
" Don't use autocomplpop.
let g:AutoComplPop_NotEnableAtStartup = 1
" Use neocomplcache.
let g:NeoComplCache_EnableAtStartup = 1
" Use smartcase.
let g:NeoComplCache_SmartCase = 1
" Use previous keyword completion.
let g:NeoComplCache_PreviousKeywordCompletion = 1
" Use tags auto update.
"let g:NeoComplCache_TagsAutoUpdate = 1
" Use preview window.
let g:NeoComplCache_EnableInfo = 1
" Use camel case completion.
let g:NeoComplCache_EnableCamelCaseCompletion = 1
" Use underbar completion.
let g:NeoComplCache_EnableUnderbarCompletion = 1
" Set minimum syntax keyword length.
let g:NeoComplCache_MinSyntaxLength = 3
" Set skip input time.
let g:NeoComplCache_SkipInputTime = '0.2'
" Set manual completion length.
let g:NeoComplCache_ManualCompletionStartLength = 0

" Print caching percent in statusline.
"let g:NeoComplCache_CachingPercentInStatusline = 1

" Define dictionary.
let g:NeoComplCache_DictionaryFileTypeLists = {
            \ 'default' : '',
            \ 'vimshell' : $HOME.'/.vimshell_hist',
            \ 'scheme' : $HOME.'/.gosh_completions'
            \ }

" Define keyword.
if !exists('g:NeoComplCache_KeywordPatterns')
    let g:NeoComplCache_KeywordPatterns = {}
endif
let g:NeoComplCache_KeywordPatterns['default'] = '\v\h\w*'

let g:NeoComplCache_SnippetsDir = $HOME.'/snippets'

" Plugin key-mappings.
imap <silent>L     <Plug>(neocomplcache_snippets_expand)
"imap <expr><silent>L    neocomplcache#snippets_complete#expandable() ? "\<Plug>(neocomplcache_snippets_expand)" : "\<C-n>"
smap <silent>L     <Plug>(neocomplcache_snippets_expand)
inoremap <expr><silent><C-g>     neocomplcache#undo_completion()

"let g:NeoComplCache_KeywordCompletionStartLength = 1
"if !exists('g:NeoComplCache_PluginCompletionLength')
    "let g:NeoComplCache_PluginCompletionLength = {}
"endif
"let g:NeoComplCache_PluginCompletionLength['snippets_complete'] = 1
"let g:NeoComplCache_PluginCompletionLength['keyword_complete'] = 2
"let g:NeoComplCache_PluginCompletionLength['syntax_complete'] = 2
"let g:NeoComplCache_PluginCompletionLength['tags_complete'] = 3

"}}}

" NERD_comments.vim"{{{
let NERDSpaceDelims = 0
let NERDShutUp = 1
" Disable <C-c>.
nnoremap <C-c> <C-c>
nunmap <C-c>
"}}}

" vimshell.vim"{{{
 
"let g:VimShell_UserPrompt = "3\ngetcwd()"
let g:VimShell_UserPrompt = 'fnamemodify(getcwd(), ":~")'
let g:VimShell_EnableInteractive = 1
let g:VimShell_EnableSmartCase = 1
let g:VimShell_EnableAutoLs = 1

if has('win32') || has('win64') 
    " Display user name on Windows.
    let g:VimShell_Prompt = $USERNAME."% "

    " Use ckw.
    let g:VimShell_UseCkw = 1
else
    " Display user name on Linux.
    let g:VimShell_Prompt = $USER."% "

    call vimshell#set_execute_file('bmp,jpg,png,gif', 'gexe eog')
    call vimshell#set_execute_file('mp3,m4a,ogg', 'gexe amarok')
    let g:VimShell_ExecuteFileList['zip'] = 'zipinfo'
    call vimshell#set_execute_file('tgz,gz', 'gzcat')
    call vimshell#set_execute_file('tbz,bz2', 'bzcat')
endif

" Initialize execute file list.
let g:VimShell_ExecuteFileList = {}
call vimshell#set_execute_file('txt,vim,c,h,cpp,d,xml,java', 'vim')
let g:VimShell_ExecuteFileList['rb'] = 'ruby'
let g:VimShell_ExecuteFileList['pl'] = 'perl'
let g:VimShell_ExecuteFileList['py'] = 'python'
call vimshell#set_execute_file('html,xhtml', 'gexe firefox')


" <C-Space>: switch to vimshell.
nmap <C-@>  <Plug>(vimshell_switch)
imap <C-@>  <Plug>(vimshell_switch)
" !: vimshell interactive execute.
nnoremap !  :<C-u>VimShellInteractive<Space>
" &: vimshell background execute.
nnoremap &  :<C-u>VimShellExecute<Space>

autocmd MyAutoCmd FileType vimshell
        \   imap <buffer><silent> &  <C-o>:call vimshell#mappings#push_and_execute('cd ..')<CR>
        \| nnoremap <buffer> T  Ga
        \nmap <buffer> R   Gah<CR>
"}}}

" scratch.vim"{{{
let g:scratch_buffer_name = 'scratch'
"}}}

" netrw.vim"{{{
let g:netrw_list_hide= '*.swp'
nnoremap <silent> <BS> :<C-u>Explore<CR>
" Change default directory.
set browsedir=current
if executable('wget')
    let g:netrw_http_cmd = 'wget'
endif
"}}}

" hexedit.vim"{{{
nnoremap <Leader>he  :<C-u>Hedit<CR>
nnoremap <Leader>hv  :<C-u>Hview<CR>
nnoremap <Leader>hw  :<C-u>Hwrite<CR>
nnoremap <Leader>hc  :<C-u>Hconvert<CR>
nnoremap <Leader>hr  :<C-u>Hredraw<CR>
nnoremap <Leader>hR  :<C-u>Hreset<CR>
"}}}

" errormarker.vim"{{{
let errormarker_errortext      = "!!"
let errormarker_warningtext    = "??"
let g:errormarker_errorgroup   = "Error"
let g:errormarker_warninggroup = "Todo"
if has('win32') || has('win64')
    let g:errormarker_erroricon    = $DOTVIM . "/signs/err.bmp"
    let g:errormarker_warningicon  = $DOTVIM . "/signs/warn.bmp"
else
    let g:errormarker_erroricon    = $DOTVIM . "/signs/err.png"
    let g:errormarker_warningicon  = $DOTVIM . "/signs/warn.png"
endif
"}}}

" QFixGrep"{{{
" Set external grep.
if has('win32') || has('win64')
    let mygrepprg = 'yagrep'
    let MyGrep_ShellEncoding = 'cp932'
else
    let mygrepprg = 'grep'
    let MyGrep_ShellEncoding = 'utf-8'
endif
" Exclude pattern.
let MyGrep_ExcludeReg =
            \'[~#]$\|\.bak$\|\.swp$\.o$\|\.obj$\|\.exe$\|\.dll$\|\.pdf$\|\.doc$\|\.xls$\|[/\\]tags$\|.cvs[/\\]\|.git[/\\]\|.svn[/\\]'

" Key-mappings.
" Grep cursor word.
nnoremap grw  :<C-u>EGrep! <C-r><C-w><CR>
" Execute fast grep.
nnoremap grf  :<C-u>FGrep!<Space>
" Execute vim grep.
nnoremap grv  :<C-u>VGrep!<Space>
" Execute grep from buffer.
nnoremap grv  :<C-u>VGrep!<Space>
" Normal grep.
nnoremap g/  :<C-u>Grep!<CR>
nnoremap [Space]/  :<C-u>Bgrep<Space>

" Execute grep from yanked string.
nnoremap gyf :<C-u>execute 'FGrep! '. expand(@0)<CR>
nnoremap gyv :<C-u>execute 'VGrep! '. expand(@0)<CR>
" Execute grep from selected string.
xmap grf  vgvygyf
xmap grv  vgvygyv

" Quickfix window.
nnoremap [Quickfix]f<Space>       :<C-u>ToggleQFixWin<CR>
nnoremap [Quickfix]ff             :<C-u>MoveToQFixWin<CR>

"}}}

" project.vim ------------------------------------------------ {{{
" カレントディレクトリにプロジェクトを作成する
nnoremap <silent> <Leader>pr  :<C-u>Project .vimprojects<CR>
" デフォルトでは短すぎる
let g:proj_window_width = 30
"}}}

" taglist.vim ------------------------------------------------- {{{
" Show only current file.
let g:Tlist_Show_One_File = 1
" Exit Vim when taglist's window is last window.
let g:Tlist_Exit_OnlyWindow = 1
" Show taglist window in right.
let g:Tlist_Use_Right_Window = 1
" Display method and class in JavaScript.
let g:tlist_javascript_settings = 'javascript;c:class;m:method;f:function'
" Shortcut key.
nnoremap <silent> <leader>tl :<C-u>TlistToggle<CR>
"}}}

" git.vim ----------------------------------------------------- {{{
let g:git_no_map_default = 1
let g:git_command_edit = 'rightbelow vnew'
nnoremap [Space]gd :<C-u>GitDiff --cached<CR>
nnoremap [Space]gD :<C-u>GitDiff<CR>
nnoremap [Space]gs :<C-u>GitStatus<CR>
nnoremap [Space]gl :<C-u>GitLog<CR>
nnoremap [Space]gL :<C-u>GitLog -u \| head -10000<CR>
nnoremap [Space]ga :<C-u>GitAdd<CR>
nnoremap [Space]gA :<C-u>GitAdd <cfile><CR>
nnoremap [Space]gc :<C-u>GitCommit --amend<CR>
nnoremap [Space]gC :<C-u>GitCommit<CR>
nnoremap [Space]gp :<C-u>Git push
"}}}

" ku.vim"{{{
" The prefix key.
nnoremap    [Ku]   <Nop>
nmap    ' [Ku]
nnoremap [Ku]u  :<C-u>Ku<Space>
nnoremap <silent> [Ku]a  :<C-u>Ku args<CR>
nnoremap <silent> [Ku]b  :<C-u>Ku buffer<CR>
nnoremap <silent> [Ku]c  :<C-u>Ku cmd_mru/cmd<CR>
nnoremap <silent> [Ku]f  :<C-u>Ku file<CR>
nnoremap <silent> [Ku]g  :<C-u>Ku metarw-git<CR>
nnoremap <silent> [Ku]h  :<C-u>Ku history<CR>
nnoremap <silent> [Ku]k  :<C-u>call ku#restart()<CR>
nnoremap <silent> [Ku]m  :<C-u>Ku file_mru<CR>
nnoremap <silent> [Ku]u  :<C-u>Ku bundle<CR>
nnoremap <silent> [Ku]p  :<C-u>Ku yankring<CR>
nnoremap <silent> [Ku]q  :<C-u>Ku quickfix<CR>
nnoremap <silent> [Ku]s  :<C-u>Ku source<CR>
nnoremap <silent> [Ku]'  :<C-u>Ku source<CR>
nnoremap <silent> [Ku]/  :<C-u>Ku cmd_mru/search<CR>
" w is for ~/working.
"nnoremap <silent> [Ku]w  :<C-u>Ku myproject<CR>
autocmd MyAutoCmd FileType ku
            \   call ku#default_key_mappings(1)
            \ | call s:Ku_my_settings()

function! s:Ku_my_settings()
    inoremap <buffer> <silent> <Tab> <C-n>
    inoremap <buffer> <silent> <S-Tab> <C-p>
    imap <buffer> <silent> <Esc><Esc> <Plug>(ku-cancel)
    imap <buffer> <silent> jj <Plug>(ku-cancel)
    nmap <buffer> <silent> <Esc><Esc> <Plug>(ku-cancel)
    nmap <buffer> <silent> jj <Plug>(ku-cancel)
    imap <buffer> <silent> <Esc><Cr> <Plug>(ku-choose-an-action)
    nmap <buffer> <silent> <Esc><Cr> <Plug>(ku-choose-an-action)
endfunction

function! s:ku_common_action_my_cd(item)
    if isdirectory(a:item.word)
        execute 'CD' a:item.word
    else  " treat a:item as a file name
        execute 'CD' fnamemodify(a:item.word, ':h')
    endif
endfunction

call ku#custom_action('bundle', 'default', 'bundle', 'args')
call ku#custom_action('common', 'cd', s:SID_PREFIX() . 'ku_common_action_my_cd')
call ku#custom_action('myproject', 'default', 'common', 'tab-Right')

call ku#custom_prefix('common', 'home', substitute($HOME, '\\', '/', 'g'))
call ku#custom_prefix('common', '~', substitute($HOME, '\\', '/', 'g'))
call ku#custom_prefix('common', '.v', substitute($DOTVIM, '\\', '/', 'g'))
call ku#custom_prefix('common', 'runtime', substitute($VIMRUNTIME, '\\', '/', 'g'))

" metarw.vim
" Define wrapper commands.
call metarw#define_wrapper_commands(1)

let g:ku_file_mru_limit = 200
"}}}

" smartword.vim"{{{
" Replace w and others with smartword-mappings
nmap w  <Plug>(smartword-w)
nmap b  <Plug>(smartword-b)
nmap ge  <Plug>(smartword-ge)
xmap w  <Plug>(smartword-w)
xmap b  <Plug>(smartword-b)
xmap e  <Plug>(smartword-e)
"xmap ge  <Plug>(smartword-ge)
" Operator pending mode.
omap <Leader>w  <Plug>(smartword-w)
omap <Leader>b  <Plug>(smartword-b)
omap <Leader>ge  <Plug>(smartword-ge)
"}}}

" vicle.vim"{{{
let g:vicle_session_name    = 'normal_session_name' 
let g:vicle_session_window  = 'normal_session_window' 

"let g:vicle_hcs             = '~~~your_command_separator~~~'
""}}}

" camlcasemotion.vim"{{{
nmap <silent> W <Plug>CamelCaseMotion_w
xmap <silent> W <Plug>CamelCaseMotion_w
nmap <silent> B <Plug>CamelCaseMotion_b
xmap <silent> W <Plug>CamelCaseMotion_b
""}}}

" AutoProtectFile.vim
let g:autoprotectfile_readonly_paths = "$VIMRUNTIME/*,~/important"
let g:autoprotectfile_nomodifiable_paths = "$VIMRUNTIME/*,~/important"

" smartchr.vim"{{{
inoremap <expr> & smartchr#one_of('&', ' & ', ' && ')
inoremap <expr> <Bar> smartchr#one_of('<Bar>', ' <Bar> ', ' <Bar><Bar> ')
inoremap <expr> , smartchr#one_of(', ', ',')

inoremap <expr> ? smartchr#one_of('?', '? ')

" Smart =.
inoremap <expr> = search('\(&\<bar><bar>\<bar>+\<bar>-\<bar>/\<bar>>\<bar><\) \%#', 'bcn')? '<bs>= '
            \ : search('\(*\<bar>!\)\%#', 'bcn') ? '= '
            \ : smartchr#one_of(' = ', '=', ' == ')
augroup MyAutoCmd
    " Substitute .. into -> .
    autocmd FileType c,cpp inoremap <buffer> <expr> . smartchr#loop('.', '->', '...')
    autocmd FileType perl,php inoremap <buffer> <expr> . smartchr#loop(' . ', '->', '.')
    autocmd FileType vim inoremap <buffer> <expr> . smartchr#loop('.', ' . ', '...')

    autocmd FileType haskell
                \ inoremap <buffer> <expr> + smartchr#loop('+', ' ++ ')
                \| inoremap <buffer> <expr> - smartchr#loop('-', ' <- ')
                \| inoremap <buffer> <expr> $ smartchr#loop(' $ ', '$')
                \| inoremap <buffer> <expr> \ smartchr#loop('\ ', '\')
                \| inoremap <buffer> <expr> : smartchr#loop(':', ' :: ', ' : ')
                \| inoremap <buffer> <expr> . smartchr#loop(' . ', '..', '.')

    autocmd FileType scala
                \ inoremap <buffer> <expr> - smartchr#loop('-', ' -> ', ' <- ')
                \| inoremap <buffer> <expr> = smartchr#loop(' = ', '=', ' => ')
                \| inoremap <buffer> <expr> : smartchr#loop(': ', ':', ' :: ')
                \| inoremap <buffer> <expr> . smartchr#loop('.', ' => ')

    autocmd FileType eruby
                \ inoremap <buffer> <expr> > smartchr#loop('>', '%>')
                \| inoremap <buffer> <expr> < smartchr#loop('<', '<%', '<%=')
augroup END
"}}}

" eev.vim"{{{
nmap >  <Plug>(eev_search_forward)
nmap <  <Plug>(eev_search_forward)
nmap <C-e>  <Plug>(eev_eval)
nmap <C-u>  <Plug>(eev_create)
"}}}

" smarttill.vim"{{{
xmap q  <Plug>(smarttill-t)
xmap Q  <Plug>(smarttill-T)
" Operator pending mode.
omap q  <Plug>(smarttill-t)
omap Q  <Plug>(smarttill-T)
"}}}

" changelog.vim"{{{
let g:changelog_timeformat = "%Y-%m-%d"
let g:changelog_username = "Shougo "
"}}}

" capslock.vim
imap G     <Plug>CapsLockToggle

" quickrun.vim"{{{
function! s:init_quickrun()
    for [key, com] in items({
    \   '<Leader>x' : '<=@i >:',
    \   '<Leader>p' : '<=@i >!',
    \   '<Leader>"' : '<=@i >=@"',
    \   '<Leader>w' : '<=@i >',
    \   '<Leader>q' : '<=@i >>',
    \   '<Leader>vx' : '-eval 1 <=@i >:',
    \   '<Leader>vp' : '-eval 1 <=@i >!',
    \   '<Leader>v"' : '-eval 1 <=@i >=@"',
    \   '<Leader>vw' : '-eval 1 <=@i >',
    \   '<Leader>vq' : '-eval 1 <=@i >>',
    \ })
        execute 'nnoremap <silent>' key ':QuickRun' com '-mode n<CR>'
        execute 'vnoremap <silent>' key ':QuickRun' com '-mode v<CR>'
    endfor

    call s:set_default('g:QuickRunConfig', {'mkd': {'command': 'mdv2html'}})
    call s:set_default('g:QuickRunConfig', {'xmodmap': {}})
endfunction
call s:init_quickrun()
nmap <silent> <Space><Plug>(quickrun-op)
"}}}

" python.vim
let python_highlight_all = 1

" fakeclip.vim
map "&Y "&y$

" Align.vim
let g:Align_xstrlen=3

"}}}

"---------------------------------------------------------------------------
" Key-mappings: "{{{
"

" Use <C-Space>.
map <C-Space>  <C-@>
cmap <C-Space>  <C-@>

" Visual mode keymappings: "{{{
" <CR>: change.
xnoremap <CR>  c
" <TAB>: indent.
xnoremap <TAB>  >
" <S-TAB>: unindent.
xnoremap <S-TAB>  <
"}}}

" Selection mode keymappings: "{{{
snoremap <CR>     <Space><BS>
snoremap <Space>  <Space><BS>
snoremap <C-f>  <ESC>a
snoremap <C-b>  <ESC>bi
"}}}

" Insert mode keymappings: "{{{
" <C-t>: insert tab.
inoremap <C-t>  <C-v><TAB>
" T: expand tab.
inoremap T  <TAB>
" <C-d>: delete char.
inoremap <C-d>  <Del>
" <C-a>: move to head.
inoremap <silent><C-a>  <C-o>^
" <C-f>, <C-b>: page move.
inoremap <expr><C-f>  pumvisible() ? "\<PageDown>" : "\<Right>"
inoremap <expr><C-b>  pumvisible() ? "\<PageUp>"   : "\<Left>"
" <A-b>: previous word.
inoremap <A-b>  <S-Left>
" <A-f>: next word.
inoremap <A-f>  <S-Right>
" Enable undo <C-w> and <C-u>.
inoremap <C-w>  <C-g>u<C-w>
inoremap <C-u>  <C-g>u<C-u>

" <TAB>: completion.
inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : <SID>check_back_space() ? "\<TAB>" : "\<C-x>\<C-u>\<C-p>"
function! s:check_back_space()"{{{
        let col = col('.') - 1
        if !col || getline('.')[col - 1]  =~ '\s'
            return 1
        else
            return 0
        endif
endfunction"}}}
" <S-TAB>: completion back.
inoremap <expr><S-TAB>  pumvisible() ? "\<C-p>" : "\<C-h>"
" <C-y>: paste.
inoremap <expr><C-y>  pumvisible() ? neocomplcache#close_popup() :  "\<C-r>\""
" <C-e>: close popup.
inoremap <expr><C-e>  pumvisible() ? neocomplcache#cancel_popup() : "\<End>"
" <C-a>: toggle preview window.
inoremap <silent><C-a>  <C-o>:<C-u>call<SID>preview_window_toggle()<CR>
" <C-j>: omni completion.
inoremap <expr> <C-j>  &filetype == 'vim' ? "\<C-x>\<C-v>\<C-p>" : neocomplcache#manual_omni_complete()
" <C-k>: delete to end.
inoremap <C-k>  <C-o>D
" <C-h>, <BS>: close popup and delete backword char.
inoremap <expr><C-h> pumvisible() ? "\<C-y>\<C-h>" : "\<C-h>"
inoremap <expr><BS> pumvisible() ? "\<C-y>\<C-h>" : "\<C-h>"
" H, D: delete camlcasemotion.
inoremap <expr>H           <SID>camelcase_delete(0) 
inoremap <expr>D           <SID>camelcase_delete(1) 
function! s:camelcase_delete(is_reverse)
    let l:save_ve = &l:virtualedit
    setlocal virtualedit=all
    if a:is_reverse
        let l:cur_text = getline('.')[virtcol('.')-1 : ]
    else
        let l:cur_text = getline('.')[: virtcol('.')-2]
    endif
    let &l:virtualedit = l:save_ve

    let l:pattern = '\d\+\|\u\+\ze\%(\u\l\|\d\)\|\u\l\+\|\%(\a\|\d\)\+\ze_\|\%(\k\@!\S\)\+\|\%(_\@!\k\)\+\>\|[_]\|\s\+'

    if a:is_reverse
        let l:cur_cnt = len(matchstr(l:cur_text, '^\%('.l:pattern.'\)'))
    else
        let l:cur_cnt = len(matchstr(l:cur_text, '\%('.l:pattern.'\)$'))
    endif

    if a:is_reverse
        return (pumvisible() ? "\<C-y>" : '')
                    \ . repeat("\<Del>", l:cur_cnt)
    else
        return (pumvisible() ? "\<C-y>" : '')
                    \ . repeat("\<BS>", l:cur_cnt)
    endif
endfunction
" <C-n>: neocomplcache.
inoremap <expr><C-n>  pumvisible() ? "\<C-n>" : "\<C-x>\<C-u>\<C-p>"
" <C-p>: keyword completion.
inoremap <expr><C-p>  pumvisible() ? "\<C-p>" : "\<C-p>\<C-n>"
" <C-x>: neocomplcache.
inoremap <expr><C-x>  pumvisible() ? "\<C-x>\<C-u>\<C-p>" : "\<C-x>"
" <CR>: close popup and save indent.
inoremap <expr><CR> pumvisible() ? neocomplcache#close_popup()."\<CR>X\<BS>" : "\<CR>X\<BS>"
" U: user completion.
inoremap <expr>U  pumvisible() ? "\<C-y>\<C-x>\<C-u>\<C-p>" : "\<C-x>\<C-u>\<C-p>"
" O: Open previous line.
inoremap O  <ESC>O
" M: Open next line.
inoremap M  <ESC>o
" C: Change.
inoremap C  <C-o>diw
" W: Move smart word.
imap W  <C-o><Plug>(smartword-w)
" B: Move smart backword.
imap B  <C-o><Plug>(smartword-b)
" E: Backward to the end of word.
inoremap E  <ESC>gea
" <Space>: close popup and insert space.
inoremap <expr><Space> pumvisible() ? neocomplcache#close_popup() . ' ' : ' '
" <C-x><C-f>: filname completion.
inoremap <expr><C-x><C-f>  neocomplcache#manual_filename_complete()
" <Up>, <Down>: move.
inoremap <expr><Down> pumvisible() ? neocomplcache#close_popup()."\<Down>" : "\<Down>"
inoremap <expr><Up> pumvisible() ? neocomplcache#close_popup()."\<Up>" : "\<Up>"
"}}}

" Command-line mode keymappings:"{{{
" <C-a>, A: move to head.
cnoremap <C-a>          <Home>
cnoremap A              <Home>
" <C-b>: previous char.
cnoremap <C-b>          <Left>
" <C-d>: delete char.
cnoremap <C-d>          <Del>
" <C-e>, E: move to end.
cnoremap <C-e>          <End>
cnoremap E              <End>
" <C-f>: next char.
cnoremap <C-f>          <Right>
" <C-n>: next history.
cnoremap <C-n>          <Down>
" <C-p>: previous history.
cnoremap <C-p>          <Up>
" <C-k>, K: delete to end.
cnoremap <C-k>          <C-f>d$<C-c><End>
cnoremap K              <C-f>d$<C-c><End>
" <C-y>: paste.
cnoremap <C-y>          <C-r>"
" <C-s>: view history.
cnoremap <C-s>          <C-f>
" <C-l>: view completion list.
cnoremap <C-l>          <C-d>
" <A-b>, W: move to previous word.
cnoremap <A-b>          <S-Left>
cnoremap B              <S-Left>
" <A-f>, B: move to next word.
cnoremap <A-f>          <S-Right>
cnoremap W              <S-Right>
" <C-j>, <C-o>: move to next/previous candidate.
" High-speed than ring TAB repeatedly.
cnoremap <C-j>          <C-n>
cnoremap <C-o>          <C-p>
cnoremap <S-TAB>        <C-p>
" <C-g>: decide candidate.
cnoremap <C-g>          <Space><C-h>
" <C-t>: insert space.
cnoremap <C-t>          <Space>
" Delete previous word.
cnoremap H    <C-w>
" Delete next word.
cnoremap D    <S-Right><C-w><C-h> 
"}}}

" [Space]: Other useful commands "{{{
" スペースキーのマッピングを見やすくする
" noremapに<Space>で始まるものを使うと[Space]が表示されなくなるので注意!
nmap  <Space>   [Space]
xmap  <Space>   [Space]
nnoremap  [Space]   <Nop>
xnoremap  [Space]   <Nop>

" Toggle highlight.
nnoremap <silent> [Space]/  :<C-u>call ToggleOption('hlsearch')<CR>
" Toggle cursorline.
nnoremap <silent> [Space]cl  :<C-u>call ToggleOption('cursorline')<CR>
" Set autoread.
nnoremap [Space]ar  :<C-u>setlocal autoread<CR>
" Output encoding information.
nnoremap <silent> [Space]en  :<C-u>setlocal encoding? termencoding? fenc? fencs?<CR>
" Set fileencoding.
nnoremap [Space]fe  :<C-u>set fileencoding=

" Easily edit .vimrc and .gvimrc "{{{
nnoremap <silent> [Space]ev  :<C-u>edit $MYVIMRC<CR>
nnoremap <silent> [Space]eg  :<C-u>edit $MYGVIMRC<CR>
" Load .gvimrc after .vimrc edited at GVim.
nnoremap <silent> [Space]rv :<C-u>source $MYVIMRC \| if has('gui_running') \| source $MYGVIMRC \| endif \| echo "source $MYVIMRC"<CR>
nnoremap <silent> [Space]rg :<C-u>source $MYGVIMRC \| echo "source $MYGVIMRC"<CR>
"}}}

" Easily edit snippets file
nnoremap [Space]er  :<C-u>NeoComplCacheEditRuntimeSnippets<Space>
nnoremap [Space]es  :<C-u>NeoComplCacheEditSnippets<Space>

" Easily check registers and marks.
nnoremap <silent> [Space]mk  :<C-u>marks<CR>
nnoremap <silent> [Space]re  :<C-u>registers<CR>

" Easily check key-mappings.
nnoremap [Space]mpn  :<C-u>nnoremap<Space>
nnoremap [Space]mpi  :<C-u>inoremap<Space>
nnoremap [Space]mpc  :<C-u>cnoremap<Space>

" Saves "{{{
" :wはよく使うので<Space>wにマッピングする
nnoremap <silent> [Space]w  :<C-u>update<CR>
" :w!はよく使うので<Space>fwにマッピングする
nnoremap <silent> [Space]fw  :<C-u>write!<CR>
" :qはよく使うので<Space>qにマッピングする
nnoremap <silent> [Space]q  :<C-u>quit<CR>
" :qaは<Space>aqにマッピングする
nnoremap <silent> [Space]aq  :<C-u>quitall<CR>
" :q!はよく使うので<Space>fqにマッピングする
nnoremap <silent> [Space]fq  :<C-u>quitall!<CR>
" <Leader><Leader>で変更があれば保存
nnoremap <Leader><Leader> :<C-u>update<CR>
"}}}

" Change current directory.
nnoremap <silent> [Space]cd :<C-u>CD<CR>

" Delete windows ^M codes.
nnoremap <silent> [Space]<C-m> mmHmt:<C-u>%s/<C-v><CR>$//ge<CR>'tzt'm

" Easily syntax change."{{{
nnoremap [Space]0 :setl syntax=<CR>
nnoremap [Space]1 :setl syntax=xhtml<CR>
nnoremap [Space]2 :setl syntax=php<CR>
nnoremap [Space]3 :setl syntax=python<CR>
nnoremap [Space]4 :setl syntax=ruby<CR>
nnoremap [Space]5 :setl ft=javascript<CR>
" Detect syntax
nnoremap [Space]$ :filetype detect<cr>
nnoremap [Space]ft  :<C-u>setfiletype<Space>
"}}}

" Save and make. "{{{
nnoremap <silent> [Space]ma    :wall \| Make!<CR>
" Save and make current file only.
nnoremap <silent> [Space]mo    :wall \| call <SID>UpdateQuickFix("", 1, 1)<CR>
" Save and make test.
nnoremap <silent> [Space]mt    :wall \| echo system('make -s test')<CR>
" Toggle automatically make.
nnoremap <silent> [Space]mm :call <SID>EnableFlyMake()<CR>
"}}}

" Exchange gj and gk to j and k. "{{{
command! -nargs=? -bar -bang ToggleGJK call s:ToggleGJK()
nnoremap <silent> [Space]gj :<C-u>ToggleGJK<CR>
xnoremap <silent> [Space]gj :<C-u>ToggleGJK<CR>
function! s:ToggleGJK()
    if exists('b:enable_mapping_gjk') && b:enable_mapping_gjk
        let b:enable_mapping_gjk = 0
        noremap <buffer> j j
        noremap <buffer> k k
        noremap <buffer> gj gj
        noremap <buffer> gk gk

        xnoremap <buffer> j j
        xnoremap <buffer> k k
        xnoremap <buffer> gj gj
        xnoremap <buffer> gk gk
    else
        let b:enable_mapping_gjk = 1
        noremap <buffer> j gj
        noremap <buffer> k gk
        noremap <buffer> gj j
        noremap <buffer> gk k

        xnoremap <buffer> j gj
        xnoremap <buffer> k gk
        xnoremap <buffer> gj j
        xnoremap <buffer> gk k
    endif
endfunction"}}}

" Screen evaluation "{{{
if &term =~ "^screen"
    nnoremap <silent> [Space]se :<C-u>call ScreenEval(getline('.'))<CR>
    xnoremap <silent> [Space]se "zy:<C-u>call ScreenEval(@z)<CR>
endif"}}}

" Change tab width. "{{{
nnoremap <silent> [Space]t2 :<C-u>setl shiftwidth=2 softtabstop=2<CR>
nnoremap <silent> [Space]t4 :<C-u>setl shiftwidth=4 softtabstop=4<CR>
nnoremap <silent> [Space]t8 :<C-u>setl shiftwidth=8 softtabstop=8<CR>
"}}}

" Easily ctags command."{{{
nnoremap <silent> [Space]tt :<C-u>NeoCompleCacheCreateTags<CR>
nnoremap <silent> [Space]tr :<C-u>silent !ctags -R<CR>
" Easily helptags command.
nnoremap <silent> [Space]td :<C-u>helptags $DOTVIM/doc<CR>
"}}}

"}}}

" t: tags-and-searches "{{{
" The prefix key.
nnoremap    [Tag]   <Nop>
nmap    t [Tag]
" 飛ぶ
nnoremap [Tag]t  <C-]>
" 進む
nnoremap <silent> [Tag]n  :<C-u>tag<CR>
" 戻る
nnoremap <silent> [Tag]p  :<C-u>pop<CR>
" 履歴一覧
nnoremap <silent> [Tag]l  :<C-u>tags<CR>
" タグのリストを表示し、選択する
nnoremap <silent> [Tag]s  :<C-u>tselect<CR>
" 現在の候補を表示
nnoremap <silent> [Tag]i  :<C-u>0tnext<CR>
" 次の候補へ
nnoremap <silent> [Tag]N  :<C-u>tnext<CR>
" 前の候補へ
nnoremap <silent> [Tag]P  :<C-u>tprevious<CR>
" 最初の候補へ
nnoremap <silent> [Tag]F  :<C-u>tfirst<CR>
" 前の候補へ
nnoremap <silent> [Tag]L  :<C-u>tlast<CR>
" タグを指定してジャンプする
nnoremap [Tag]f  :<C-u>tag<Space>
" Display in preview window.
nnoremap [Tag]'t  <C-w>}
xnoremap [Tag]'t  <C-w>}
nnoremap <silent> [Tag]'n  :<C-u>ptnext<CR>
nnoremap <silent> [Tag]'p  :<C-u>ptprevious<CR>
nnoremap <silent> [Tag]'P  :<C-u>ptfirst<CR>
nnoremap <silent> [Tag]'N  :<C-u>ptlast<CR>
" プレビューウインドウを閉じる
nnoremap <silent> [Tag]'c  :<C-u>pclose<CR>
" 分割して飛ぶ
nnoremap [Tag]]  <C-w>]
"}}}

" s: Windows and buffers(High priority) "{{{
" The prefix key.
nnoremap    [Window]   <Nop>
nmap    s [Window]
nnoremap C         s
xnoremap C         s
nnoremap <silent> [Window]p  :<C-u>call <SID>split_nicely()<CR>
nnoremap <silent> [Window]v  :<C-u>vsplit<CR>
nnoremap <silent> [Window]c  :<C-u>close<CR>
nnoremap <silent> [Window]o  :<C-u>only<CR>
nnoremap <silent> [Window]w  :<C-u>call <SID>MovePreviousWindow()<CR>
nnoremap <silent> <Tab>      <C-w>w
nnoremap <silent> [Window]<Space>  :<C-u>call <SID>ToggleSplit()<CR>
function! s:MovePreviousWindow()
    let l:prev_name = winnr()
    silent! wincmd p
    if l:prev_name == winnr()
        silent! wincmd w
    endif
endfunction
" If window isn't splited, split buffer.
function! s:ToggleSplit()
    let l:prev_name = winnr()
    silent! wincmd w
    if l:prev_name == winnr()
        split
    else
        close
    endif
endfunction
" Split nicely."{{{
command! SplitNicely call s:split_nicely()
function! s:split_nicely()
    " Split nicely.
    if winheight(0) > &winheight
        split
    else
        vsplit
    endif
endfunction
"}}}
" Delete current buffer."{{{
nnoremap <silent> [Window]d  :<C-u>call <SID>CustomBufferDelete(0)<CR>
function! s:CustomBufferDelete(is_force)
    let current = bufnr('%')

    call s:CustomAlternateBuffer()

    if a:is_force
        silent! execute 'bdelete! ' . current
    else
        silent! execute 'bdelete ' . current
    endif
endfunction
"}}}
" Delete input buffer."{{{
nnoremap <silent> [Window]D  :<C-u>call <SID>InputBufferDelete(0)<CR>
function! s:InputBufferDelete(is_force)
    call s:ViewBufferList()

    " Create list.
    let [l:cnt, l:pos, l:list] = [0, 1, {}]
    while l:pos <= bufnr('$')
        if buflisted(l:pos)
            let l:list[l:cnt] = l:pos
            let l:cnt += 1
        endif
        let l:pos += 1
    endwhile

    let l:input = input('Select delete buffer: ', '')
    if l:input == ''
        " Cancel.
        return
    endif

    for l:in in split(l:input)
        if !has_key(l:list, l:in) || !bufexists(l:list[l:in])
            echo "\nDon't exists buffer " . l:in
            continue
        endif

        if l:in == bufnr('%') || l:in == bufname('%')
            call s:CustomAlternateBuffer()
        endif

        echo bufnr(l:list[l:in])
        if a:is_force
            silent! execute 'bdelete! ' . l:list[l:in]
        else
            silent! execute 'bdelete ' . l:list[l:in]
        endif
    endfor
endfunction
"}}}
" Force delete current buffer.
nnoremap <silent> [Window]fq  :<C-u>call <SID>CustomBufferDelete(1)<CR>
nnoremap <silent> [Window]fQ  :<C-u>call <SID>InputBufferDelete(1)<CR>
" Delete current buffer and close current window.
nnoremap <silent> [Window]d  :<C-u>call <SID>CustomBufferDelete(0)<CR>:if winnr() != 1 <Bar> close<CR>:endif<CR>
nnoremap <silent> [Window]fd  :<C-u>call <SID>CustomBufferDelete(1)<CR>:<C-u>close<CR>
" Buffer move.
nnoremap <silent> [Window][  :<C-u>bfirst<CR>
nnoremap <silent> [Window]<C-a>  :<C-u>bfirst<CR>
nnoremap <silent> [Window]]  :<C-u>blast<CR>
nnoremap <silent> [Window]<C-e>  :<C-u>blast<CR>
nnoremap <silent> [Window]k  :<C-u>bprevious<CR>
nnoremap <silent> [Window]j  :<C-u>bnext<CR>
nnoremap <silent> [Window];  :<C-u>bnext<CR>
nnoremap <silent> [Window]'  :<C-u>bprevious<CR>
nnoremap <silent> <C-s>  :<C-u>bnext<CR>
nnoremap <silent> <C-d>  :<C-u>bprevious<CR>
" Fast buffer switch."{{{
nnoremap <silent> [Window]s :<C-u>call <SID>CustomAlternateBuffer()<CR>
function! s:CustomAlternateBuffer()
    if bufnr('%') != bufnr('#') && buflisted(bufnr('#'))
        buffer # 
    else
        let l:cnt = 0
        let l:pos = 1
        let l:current = 0
        while l:pos <= bufnr('$')
            if buflisted(l:pos)
                if l:pos == bufnr('%')
                    let l:current = l:cnt
                endif

                let l:cnt += 1
            endif

            let l:pos += 1
        endwhile

        if l:current > l:cnt / 2
            bprevious
        else
            bnext
        endif
    endif
endfunction
"}}}
nnoremap <silent> [Window]q  :<C-u>call <SID>CustomBufferDelete(0)<CR>
" Move to other buffer numbering from left."{{{
for i in range(0, 9)
  execute 'nnoremap <silent>' ('[Window]'.i)  (':<C-u>call '.s:SID_PREFIX().'MoveBufferFromLeft('.i.')<CR>')
endfor"}}}
" Move with count."{{{
for i in range(1, 9)
    execute 'nnoremap <silent>' (i.'[Window]n')  (':'. i . 'bnext<CR>')
    execute 'nnoremap <silent>' (i.'[Window];')  (':'. i . 'bnext<CR>')
    execute 'nnoremap <silent>' (i.'[Window],')  (':'. i . 'bprevious<CR>')
    execute 'nnoremap <silent>' (i.'[Window]p')  (':'. i . 'bprevious<CR>')
endfor
unlet i
function! s:MoveBufferFromLeft(num)
    let l:cnt = 0
    let l:pos = 1
    while l:pos <= bufnr('$')
        if buflisted(l:pos)
            if l:cnt >= a:num
                execute 'buffer' . l:pos
                return
            endif

            let l:cnt += 1
        endif

        let l:pos += 1
    endwhile
endfunction"}}}
" Move to input buffer numbering from left."{{{
nnoremap <silent> [Window].  :<C-u>call <SID>MoveInputBufferFromLeft()<CR>
function! s:MoveInputBufferFromLeft()
    call s:ViewBufferList()
    let l:in = input('Select the buffer from left position: ', '', 'buffer')
    if l:in !~ '^\d\+$'
        " Search buffer.
        execute 'buffer ' . l:in
        return
    else
        call s:MoveBufferFromLeft(l:in)
    endif
endfunction"}}}
" Move to medium buffer numbering from left."{{{
nnoremap <silent> [Window]/  :<C-u>call <SID>MoveBufferMedium()<CR>
function! s:MoveBufferMedium()
    let l:pos = 1
    let l:buf = []
    while l:pos <= bufnr('$')
        if buflisted(l:pos)
            call add(l:buf, l:pos)
        endif
        let l:pos += 1
    endwhile

    execute 'buffer' . l:buf[len(l:buf)/2]
endfunction"}}}
" Edit"{{{
nnoremap [Window]b  :<C-u>edit<Space>
nnoremap <silent> [Window]en  :<C-u>new<CR>
nnoremap <silent> [Window]ee  :<C-u>enew<CR>
nnoremap <silent> [Window]ej  :<C-u>JunkFile<CR>
nnoremap [Window]r  :<C-u>REdit<Space>
nmap <silent> [Window]es  <Plug>(scratch-open)
imap <silent> <C-z> <C-o><Plug>(scratch-open)
"}}}
" View buffer list."{{{
nnoremap <silent> [Window]l  :<C-u>call <SID>ViewBufferList()<CR>
function! s:ViewBufferList()
    let [l:pos, l:cnt] = [1, 0]
    while l:pos <= bufnr('$')
        if buflisted(l:pos)
            if l:pos == bufnr('%')
                let l:flags = '%'
            elseif l:pos == bufnr('#')
                let l:flags = '#'
            else
                let l:flags = ' '
            endif

            if getbufvar(l:pos, '&modified')
                let l:flags .= '!'
            elseif getbufvar(l:pos, '&modifiable') == 0
                let l:flags .= '-'
            endif

            echo printf('%3d %3s   %s', l:cnt, l:flags, fnamemodify(bufname(l:pos), ':.'))
            let l:cnt += 1
        endif
        let l:pos += 1
    endwhile
endfunction"}}}
"}}}

" e: Change basic commands "{{{
" The prefix key.
nnoremap [Alt]   <Nop>
nmap    e  [Alt]

" Indent paste.
"nnoremap [Alt]p pm``[=`]``
"nnoremap [Alt]P Pm``[=`]``
nnoremap <silent> [Alt]p o<ESC>:call <SID>chomp_register()<CR>pm``[=`]``^
nnoremap <silent> [Alt]P O<ESC>:call <SID>chomp_register()<CR>Pm``[=`]``^
" Insert blank line.
nnoremap <silent> [Alt]o o<Space><BS><ESC>
nnoremap <silent> [Alt]O O<Space><BS><ESC>
" Yank to end line.
nmap [Alt]y y$
nmap Y y$
" Delete first character.
nnoremap [Alt]x ^"_x
nnoremap X ^"_x
nnoremap x "_x
" Line selection <C-v>.
nnoremap [Alt]V 0<C-v>$h
" Folding close.
nnoremap [Alt]h  zc

" Useless commands
nnoremap [Alt];  ;
nnoremap [Alt],  ,

"}}}

" <C-g>: Argument list  "{{{
"
" The prefix key.
nnoremap [Argument]   <Nop>
nmap    <C-g>  [Argument]
 
nnoremap [Argument]<Space>  :<C-u>args<Space>
nnoremap <silent> [Argument]l  :<C-u>args<CR>
nnoremap <silent> [Argument]n  :<C-u>next<CR>
nnoremap <silent> [Argument]p  :<C-u>previous<CR>
nnoremap <silent> [Argument]P  :<C-u>first<CR>
nnoremap <silent> [Argument]N  :<C-u>last<CR>
nnoremap <silent> [Argument]wp :<C-u>wnext<CR>
nnoremap <silent> [Argument]wn :<C-u>wprevious<CR>
"}}}

" <C-t>: Tab pages"{{{
"
" The prefix key.
nnoremap [Tabbed]   <Nop>
nmap    <C-t>  [Tabbed]
" Create tab page.
nnoremap <silent> [Tabbed]c  :<C-u>tabnew<CR>
nnoremap <silent> [Tabbed]d  :<C-u>tabclose<CR>
nnoremap <silent> [Tabbed]o  :<C-u>tabonly<CR>
nnoremap <silent> [Tabbed]i  :<C-u>tabs<CR>
nmap [Tabbed]<C-n>  [Tabbed]n
nmap [Tabbed]<C-c>  [Tabbed]c
nmap [Tabbed]<C-o>  [Tabbed]o
nmap [Tabbed]<C-i>  [Tabbed]i
" Move to other tab page.
nnoremap <silent> [Tabbed]j
            \ :execute 'tabnext' 1 + (tabpagenr() + v:count1 - 1) % tabpagenr('$')<CR>
nnoremap <silent> [Tabbed]k  :<C-u>tabprevious<CR>
nnoremap <silent> [Tabbed]K  :<C-u>tabfirst<CR>
nnoremap <silent> [Tabbed]J  :<C-u>tablast<CR>
nnoremap <silent> [Tabbed]l
            \ :<C-u>execute 'tabmove' min([tabpagenr() + v:count1 - 1, tabpagenr('$')])<CR>
nnoremap <silent> [Tabbed]h
            \ :<C-u>execute 'tabmove' max([tabpagenr() - v:count1 - 1, 0])<CR>
nnoremap <silent> [Tabbed]L  :<C-u>tabmove<CR>
nnoremap <silent> [Tabbed]H  :<C-u>tabmove 0<CR>
nmap [Tabbed]n  [Tabbed]j
nmap [Tabbed]p  [Tabbed]k
nmap [Tabbed]<C-t>  [Tabbed]j
nmap [Tabbed]<C-l>  [Tabbed]l
nmap [Tabbed]<C-h>  [Tabbed]h

" Move to previous tab.
nnoremap <silent>[Tabbed]<Space> :<C-u>TabRecent<CR>
nnoremap [Tabbed]r :<C-u>TabRecent<Space>

" Change current tab like GNU screen.
" Note that the numbers in {lhs}s are 0-origin.  See also 'tabline'.
for i in range(10)
  execute 'nnoremap <silent>' ('[Tabbed]'.(i))  ((i+1).'gt')
endfor
unlet i
"}}}

" q: Quickfix  "{{{
 
" The prefix key.
nnoremap [Quickfix]   <Nop>
nmap    q  [Quickfix]
" Disable Ex-mode.
nnoremap Q  q
 
" For quickfix list  "{{{3
nnoremap <silent> [Quickfix]n  :<C-u>cnext<CR>
nnoremap <silent> [Quickfix]p  :<C-u>cprevious<CR>
nnoremap <silent> [Quickfix]r  :<C-u>crewind<CR>
nnoremap <silent> [Quickfix]N  :<C-u>cfirst<CR>
nnoremap <silent> [Quickfix]P  :<C-u>clast<CR>
nnoremap <silent> [Quickfix]fn :<C-u>cnfile<CR>
nnoremap <silent> [Quickfix]fp :<C-u>cpfile<CR>
nnoremap <silent> [Quickfix]l  :<C-u>clist<CR>
nnoremap <silent> [Quickfix]q  :<C-u>cc<CR>
nnoremap <silent> [Quickfix]o  :<C-u>copen<CR>
nnoremap <silent> [Quickfix]c  :<C-u>cclose<CR>
nnoremap <silent> [Quickfix]en :<C-u>cnewer<CR>
nnoremap <silent> [Quickfix]ep :<C-u>colder<CR>
nnoremap <silent> [Quickfix]m  :<C-u>make<CR>
nnoremap [Quickfix]M  :<C-u>make<Space>
nnoremap [Quickfix]g  :<C-u>grep<Space>
" Toggle quickfix window.
nnoremap <silent> [Quickfix]<Space> :<C-u>call <SID>toggle_quickfix_window()<CR>
function! s:toggle_quickfix_window()
  let _ = winnr('$')
  cclose
  if _ == winnr('$')
    copen
    setlocal nowrap
    setlocal whichwrap=b,s
  endif
endfunction

" For location list (mnemonic: Quickfix list for the current Window)  "{{{3
nnoremap <silent> [Quickfix]wn  :<C-u>lnext<CR>
nnoremap <silent> [Quickfix]wp  :<C-u>lprevious<CR>
nnoremap <silent> [Quickfix]wr  :<C-u>lrewind<CR>
nnoremap <silent> [Quickfix]wP  :<C-u>lfirst<CR>
nnoremap <silent> [Quickfix]wN  :<C-u>llast<CR>
nnoremap <silent> [Quickfix]wfn :<C-u>lnfile<CR>
nnoremap <silent> [Quickfix]wfp :<C-u>lpfile<CR>
nnoremap <silent> [Quickfix]wl  :<C-u>llist<CR>
nnoremap <silent> [Quickfix]wq  :<C-u>ll<CR>
nnoremap <silent> [Quickfix]wo  :<C-u>lopen<CR>
nnoremap <silent> [Quickfix]wc  :<C-u>lclose<CR>
nnoremap <silent> [Quickfix]wep :<C-u>lolder<CR>
nnoremap <silent> [Quickfix]wen :<C-u>lnewer<CR>
nnoremap <silent> [Quickfix]wm  :<C-u>lmake<CR>
nnoremap [Quickfix]wM  :<C-u>lmake<Space>
nnoremap [Quickfix]w<Space>  :<C-u>lmake<Space>
nnoremap [Quickfix]wg  :<C-u>lgrep<Space>
"}}}

"}}}

" f: FuzzyJump "{{{
" The prefix key.
nnoremap [Fuzzy]   <Nop>
nmap    f  [Fuzzy]

" FuzzyJump
nmap [Fuzzy]j  <Plug>(fuzzyjump-prefix)

"}}}

" 0: Preview window "{{{
" The prefix key.
nnoremap [Preview]   <Nop>
nmap    0  [Preview]

" Toggle preview window."{{{
nnoremap <silent> [Preview]0  :<C-u>call<SID>preview_window_toggle()<CR>
function! s:preview_window_toggle()
    silent! wincmd P
    if &previewwindow
        pclose
    elseif expand('%') != ''
        mkview
        silent! pedit
        silent loadview
        if foldclosed(line('.')) != -1 
            " Open folding.
            normal! zogv0
        endif
    else
        normal! ma
        silent! pedit
        normal! `a
        if foldclosed(line('.')) != -1 
            " Open folding.
            normal! zogv0
        endif
    endif
endfunction"}}}
" Open preview window.
nnoremap [Preview]o  :<C-u>pedit<CR>
" Close preview window.
nnoremap [Preview]c  :<C-u>pclose<CR>
" Move to preview window."{{{
nnoremap <silent> [Preview]p :<C-u>call<SID>move_to_preview_window()<CR>
function! s:move_to_preview_window()
    if &previewwindow
        wincmd p
    else
        silent! wincmd P
    endif
endfunction"}}}
"}}}

" Jump mark can restore column."{{{
nnoremap \  `
" mもMに降格
nnoremap M  m
"}}}

" Don't calc octal.
set nrformats-=octal

" Jump history.
nnoremap <silent> <C-k> <C-o>
nnoremap <silent> <C-j> <C-i>

" Finish with having left a screen of vim.
nnoremap <silent> gZZ :<C-u>set t_te= t_ti= \| quit \| set t_te& t_ti&<CR>
" Start a shell with having left a screen of vim.
nnoremap <silent> gsh :<C-u>set t_te= t_ti= \| sh \| set t_te& t_ti&<CR>

" Move search word to middle screen."{{{
nnoremap n  nzz
nnoremap N  Nzz
nnoremap *  *zz
nnoremap #  #zz
nnoremap g*  g*zz
nnoremap g#  g#zz
"}}}

" Smart <C-f>, <C-b>.
nnoremap <silent> <C-f> z<CR><C-f>z.
nnoremap <silent> <C-b> z-<C-b>z.

" Execute help."{{{
nnoremap <C-h>  :<C-u>help<Space>
" Execute help by cursor keyword.
nnoremap <silent> g<C-h>  :<C-u>help<Space><C-r><C-w><CR>
" Grep in help.
nnoremap grh  :<C-u>Hg<Space>
"}}}

" Disable ZZ.
nnoremap ZZ  <Nop>

" Exchange ';' to ':'.
nnoremap ;  :
xnoremap ;  :

" Like gv, but select the last changed text.
nnoremap gc  `[v`]
" Specify the last changed text as {motion}.
vnoremap <silent> gc  :<C-u>normal gc<CR>
onoremap <silent> gc  :<C-u>normal gc<CR>

" Auto escape / and ? in search command.
cnoremap <expr> / getcmdtype() == '/' ? '\/' : '/'

" Smart }."{{{
nnoremap <silent> } :<C-u>call ForwardParagraph()<CR>
onoremap <silent> } :<C-u>call ForwardParagraph()<CR>
xnoremap <silent> } <Esc>:<C-u>call ForwardParagraph()<CR>mzgv`z
function! ForwardParagraph()
    let cnt = v:count ? v:count : 1
    let i = 0
    while i < cnt
        if !search('^\s*\n.*\S','W')
            normal! G$
            return
        endif
        let i = i + 1
    endwhile
endfunction
"}}}

" Context sensitive H,L."{{{
nnoremap <silent> H :<C-u>call HContext()<CR>
nnoremap <silent> L :<C-u>call LContext()<CR>
xnoremap <silent> H <ESC>:<C-u>call HContext()<CR>mzgv`z
xnoremap <silent> L <ESC>:<C-u>call LContext()<CR>mzgv`z
function! HContext() 
    let l:moved = MoveCursor("H") 
    if !l:moved && line('.') != 1 
        execute "normal! " . "\<pageup>H" 
    endif 
endfunction
function! LContext() 
    let l:moved = MoveCursor("L") 

    if !l:moved && line('.') != line('$') 
        execute "normal! " . "\<pagedown>L" 
    endif 
endfunction
function! MoveCursor(key) 
    let l:cnum = col('.') 
    let l:lnum = line('.') 
    let l:wline = winline() 

    execute "normal! " . v:count . a:key 
    let l:moved =  l:cnum != col('.') || l:lnum != line('.') || l:wline != winline() 

    return l:moved 
endfunction
"}}}

" Smart home and smart end."{{{
nnoremap <silent> gh  :<C-u>call SmartHome("n")<CR>
nnoremap <silent> gl  :<C-u>call SmartEnd("n")<CR>
xnoremap <silent> gh  <ESC>:<C-u>call SmartHome("v")<CR>
xnoremap <silent> gl  <ESC>:<C-u>call SmartEnd("v")<CR>
nnoremap <expr> gm    (virtcol('$')/2).'\|'
xnoremap <expr> gm    (virtcol('$')/2).'\|'
" Mappings normal commands.
nnoremap <silent> ^  :<C-u>call SmartHome("n")<CR>
nnoremap <silent> _  :<C-u>call SmartHome("n")<CR>
xnoremap <silent> ^  <ESC>:<C-u>call SmartHome("v")<CR>
xnoremap <silent> _  <ESC>:<C-u>call SmartHome("v")<CR>
" Smart home function"{{{
function! SmartHome(mode)
    let l:curcol = col(".")

    if &wrap
        normal! g^
    else
        normal! ^
    endif
    if col(".") == l:curcol
        if &wrap
            normal! g0
        else
            normal! 0
        endif
    endif

    if a:mode == "v"
        normal! msgv`s
    endif

    return ""
endfunction"}}}

" Smart end function"{{{
function! SmartEnd(mode)
    let l:curcol = col(".")
    let l:lastcol = a:mode == "i" ? col("$") : col("$") - 1

    " Gravitate towards ending for wrapped lines
    if l:curcol < l:lastcol - 1
        call cursor(0, l:curcol + 1)
    endif

    if l:curcol < l:lastcol
        if &wrap
            normal! g$
        else
            normal! $
        endif
    else
        normal! g_
    endif

    " Correct edit mode cursor position, put after current character
    if a:mode == "i"
        call cursor(0, col(".") + 1)
    endif

    if a:mode == "v"
        normal! msgv`s
    endif

    return ""
endfunction "}}}
"}}}

" Jump to a line and the line of before and after of the same indent."{{{
" Useful for Python.
nnoremap <silent> g{ :<C-u>call search("^" . matchstr(getline(line(".") + 1), '\(\s*\)') ."\\S", 'b')<CR>^
nnoremap <silent> g} :<C-u>call search("^" . matchstr(getline(line(".")), '\(\s*\)') ."\\S")<CR>^
"}}}

" Select rectangle.
xnoremap r <C-v>
" Select until end of current line in visual mode.
xnoremap v $h

" Search for selecting text.
" ^@ などキー入力が困難なコントロール文字を検索(もしくは置換)対象にするときに重宝する。
xnoremap g* y/\V<C-R>=substitute(escape(@",'/'),"\n","\\\\n","g")<CR>/<CR>

" Insert buffer directory in command line."{{{
" Expand path.
cnoremap <C-x> <C-r>=<SID>GetBufferDirectory(1)<CR>/
" Expand file (not ext).
cnoremap <C-z> <C-r>=<SID>GetBufferDirectory(0)<CR>
function! s:GetBufferDirectory(with_ext)
    if a:with_ext
        let l:path = expand('%:p:h')
    else
        let l:path = expand('%:p:r')
    endif
  let l:cwd = getcwd()
  if match(l:path, l:cwd) != 0
    return l:path
  elseif strlen(l:path) > strlen(l:cwd)
    return strpart(l:path, strlen(l:cwd) + 1)
  else
    return '.'
  endif
endfunction
"}}}

" Paste current line.
nnoremap cp Pjdd
" Paste next line.
nnoremap <silent> gp o<ESC>:call <SID>chomp_register()<CR>p^
nnoremap <silent> gP O<ESC>:call <SID>chomp_register()<CR>p^
function! s:chomp_register()
    if @* =~ '\n$'
        let @* = @*[:-2]
    endif
endfunction

" Paste and indent line.
nnoremap ]p p`[=`]^
nnoremap ]P P`[=`]^

"Return Redraw
nnoremap <silent> <C-l>    :<C-u>redraw!<CR>

" Folding."{{{
" If press h on head, fold close.
"nnoremap <expr> h col('.') == 1 && foldlevel(line('.')) > 0 ? 'zc' : 'h'
" If press l on fold, fold open.
nnoremap <expr> l foldclosed(line('.')) != -1 ? 'zo0' : 'l'
" If press h on head, range fold close.
"xnoremap <expr> h col('.') == 1 && foldlevel(line('.')) > 0 ? 'zcgv' : 'h'
" If press l on fold, range fold open.
xnoremap <expr> l foldclosed(line('.')) != -1 ? 'zogv0' : 'l'
" Useful command.
nnoremap z<Space>   za
"}}}

" Fast search pair.
nmap [Space]p    %
xmap [Space]p    %

" Search a parenthesis.
onoremap <silent> q /["',.{}()[\]<>]<CR>

" Fast substitute.
xnoremap s y:%s/\<<C-R>"\>//g<Left><Left>

" Paste yanked text."{{{
xnoremap <silent> p :<C-u>call <SID>YankPaste()<CR>
xnoremap <silent> P :<C-u>call <SID>YankPaste()<CR>
function! s:YankPaste()
    let a = @*
    normal! gvp
    let @* = a
endfunction

" Exchange cursor word to yanked word.
nnoremap <silent> ciy ciw<C-r>0<ESC>:let@/=@1<CR>:noh<CR>
nnoremap <silent> cy   ce<C-r>0<ESC>:let@/=@1<CR>:noh<CR>
" Paste yanked character.
nnoremap gy "0P

"}}}

" Move last modified text.
nnoremap gb `.zz
nnoremap g, g;
nnoremap g; g,

" Repeat previous command.
nnoremap ^   @:

" Recording commands."{{{
nnoremap <silent> +      :<C-u>call <SID>recording_commands()<CR>
function! s:recording_commands()
    let l:prev_command = substitute(@z, "\<CR>", '', 'g')
    let l:input = input('Input command: ', l:prev_command, 'mapping')
    if l:input != ''
        let @z = substitute(l:input, '<CR>', "\<CR>", 'g')
    endif
endfunction
" Execute macro.
nnoremap <silent> \   @z
nnoremap <silent> -          :<C-u>call <SID>recording_macro()<CR>
let s:recording = 0
function! s:recording_macro()
    if s:recording
        let s:recording = 0
        normal! q
        " Delete last '-'.
        let @z = substitute(@z, '-$', '', '')
    else
        let s:recording = 1
        normal! qz
    endif
endfunction
"}}}

" Change the height of the current window to match the visual selection and scroll 
" the text so that all of the selection is visible.
xmap <C-w><C-_>  <C-w>
xnoremap <silent> <C-w>_  :<C-u><C-r>=line("'>") - line("'<") + 1<CR>wincmd _<CR>`<zt

" Sticky shift in English keyboard."{{{
" Sticky key.
inoremap <expr> ;  <SID>sticky_func()
cnoremap <expr> ;  <SID>sticky_func()
snoremap <expr> ;  <SID>sticky_func()

function! s:sticky_func()
    let l:sticky_table = {
                \',' : '<', '.' : '>', '/' : '?',
                \'1' : '!', '2' : '@', '3' : '#', '4' : '$', '5' : '%',
                \'6' : '^', '7' : '&', '8' : '*', '9' : '(', '0' : ')', '-' : '_', '=' : '+',
                \';' : ':', '[' : '{', ']' : '}', '`' : '~', "'" : "\"", '\' : '|',
                \}
    let l:special_table = {
                \"\<ESC>" : "\<ESC>", "\<Space>" : ';', "\<CR>" : ";\<CR>"
                \}

    let l:key = getchar()
    if nr2char(l:key) =~ '\l'
        return toupper(nr2char(l:key))
    elseif has_key(l:sticky_table, nr2char(l:key))
        return l:sticky_table[nr2char(l:key)]
    elseif has_key(l:special_table, nr2char(l:key))
        return l:special_table[nr2char(l:key)]
    else
        return ''
    endif
endfunction

" Easy escape."{{{
xnoremap J            <ESC>
onoremap J            <ESC>
inoremap J            <ESC>
cnoremap J            <C-c>
onoremap jj           <ESC>
inoremap <expr>jj pumvisible() ? neocomplcache#close_popup()."\<ESC>" : "\<ESC>"
cnoremap jj           <C-c>
onoremap j;           j
inoremap j;           j
cnoremap j;           j
"}}}

" }}}

" Smart word search."{{{
" Search cursor word by word unit.
nnoremap <silent> *  :<C-u>call <SID>SetSearch('""yiw', 'word')<CR>
" Search cursor word.
nnoremap <silent> g* :<C-u>call <SID>SetSearch('""yiw')<CR>
" Search from cursor to word end.
nnoremap <silent> #  :<C-u>call <SID>SetSearch('""ye')<CR>

" Search selected text.
xnoremap <silent> * :<C-u>call <SID>SetSearch('""vgvy')<CR>
xnoremap <silent> # :<C-u>call <SID>SetSearch('""vgvy')<CR>

""""""""""""""""""""""""""""""
" Set search word.
" If set additional parametar, search by word unit.
""""""""""""""""""""""""""""""
function! s:SetSearch(cmd, ...)
  let saved_reg = @"
  if a:cmd != ''
    silent exec 'normal! '.a:cmd
  endif
  let pattern = escape(@", '\\/.*$^~[]')
  let pattern = substitute(pattern, '\n$', '', '')
  if a:0 > 0
    let pattern = '\<'.pattern.'\>'
  endif
  let @/ = pattern
  let @" = saved_reg
  echo @/
endfunction "}}}

" Replace cursor word with yank text.
nnoremap <silent> ciy ciw<C-r>0<ESC>:let@/=@1<CR>:noh<CR>
nnoremap <silent> cy   ce<C-r>0<ESC>:let@/=@1<CR>:noh<CR>

" Execute countable 'n.'.
" EXAMPLE: 3@n
let @n='n.'

" a>, i], etc... "{{{
" <angle>
onoremap aa  a>
xnoremap aa  a>
onoremap ia  i>
xnoremap ia  i>

" [rectangle]
onoremap ar  a]
xnoremap ar  a]
onoremap ir  i]
xnoremap ir  i]

" 'quote'
onoremap aq  a'
xnoremap aq  a'
onoremap iq  i'
xnoremap iq  i'

" "double quote"
onoremap ad  a"
xnoremap ad  a"
onoremap id  i"
xnoremap id  i"
"}}}

" almigh-t
onoremap <silent> q
\      :for i in range(v:count1)
\ <Bar>   call search('.\&\(\k\<Bar>\_s\)\@!', 'W')
\ <Bar> endfor<CR>

" Upcase word.
nnoremap [Alt]u  gUiw
nnoremap U  gU

"}}}

"---------------------------------------------------------------------------
" Commands:"{{{
"
" Toggle options. "{{{
function! ToggleOption(option_name)
    execute 'setlocal' a:option_name.'!'
    execute 'setlocal' a:option_name.'?'
endfunction  "}}}
" Toggle variables. "{{{
function! ToggleVariable(variable_name)
    if eval(a:variable_name)
        execute 'let' a:variable_name.' = 0'
    else
        execute 'let' a:variable_name.' = 1'
    endif
    echo printf('%s = %s', a:variable_name, eval(a:variable_name))
endfunction  "}}}

" :Hg (alternative of ':helpg[rep]')"{{{
" Because if use default ':helpgrep', Japanese texts are garbled.
command! -nargs=1 Hg call NewHelpgrep("<args>") 
function! NewHelpgrep( arg ) 
    " Convert helpgrep argments.
    exec ":helpgrep " . iconv(a:arg, "cp932", "utf-8") 
endfunction
"}}}

" 指定したファイルとの差分を表示
command! -nargs=1 -complete=file VDsplit vertical diffsplit <args>
" 最後の保存から、どれだけ編集したのか差分を表示
command! DiffOrig vert new | setlocal bt=nofile | r # | 0d_ | diffthis | wincmd p | diffthis
" diffモードを解除する
command! -nargs=0 Undiff setlocal nodiff noscrollbind wrap

" Smart make."{{{
" Unlike normal ':make', don't flick.
function! s:UpdateQuickFix(command, jump, only)
    " Rubyではruby -wcで文法チェックを行う
    if filereadable("Makefile")
        let lines = split(system('make -s'), "\n")
        cgetexpr lines
    elseif &ft == 'tex'
        " Because make error if no filename.
        call s:ChangeCurrentDir('', '!')
        if a:command == ''
            silent make %<
        else
            execute "silent make " . a:command
        endif

        " remove deadwoods
        call delete(expand('%:r') . '.aux')
        call delete(expand('%:r') . '.log')
    else
        " Do ':make'
        if a:command != ''
            if a:only
                " Current file only.
                execute 'make '.expand("%:r").'.o'
            else
                silent make
            endif
        else
            execute "silent make " . a:command
        endif
    endif

    let n_error = len(filter(getqflist(), 'v:val.valid || v:val.type == "E"'))
    let n_warning = len(filter(getqflist(), 'v:val.type == "W"'))
    if n_error == 0
        cclose
        redraw
        echo printf('QuickFix: no error and %d warnings.  :)', n_warning)
    else
        copen

        if a:jump
            cc
            normal! zv
        else
            wincmd p
        endif
        redraw
        echo printf('QuickFix: %d errors and %d warnings.', n_error, n_warning)
    endif
    " for errormarker.vim
    silent doautocmd QuickFixCmdPost make
endfunction"}}}

command! -nargs=? -bar -bang Make call s:UpdateQuickFix("<args>", len('<bang>'), 0)

" arg: 1->enable / 0->disable / omitted->toggle"{{{
function! s:EnableFlyMake(...)
    if a:0
        let b:flymake_enabled = a:1
    else
        let b:flymake_enabled = (!exists('b:flymake_enabled') || !b:flymake_enabled)
    endif
    redraw
    augroup MyAutoCmd
        if s:flymake_enabled
            autocmd BufWritePost * Make
            echo "flymake enabled."
        else
            echo "flymake disabled."
        endif
    augroup END
endfunction"}}}

" Change current directory."{{{
command! -nargs=? -complete=customlist,CompleteCD -bang CD  call s:ChangeCurrentDir('<args>', '<bang>') 
function! s:ChangeCurrentDir(directory, bang)
    if a:directory == ''
        lcd %:p:h
    else
        execute 'lcd' . a:directory
    endif

    if a:bang == ''
        pwd
    endif
endfunction"}}}
function! CompleteCD(arglead, cmdline, cursorpos)
    let l:pattern = join(split(a:cmdline, '\s', !0)[1:], ' ') . '*/'
    return split(globpath(&cdpath, l:pattern), "\n")
endfunction
cnoreabbrev <expr> cd  (getcmdtype() == ':' && getcmdline()  ==# 'cd') ? 'CD' : 'cd'

function! s:Batch() range"{{{
    " read vimscript from selected area.
    let l:selected = getline(a:firstline, a:lastline)
    " get temp file.
    let l:tempfile = tempname()
    " try-finally
    try
    " write vimscript to temp file.
        call writefile(l:selected, l:tempfile)
        try
            " execute temp file.
            execute "source " . l:tempfile
        catch
            " catch exception
            echohl WarningMsg |
                        \ echo "EXCEPTION :" v:exception |
                        \ echo "THROWPOINT:" v:throwpoint |
                        \ echohl None
        endtry
        finally
        " delete temp file.
        if filewritable(l:tempfile)
            call delete(l:tempfile)
        endif
    endtry
endfunction"}}}
" Range source.
command! -range -narg=0 Batch :<line1>,<line2>call s:Batch()

" Substitute indent.
command! -range=% LeadUnderscores <line1>,<line2>s/^\s*/\=repeat('_', strlen(submatch(0)))/g
nnoremap <silent> [Space]u        :LeadUnderscores<CR>
xnoremap <silent> [Space]u        :LeadUnderscores<CR>

" Open junk file."{{{
command! -nargs=0 JunkFile call s:open_junk_file()
function! s:open_junk_file()
    let l:junk_dir = $HOME . '/.vim_junk'. strftime('/%Y/%m')
    if !isdirectory(l:junk_dir)
        call mkdir(l:junk_dir, 'p')
    endif

    let l:filename = input('Junk Code: ', l:junk_dir.strftime('/%Y-%m-%d-%H%M%S.'))
    if l:filename != ''
        execute 'edit ' . l:filename
    endif
endfunction"}}}

" LevenShtein argorithm."{{{
function! CalcLeven(str1, str2)
    let [l:p1, l:p2, l:l1, l:l2] = [[], [], len(a:str1), len(a:str2)]

    for l:i in range(l:l2+1) 
        call add(l:p1, l:i)
    endfor 
    for l:i in range(l:l2+1) 
        call add(l:p2, 0)
    endfor 

    for l:i in range(l:l1)
        let l:p2[0] = l:p1[0] + 1
        for l:j in range(l:l2)
            let l:p2[l:j+1] = min([l:p1[l:j] + ((a:str1[l:i] == a:str2[l:j]) ? 0 : 1), 
                        \l:p1[l:j+1] + 1, l:p2[l:j]+1])
        endfor
        let [l:p1, l:p2] = [l:p2, l:p1]
    endfor

    return l:p1[l:l2]
endfunction"}}}

command! -nargs=1 -bang -bar -complete=file Rename saveas<bang> <args> | call delete(expand('#:p'))
command! -nargs=+ Grep  execute 'grep' '/'.[<f-args>][-1].'/' join([<f-args>][:-2])

" Calc Vim fight power.
command! -bar -nargs=? -complete=file CalcFP echo len(filter(readfile(empty(<q-args>) ? $MYVIMRC : expand(<q-args>)),'v:val !~ "^\\s*$\\|^\\s*\""'))

" Search match pair.
function! MatchPair(string, start_pattern, end_pattern, start_cnt)
    let l:end = -1
    let l:start_pattern = '\%(' . a:start_pattern . '\)'
    let l:end_pattern = '\%(' . a:end_pattern . '\)'

    let l:i = a:start_cnt
    let l:max = len(a:string)
    let l:nest_level = 0
    while l:i < l:max
        if match(a:string, l:start_pattern, l:i) >= 0
            let l:i = matchend(a:string, l:start_pattern, l:i)
            let l:nest_level += 1
        elseif match(a:string, l:end_pattern, l:i) >= 0
            let l:end = match(a:string, l:end_pattern, l:i)
            let l:nest_level -= 1

            if l:nest_level == 0
                return l:end
            endif

            let l:i = matchend(a:string, l:end_pattern, l:i)
        else
            break
        endif
    endwhile

    if l:nest_level != 0
        return -1
    else
        return l:end
    endif
endfunction

"}}}
  
"---------------------------------------------------------------------------
" Platform depends:"{{{
"
if has('win32') || has('win64') 
    " For Windows"{{{

    " WinではPATHに$VIMが含まれていないときにexeを見つけ出せないので修正
    if $PATH !~? '\(^\|;\)' . escape($VIM, '\\') . '\(;\|$\)'
        let $PATH = $VIM . ';' . $PATH
    endif

    " Shell settings.
    " Use NYACUS.
    set shell=nyacus.exe
    set shellcmdflag=-e
    set shellpipe=\|&\ tee
    set shellredir=>%s\ 2>&1
    set shellxquote=\"

    " Use bash.
    "set shell=bash.exe
    "set shellcmdflag=-c
    "set shellpipe=2>&1\|\ tee
    "set shellredir=>%s\ 2>&1
    "set shellxquote=\"

    " Change colorscheme.
    " Don't override colorscheme.
    if !exists('g:colors_name') && !has('gui_running')
        colorscheme darkblue 
    endif
    " Disable error messages.
    let g:CSApprox_verbose_level = 0

    " そこそこ見れる補完リストにする
    hi Pmenu ctermbg=8
    hi PmenuSel ctermbg=1
    hi PmenuSbar ctermbg=0

    " Display the directory of the baing current buffer in afx.
    noremap <silent> <F1> :execute '!start runafx.bat' '-s "-p%:p"'<cr>
    "}}}
else
    " For Linux"{{{

    " Use zsh.
    set shell=zsh

    " For non GVim.
    if !has('gui_running')
        " Enable 256 color terminal.
        set t_Co=256

        if has('gui')
            " Use CSApprox.vim
            
            " Convert colorscheme in Konsole.
            let g:CSApprox_konsole = 1
            let g:CSApprox_attr_map = { 'bold' : 'bold', 'italic' : '', 'sp' : '' }
            if !exists('g:colors_name')
                colorscheme candy
            endif
        else
            " Use guicolorscheme.vim
            autocmd MyAutoCmd VimEnter,BufAdd * if !exists('g:colors_name') | GuiColorScheme candy
        endif

        " For prevent bug.
        autocmd MyAutoCmd VimLeave * set term=screen

        " For screen."{{{
        if &term =~ "^screen"
            augroup MyAutoCmd
                " Show filename on screen statusline.
                " But invalid 'another' screen buffer.
                autocmd BufEnter * if $WINDOW != 0 &&  bufname("") !~ "^\[A-Za-z0-9\]*://" 
                            \ | silent! exe '!echo -n "^[kv:%:t^[\\"' | endif
                " なぜかは知らないがmouseを空にしないと終了時にフリーズする
                autocmd VimLeave * :set mouse=
            augroup END

            " screenでマウスを使用するとフリーズするのでその対策
            set ttymouse=xterm2

            " Split Vim and screen.
            function! ScreenSpiritOpen(cmd)
                call system("screen -X eval split  focus 'screen " . a:cmd ."' focus")
            endfunction
            function! ScreenEval(str)
                let s = substitute(a:str, "[\n]*$", "\n\n", "") " 最後が改行 * 2で終わるようにする。
                call writefile(split(s, "\n"), "/tmp/vim-screen", "b")
                call system("screen -X eval focus 'readreg p /tmp/vim-screen' 'paste p' focus")
            endfunction

            command! -nargs=1 Screen call ScreenSpiritOpen("<args>")

            " Pseudo :suspend with automtic cd.
            " Assumption: Use GNU screen.
            " Assumption: There is a window with the title "another".
            noremap <silent> <C-z>  :<C-u>call PseudoSuspendWithAutomaticCD()<CR>

            if !exists('g:gnu_screen_availablep')
                " Check the existence of $WINDOW to avoid using GNU screen in Vim on
                " a remote machine (for example, "screen -t remote ssh example.com").
                let g:gnu_screen_availablep = len($WINDOW) != 0
            endif
            function! PseudoSuspendWithAutomaticCD()
                if g:gnu_screen_availablep
                    " \015 = <C-m>
                    " To avoid adding the cd script into the command-line history,
                    " there are extra leading whitespaces in the cd script.
                    silent execute '!screen -X eval'
                                \         '''select another'''
                                \         '''stuff " cd \"'.getcwd().'\"  \#\#,vim-auto-cd\015"'''
                    redraw!
                    let g:gnu_screen_availablep = (v:shell_error == 0)
                endif

                if !g:gnu_screen_availablep
                    suspend
                endif
            endfunction
        endif
        "}}}
    endif

    "}}}
endif

"}}}

"---------------------------------------------------------------------------
" Others:"{{{
"
" Enable mouse support.
set mouse=a

" If true Vim master, use English help file.
set helplang& helplang=en,ja

" Default home directory.
let g:home = getcwd()

" Each tab has current directory."{{{
command! -nargs=? TabCD
      \   execute 'cd' fnameescape(<q-args>)
      \ | let t:cwd = getcwd()

autocmd MyAutoCmd TabEnter *
            \   if !exists('t:cwd')
            \ |   let t:cwd = getcwd()
            \ | endif
        \ | execute 'cd' fnameescape(t:cwd)

" Exchange ':cd' to ':TabCD'.
cnoreabbrev <expr> lhs (getcmdtype() == ':' && getcmdline() ==# 'cd') ? 'TabCD' : 'cd'
"}}}


"}}}

set secure

let g:loaded_vimrc = 1
" vim: foldmethod=marker

vimrcbox © Shota Fukumori (sora_h) - Top How to use Ranking