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 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331 10332 10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364 10365 10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380 10381 10382 10383 10384 10385 10386 10387 10388 10389 10390 10391 10392 10393 10394 10395 10396 10397 10398 10399 10400 10401 10402 10403 10404 10405 10406 10407 10408 10409 10410 10411 10412 10413 10414 10415 10416 10417 10418 10419 10420 10421 10422 10423 10424 10425 10426 10427 10428 10429 10430 10431 10432 10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444 10445 10446 10447 10448
|
/* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* fileio.c: read from and write to a file
*/
#include "vim.h"
#if defined(__TANDEM) || defined(__MINT__)
# include <limits.h> /* for SSIZE_MAX */
#endif
#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
# include <utime.h> /* for struct utimbuf */
#endif
#define BUFSIZE 8192 /* size of normal write buffer */
#define SMBUFSIZE 256 /* size of emergency write buffer */
/* Is there any system that doesn't have access()? */
#define USE_MCH_ACCESS
#ifdef FEAT_MBYTE
static char_u *next_fenc(char_u **pp);
# ifdef FEAT_EVAL
static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
# endif
#endif
#ifdef FEAT_VIMINFO
static void check_marks_read(void);
#endif
#ifdef FEAT_CRYPT
static char_u *check_for_cryptkey(char_u *cryptkey, char_u *ptr, long *sizep, off_T *filesizep, int newfile, char_u *fname, int *did_ask);
#endif
#ifdef UNIX
static void set_file_time(char_u *fname, time_t atime, time_t mtime);
#endif
static int set_rw_fname(char_u *fname, char_u *sfname);
static int msg_add_fileformat(int eol_type);
static void msg_add_eol(void);
static int check_mtime(buf_T *buf, stat_T *s);
static int time_differs(long t1, long t2);
#ifdef FEAT_AUTOCMD
static int apply_autocmds_exarg(event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap);
static int au_find_group(char_u *name);
# define AUGROUP_DEFAULT -1 /* default autocmd group */
# define AUGROUP_ERROR -2 /* erroneous autocmd group */
# define AUGROUP_ALL -3 /* all autocmd groups */
#endif
#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
# define HAS_BW_FLAGS
# define FIO_LATIN1 0x01 /* convert Latin1 */
# define FIO_UTF8 0x02 /* convert UTF-8 */
# define FIO_UCS2 0x04 /* convert UCS-2 */
# define FIO_UCS4 0x08 /* convert UCS-4 */
# define FIO_UTF16 0x10 /* convert UTF-16 */
# ifdef WIN3264
# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
# endif
# ifdef MACOS_X
# define FIO_MACROMAN 0x20 /* convert MacRoman */
# endif
# define FIO_ENDIAN_L 0x80 /* little endian */
# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
# define FIO_ALL -1 /* allow all formats */
#endif
/* When converting, a read() or write() may leave some bytes to be converted
* for the next call. The value is guessed... */
#define CONV_RESTLEN 30
/* We have to guess how much a sequence of bytes may expand when converting
* with iconv() to be able to allocate a buffer. */
#define ICONV_MULT 8
/*
* Structure to pass arguments from buf_write() to buf_write_bytes().
*/
struct bw_info
{
int bw_fd; /* file descriptor */
char_u *bw_buf; /* buffer with data to be written */
int bw_len; /* length of data */
#ifdef HAS_BW_FLAGS
int bw_flags; /* FIO_ flags */
#endif
#ifdef FEAT_CRYPT
buf_T *bw_buffer; /* buffer being written */
#endif
#ifdef FEAT_MBYTE
char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
int bw_restlen; /* nr of bytes in bw_rest[] */
int bw_first; /* first write call */
char_u *bw_conv_buf; /* buffer for writing converted chars */
int bw_conv_buflen; /* size of bw_conv_buf */
int bw_conv_error; /* set for conversion error */
linenr_T bw_conv_error_lnum; /* first line with error or zero */
linenr_T bw_start_lnum; /* line number at start of buffer */
# ifdef USE_ICONV
iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
# endif
#endif
};
static int buf_write_bytes(struct bw_info *ip);
#ifdef FEAT_MBYTE
static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
static int ucs2bytes(unsigned c, char_u **pp, int flags);
static int need_conversion(char_u *fenc);
static int get_fio_flags(char_u *ptr);
static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
static int make_bom(char_u *buf, char_u *name);
# ifdef WIN3264
static int get_win_fio_flags(char_u *ptr);
# endif
# ifdef MACOS_X
static int get_mac_fio_flags(char_u *ptr);
# endif
#endif
static int move_lines(buf_T *frombuf, buf_T *tobuf);
#ifdef TEMPDIRNAMES
static void vim_settempdir(char_u *tempdir);
#endif
#ifdef FEAT_AUTOCMD
static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
#endif
#ifdef FEAT_AUTOCMD
/*
* Set by the apply_autocmds_group function if the given event is equal to
* EVENT_FILETYPE. Used by the readfile function in order to determine if
* EVENT_BUFREADPOST triggered the EVENT_FILETYPE.
*
* Relying on this value requires one to reset it prior calling
* apply_autocmds_group.
*/
static int au_did_filetype INIT(= FALSE);
#endif
void
filemess(
buf_T *buf,
char_u *name,
char_u *s,
int attr)
{
int msg_scroll_save;
if (msg_silent != 0)
return;
msg_add_fname(buf, name); /* put file name in IObuff with quotes */
/* If it's extremely long, truncate it. */
if (STRLEN(IObuff) > IOSIZE - 80)
IObuff[IOSIZE - 80] = NUL;
STRCAT(IObuff, s);
/*
* For the first message may have to start a new line.
* For further ones overwrite the previous one, reset msg_scroll before
* calling filemess().
*/
msg_scroll_save = msg_scroll;
if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
msg_scroll = FALSE;
if (!msg_scroll) /* wait a bit when overwriting an error msg */
check_for_delay(FALSE);
msg_start();
msg_scroll = msg_scroll_save;
msg_scrolled_ign = TRUE;
/* may truncate the message to avoid a hit-return prompt */
msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
msg_clr_eos();
out_flush();
msg_scrolled_ign = FALSE;
}
/*
* Read lines from file "fname" into the buffer after line "from".
*
* 1. We allocate blocks with lalloc, as big as possible.
* 2. Each block is filled with characters from the file with a single read().
* 3. The lines are inserted in the buffer with ml_append().
*
* (caller must check that fname != NULL, unless READ_STDIN is used)
*
* "lines_to_skip" is the number of lines that must be skipped
* "lines_to_read" is the number of lines that are appended
* When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
*
* flags:
* READ_NEW starting to edit a new buffer
* READ_FILTER reading filter output
* READ_STDIN read from stdin instead of a file
* READ_BUFFER read from curbuf instead of a file (converting after reading
* stdin)
* READ_DUMMY read into a dummy buffer (to check if file contents changed)
* READ_KEEP_UNDO don't clear undo info or read it from a file
* READ_FIFO read from fifo/socket instead of a file
*
* return FAIL for failure, NOTDONE for directory (failure), or OK
*/
int
readfile(
char_u *fname,
char_u *sfname,
linenr_T from,
linenr_T lines_to_skip,
linenr_T lines_to_read,
exarg_T *eap, /* can be NULL! */
int flags)
{
int fd = 0;
int newfile = (flags & READ_NEW);
int check_readonly;
int filtering = (flags & READ_FILTER);
int read_stdin = (flags & READ_STDIN);
int read_buffer = (flags & READ_BUFFER);
int read_fifo = (flags & READ_FIFO);
int set_options = newfile || read_buffer
|| (eap != NULL && eap->read_edit);
linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
colnr_T read_buf_col = 0; /* next char to read from this line */
char_u c;
linenr_T lnum = from;
char_u *ptr = NULL; /* pointer into read buffer */
char_u *buffer = NULL; /* read buffer */
char_u *new_buffer = NULL; /* init to shut up gcc */
char_u *line_start = NULL; /* init to shut up gcc */
int wasempty; /* buffer was empty before reading */
colnr_T len;
long size = 0;
char_u *p;
off_T filesize = 0;
int skip_read = FALSE;
#ifdef FEAT_CRYPT
char_u *cryptkey = NULL;
int did_ask_for_key = FALSE;
#endif
#ifdef FEAT_PERSISTENT_UNDO
context_sha256_T sha_ctx;
int read_undo_file = FALSE;
#endif
int split = 0; /* number of split lines */
#define UNKNOWN 0x0fffffff /* file size is unknown */
linenr_T linecnt;
int error = FALSE; /* errors encountered */
int ff_error = EOL_UNKNOWN; /* file format with errors */
long linerest = 0; /* remaining chars in line */
#ifdef UNIX
int perm = 0;
int swap_mode = -1; /* protection bits for swap file */
#else
int perm;
#endif
int fileformat = 0; /* end-of-line format */
int keep_fileformat = FALSE;
stat_T st;
int file_readonly;
linenr_T skip_count = 0;
linenr_T read_count = 0;
int msg_save = msg_scroll;
linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
* last read was missing the eol */
int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
int file_rewind = FALSE;
#ifdef FEAT_MBYTE
int can_retry;
linenr_T conv_error = 0; /* line nr with conversion error */
linenr_T illegal_byte = 0; /* line nr with illegal byte */
int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
in destination encoding */
int bad_char_behavior = BAD_REPLACE;
/* BAD_KEEP, BAD_DROP or character to
* replace with */
char_u *tmpname = NULL; /* name of 'charconvert' output file */
int fio_flags = 0;
char_u *fenc; /* fileencoding to use */
int fenc_alloced; /* fenc_next is in allocated memory */
char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
int advance_fenc = FALSE;
long real_size = 0;
# ifdef USE_ICONV
iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
# ifdef FEAT_EVAL
int did_iconv = FALSE; /* TRUE when iconv() failed and trying
'charconvert' next */
# endif
# endif
int converted = FALSE; /* TRUE if conversion done */
int notconverted = FALSE; /* TRUE if conversion wanted but it
wasn't possible */
char_u conv_rest[CONV_RESTLEN];
int conv_restlen = 0; /* nr of bytes in conv_rest[] */
#endif
#ifdef FEAT_AUTOCMD
buf_T *old_curbuf;
char_u *old_b_ffname;
char_u *old_b_fname;
int using_b_ffname;
int using_b_fname;
#endif
#ifdef FEAT_AUTOCMD
au_did_filetype = FALSE; /* reset before triggering any autocommands */
#endif
curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
/*
* If there is no file name yet, use the one for the read file.
* BF_NOTEDITED is set to reflect this.
* Don't do this for a read from a filter.
* Only do this when 'cpoptions' contains the 'f' flag.
*/
if (curbuf->b_ffname == NULL
&& !filtering
&& fname != NULL
&& vim_strchr(p_cpo, CPO_FNAMER) != NULL
&& !(flags & READ_DUMMY))
{
if (set_rw_fname(fname, sfname) == FAIL)
return FAIL;
}
#ifdef FEAT_AUTOCMD
/* Remember the initial values of curbuf, curbuf->b_ffname and
* curbuf->b_fname to detect whether they are altered as a result of
* executing nasty autocommands. Also check if "fname" and "sfname"
* point to one of these values. */
old_curbuf = curbuf;
old_b_ffname = curbuf->b_ffname;
old_b_fname = curbuf->b_fname;
using_b_ffname = (fname == curbuf->b_ffname)
|| (sfname == curbuf->b_ffname);
using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
#endif
/* After reading a file the cursor line changes but we don't want to
* display the line. */
ex_no_reprint = TRUE;
/* don't display the file info for another buffer now */
need_fileinfo = FALSE;
/*
* For Unix: Use the short file name whenever possible.
* Avoids problems with networks and when directory names are changed.
* Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
* another directory, which we don't detect.
*/
if (sfname == NULL)
sfname = fname;
#if defined(UNIX)
fname = sfname;
#endif
#ifdef FEAT_AUTOCMD
/*
* The BufReadCmd and FileReadCmd events intercept the reading process by
* executing the associated commands instead.
*/
if (!filtering && !read_stdin && !read_buffer)
{
pos_T pos;
pos = curbuf->b_op_start;
/* Set '[ mark to the line above where the lines go (line 1 if zero). */
curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
curbuf->b_op_start.col = 0;
if (newfile)
{
if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
FALSE, curbuf, eap))
#ifdef FEAT_EVAL
return aborting() ? FAIL : OK;
#else
return OK;
#endif
}
else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
FALSE, NULL, eap))
#ifdef FEAT_EVAL
return aborting() ? FAIL : OK;
#else
return OK;
#endif
curbuf->b_op_start = pos;
}
#endif
if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
msg_scroll = FALSE; /* overwrite previous file message */
else
msg_scroll = TRUE; /* don't overwrite previous file message */
/*
* If the name ends in a path separator, we can't open it. Check here,
* because reading the file may actually work, but then creating the swap
* file may destroy it! Reported on MS-DOS and Win 95.
* If the name is too long we might crash further on, quit here.
*/
if (fname != NULL && *fname != NUL)
{
p = fname + STRLEN(fname);
if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
{
filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
msg_end();
msg_scroll = msg_save;
return FAIL;
}
}
if (!read_stdin && !read_buffer && !read_fifo)
{
#ifdef UNIX
/*
* On Unix it is possible to read a directory, so we have to
* check for it before the mch_open().
*/
perm = mch_getperm(fname);
if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
# ifdef S_ISFIFO
&& !S_ISFIFO(perm) /* ... or fifo */
# endif
# ifdef S_ISSOCK
&& !S_ISSOCK(perm) /* ... or socket */
# endif
# ifdef OPEN_CHR_FILES
&& !(S_ISCHR(perm) && is_dev_fd_file(fname))
/* ... or a character special file named /dev/fd/<n> */
# endif
)
{
int retval = FAIL;
if (S_ISDIR(perm))
{
filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
retval = NOTDONE;
}
else
filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
msg_end();
msg_scroll = msg_save;
return retval;
}
#endif
#if defined(MSWIN)
/*
* MS-Windows allows opening a device, but we will probably get stuck
* trying to read it.
*/
if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
{
filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
msg_end();
msg_scroll = msg_save;
return FAIL;
}
#endif
}
/* Set default or forced 'fileformat' and 'binary'. */
set_file_options(set_options, eap);
/*
* When opening a new file we take the readonly flag from the file.
* Default is r/w, can be set to r/o below.
* Don't reset it when in readonly mode
* Only set/reset b_p_ro when BF_CHECK_RO is set.
*/
check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
if (check_readonly && !readonlymode)
curbuf->b_p_ro = FALSE;
if (newfile && !read_stdin && !read_buffer && !read_fifo)
{
/* Remember time of file. */
if (mch_stat((char *)fname, &st) >= 0)
{
buf_store_time(curbuf, &st, fname);
curbuf->b_mtime_read = curbuf->b_mtime;
#ifdef UNIX
/*
* Use the protection bits of the original file for the swap file.
* This makes it possible for others to read the name of the
* edited file from the swapfile, but only if they can read the
* edited file.
* Remove the "write" and "execute" bits for group and others
* (they must not write the swapfile).
* Add the "read" and "write" bits for the user, otherwise we may
* not be able to write to the file ourselves.
* Setting the bits is done below, after creating the swap file.
*/
swap_mode = (st.st_mode & 0644) | 0600;
#endif
#ifdef FEAT_CW_EDITOR
/* Get the FSSpec on MacOS
* TODO: Update it properly when the buffer name changes
*/
(void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
#endif
#ifdef VMS
curbuf->b_fab_rfm = st.st_fab_rfm;
curbuf->b_fab_rat = st.st_fab_rat;
curbuf->b_fab_mrs = st.st_fab_mrs;
#endif
}
else
{
curbuf->b_mtime = 0;
curbuf->b_mtime_read = 0;
curbuf->b_orig_size = 0;
curbuf->b_orig_mode = 0;
}
/* Reset the "new file" flag. It will be set again below when the
* file doesn't exist. */
curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
}
/*
* for UNIX: check readonly with perm and mch_access()
* for Amiga: check readonly by trying to open the file for writing
*/
file_readonly = FALSE;
if (read_stdin)
{
#if defined(MSWIN)
/* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
setmode(0, O_BINARY);
#endif
}
else if (!read_buffer)
{
#ifdef USE_MCH_ACCESS
if (
# ifdef UNIX
!(perm & 0222) ||
# endif
mch_access((char *)fname, W_OK))
file_readonly = TRUE;
fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
#else
if (!newfile
|| readonlymode
|| (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
{
file_readonly = TRUE;
/* try to open ro */
fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
}
#endif
}
if (fd < 0) /* cannot open at all */
{
#ifndef UNIX
int isdir_f;
#endif
msg_scroll = msg_save;
#ifndef UNIX
/*
* On Amiga we can't open a directory, check here.
*/
isdir_f = (mch_isdir(fname));
perm = mch_getperm(fname); /* check if the file exists */
if (isdir_f)
{
filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
curbuf->b_p_ro = TRUE; /* must use "w!" now */
}
else
#endif
if (newfile)
{
if (perm < 0
#ifdef ENOENT
&& errno == ENOENT
#endif
)
{
/*
* Set the 'new-file' flag, so that when the file has
* been created by someone else, a ":w" will complain.
*/
curbuf->b_flags |= BF_NEW;
/* Create a swap file now, so that other Vims are warned
* that we are editing this file. Don't do this for a
* "nofile" or "nowrite" buffer type. */
#ifdef FEAT_QUICKFIX
if (!bt_dontwrite(curbuf))
#endif
{
check_need_swap(newfile);
#ifdef FEAT_AUTOCMD
/* SwapExists autocommand may mess things up */
if (curbuf != old_curbuf
|| (using_b_ffname
&& (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname
&& (old_b_fname != curbuf->b_fname)))
{
EMSG(_(e_auchangedbuf));
return FAIL;
}
#endif
}
if (dir_of_file_exists(fname))
filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
else
filemess(curbuf, sfname,
(char_u *)_("[New DIRECTORY]"), 0);
#ifdef FEAT_VIMINFO
/* Even though this is a new file, it might have been
* edited before and deleted. Get the old marks. */
check_marks_read();
#endif
#ifdef FEAT_MBYTE
/* Set forced 'fileencoding'. */
if (eap != NULL)
set_forced_fenc(eap);
#endif
#ifdef FEAT_AUTOCMD
apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
FALSE, curbuf, eap);
#endif
/* remember the current fileformat */
save_file_ff(curbuf);
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (aborting()) /* autocmds may abort script processing */
return FAIL;
#endif
return OK; /* a new file is not an error */
}
else
{
filemess(curbuf, sfname, (char_u *)(
# ifdef EFBIG
(errno == EFBIG) ? _("[File too big]") :
# endif
# ifdef EOVERFLOW
(errno == EOVERFLOW) ? _("[File too big]") :
# endif
_("[Permission Denied]")), 0);
curbuf->b_p_ro = TRUE; /* must use "w!" now */
}
}
return FAIL;
}
/*
* Only set the 'ro' flag for readonly files the first time they are
* loaded. Help files always get readonly mode
*/
if ((check_readonly && file_readonly) || curbuf->b_help)
curbuf->b_p_ro = TRUE;
if (set_options)
{
/* Don't change 'eol' if reading from buffer as it will already be
* correctly set when reading stdin. */
if (!read_buffer)
{
curbuf->b_p_eol = TRUE;
curbuf->b_start_eol = TRUE;
}
#ifdef FEAT_MBYTE
curbuf->b_p_bomb = FALSE;
curbuf->b_start_bomb = FALSE;
#endif
}
/* Create a swap file now, so that other Vims are warned that we are
* editing this file.
* Don't do this for a "nofile" or "nowrite" buffer type. */
#ifdef FEAT_QUICKFIX
if (!bt_dontwrite(curbuf))
#endif
{
check_need_swap(newfile);
#ifdef FEAT_AUTOCMD
if (!read_stdin && (curbuf != old_curbuf
|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname && (old_b_fname != curbuf->b_fname))))
{
EMSG(_(e_auchangedbuf));
if (!read_buffer)
close(fd);
return FAIL;
}
#endif
#ifdef UNIX
/* Set swap file protection bits after creating it. */
if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
&& curbuf->b_ml.ml_mfp->mf_fname != NULL)
(void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
#endif
}
#if defined(HAS_SWAP_EXISTS_ACTION)
/* If "Quit" selected at ATTENTION dialog, don't load the file */
if (swap_exists_action == SEA_QUIT)
{
if (!read_buffer && !read_stdin)
close(fd);
return FAIL;
}
#endif
++no_wait_return; /* don't wait for return yet */
/*
* Set '[ mark to the line above where the lines go (line 1 if zero).
*/
curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
curbuf->b_op_start.col = 0;
#ifdef FEAT_AUTOCMD
if (!read_buffer)
{
int m = msg_scroll;
int n = msg_scrolled;
/*
* The file must be closed again, the autocommands may want to change
* the file before reading it.
*/
if (!read_stdin)
close(fd); /* ignore errors */
/*
* The output from the autocommands should not overwrite anything and
* should not be overwritten: Set msg_scroll, restore its value if no
* output was done.
*/
msg_scroll = TRUE;
if (filtering)
apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
FALSE, curbuf, eap);
else if (read_stdin)
apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
FALSE, curbuf, eap);
else if (newfile)
apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
FALSE, curbuf, eap);
else
apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
FALSE, NULL, eap);
if (msg_scrolled == n)
msg_scroll = m;
#ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
{
--no_wait_return;
msg_scroll = msg_save;
curbuf->b_p_ro = TRUE; /* must use "w!" now */
return FAIL;
}
#endif
/*
* Don't allow the autocommands to change the current buffer.
* Try to re-open the file.
*
* Don't allow the autocommands to change the buffer name either
* (cd for example) if it invalidates fname or sfname.
*/
if (!read_stdin && (curbuf != old_curbuf
|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname && (old_b_fname != curbuf->b_fname))
|| (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
{
--no_wait_return;
msg_scroll = msg_save;
if (fd < 0)
EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
else
EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
curbuf->b_p_ro = TRUE; /* must use "w!" now */
return FAIL;
}
}
#endif /* FEAT_AUTOCMD */
/* Autocommands may add lines to the file, need to check if it is empty */
wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
if (!recoverymode && !filtering && !(flags & READ_DUMMY))
{
/*
* Show the user that we are busy reading the input. Sometimes this
* may take a while. When reading from stdin another program may
* still be running, don't move the cursor to the last line, unless
* always using the GUI.
*/
if (read_stdin)
{
#ifndef ALWAYS_USE_GUI
mch_msg(_("Vim: Reading from stdin...\n"));
#endif
#ifdef FEAT_GUI
/* Also write a message in the GUI window, if there is one. */
if (gui.in_use && !gui.dying && !gui.starting)
{
p = (char_u *)_("Reading from stdin...");
gui_write(p, (int)STRLEN(p));
}
#endif
}
else if (!read_buffer)
filemess(curbuf, sfname, (char_u *)"", 0);
}
msg_scroll = FALSE; /* overwrite the file message */
/*
* Set linecnt now, before the "retry" caused by a wrong guess for
* fileformat, and after the autocommands, which may change them.
*/
linecnt = curbuf->b_ml.ml_line_count;
#ifdef FEAT_MBYTE
/* "++bad=" argument. */
if (eap != NULL && eap->bad_char != 0)
{
bad_char_behavior = eap->bad_char;
if (set_options)
curbuf->b_bad_char = eap->bad_char;
}
else
curbuf->b_bad_char = 0;
/*
* Decide which 'encoding' to use or use first.
*/
if (eap != NULL && eap->force_enc != 0)
{
fenc = enc_canonize(eap->cmd + eap->force_enc);
fenc_alloced = TRUE;
keep_dest_enc = TRUE;
}
else if (curbuf->b_p_bin)
{
fenc = (char_u *)""; /* binary: don't convert */
fenc_alloced = FALSE;
}
else if (curbuf->b_help)
{
char_u firstline[80];
int fc;
/* Help files are either utf-8 or latin1. Try utf-8 first, if this
* fails it must be latin1.
* Always do this when 'encoding' is "utf-8". Otherwise only do
* this when needed to avoid [converted] remarks all the time.
* It is needed when the first line contains non-ASCII characters.
* That is only in *.??x files. */
fenc = (char_u *)"latin1";
c = enc_utf8;
if (!c && !read_stdin)
{
fc = fname[STRLEN(fname) - 1];
if (TOLOWER_ASC(fc) == 'x')
{
/* Read the first line (and a bit more). Immediately rewind to
* the start of the file. If the read() fails "len" is -1. */
len = read_eintr(fd, firstline, 80);
vim_lseek(fd, (off_T)0L, SEEK_SET);
for (p = firstline; p < firstline + len; ++p)
if (*p >= 0x80)
{
c = TRUE;
break;
}
}
}
if (c)
{
fenc_next = fenc;
fenc = (char_u *)"utf-8";
/* When the file is utf-8 but a character doesn't fit in
* 'encoding' don't retry. In help text editing utf-8 bytes
* doesn't make sense. */
if (!enc_utf8)
keep_dest_enc = TRUE;
}
fenc_alloced = FALSE;
}
else if (*p_fencs == NUL)
{
fenc = curbuf->b_p_fenc; /* use format from buffer */
fenc_alloced = FALSE;
}
else
{
fenc_next = p_fencs; /* try items in 'fileencodings' */
fenc = next_fenc(&fenc_next);
fenc_alloced = TRUE;
}
#endif
/*
* Jump back here to retry reading the file in different ways.
* Reasons to retry:
* - encoding conversion failed: try another one from "fenc_next"
* - BOM detected and fenc was set, need to setup conversion
* - "fileformat" check failed: try another
*
* Variables set for special retry actions:
* "file_rewind" Rewind the file to start reading it again.
* "advance_fenc" Advance "fenc" using "fenc_next".
* "skip_read" Re-use already read bytes (BOM detected).
* "did_iconv" iconv() conversion failed, try 'charconvert'.
* "keep_fileformat" Don't reset "fileformat".
*
* Other status indicators:
* "tmpname" When != NULL did conversion with 'charconvert'.
* Output file has to be deleted afterwards.
* "iconv_fd" When != -1 did conversion with iconv().
*/
retry:
if (file_rewind)
{
if (read_buffer)
{
read_buf_lnum = 1;
read_buf_col = 0;
}
else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
{
/* Can't rewind the file, give up. */
error = TRUE;
goto failed;
}
/* Delete the previously read lines. */
while (lnum > from)
ml_delete(lnum--, FALSE);
file_rewind = FALSE;
#ifdef FEAT_MBYTE
if (set_options)
{
curbuf->b_p_bomb = FALSE;
curbuf->b_start_bomb = FALSE;
}
conv_error = 0;
#endif
}
/*
* When retrying with another "fenc" and the first time "fileformat"
* will be reset.
*/
if (keep_fileformat)
keep_fileformat = FALSE;
else
{
if (eap != NULL && eap->force_ff != 0)
{
fileformat = get_fileformat_force(curbuf, eap);
try_unix = try_dos = try_mac = FALSE;
}
else if (curbuf->b_p_bin)
fileformat = EOL_UNIX; /* binary: use Unix format */
else if (*p_ffs == NUL)
fileformat = get_fileformat(curbuf);/* use format from buffer */
else
fileformat = EOL_UNKNOWN; /* detect from file */
}
#ifdef FEAT_MBYTE
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
{
/* aborted conversion with iconv(), close the descriptor */
iconv_close(iconv_fd);
iconv_fd = (iconv_t)-1;
}
# endif
if (advance_fenc)
{
/*
* Try the next entry in 'fileencodings'.
*/
advance_fenc = FALSE;
if (eap != NULL && eap->force_enc != 0)
{
/* Conversion given with "++cc=" wasn't possible, read
* without conversion. */
notconverted = TRUE;
conv_error = 0;
if (fenc_alloced)
vim_free(fenc);
fenc = (char_u *)"";
fenc_alloced = FALSE;
}
else
{
if (fenc_alloced)
vim_free(fenc);
if (fenc_next != NULL)
{
fenc = next_fenc(&fenc_next);
fenc_alloced = (fenc_next != NULL);
}
else
{
fenc = (char_u *)"";
fenc_alloced = FALSE;
}
}
if (tmpname != NULL)
{
mch_remove(tmpname); /* delete converted file */
vim_free(tmpname);
tmpname = NULL;
}
}
/*
* Conversion may be required when the encoding of the file is different
* from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
*/
fio_flags = 0;
converted = need_conversion(fenc);
if (converted)
{
/* "ucs-bom" means we need to check the first bytes of the file
* for a BOM. */
if (STRCMP(fenc, ENC_UCSBOM) == 0)
fio_flags = FIO_UCSBOM;
/*
* Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
* done. This is handled below after read(). Prepare the
* fio_flags to avoid having to parse the string each time.
* Also check for Unicode to Latin1 conversion, because iconv()
* appears not to handle this correctly. This works just like
* conversion to UTF-8 except how the resulting character is put in
* the buffer.
*/
else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
fio_flags = get_fio_flags(fenc);
# ifdef WIN3264
/*
* Conversion from an MS-Windows codepage to UTF-8 or another codepage
* is handled with MultiByteToWideChar().
*/
if (fio_flags == 0)
fio_flags = get_win_fio_flags(fenc);
# endif
# ifdef MACOS_X
/* Conversion from Apple MacRoman to latin1 or UTF-8 */
if (fio_flags == 0)
fio_flags = get_mac_fio_flags(fenc);
# endif
# ifdef USE_ICONV
/*
* Try using iconv() if we can't convert internally.
*/
if (fio_flags == 0
# ifdef FEAT_EVAL
&& !did_iconv
# endif
)
iconv_fd = (iconv_t)my_iconv_open(
enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
# endif
# ifdef FEAT_EVAL
/*
* Use the 'charconvert' expression when conversion is required
* and we can't do it internally or with iconv().
*/
if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
&& !read_fifo
# ifdef USE_ICONV
&& iconv_fd == (iconv_t)-1
# endif
)
{
# ifdef USE_ICONV
did_iconv = FALSE;
# endif
/* Skip conversion when it's already done (retry for wrong
* "fileformat"). */
if (tmpname == NULL)
{
tmpname = readfile_charconvert(fname, fenc, &fd);
if (tmpname == NULL)
{
/* Conversion failed. Try another one. */
advance_fenc = TRUE;
if (fd < 0)
{
/* Re-opening the original file failed! */
EMSG(_("E202: Conversion made file unreadable!"));
error = TRUE;
goto failed;
}
goto retry;
}
}
}
else
# endif
{
if (fio_flags == 0
# ifdef USE_ICONV
&& iconv_fd == (iconv_t)-1
# endif
)
{
/* Conversion wanted but we can't.
* Try the next conversion in 'fileencodings' */
advance_fenc = TRUE;
goto retry;
}
}
}
/* Set "can_retry" when it's possible to rewind the file and try with
* another "fenc" value. It's FALSE when no other "fenc" to try, reading
* stdin or fixed at a specific encoding. */
can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
#endif
if (!skip_read)
{
linerest = 0;
filesize = 0;
skip_count = lines_to_skip;
read_count = lines_to_read;
#ifdef FEAT_MBYTE
conv_restlen = 0;
#endif
#ifdef FEAT_PERSISTENT_UNDO
read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
&& curbuf->b_ffname != NULL
&& curbuf->b_p_udf
&& !filtering
&& !read_fifo
&& !read_stdin
&& !read_buffer);
if (read_undo_file)
sha256_start(&sha_ctx);
#endif
#ifdef FEAT_CRYPT
if (curbuf->b_cryptstate != NULL)
{
/* Need to free the state, but keep the key, don't want to ask for
* it again. */
crypt_free_state(curbuf->b_cryptstate);
curbuf->b_cryptstate = NULL;
}
#endif
}
while (!error && !got_int)
{
/*
* We allocate as much space for the file as we can get, plus
* space for the old line plus room for one terminating NUL.
* The amount is limited by the fact that read() only can read
* upto max_unsigned characters (and other things).
*/
#if VIM_SIZEOF_INT <= 2
if (linerest >= 0x7ff0)
{
++split;
*ptr = NL; /* split line by inserting a NL */
size = 1;
}
else
#endif
{
if (!skip_read)
{
#if VIM_SIZEOF_INT > 2
# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
size = SSIZE_MAX; /* use max I/O size, 52K */
# else
size = 0x10000L; /* use buffer >= 64K */
# endif
#else
size = 0x7ff0L - linerest; /* limit buffer to 32K */
#endif
for ( ; size >= 10; size = (long)((long_u)size >> 1))
{
if ((new_buffer = lalloc((long_u)(size + linerest + 1),
FALSE)) != NULL)
break;
}
if (new_buffer == NULL)
{
do_outofmem_msg((long_u)(size * 2 + linerest + 1));
error = TRUE;
break;
}
if (linerest) /* copy characters from the previous buffer */
mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
vim_free(buffer);
buffer = new_buffer;
ptr = buffer + linerest;
line_start = buffer;
#ifdef FEAT_MBYTE
/* May need room to translate into.
* For iconv() we don't really know the required space, use a
* factor ICONV_MULT.
* latin1 to utf-8: 1 byte becomes up to 2 bytes
* utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
* become up to 4 bytes, size must be multiple of 2
* ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
* multiple of 2
* ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
* multiple of 4 */
real_size = (int)size;
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
size = size / ICONV_MULT;
else
# endif
if (fio_flags & FIO_LATIN1)
size = size / 2;
else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
size = (size * 2 / 3) & ~1;
else if (fio_flags & FIO_UCS4)
size = (size * 2 / 3) & ~3;
else if (fio_flags == FIO_UCSBOM)
size = size / ICONV_MULT; /* worst case */
# ifdef WIN3264
else if (fio_flags & FIO_CODEPAGE)
size = size / ICONV_MULT; /* also worst case */
# endif
# ifdef MACOS_X
else if (fio_flags & FIO_MACROMAN)
size = size / ICONV_MULT; /* also worst case */
# endif
#endif
#ifdef FEAT_MBYTE
if (conv_restlen > 0)
{
/* Insert unconverted bytes from previous line. */
mch_memmove(ptr, conv_rest, conv_restlen);
ptr += conv_restlen;
size -= conv_restlen;
}
#endif
if (read_buffer)
{
/*
* Read bytes from curbuf. Used for converting text read
* from stdin.
*/
if (read_buf_lnum > from)
size = 0;
else
{
int n, ni;
long tlen;
tlen = 0;
for (;;)
{
p = ml_get(read_buf_lnum) + read_buf_col;
n = (int)STRLEN(p);
if ((int)tlen + n + 1 > size)
{
/* Filled up to "size", append partial line.
* Change NL to NUL to reverse the effect done
* below. */
n = (int)(size - tlen);
for (ni = 0; ni < n; ++ni)
{
if (p[ni] == NL)
ptr[tlen++] = NUL;
else
ptr[tlen++] = p[ni];
}
read_buf_col += n;
break;
}
else
{
/* Append whole line and new-line. Change NL
* to NUL to reverse the effect done below. */
for (ni = 0; ni < n; ++ni)
{
if (p[ni] == NL)
ptr[tlen++] = NUL;
else
ptr[tlen++] = p[ni];
}
ptr[tlen++] = NL;
read_buf_col = 0;
if (++read_buf_lnum > from)
{
/* When the last line didn't have an
* end-of-line don't add it now either. */
if (!curbuf->b_p_eol)
--tlen;
size = tlen;
break;
}
}
}
}
}
else
{
/*
* Read bytes from the file.
*/
size = read_eintr(fd, ptr, size);
}
#ifdef FEAT_CRYPT
/*
* At start of file: Check for magic number of encryption.
*/
if (filesize == 0 && size > 0)
cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
&filesize, newfile, sfname,
&did_ask_for_key);
/*
* Decrypt the read bytes. This is done before checking for
* EOF because the crypt layer may be buffering.
*/
if (cryptkey != NULL && size > 0)
{
if (crypt_works_inplace(curbuf->b_cryptstate))
{
crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
}
else
{
char_u *newptr = NULL;
int decrypted_size;
decrypted_size = crypt_decode_alloc(
curbuf->b_cryptstate, ptr, size, &newptr);
/* If the crypt layer is buffering, not producing
* anything yet, need to read more. */
if (size > 0 && decrypted_size == 0)
continue;
if (linerest == 0)
{
/* Simple case: reuse returned buffer (may be
* NULL, checked later). */
new_buffer = newptr;
}
else
{
long_u new_size;
/* Need new buffer to add bytes carried over. */
new_size = (long_u)(decrypted_size + linerest + 1);
new_buffer = lalloc(new_size, FALSE);
if (new_buffer == NULL)
{
do_outofmem_msg(new_size);
error = TRUE;
break;
}
mch_memmove(new_buffer, buffer, linerest);
if (newptr != NULL)
mch_memmove(new_buffer + linerest, newptr,
decrypted_size);
}
if (new_buffer != NULL)
{
vim_free(buffer);
buffer = new_buffer;
new_buffer = NULL;
line_start = buffer;
ptr = buffer + linerest;
}
size = decrypted_size;
}
}
#endif
if (size <= 0)
{
if (size < 0) /* read error */
error = TRUE;
#ifdef FEAT_MBYTE
else if (conv_restlen > 0)
{
/*
* Reached end-of-file but some trailing bytes could
* not be converted. Truncated file?
*/
/* When we did a conversion report an error. */
if (fio_flags != 0
# ifdef USE_ICONV
|| iconv_fd != (iconv_t)-1
# endif
)
{
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = curbuf->b_ml.ml_line_count
- linecnt + 1;
}
/* Remember the first linenr with an illegal byte */
else if (illegal_byte == 0)
illegal_byte = curbuf->b_ml.ml_line_count
- linecnt + 1;
if (bad_char_behavior == BAD_DROP)
{
*(ptr - conv_restlen) = NUL;
conv_restlen = 0;
}
else
{
/* Replace the trailing bytes with the replacement
* character if we were converting; if we weren't,
* leave the UTF8 checking code to do it, as it
* works slightly differently. */
if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
# ifdef USE_ICONV
|| iconv_fd != (iconv_t)-1
# endif
))
{
while (conv_restlen > 0)
{
*(--ptr) = bad_char_behavior;
--conv_restlen;
}
}
fio_flags = 0; /* don't convert this */
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
{
iconv_close(iconv_fd);
iconv_fd = (iconv_t)-1;
}
# endif
}
}
#endif
}
}
skip_read = FALSE;
#ifdef FEAT_MBYTE
/*
* At start of file (or after crypt magic number): Check for BOM.
* Also check for a BOM for other Unicode encodings, but not after
* converting with 'charconvert' or when a BOM has already been
* found.
*/
if ((filesize == 0
# ifdef FEAT_CRYPT
|| (cryptkey != NULL
&& filesize == crypt_get_header_len(
crypt_get_method_nr(curbuf)))
# endif
)
&& (fio_flags == FIO_UCSBOM
|| (!curbuf->b_p_bomb
&& tmpname == NULL
&& (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
{
char_u *ccname;
int blen;
/* no BOM detection in a short file or in binary mode */
if (size < 2 || curbuf->b_p_bin)
ccname = NULL;
else
ccname = check_for_bom(ptr, size, &blen,
fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
if (ccname != NULL)
{
/* Remove BOM from the text */
filesize += blen;
size -= blen;
mch_memmove(ptr, ptr + blen, (size_t)size);
if (set_options)
{
curbuf->b_p_bomb = TRUE;
curbuf->b_start_bomb = TRUE;
}
}
if (fio_flags == FIO_UCSBOM)
{
if (ccname == NULL)
{
/* No BOM detected: retry with next encoding. */
advance_fenc = TRUE;
}
else
{
/* BOM detected: set "fenc" and jump back */
if (fenc_alloced)
vim_free(fenc);
fenc = ccname;
fenc_alloced = FALSE;
}
/* retry reading without getting new bytes or rewinding */
skip_read = TRUE;
goto retry;
}
}
/* Include not converted bytes. */
ptr -= conv_restlen;
size += conv_restlen;
conv_restlen = 0;
#endif
/*
* Break here for a read error or end-of-file.
*/
if (size <= 0)
break;
#ifdef FEAT_MBYTE
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
{
/*
* Attempt conversion of the read bytes to 'encoding' using
* iconv().
*/
const char *fromp;
char *top;
size_t from_size;
size_t to_size;
fromp = (char *)ptr;
from_size = size;
ptr += size;
top = (char *)ptr;
to_size = real_size - size;
/*
* If there is conversion error or not enough room try using
* another conversion. Except for when there is no
* alternative (help files).
*/
while ((iconv(iconv_fd, (void *)&fromp, &from_size,
&top, &to_size)
== (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
|| from_size > CONV_RESTLEN)
{
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt,
ptr, (char_u *)top);
/* Deal with a bad byte and continue with the next. */
++fromp;
--from_size;
if (bad_char_behavior == BAD_KEEP)
{
*top++ = *(fromp - 1);
--to_size;
}
else if (bad_char_behavior != BAD_DROP)
{
*top++ = bad_char_behavior;
--to_size;
}
}
if (from_size > 0)
{
/* Some remaining characters, keep them for the next
* round. */
mch_memmove(conv_rest, (char_u *)fromp, from_size);
conv_restlen = (int)from_size;
}
/* move the linerest to before the converted characters */
line_start = ptr - linerest;
mch_memmove(line_start, buffer, (size_t)linerest);
size = (long)((char_u *)top - ptr);
}
# endif
# ifdef WIN3264
if (fio_flags & FIO_CODEPAGE)
{
char_u *src, *dst;
WCHAR ucs2buf[3];
int ucs2len;
int codepage = FIO_GET_CP(fio_flags);
int bytelen;
int found_bad;
char replstr[2];
/*
* Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
* a codepage, using standard MS-Windows functions. This
* requires two steps:
* 1. convert from 'fileencoding' to ucs-2
* 2. convert from ucs-2 to 'encoding'
*
* Because there may be illegal bytes AND an incomplete byte
* sequence at the end, we may have to do the conversion one
* character at a time to get it right.
*/
/* Replacement string for WideCharToMultiByte(). */
if (bad_char_behavior > 0)
replstr[0] = bad_char_behavior;
else
replstr[0] = '?';
replstr[1] = NUL;
/*
* Move the bytes to the end of the buffer, so that we have
* room to put the result at the start.
*/
src = ptr + real_size - size;
mch_memmove(src, ptr, size);
/*
* Do the conversion.
*/
dst = ptr;
size = size;
while (size > 0)
{
found_bad = FALSE;
# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
if (codepage == CP_UTF8)
{
/* Handle CP_UTF8 input ourselves to be able to handle
* trailing bytes properly.
* Get one UTF-8 character from src. */
bytelen = (int)utf_ptr2len_len(src, size);
if (bytelen > size)
{
/* Only got some bytes of a character. Normally
* it's put in "conv_rest", but if it's too long
* deal with it as if they were illegal bytes. */
if (bytelen <= CONV_RESTLEN)
break;
/* weird overlong byte sequence */
bytelen = size;
found_bad = TRUE;
}
else
{
int u8c = utf_ptr2char(src);
if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
found_bad = TRUE;
ucs2buf[0] = u8c;
ucs2len = 1;
}
}
else
# endif
{
/* We don't know how long the byte sequence is, try
* from one to three bytes. */
for (bytelen = 1; bytelen <= size && bytelen <= 3;
++bytelen)
{
ucs2len = MultiByteToWideChar(codepage,
MB_ERR_INVALID_CHARS,
(LPCSTR)src, bytelen,
ucs2buf, 3);
if (ucs2len > 0)
break;
}
if (ucs2len == 0)
{
/* If we have only one byte then it's probably an
* incomplete byte sequence. Otherwise discard
* one byte as a bad character. */
if (size == 1)
break;
found_bad = TRUE;
bytelen = 1;
}
}
if (!found_bad)
{
int i;
/* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
if (enc_utf8)
{
/* From UCS-2 to UTF-8. Cannot fail. */
for (i = 0; i < ucs2len; ++i)
dst += utf_char2bytes(ucs2buf[i], dst);
}
else
{
BOOL bad = FALSE;
int dstlen;
/* From UCS-2 to "enc_codepage". If the
* conversion uses the default character "?",
* the data doesn't fit in this encoding. */
dstlen = WideCharToMultiByte(enc_codepage, 0,
(LPCWSTR)ucs2buf, ucs2len,
(LPSTR)dst, (int)(src - dst),
replstr, &bad);
if (bad)
found_bad = TRUE;
else
dst += dstlen;
}
}
if (found_bad)
{
/* Deal with bytes we can't convert. */
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt, ptr, dst);
if (bad_char_behavior != BAD_DROP)
{
if (bad_char_behavior == BAD_KEEP)
{
mch_memmove(dst, src, bytelen);
dst += bytelen;
}
else
*dst++ = bad_char_behavior;
}
}
src += bytelen;
size -= bytelen;
}
if (size > 0)
{
/* An incomplete byte sequence remaining. */
mch_memmove(conv_rest, src, size);
conv_restlen = size;
}
/* The new size is equal to how much "dst" was advanced. */
size = (long)(dst - ptr);
}
else
# endif
# ifdef MACOS_CONVERT
if (fio_flags & FIO_MACROMAN)
{
/*
* Conversion from Apple MacRoman char encoding to UTF-8 or
* latin1. This is in os_mac_conv.c.
*/
if (macroman2enc(ptr, &size, real_size) == FAIL)
goto rewind_retry;
}
else
# endif
if (fio_flags != 0)
{
int u8c;
char_u *dest;
char_u *tail = NULL;
/*
* "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
* "enc_utf8" not set: Convert Unicode to Latin1.
* Go from end to start through the buffer, because the number
* of bytes may increase.
* "dest" points to after where the UTF-8 bytes go, "p" points
* to after the next character to convert.
*/
dest = ptr + real_size;
if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
{
p = ptr + size;
if (fio_flags == FIO_UTF8)
{
/* Check for a trailing incomplete UTF-8 sequence */
tail = ptr + size - 1;
while (tail > ptr && (*tail & 0xc0) == 0x80)
--tail;
if (tail + utf_byte2len(*tail) <= ptr + size)
tail = NULL;
else
p = tail;
}
}
else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
{
/* Check for a trailing byte */
p = ptr + (size & ~1);
if (size & 1)
tail = p;
if ((fio_flags & FIO_UTF16) && p > ptr)
{
/* Check for a trailing leading word */
if (fio_flags & FIO_ENDIAN_L)
{
u8c = (*--p << 8);
u8c += *--p;
}
else
{
u8c = *--p;
u8c += (*--p << 8);
}
if (u8c >= 0xd800 && u8c <= 0xdbff)
tail = p;
else
p += 2;
}
}
else /* FIO_UCS4 */
{
/* Check for trailing 1, 2 or 3 bytes */
p = ptr + (size & ~3);
if (size & 3)
tail = p;
}
/* If there is a trailing incomplete sequence move it to
* conv_rest[]. */
if (tail != NULL)
{
conv_restlen = (int)((ptr + size) - tail);
mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
size -= conv_restlen;
}
while (p > ptr)
{
if (fio_flags & FIO_LATIN1)
u8c = *--p;
else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
{
if (fio_flags & FIO_ENDIAN_L)
{
u8c = (*--p << 8);
u8c += *--p;
}
else
{
u8c = *--p;
u8c += (*--p << 8);
}
if ((fio_flags & FIO_UTF16)
&& u8c >= 0xdc00 && u8c <= 0xdfff)
{
int u16c;
if (p == ptr)
{
/* Missing leading word. */
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt,
ptr, p);
if (bad_char_behavior == BAD_DROP)
continue;
if (bad_char_behavior != BAD_KEEP)
u8c = bad_char_behavior;
}
/* found second word of double-word, get the first
* word and compute the resulting character */
if (fio_flags & FIO_ENDIAN_L)
{
u16c = (*--p << 8);
u16c += *--p;
}
else
{
u16c = *--p;
u16c += (*--p << 8);
}
u8c = 0x10000 + ((u16c & 0x3ff) << 10)
+ (u8c & 0x3ff);
/* Check if the word is indeed a leading word. */
if (u16c < 0xd800 || u16c > 0xdbff)
{
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt,
ptr, p);
if (bad_char_behavior == BAD_DROP)
continue;
if (bad_char_behavior != BAD_KEEP)
u8c = bad_char_behavior;
}
}
}
else if (fio_flags & FIO_UCS4)
{
if (fio_flags & FIO_ENDIAN_L)
{
u8c = (*--p << 24);
u8c += (*--p << 16);
u8c += (*--p << 8);
u8c += *--p;
}
else /* big endian */
{
u8c = *--p;
u8c += (*--p << 8);
u8c += (*--p << 16);
u8c += (*--p << 24);
}
}
else /* UTF-8 */
{
if (*--p < 0x80)
u8c = *p;
else
{
len = utf_head_off(ptr, p);
p -= len;
u8c = utf_ptr2char(p);
if (len == 0)
{
/* Not a valid UTF-8 character, retry with
* another fenc when possible, otherwise just
* report the error. */
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt,
ptr, p);
if (bad_char_behavior == BAD_DROP)
continue;
if (bad_char_behavior != BAD_KEEP)
u8c = bad_char_behavior;
}
}
}
if (enc_utf8) /* produce UTF-8 */
{
dest -= utf_char2len(u8c);
(void)utf_char2bytes(u8c, dest);
}
else /* produce Latin1 */
{
--dest;
if (u8c >= 0x100)
{
/* character doesn't fit in latin1, retry with
* another fenc when possible, otherwise just
* report the error. */
if (can_retry)
goto rewind_retry;
if (conv_error == 0)
conv_error = readfile_linenr(linecnt, ptr, p);
if (bad_char_behavior == BAD_DROP)
++dest;
else if (bad_char_behavior == BAD_KEEP)
*dest = u8c;
else if (eap != NULL && eap->bad_char != 0)
*dest = bad_char_behavior;
else
*dest = 0xBF;
}
else
*dest = u8c;
}
}
/* move the linerest to before the converted characters */
line_start = dest - linerest;
mch_memmove(line_start, buffer, (size_t)linerest);
size = (long)((ptr + real_size) - dest);
ptr = dest;
}
else if (enc_utf8 && !curbuf->b_p_bin)
{
int incomplete_tail = FALSE;
/* Reading UTF-8: Check if the bytes are valid UTF-8. */
for (p = ptr; ; ++p)
{
int todo = (int)((ptr + size) - p);
int l;
if (todo <= 0)
break;
if (*p >= 0x80)
{
/* A length of 1 means it's an illegal byte. Accept
* an incomplete character at the end though, the next
* read() will get the next bytes, we'll check it
* then. */
l = utf_ptr2len_len(p, todo);
if (l > todo && !incomplete_tail)
{
/* Avoid retrying with a different encoding when
* a truncated file is more likely, or attempting
* to read the rest of an incomplete sequence when
* we have already done so. */
if (p > ptr || filesize > 0)
incomplete_tail = TRUE;
/* Incomplete byte sequence, move it to conv_rest[]
* and try to read the rest of it, unless we've
* already done so. */
if (p > ptr)
{
conv_restlen = todo;
mch_memmove(conv_rest, p, conv_restlen);
size -= conv_restlen;
break;
}
}
if (l == 1 || l > todo)
{
/* Illegal byte. If we can try another encoding
* do that, unless at EOF where a truncated
* file is more likely than a conversion error. */
if (can_retry && !incomplete_tail)
break;
# ifdef USE_ICONV
/* When we did a conversion report an error. */
if (iconv_fd != (iconv_t)-1 && conv_error == 0)
conv_error = readfile_linenr(linecnt, ptr, p);
# endif
/* Remember the first linenr with an illegal byte */
if (conv_error == 0 && illegal_byte == 0)
illegal_byte = readfile_linenr(linecnt, ptr, p);
/* Drop, keep or replace the bad byte. */
if (bad_char_behavior == BAD_DROP)
{
mch_memmove(p, p + 1, todo - 1);
--p;
--size;
}
else if (bad_char_behavior != BAD_KEEP)
*p = bad_char_behavior;
}
else
p += l - 1;
}
}
if (p < ptr + size && !incomplete_tail)
{
/* Detected a UTF-8 error. */
rewind_retry:
/* Retry reading with another conversion. */
# if defined(FEAT_EVAL) && defined(USE_ICONV)
if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
/* iconv() failed, try 'charconvert' */
did_iconv = TRUE;
else
# endif
/* use next item from 'fileencodings' */
advance_fenc = TRUE;
file_rewind = TRUE;
goto retry;
}
}
#endif
/* count the number of characters (after conversion!) */
filesize += size;
/*
* when reading the first part of a file: guess EOL type
*/
if (fileformat == EOL_UNKNOWN)
{
/* First try finding a NL, for Dos and Unix */
if (try_dos || try_unix)
{
/* Reset the carriage return counter. */
if (try_mac)
try_mac = 1;
for (p = ptr; p < ptr + size; ++p)
{
if (*p == NL)
{
if (!try_unix
|| (try_dos && p > ptr && p[-1] == CAR))
fileformat = EOL_DOS;
else
fileformat = EOL_UNIX;
break;
}
else if (*p == CAR && try_mac)
try_mac++;
}
/* Don't give in to EOL_UNIX if EOL_MAC is more likely */
if (fileformat == EOL_UNIX && try_mac)
{
/* Need to reset the counters when retrying fenc. */
try_mac = 1;
try_unix = 1;
for (; p >= ptr && *p != CAR; p--)
;
if (p >= ptr)
{
for (p = ptr; p < ptr + size; ++p)
{
if (*p == NL)
try_unix++;
else if (*p == CAR)
try_mac++;
}
if (try_mac > try_unix)
fileformat = EOL_MAC;
}
}
else if (fileformat == EOL_UNKNOWN && try_mac == 1)
/* Looking for CR but found no end-of-line markers at
* all: use the default format. */
fileformat = default_fileformat();
}
/* No NL found: may use Mac format */
if (fileformat == EOL_UNKNOWN && try_mac)
fileformat = EOL_MAC;
/* Still nothing found? Use first format in 'ffs' */
if (fileformat == EOL_UNKNOWN)
fileformat = default_fileformat();
/* if editing a new file: may set p_tx and p_ff */
if (set_options)
set_fileformat(fileformat, OPT_LOCAL);
}
}
/*
* This loop is executed once for every character read.
* Keep it fast!
*/
if (fileformat == EOL_MAC)
{
--ptr;
while (++ptr, --size >= 0)
{
/* catch most common case first */
if ((c = *ptr) != NUL && c != CAR && c != NL)
continue;
if (c == NUL)
*ptr = NL; /* NULs are replaced by newlines! */
else if (c == NL)
*ptr = CAR; /* NLs are replaced by CRs! */
else
{
if (skip_count == 0)
{
*ptr = NUL; /* end of line */
len = (colnr_T) (ptr - line_start + 1);
if (ml_append(lnum, line_start, len, newfile) == FAIL)
{
error = TRUE;
break;
}
#ifdef FEAT_PERSISTENT_UNDO
if (read_undo_file)
sha256_update(&sha_ctx, line_start, len);
#endif
++lnum;
if (--read_count == 0)
{
error = TRUE; /* break loop */
line_start = ptr; /* nothing left to write */
break;
}
}
else
--skip_count;
line_start = ptr + 1;
}
}
}
else
{
--ptr;
while (++ptr, --size >= 0)
{
if ((c = *ptr) != NUL && c != NL) /* catch most common case */
continue;
if (c == NUL)
*ptr = NL; /* NULs are replaced by newlines! */
else
{
if (skip_count == 0)
{
*ptr = NUL; /* end of line */
len = (colnr_T)(ptr - line_start + 1);
if (fileformat == EOL_DOS)
{
if (ptr[-1] == CAR) /* remove CR */
{
ptr[-1] = NUL;
--len;
}
/*
* Reading in Dos format, but no CR-LF found!
* When 'fileformats' includes "unix", delete all
* the lines read so far and start all over again.
* Otherwise give an error message later.
*/
else if (ff_error != EOL_DOS)
{
if ( try_unix
&& !read_stdin
&& (read_buffer
|| vim_lseek(fd, (off_T)0L, SEEK_SET)
== 0))
{
fileformat = EOL_UNIX;
if (set_options)
set_fileformat(EOL_UNIX, OPT_LOCAL);
file_rewind = TRUE;
keep_fileformat = TRUE;
goto retry;
}
ff_error = EOL_DOS;
}
}
if (ml_append(lnum, line_start, len, newfile) == FAIL)
{
error = TRUE;
break;
}
#ifdef FEAT_PERSISTENT_UNDO
if (read_undo_file)
sha256_update(&sha_ctx, line_start, len);
#endif
++lnum;
if (--read_count == 0)
{
error = TRUE; /* break loop */
line_start = ptr; /* nothing left to write */
break;
}
}
else
--skip_count;
line_start = ptr + 1;
}
}
}
linerest = (long)(ptr - line_start);
ui_breakcheck();
}
failed:
/* not an error, max. number of lines reached */
if (error && read_count == 0)
error = FALSE;
/*
* If we get EOF in the middle of a line, note the fact and
* complete the line ourselves.
* In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
*/
if (!error
&& !got_int
&& linerest != 0
&& !(!curbuf->b_p_bin
&& fileformat == EOL_DOS
&& *line_start == Ctrl_Z
&& ptr == line_start + 1))
{
/* remember for when writing */
if (set_options)
curbuf->b_p_eol = FALSE;
*ptr = NUL;
len = (colnr_T)(ptr - line_start + 1);
if (ml_append(lnum, line_start, len, newfile) == FAIL)
error = TRUE;
else
{
#ifdef FEAT_PERSISTENT_UNDO
if (read_undo_file)
sha256_update(&sha_ctx, line_start, len);
#endif
read_no_eol_lnum = ++lnum;
}
}
if (set_options)
save_file_ff(curbuf); /* remember the current file format */
#ifdef FEAT_CRYPT
if (curbuf->b_cryptstate != NULL)
{
crypt_free_state(curbuf->b_cryptstate);
curbuf->b_cryptstate = NULL;
}
if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
crypt_free_key(cryptkey);
/* Don't set cryptkey to NULL, it's used below as a flag that
* encryption was used. */
#endif
#ifdef FEAT_MBYTE
/* If editing a new file: set 'fenc' for the current buffer.
* Also for ":read ++edit file". */
if (set_options)
set_string_option_direct((char_u *)"fenc", -1, fenc,
OPT_FREE|OPT_LOCAL, 0);
if (fenc_alloced)
vim_free(fenc);
# ifdef USE_ICONV
if (iconv_fd != (iconv_t)-1)
{
iconv_close(iconv_fd);
iconv_fd = (iconv_t)-1;
}
# endif
#endif
if (!read_buffer && !read_stdin)
close(fd); /* errors are ignored */
#ifdef HAVE_FD_CLOEXEC
else
{
int fdflags = fcntl(fd, F_GETFD);
if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
(void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
}
#endif
vim_free(buffer);
#ifdef HAVE_DUP
if (read_stdin)
{
/* Use stderr for stdin, makes shell commands work. */
close(0);
ignored = dup(2);
}
#endif
#ifdef FEAT_MBYTE
if (tmpname != NULL)
{
mch_remove(tmpname); /* delete converted file */
vim_free(tmpname);
}
#endif
--no_wait_return; /* may wait for return now */
/*
* In recovery mode everything but autocommands is skipped.
*/
if (!recoverymode)
{
/* need to delete the last line, which comes from the empty buffer */
if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
{
#ifdef FEAT_NETBEANS_INTG
netbeansFireChanges = 0;
#endif
ml_delete(curbuf->b_ml.ml_line_count, FALSE);
#ifdef FEAT_NETBEANS_INTG
netbeansFireChanges = 1;
#endif
--linecnt;
}
linecnt = curbuf->b_ml.ml_line_count - linecnt;
if (filesize == 0)
linecnt = 0;
if (newfile || read_buffer)
{
redraw_curbuf_later(NOT_VALID);
#ifdef FEAT_DIFF
/* After reading the text into the buffer the diff info needs to
* be updated. */
diff_invalidate(curbuf);
#endif
#ifdef FEAT_FOLDING
/* All folds in the window are invalid now. Mark them for update
* before triggering autocommands. */
foldUpdateAll(curwin);
#endif
}
else if (linecnt) /* appended at least one line */
appended_lines_mark(from, linecnt);
#ifndef ALWAYS_USE_GUI
/*
* If we were reading from the same terminal as where messages go,
* the screen will have been messed up.
* Switch on raw mode now and clear the screen.
*/
if (read_stdin)
{
settmode(TMODE_RAW); /* set to raw mode */
starttermcap();
screenclear();
}
#endif
if (got_int)
{
if (!(flags & READ_DUMMY))
{
filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
if (newfile)
curbuf->b_p_ro = TRUE; /* must use "w!" now */
}
msg_scroll = msg_save;
#ifdef FEAT_VIMINFO
check_marks_read();
#endif
return OK; /* an interrupt isn't really an error */
}
if (!filtering && !(flags & READ_DUMMY))
{
msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
c = FALSE;
#ifdef UNIX
# ifdef S_ISFIFO
if (S_ISFIFO(perm)) /* fifo or socket */
{
STRCAT(IObuff, _("[fifo/socket]"));
c = TRUE;
}
# else
# ifdef S_IFIFO
if ((perm & S_IFMT) == S_IFIFO) /* fifo */
{
STRCAT(IObuff, _("[fifo]"));
c = TRUE;
}
# endif
# ifdef S_IFSOCK
if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
{
STRCAT(IObuff, _("[socket]"));
c = TRUE;
}
# endif
# endif
# ifdef OPEN_CHR_FILES
if (S_ISCHR(perm)) /* or character special */
{
STRCAT(IObuff, _("[character special]"));
c = TRUE;
}
# endif
#endif
if (curbuf->b_p_ro)
{
STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
c = TRUE;
}
if (read_no_eol_lnum)
{
msg_add_eol();
c = TRUE;
}
if (ff_error == EOL_DOS)
{
STRCAT(IObuff, _("[CR missing]"));
c = TRUE;
}
if (split)
{
STRCAT(IObuff, _("[long lines split]"));
c = TRUE;
}
#ifdef FEAT_MBYTE
if (notconverted)
{
STRCAT(IObuff, _("[NOT converted]"));
c = TRUE;
}
else if (converted)
{
STRCAT(IObuff, _("[converted]"));
c = TRUE;
}
#endif
#ifdef FEAT_CRYPT
if (cryptkey != NULL)
{
crypt_append_msg(curbuf);
c = TRUE;
}
#endif
#ifdef FEAT_MBYTE
if (conv_error != 0)
{
sprintf((char *)IObuff + STRLEN(IObuff),
_("[CONVERSION ERROR in line %ld]"), (long)conv_error);
c = TRUE;
}
else if (illegal_byte > 0)
{
sprintf((char *)IObuff + STRLEN(IObuff),
_("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
c = TRUE;
}
else
#endif
if (error)
{
STRCAT(IObuff, _("[READ ERRORS]"));
c = TRUE;
}
if (msg_add_fileformat(fileformat))
c = TRUE;
#ifdef FEAT_CRYPT
if (cryptkey != NULL)
msg_add_lines(c, (long)linecnt, filesize
- crypt_get_header_len(crypt_get_method_nr(curbuf)));
else
#endif
msg_add_lines(c, (long)linecnt, filesize);
vim_free(keep_msg);
keep_msg = NULL;
msg_scrolled_ign = TRUE;
#ifdef ALWAYS_USE_GUI
/* Don't show the message when reading stdin, it would end up in a
* message box (which might be shown when exiting!) */
if (read_stdin || read_buffer)
p = msg_may_trunc(FALSE, IObuff);
else
#endif
p = msg_trunc_attr(IObuff, FALSE, 0);
if (read_stdin || read_buffer || restart_edit != 0
|| (msg_scrolled != 0 && !need_wait_return))
/* Need to repeat the message after redrawing when:
* - When reading from stdin (the screen will be cleared next).
* - When restart_edit is set (otherwise there will be a delay
* before redrawing).
* - When the screen was scrolled but there is no wait-return
* prompt. */
set_keep_msg(p, 0);
msg_scrolled_ign = FALSE;
}
/* with errors writing the file requires ":w!" */
if (newfile && (error
#ifdef FEAT_MBYTE
|| conv_error != 0
|| (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
#endif
))
curbuf->b_p_ro = TRUE;
u_clearline(); /* cannot use "U" command after adding lines */
/*
* In Ex mode: cursor at last new line.
* Otherwise: cursor at first new line.
*/
if (exmode_active)
curwin->w_cursor.lnum = from + linecnt;
else
curwin->w_cursor.lnum = from + 1;
check_cursor_lnum();
beginline(BL_WHITE | BL_FIX); /* on first non-blank */
/*
* Set '[ and '] marks to the newly read lines.
*/
curbuf->b_op_start.lnum = from + 1;
curbuf->b_op_start.col = 0;
curbuf->b_op_end.lnum = from + linecnt;
curbuf->b_op_end.col = 0;
#ifdef WIN32
/*
* Work around a weird problem: When a file has two links (only
* possible on NTFS) and we write through one link, then stat() it
* through the other link, the timestamp information may be wrong.
* It's correct again after reading the file, thus reset the timestamp
* here.
*/
if (newfile && !read_stdin && !read_buffer
&& mch_stat((char *)fname, &st) >= 0)
{
buf_store_time(curbuf, &st, fname);
curbuf->b_mtime_read = curbuf->b_mtime;
}
#endif
}
msg_scroll = msg_save;
#ifdef FEAT_VIMINFO
/*
* Get the marks before executing autocommands, so they can be used there.
*/
check_marks_read();
#endif
/*
* We remember if the last line of the read didn't have
* an eol even when 'binary' is off, to support turning 'fixeol' off,
* or writing the read again with 'binary' on. The latter is required
* for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
*/
curbuf->b_no_eol_lnum = read_no_eol_lnum;
/* When reloading a buffer put the cursor at the first line that is
* different. */
if (flags & READ_KEEP_UNDO)
u_find_first_changed();
#ifdef FEAT_PERSISTENT_UNDO
/*
* When opening a new file locate undo info and read it.
*/
if (read_undo_file)
{
char_u hash[UNDO_HASH_SIZE];
sha256_finish(&sha_ctx, hash);
u_read_undo(NULL, hash, fname);
}
#endif
#ifdef FEAT_AUTOCMD
if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
{
int m = msg_scroll;
int n = msg_scrolled;
/* Save the fileformat now, otherwise the buffer will be considered
* modified if the format/encoding was automatically detected. */
if (set_options)
save_file_ff(curbuf);
/*
* The output from the autocommands should not overwrite anything and
* should not be overwritten: Set msg_scroll, restore its value if no
* output was done.
*/
msg_scroll = TRUE;
if (filtering)
apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
FALSE, curbuf, eap);
else if (newfile || (read_buffer && sfname != NULL))
{
apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
FALSE, curbuf, eap);
if (!au_did_filetype && *curbuf->b_p_ft != NUL)
/*
* EVENT_FILETYPE was not triggered but the buffer already has a
* filetype. Trigger EVENT_FILETYPE using the existing filetype.
*/
apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
TRUE, curbuf);
}
else
apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
FALSE, NULL, eap);
if (msg_scrolled == n)
msg_scroll = m;
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
return FAIL;
# endif
}
#endif
if (recoverymode && error)
return FAIL;
return OK;
}
#if defined(OPEN_CHR_FILES) || defined(PROTO)
/*
* Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
* which is the name of files used for process substitution output by
* some shells on some operating systems, e.g., bash on SunOS.
* Do not accept "/dev/fd/[012]", opening these may hang Vim.
*/
int
is_dev_fd_file(char_u *fname)
{
return (STRNCMP(fname, "/dev/fd/", 8) == 0
&& VIM_ISDIGIT(fname[8])
&& *skipdigits(fname + 9) == NUL
&& (fname[9] != NUL
|| (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
}
#endif
#ifdef FEAT_MBYTE
/*
* From the current line count and characters read after that, estimate the
* line number where we are now.
* Used for error messages that include a line number.
*/
static linenr_T
readfile_linenr(
linenr_T linecnt, /* line count before reading more bytes */
char_u *p, /* start of more bytes read */
char_u *endp) /* end of more bytes read */
{
char_u *s;
linenr_T lnum;
lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
for (s = p; s < endp; ++s)
if (*s == '\n')
++lnum;
return lnum;
}
#endif
/*
* Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
* equal to the buffer "buf". Used for calling readfile().
* Returns OK or FAIL.
*/
int
prep_exarg(exarg_T *eap, buf_T *buf)
{
eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
#ifdef FEAT_MBYTE
+ STRLEN(buf->b_p_fenc)
#endif
+ 15));
if (eap->cmd == NULL)
return FAIL;
#ifdef FEAT_MBYTE
sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
eap->bad_char = buf->b_bad_char;
#else
sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
#endif
eap->force_ff = 7;
eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
eap->read_edit = FALSE;
eap->forceit = FALSE;
return OK;
}
/*
* Set default or forced 'fileformat' and 'binary'.
*/
void
set_file_options(int set_options, exarg_T *eap)
{
/* set default 'fileformat' */
if (set_options)
{
if (eap != NULL && eap->force_ff != 0)
set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
else if (*p_ffs != NUL)
set_fileformat(default_fileformat(), OPT_LOCAL);
}
/* set or reset 'binary' */
if (eap != NULL && eap->force_bin != 0)
{
int oldval = curbuf->b_p_bin;
curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
}
}
#if defined(FEAT_MBYTE) || defined(PROTO)
/*
* Set forced 'fileencoding'.
*/
void
set_forced_fenc(exarg_T *eap)
{
if (eap->force_enc != 0)
{
char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
if (fenc != NULL)
set_string_option_direct((char_u *)"fenc", -1,
fenc, OPT_FREE|OPT_LOCAL, 0);
vim_free(fenc);
}
}
/*
* Find next fileencoding to use from 'fileencodings'.
* "pp" points to fenc_next. It's advanced to the next item.
* When there are no more items, an empty string is returned and *pp is set to
* NULL.
* When *pp is not set to NULL, the result is in allocated memory.
*/
static char_u *
next_fenc(char_u **pp)
{
char_u *p;
char_u *r;
if (**pp == NUL)
{
*pp = NULL;
return (char_u *)"";
}
p = vim_strchr(*pp, ',');
if (p == NULL)
{
r = enc_canonize(*pp);
*pp += STRLEN(*pp);
}
else
{
r = vim_strnsave(*pp, (int)(p - *pp));
*pp = p + 1;
if (r != NULL)
{
p = enc_canonize(r);
vim_free(r);
r = p;
}
}
if (r == NULL) /* out of memory */
{
r = (char_u *)"";
*pp = NULL;
}
return r;
}
# ifdef FEAT_EVAL
/*
* Convert a file with the 'charconvert' expression.
* This closes the file which is to be read, converts it and opens the
* resulting file for reading.
* Returns name of the resulting converted file (the caller should delete it
* after reading it).
* Returns NULL if the conversion failed ("*fdp" is not set) .
*/
static char_u *
readfile_charconvert(
char_u *fname, /* name of input file */
char_u *fenc, /* converted from */
int *fdp) /* in/out: file descriptor of file */
{
char_u *tmpname;
char_u *errmsg = NULL;
tmpname = vim_tempname('r', FALSE);
if (tmpname == NULL)
errmsg = (char_u *)_("Can't find temp file for conversion");
else
{
close(*fdp); /* close the input file, ignore errors */
*fdp = -1;
if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
fname, tmpname) == FAIL)
errmsg = (char_u *)_("Conversion with 'charconvert' failed");
if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
O_RDONLY | O_EXTRA, 0)) < 0)
errmsg = (char_u *)_("can't read output of 'charconvert'");
}
if (errmsg != NULL)
{
/* Don't use emsg(), it breaks mappings, the retry with
* another type of conversion might still work. */
MSG(errmsg);
if (tmpname != NULL)
{
mch_remove(tmpname); /* delete converted file */
vim_free(tmpname);
tmpname = NULL;
}
}
/* If the input file is closed, open it (caller should check for error). */
if (*fdp < 0)
*fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
return tmpname;
}
# endif
#endif
#ifdef FEAT_VIMINFO
/*
* Read marks for the current buffer from the viminfo file, when we support
* buffer marks and the buffer has a name.
*/
static void
check_marks_read(void)
{
if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
&& curbuf->b_ffname != NULL)
read_viminfo(NULL, VIF_WANT_MARKS);
/* Always set b_marks_read; needed when 'viminfo' is changed to include
* the ' parameter after opening a buffer. */
curbuf->b_marks_read = TRUE;
}
#endif
#if defined(FEAT_CRYPT) || defined(PROTO)
/*
* Check for magic number used for encryption. Applies to the current buffer.
* If found, the magic number is removed from ptr[*sizep] and *sizep and
* *filesizep are updated.
* Return the (new) encryption key, NULL for no encryption.
*/
static char_u *
check_for_cryptkey(
char_u *cryptkey, /* previous encryption key or NULL */
char_u *ptr, /* pointer to read bytes */
long *sizep, /* length of read bytes */
off_T *filesizep, /* nr of bytes used from file */
int newfile, /* editing a new buffer */
char_u *fname, /* file name to display */
int *did_ask) /* flag: whether already asked for key */
{
int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
int b_p_ro = curbuf->b_p_ro;
if (method >= 0)
{
/* Mark the buffer as read-only until the decryption has taken place.
* Avoids accidentally overwriting the file with garbage. */
curbuf->b_p_ro = TRUE;
/* Set the cryptmethod local to the buffer. */
crypt_set_cm_option(curbuf, method);
if (cryptkey == NULL && !*did_ask)
{
if (*curbuf->b_p_key)
cryptkey = curbuf->b_p_key;
else
{
/* When newfile is TRUE, store the typed key in the 'key'
* option and don't free it. bf needs hash of the key saved.
* Don't ask for the key again when first time Enter was hit.
* Happens when retrying to detect encoding. */
smsg((char_u *)_(need_key_msg), fname);
msg_scroll = TRUE;
crypt_check_method(method);
cryptkey = crypt_get_key(newfile, FALSE);
*did_ask = TRUE;
/* check if empty key entered */
if (cryptkey != NULL && *cryptkey == NUL)
{
if (cryptkey != curbuf->b_p_key)
vim_free(cryptkey);
cryptkey = NULL;
}
}
}
if (cryptkey != NULL)
{
int header_len;
curbuf->b_cryptstate = crypt_create_from_header(
method, cryptkey, ptr);
crypt_set_cm_option(curbuf, method);
/* Remove cryptmethod specific header from the text. */
header_len = crypt_get_header_len(method);
if (*sizep <= header_len)
/* invalid header, buffer can't be encrypted */
return NULL;
*filesizep += header_len;
*sizep -= header_len;
mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
/* Restore the read-only flag. */
curbuf->b_p_ro = b_p_ro;
}
}
/* When starting to edit a new file which does not have encryption, clear
* the 'key' option, except when starting up (called with -x argument) */
else if (newfile && *curbuf->b_p_key != NUL && !starting)
set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
return cryptkey;
}
#endif /* FEAT_CRYPT */
#ifdef UNIX
static void
set_file_time(
char_u *fname,
time_t atime, /* access time */
time_t mtime) /* modification time */
{
# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
struct utimbuf buf;
buf.actime = atime;
buf.modtime = mtime;
(void)utime((char *)fname, &buf);
# else
# if defined(HAVE_UTIMES)
struct timeval tvp[2];
tvp[0].tv_sec = atime;
tvp[0].tv_usec = 0;
tvp[1].tv_sec = mtime;
tvp[1].tv_usec = 0;
# ifdef NeXT
(void)utimes((char *)fname, tvp);
# else
(void)utimes((char *)fname, (const struct timeval *)&tvp);
# endif
# endif
# endif
}
#endif /* UNIX */
#if defined(VMS) && !defined(MIN)
/* Older DECC compiler for VAX doesn't define MIN() */
# define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
/*
* Return TRUE if a file appears to be read-only from the file permissions.
*/
int
check_file_readonly(
char_u *fname, /* full path to file */
int perm) /* known permissions on file */
{
#ifndef USE_MCH_ACCESS
int fd = 0;
#endif
return (
#ifdef USE_MCH_ACCESS
# ifdef UNIX
(perm & 0222) == 0 ||
# endif
mch_access((char *)fname, W_OK)
#else
(fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
? TRUE : (close(fd), FALSE)
#endif
);
}
/*
* buf_write() - write to file "fname" lines "start" through "end"
*
* We do our own buffering here because fwrite() is so slow.
*
* If "forceit" is true, we don't care for errors when attempting backups.
* In case of an error everything possible is done to restore the original
* file. But when "forceit" is TRUE, we risk losing it.
*
* When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
* "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
*
* This function must NOT use NameBuff (because it's called by autowrite()).
*
* return FAIL for failure, OK otherwise
*/
int
buf_write(
buf_T *buf,
char_u *fname,
char_u *sfname,
linenr_T start,
linenr_T end,
exarg_T *eap, /* for forced 'ff' and 'fenc', can be
NULL! */
int append, /* append to the file */
int forceit,
int reset_changed,
int filtering)
{
int fd;
char_u *backup = NULL;
int backup_copy = FALSE; /* copy the original file? */
int dobackup;
char_u *ffname;
char_u *wfname = NULL; /* name of file to write to */
char_u *s;
char_u *ptr;
char_u c;
int len;
linenr_T lnum;
long nchars;
char_u *errmsg = NULL;
int errmsg_allocated = FALSE;
char_u *errnum = NULL;
char_u *buffer;
char_u smallbuf[SMBUFSIZE];
char_u *backup_ext;
int bufsize;
long perm; /* file permissions */
int retval = OK;
int newfile = FALSE; /* TRUE if file doesn't exist yet */
int msg_save = msg_scroll;
int overwriting; /* TRUE if writing over original */
int no_eol = FALSE; /* no end-of-line written */
int device = FALSE; /* writing to a device */
stat_T st_old;
int prev_got_int = got_int;
int file_readonly = FALSE; /* overwritten file is read-only */
static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
#if defined(UNIX) /*XXX fix me sometime? */
int made_writable = FALSE; /* 'w' bit has been set */
#endif
/* writing everything */
int whole = (start == 1 && end == buf->b_ml.ml_line_count);
#ifdef FEAT_AUTOCMD
linenr_T old_line_count = buf->b_ml.ml_line_count;
#endif
int attr;
int fileformat;
int write_bin;
struct bw_info write_info; /* info for buf_write_bytes() */
#ifdef FEAT_MBYTE
int converted = FALSE;
int notconverted = FALSE;
char_u *fenc; /* effective 'fileencoding' */
char_u *fenc_tofree = NULL; /* allocated "fenc" */
#endif
#ifdef HAS_BW_FLAGS
int wb_flags = 0;
#endif
#ifdef HAVE_ACL
vim_acl_T acl = NULL; /* ACL copied from original file to
backup or new file */
#endif
#ifdef FEAT_PERSISTENT_UNDO
int write_undo_file = FALSE;
context_sha256_T sha_ctx;
#endif
unsigned int bkc = get_bkc_value(buf);
if (fname == NULL || *fname == NUL) /* safety check */
return FAIL;
if (buf->b_ml.ml_mfp == NULL)
{
/* This can happen during startup when there is a stray "w" in the
* vimrc file. */
EMSG(_(e_emptybuf));
return FAIL;
}
/*
* Disallow writing from .exrc and .vimrc in current directory for
* security reasons.
*/
if (check_secure())
return FAIL;
/* Avoid a crash for a long name. */
if (STRLEN(fname) >= MAXPATHL)
{
EMSG(_(e_longname));
return FAIL;
}
#ifdef FEAT_MBYTE
/* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
write_info.bw_conv_buf = NULL;
write_info.bw_conv_error = FALSE;
write_info.bw_conv_error_lnum = 0;
write_info.bw_restlen = 0;
# ifdef USE_ICONV
write_info.bw_iconv_fd = (iconv_t)-1;
# endif
#endif
#ifdef FEAT_CRYPT
write_info.bw_buffer = buf;
#endif
/* After writing a file changedtick changes but we don't want to display
* the line. */
ex_no_reprint = TRUE;
/*
* If there is no file name yet, use the one for the written file.
* BF_NOTEDITED is set to reflect this (in case the write fails).
* Don't do this when the write is for a filter command.
* Don't do this when appending.
* Only do this when 'cpoptions' contains the 'F' flag.
*/
if (buf->b_ffname == NULL
&& reset_changed
&& whole
&& buf == curbuf
#ifdef FEAT_QUICKFIX
&& !bt_nofile(buf)
#endif
&& !filtering
&& (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
&& vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
{
if (set_rw_fname(fname, sfname) == FAIL)
return FAIL;
buf = curbuf; /* just in case autocmds made "buf" invalid */
}
if (sfname == NULL)
sfname = fname;
/*
* For Unix: Use the short file name whenever possible.
* Avoids problems with networks and when directory names are changed.
* Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
* another directory, which we don't detect
*/
ffname = fname; /* remember full fname */
#ifdef UNIX
fname = sfname;
#endif
if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
overwriting = TRUE;
else
overwriting = FALSE;
if (exiting)
settmode(TMODE_COOK); /* when exiting allow typeahead now */
++no_wait_return; /* don't wait for return yet */
/*
* Set '[ and '] marks to the lines to be written.
*/
buf->b_op_start.lnum = start;
buf->b_op_start.col = 0;
buf->b_op_end.lnum = end;
buf->b_op_end.col = 0;
#ifdef FEAT_AUTOCMD
{
aco_save_T aco;
int buf_ffname = FALSE;
int buf_sfname = FALSE;
int buf_fname_f = FALSE;
int buf_fname_s = FALSE;
int did_cmd = FALSE;
int nofile_err = FALSE;
int empty_memline = (buf->b_ml.ml_mfp == NULL);
bufref_T bufref;
/*
* Apply PRE autocommands.
* Set curbuf to the buffer to be written.
* Careful: The autocommands may call buf_write() recursively!
*/
if (ffname == buf->b_ffname)
buf_ffname = TRUE;
if (sfname == buf->b_sfname)
buf_sfname = TRUE;
if (fname == buf->b_ffname)
buf_fname_f = TRUE;
if (fname == buf->b_sfname)
buf_fname_s = TRUE;
/* set curwin/curbuf to buf and save a few things */
aucmd_prepbuf(&aco, buf);
set_bufref(&bufref, buf);
if (append)
{
if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
sfname, sfname, FALSE, curbuf, eap)))
{
#ifdef FEAT_QUICKFIX
if (overwriting && bt_nofile(curbuf))
nofile_err = TRUE;
else
#endif
apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
sfname, sfname, FALSE, curbuf, eap);
}
}
else if (filtering)
{
apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
NULL, sfname, FALSE, curbuf, eap);
}
else if (reset_changed && whole)
{
int was_changed = curbufIsChanged();
did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
sfname, sfname, FALSE, curbuf, eap);
if (did_cmd)
{
if (was_changed && !curbufIsChanged())
{
/* Written everything correctly and BufWriteCmd has reset
* 'modified': Correct the undo information so that an
* undo now sets 'modified'. */
u_unchanged(curbuf);
u_update_save_nr(curbuf);
}
}
else
{
#ifdef FEAT_QUICKFIX
if (overwriting && bt_nofile(curbuf))
nofile_err = TRUE;
else
#endif
apply_autocmds_exarg(EVENT_BUFWRITEPRE,
sfname, sfname, FALSE, curbuf, eap);
}
}
else
{
if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
sfname, sfname, FALSE, curbuf, eap)))
{
#ifdef FEAT_QUICKFIX
if (overwriting && bt_nofile(curbuf))
nofile_err = TRUE;
else
#endif
apply_autocmds_exarg(EVENT_FILEWRITEPRE,
sfname, sfname, FALSE, curbuf, eap);
}
}
/* restore curwin/curbuf and a few other things */
aucmd_restbuf(&aco);
/*
* In three situations we return here and don't write the file:
* 1. the autocommands deleted or unloaded the buffer.
* 2. The autocommands abort script processing.
* 3. If one of the "Cmd" autocommands was executed.
*/
if (!bufref_valid(&bufref))
buf = NULL;
if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
|| did_cmd || nofile_err
#ifdef FEAT_EVAL
|| aborting()
#endif
)
{
--no_wait_return;
msg_scroll = msg_save;
if (nofile_err)
EMSG(_("E676: No matching autocommands for acwrite buffer"));
if (nofile_err
#ifdef FEAT_EVAL
|| aborting()
#endif
)
/* An aborting error, interrupt or exception in the
* autocommands. */
return FAIL;
if (did_cmd)
{
if (buf == NULL)
/* The buffer was deleted. We assume it was written
* (can't retry anyway). */
return OK;
if (overwriting)
{
/* Assume the buffer was written, update the timestamp. */
ml_timestamp(buf);
if (append)
buf->b_flags &= ~BF_NEW;
else
buf->b_flags &= ~BF_WRITE_MASK;
}
if (reset_changed && buf->b_changed && !append
&& (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
/* Buffer still changed, the autocommands didn't work
* properly. */
return FAIL;
return OK;
}
#ifdef FEAT_EVAL
if (!aborting())
#endif
EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
return FAIL;
}
/*
* The autocommands may have changed the number of lines in the file.
* When writing the whole file, adjust the end.
* When writing part of the file, assume that the autocommands only
* changed the number of lines that are to be written (tricky!).
*/
if (buf->b_ml.ml_line_count != old_line_count)
{
if (whole) /* write all */
end = buf->b_ml.ml_line_count;
else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
end += buf->b_ml.ml_line_count - old_line_count;
else /* less lines */
{
end -= old_line_count - buf->b_ml.ml_line_count;
if (end < start)
{
--no_wait_return;
msg_scroll = msg_save;
EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
return FAIL;
}
}
}
/*
* The autocommands may have changed the name of the buffer, which may
* be kept in fname, ffname and sfname.
*/
if (buf_ffname)
ffname = buf->b_ffname;
if (buf_sfname)
sfname = buf->b_sfname;
if (buf_fname_f)
fname = buf->b_ffname;
if (buf_fname_s)
fname = buf->b_sfname;
}
#endif
#ifdef FEAT_NETBEANS_INTG
if (netbeans_active() && isNetbeansBuffer(buf))
{
if (whole)
{
/*
* b_changed can be 0 after an undo, but we still need to write
* the buffer to NetBeans.
*/
if (buf->b_changed || isNetbeansModified(buf))
{
--no_wait_return; /* may wait for return now */
msg_scroll = msg_save;
netbeans_save_buffer(buf); /* no error checking... */
return retval;
}
else
{
errnum = (char_u *)"E656: ";
errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
buffer = NULL;
goto fail;
}
}
else
{
errnum = (char_u *)"E657: ";
errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
buffer = NULL;
goto fail;
}
}
#endif
if (shortmess(SHM_OVER) && !exiting)
msg_scroll = FALSE; /* overwrite previous file message */
else
msg_scroll = TRUE; /* don't overwrite previous file message */
if (!filtering)
filemess(buf,
#ifndef UNIX
sfname,
#else
fname,
#endif
(char_u *)"", 0); /* show that we are busy */
msg_scroll = FALSE; /* always overwrite the file message now */
buffer = alloc(BUFSIZE);
if (buffer == NULL) /* can't allocate big buffer, use small
* one (to be able to write when out of
* memory) */
{
buffer = smallbuf;
bufsize = SMBUFSIZE;
}
else
bufsize = BUFSIZE;
/*
* Get information about original file (if there is one).
*/
#if defined(UNIX)
st_old.st_dev = 0;
st_old.st_ino = 0;
perm = -1;
if (mch_stat((char *)fname, &st_old) < 0)
newfile = TRUE;
else
{
perm = st_old.st_mode;
if (!S_ISREG(st_old.st_mode)) /* not a file */
{
if (S_ISDIR(st_old.st_mode))
{
errnum = (char_u *)"E502: ";
errmsg = (char_u *)_("is a directory");
goto fail;
}
if (mch_nodetype(fname) != NODE_WRITABLE)
{
errnum = (char_u *)"E503: ";
errmsg = (char_u *)_("is not a file or writable device");
goto fail;
}
/* It's a device of some kind (or a fifo) which we can write to
* but for which we can't make a backup. */
device = TRUE;
newfile = TRUE;
perm = -1;
}
}
#else /* !UNIX */
/*
* Check for a writable device name.
*/
c = mch_nodetype(fname);
if (c == NODE_OTHER)
{
errnum = (char_u *)"E503: ";
errmsg = (char_u *)_("is not a file or writable device");
goto fail;
}
if (c == NODE_WRITABLE)
{
# if defined(MSWIN)
/* MS-Windows allows opening a device, but we will probably get stuck
* trying to write to it. */
if (!p_odev)
{
errnum = (char_u *)"E796: ";
errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
goto fail;
}
# endif
device = TRUE;
newfile = TRUE;
perm = -1;
}
else
{
perm = mch_getperm(fname);
if (perm < 0)
newfile = TRUE;
else if (mch_isdir(fname))
{
errnum = (char_u *)"E502: ";
errmsg = (char_u *)_("is a directory");
goto fail;
}
if (overwriting)
(void)mch_stat((char *)fname, &st_old);
}
#endif /* !UNIX */
if (!device && !newfile)
{
/*
* Check if the file is really writable (when renaming the file to
* make a backup we won't discover it later).
*/
file_readonly = check_file_readonly(fname, (int)perm);
if (!forceit && file_readonly)
{
if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
{
errnum = (char_u *)"E504: ";
errmsg = (char_u *)_(err_readonly);
}
else
{
errnum = (char_u *)"E505: ";
errmsg = (char_u *)_("is read-only (add ! to override)");
}
goto fail;
}
/*
* Check if the timestamp hasn't changed since reading the file.
*/
if (overwriting)
{
retval = check_mtime(buf, &st_old);
if (retval == FAIL)
goto fail;
}
}
#ifdef HAVE_ACL
/*
* For systems that support ACL: get the ACL from the original file.
*/
if (!newfile)
acl = mch_get_acl(fname);
#endif
/*
* If 'backupskip' is not empty, don't make a backup for some files.
*/
dobackup = (p_wb || p_bk || *p_pm != NUL);
#ifdef FEAT_WILDIGN
if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
dobackup = FALSE;
#endif
/*
* Save the value of got_int and reset it. We don't want a previous
* interruption cancel writing, only hitting CTRL-C while writing should
* abort it.
*/
prev_got_int = got_int;
got_int = FALSE;
/* Mark the buffer as 'being saved' to prevent changed buffer warnings */
buf->b_saving = TRUE;
/*
* If we are not appending or filtering, the file exists, and the
* 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
* When 'patchmode' is set also make a backup when appending.
*
* Do not make any backup, if 'writebackup' and 'backup' are both switched
* off. This helps when editing large files on almost-full disks.
*/
if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
{
#if defined(UNIX) || defined(WIN32)
stat_T st;
#endif
if ((bkc & BKC_YES) || append) /* "yes" */
backup_copy = TRUE;
#if defined(UNIX) || defined(WIN32)
else if ((bkc & BKC_AUTO)) /* "auto" */
{
int i;
# ifdef UNIX
/*
* Don't rename the file when:
* - it's a hard link
* - it's a symbolic link
* - we don't have write permission in the directory
* - we can't set the owner/group of the new file
*/
if (st_old.st_nlink > 1
|| mch_lstat((char *)fname, &st) < 0
|| st.st_dev != st_old.st_dev
|| st.st_ino != st_old.st_ino
# ifndef HAVE_FCHOWN
|| st.st_uid != st_old.st_uid
|| st.st_gid != st_old.st_gid
# endif
)
backup_copy = TRUE;
else
# else
# ifdef WIN32
/* On NTFS file systems hard links are possible. */
if (mch_is_linked(fname))
backup_copy = TRUE;
else
# endif
# endif
{
/*
* Check if we can create a file and set the owner/group to
* the ones from the original file.
* First find a file name that doesn't exist yet (use some
* arbitrary numbers).
*/
STRCPY(IObuff, fname);
for (i = 4913; ; i += 123)
{
sprintf((char *)gettail(IObuff), "%d", i);
if (mch_lstat((char *)IObuff, &st) < 0)
break;
}
fd = mch_open((char *)IObuff,
O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
if (fd < 0) /* can't write in directory */
backup_copy = TRUE;
else
{
# ifdef UNIX
# ifdef HAVE_FCHOWN
ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
# endif
if (mch_stat((char *)IObuff, &st) < 0
|| st.st_uid != st_old.st_uid
|| st.st_gid != st_old.st_gid
|| (long)st.st_mode != perm)
backup_copy = TRUE;
# endif
/* Close the file before removing it, on MS-Windows we
* can't delete an open file. */
close(fd);
mch_remove(IObuff);
# ifdef MSWIN
/* MS-Windows may trigger a virus scanner to open the
* file, we can't delete it then. Keep trying for half a
* second. */
{
int try;
for (try = 0; try < 10; ++try)
{
if (mch_lstat((char *)IObuff, &st) < 0)
break;
ui_delay(50L, TRUE); /* wait 50 msec */
mch_remove(IObuff);
}
}
# endif
}
}
}
/*
* Break symlinks and/or hardlinks if we've been asked to.
*/
if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
{
# ifdef UNIX
int lstat_res;
lstat_res = mch_lstat((char *)fname, &st);
/* Symlinks. */
if ((bkc & BKC_BREAKSYMLINK)
&& lstat_res == 0
&& st.st_ino != st_old.st_ino)
backup_copy = FALSE;
/* Hardlinks. */
if ((bkc & BKC_BREAKHARDLINK)
&& st_old.st_nlink > 1
&& (lstat_res != 0 || st.st_ino == st_old.st_ino))
backup_copy = FALSE;
# else
# if defined(WIN32)
/* Symlinks. */
if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
backup_copy = FALSE;
/* Hardlinks. */
if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
backup_copy = FALSE;
# endif
# endif
}
#endif
/* make sure we have a valid backup extension to use */
if (*p_bex == NUL)
backup_ext = (char_u *)".bak";
else
backup_ext = p_bex;
if (backup_copy
&& (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
{
int bfd;
char_u *copybuf, *wp;
int some_error = FALSE;
stat_T st_new;
char_u *dirp;
char_u *rootname;
#if defined(UNIX)
int did_set_shortname;
#endif
copybuf = alloc(BUFSIZE + 1);
if (copybuf == NULL)
{
some_error = TRUE; /* out of memory */
goto nobackup;
}
/*
* Try to make the backup in each directory in the 'bdir' option.
*
* Unix semantics has it, that we may have a writable file,
* that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
* - the directory is not writable,
* - the file may be a symbolic link,
* - the file may belong to another user/group, etc.
*
* For these reasons, the existing writable file must be truncated
* and reused. Creation of a backup COPY will be attempted.
*/
dirp = p_bdir;
while (*dirp)
{
#ifdef UNIX
st_new.st_ino = 0;
st_new.st_dev = 0;
st_new.st_gid = 0;
#endif
/*
* Isolate one directory name, using an entry in 'bdir'.
*/
(void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
rootname = get_file_in_dir(fname, copybuf);
if (rootname == NULL)
{
some_error = TRUE; /* out of memory */
goto nobackup;
}
#if defined(UNIX)
did_set_shortname = FALSE;
#endif
/*
* May try twice if 'shortname' not set.
*/
for (;;)
{
/*
* Make backup file name.
*/
backup = buf_modname((buf->b_p_sn || buf->b_shortname),
rootname, backup_ext, FALSE);
if (backup == NULL)
{
vim_free(rootname);
some_error = TRUE; /* out of memory */
goto nobackup;
}
/*
* Check if backup file already exists.
*/
if (mch_stat((char *)backup, &st_new) >= 0)
{
#ifdef UNIX
/*
* Check if backup file is same as original file.
* May happen when modname() gave the same file back.
* E.g. silly link, or file name-length reached.
* If we don't check here, we either ruin the file
* when copying or erase it after writing. jw.
*/
if (st_new.st_dev == st_old.st_dev
&& st_new.st_ino == st_old.st_ino)
{
vim_free(backup);
backup = NULL; /* no backup file to delete */
/*
* may try again with 'shortname' set
*/
if (!(buf->b_shortname || buf->b_p_sn))
{
buf->b_shortname = TRUE;
did_set_shortname = TRUE;
continue;
}
/* setting shortname didn't help */
if (did_set_shortname)
buf->b_shortname = FALSE;
break;
}
#endif
/*
* If we are not going to keep the backup file, don't
* delete an existing one, try to use another name.
* Change one character, just before the extension.
*/
if (!p_bk)
{
wp = backup + STRLEN(backup) - 1
- STRLEN(backup_ext);
if (wp < backup) /* empty file name ??? */
wp = backup;
*wp = 'z';
while (*wp > 'a'
&& mch_stat((char *)backup, &st_new) >= 0)
--*wp;
/* They all exist??? Must be something wrong. */
if (*wp == 'a')
{
vim_free(backup);
backup = NULL;
}
}
}
break;
}
vim_free(rootname);
/*
* Try to create the backup file
*/
if (backup != NULL)
{
/* remove old backup, if present */
mch_remove(backup);
/* Open with O_EXCL to avoid the file being created while
* we were sleeping (symlink hacker attack?) */
bfd = mch_open((char *)backup,
O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
perm & 0777);
if (bfd < 0)
{
vim_free(backup);
backup = NULL;
}
else
{
/* set file protection same as original file, but
* strip s-bit */
(void)mch_setperm(backup, perm & 0777);
#ifdef UNIX
/*
* Try to set the group of the backup same as the
* original file. If this fails, set the protection
* bits for the group same as the protection bits for
* others.
*/
if (st_new.st_gid != st_old.st_gid
# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
&& fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
# endif
)
mch_setperm(backup,
(perm & 0707) | ((perm & 07) << 3));
# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
mch_copy_sec(fname, backup);
# endif
#endif
/*
* copy the file.
*/
write_info.bw_fd = bfd;
write_info.bw_buf = copybuf;
#ifdef HAS_BW_FLAGS
write_info.bw_flags = FIO_NOCONVERT;
#endif
while ((write_info.bw_len = read_eintr(fd, copybuf,
BUFSIZE)) > 0)
{
if (buf_write_bytes(&write_info) == FAIL)
{
errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
break;
}
ui_breakcheck();
if (got_int)
{
errmsg = (char_u *)_(e_interr);
break;
}
}
if (close(bfd) < 0 && errmsg == NULL)
errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
if (write_info.bw_len < 0)
errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
#ifdef UNIX
set_file_time(backup, st_old.st_atime, st_old.st_mtime);
#endif
#ifdef HAVE_ACL
mch_set_acl(backup, acl);
#endif
#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
mch_copy_sec(fname, backup);
#endif
break;
}
}
}
nobackup:
close(fd); /* ignore errors for closing read file */
vim_free(copybuf);
if (backup == NULL && errmsg == NULL)
errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
/* ignore errors when forceit is TRUE */
if ((some_error || errmsg != NULL) && !forceit)
{
retval = FAIL;
goto fail;
}
errmsg = NULL;
}
else
{
char_u *dirp;
char_u *p;
char_u *rootname;
/*
* Make a backup by renaming the original file.
*/
/*
* If 'cpoptions' includes the "W" flag, we don't want to
* overwrite a read-only file. But rename may be possible
* anyway, thus we need an extra check here.
*/
if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
{
errnum = (char_u *)"E504: ";
errmsg = (char_u *)_(err_readonly);
goto fail;
}
/*
*
* Form the backup file name - change path/fo.o.h to
* path/fo.o.h.bak Try all directories in 'backupdir', first one
* that works is used.
*/
dirp = p_bdir;
while (*dirp)
{
/*
* Isolate one directory name and make the backup file name.
*/
(void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
rootname = get_file_in_dir(fname, IObuff);
if (rootname == NULL)
backup = NULL;
else
{
backup = buf_modname((buf->b_p_sn || buf->b_shortname),
rootname, backup_ext, FALSE);
vim_free(rootname);
}
if (backup != NULL)
{
/*
* If we are not going to keep the backup file, don't
* delete an existing one, try to use another name.
* Change one character, just before the extension.
*/
if (!p_bk && mch_getperm(backup) >= 0)
{
p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
if (p < backup) /* empty file name ??? */
p = backup;
*p = 'z';
while (*p > 'a' && mch_getperm(backup) >= 0)
--*p;
/* They all exist??? Must be something wrong! */
if (*p == 'a')
{
vim_free(backup);
backup = NULL;
}
}
}
if (backup != NULL)
{
/*
* Delete any existing backup and move the current version
* to the backup. For safety, we don't remove the backup
* until the write has finished successfully. And if the
* 'backup' option is set, leave it around.
*/
/*
* If the renaming of the original file to the backup file
* works, quit here.
*/
if (vim_rename(fname, backup) == 0)
break;
vim_free(backup); /* don't do the rename below */
backup = NULL;
}
}
if (backup == NULL && !forceit)
{
errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
goto fail;
}
}
}
#if defined(UNIX)
/* When using ":w!" and the file was read-only: make it writable */
if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
&& vim_strchr(p_cpo, CPO_FWRITE) == NULL)
{
perm |= 0200;
(void)mch_setperm(fname, perm);
made_writable = TRUE;
}
#endif
/* When using ":w!" and writing to the current file, 'readonly' makes no
* sense, reset it, unless 'Z' appears in 'cpoptions'. */
if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
{
buf->b_p_ro = FALSE;
#ifdef FEAT_TITLE
need_maketitle = TRUE; /* set window title later */
#endif
#ifdef FEAT_WINDOWS
status_redraw_all(); /* redraw status lines later */
#endif
}
if (end > buf->b_ml.ml_line_count)
end = buf->b_ml.ml_line_count;
if (buf->b_ml.ml_flags & ML_EMPTY)
start = end + 1;
/*
* If the original file is being overwritten, there is a small chance that
* we crash in the middle of writing. Therefore the file is preserved now.
* This makes all block numbers positive so that recovery does not need
* the original file.
* Don't do this if there is a backup file and we are exiting.
*/
if (reset_changed && !newfile && overwriting
&& !(exiting && backup != NULL))
{
ml_preserve(buf, FALSE);
if (got_int)
{
errmsg = (char_u *)_(e_interr);
goto restore_backup;
}
}
#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
/*
* Before risking to lose the original file verify if there's
* a resource fork to preserve, and if cannot be done warn
* the users. This happens when overwriting without backups.
*/
if (backup == NULL && overwriting && !append)
if (mch_has_resource_fork(fname))
{
errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
goto restore_backup;
}
#endif
#ifdef VMS
vms_remove_version(fname); /* remove version */
#endif
/* Default: write the file directly. May write to a temp file for
* multi-byte conversion. */
wfname = fname;
#ifdef FEAT_MBYTE
/* Check for forced 'fileencoding' from "++opt=val" argument. */
if (eap != NULL && eap->force_enc != 0)
{
fenc = eap->cmd + eap->force_enc;
fenc = enc_canonize(fenc);
fenc_tofree = fenc;
}
else
fenc = buf->b_p_fenc;
/*
* Check if the file needs to be converted.
*/
converted = need_conversion(fenc);
/*
* Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
* Latin1 to Unicode conversion. This is handled in buf_write_bytes().
* Prepare the flags for it and allocate bw_conv_buf when needed.
*/
if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
{
wb_flags = get_fio_flags(fenc);
if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
{
/* Need to allocate a buffer to translate into. */
if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
write_info.bw_conv_buflen = bufsize * 2;
else /* FIO_UCS4 */
write_info.bw_conv_buflen = bufsize * 4;
write_info.bw_conv_buf
= lalloc((long_u)write_info.bw_conv_buflen, TRUE);
if (write_info.bw_conv_buf == NULL)
end = 0;
}
}
# ifdef WIN3264
if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
{
/* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
write_info.bw_conv_buflen = bufsize * 4;
write_info.bw_conv_buf
= lalloc((long_u)write_info.bw_conv_buflen, TRUE);
if (write_info.bw_conv_buf == NULL)
end = 0;
}
# endif
# ifdef MACOS_X
if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
{
write_info.bw_conv_buflen = bufsize * 3;
write_info.bw_conv_buf
= lalloc((long_u)write_info.bw_conv_buflen, TRUE);
if (write_info.bw_conv_buf == NULL)
end = 0;
}
# endif
# if defined(FEAT_EVAL) || defined(USE_ICONV)
if (converted && wb_flags == 0)
{
# ifdef USE_ICONV
/*
* Use iconv() conversion when conversion is needed and it's not done
* internally.
*/
write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
enc_utf8 ? (char_u *)"utf-8" : p_enc);
if (write_info.bw_iconv_fd != (iconv_t)-1)
{
/* We're going to use iconv(), allocate a buffer to convert in. */
write_info.bw_conv_buflen = bufsize * ICONV_MULT;
write_info.bw_conv_buf
= lalloc((long_u)write_info.bw_conv_buflen, TRUE);
if (write_info.bw_conv_buf == NULL)
end = 0;
write_info.bw_first = TRUE;
}
# ifdef FEAT_EVAL
else
# endif
# endif
# ifdef FEAT_EVAL
/*
* When the file needs to be converted with 'charconvert' after
* writing, write to a temp file instead and let the conversion
* overwrite the original file.
*/
if (*p_ccv != NUL)
{
wfname = vim_tempname('w', FALSE);
if (wfname == NULL) /* Can't write without a tempfile! */
{
errmsg = (char_u *)_("E214: Can't find temp file for writing");
goto restore_backup;
}
}
# endif
}
# endif
if (converted && wb_flags == 0
# ifdef USE_ICONV
&& write_info.bw_iconv_fd == (iconv_t)-1
# endif
# ifdef FEAT_EVAL
&& wfname == fname
# endif
)
{
if (!forceit)
{
errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
goto restore_backup;
}
notconverted = TRUE;
}
#endif
/*
* Open the file "wfname" for writing.
* We may try to open the file twice: If we can't write to the
* file and forceit is TRUE we delete the existing file and try to create
* a new one. If this still fails we may have lost the original file!
* (this may happen when the user reached his quotum for number of files).
* Appending will fail if the file does not exist and forceit is FALSE.
*/
while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
: (O_CREAT | O_TRUNC))
, perm < 0 ? 0666 : (perm & 0777))) < 0)
{
/*
* A forced write will try to create a new file if the old one is
* still readonly. This may also happen when the directory is
* read-only. In that case the mch_remove() will fail.
*/
if (errmsg == NULL)
{
#ifdef UNIX
stat_T st;
/* Don't delete the file when it's a hard or symbolic link. */
if ((!newfile && st_old.st_nlink > 1)
|| (mch_lstat((char *)fname, &st) == 0
&& (st.st_dev != st_old.st_dev
|| st.st_ino != st_old.st_ino)))
errmsg = (char_u *)_("E166: Can't open linked file for writing");
else
#endif
{
errmsg = (char_u *)_("E212: Can't open file for writing");
if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
&& perm >= 0)
{
#ifdef UNIX
/* we write to the file, thus it should be marked
writable after all */
if (!(perm & 0200))
made_writable = TRUE;
perm |= 0200;
if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
perm &= 0777;
#endif
if (!append) /* don't remove when appending */
mch_remove(wfname);
continue;
}
}
}
restore_backup:
{
stat_T st;
/*
* If we failed to open the file, we don't need a backup. Throw it
* away. If we moved or removed the original file try to put the
* backup in its place.
*/
if (backup != NULL && wfname == fname)
{
if (backup_copy)
{
/*
* There is a small chance that we removed the original,
* try to move the copy in its place.
* This may not work if the vim_rename() fails.
* In that case we leave the copy around.
*/
/* If file does not exist, put the copy in its place */
if (mch_stat((char *)fname, &st) < 0)
vim_rename(backup, fname);
/* if original file does exist throw away the copy */
if (mch_stat((char *)fname, &st) >= 0)
mch_remove(backup);
}
else
{
/* try to put the original file back */
vim_rename(backup, fname);
}
}
/* if original file no longer exists give an extra warning */
if (!newfile && mch_stat((char *)fname, &st) < 0)
end = 0;
}
#ifdef FEAT_MBYTE
if (wfname != fname)
vim_free(wfname);
#endif
goto fail;
}
errmsg = NULL;
#if defined(MACOS_CLASSIC) || defined(WIN3264)
/* TODO: Is it need for MACOS_X? (Dany) */
/*
* On macintosh copy the original files attributes (i.e. the backup)
* This is done in order to preserve the resource fork and the
* Finder attribute (label, comments, custom icons, file creator)
*/
if (backup != NULL && overwriting && !append)
{
if (backup_copy)
(void)mch_copy_file_attribute(wfname, backup);
else
(void)mch_copy_file_attribute(backup, wfname);
}
if (!overwriting && !append)
{
if (buf->b_ffname != NULL)
(void)mch_copy_file_attribute(buf->b_ffname, wfname);
/* Should copy resource fork */
}
#endif
write_info.bw_fd = fd;
#ifdef FEAT_CRYPT
if (*buf->b_p_key != NUL && !filtering)
{
char_u *header;
int header_len;
buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
buf->b_p_key, &header, &header_len);
if (buf->b_cryptstate == NULL || header == NULL)
end = 0;
else
{
/* Write magic number, so that Vim knows how this file is
* encrypted when reading it back. */
write_info.bw_buf = header;
write_info.bw_len = header_len;
write_info.bw_flags = FIO_NOCONVERT;
if (buf_write_bytes(&write_info) == FAIL)
end = 0;
wb_flags |= FIO_ENCRYPTED;
vim_free(header);
}
}
#endif
write_info.bw_buf = buffer;
nchars = 0;
/* use "++bin", "++nobin" or 'binary' */
if (eap != NULL && eap->force_bin != 0)
write_bin = (eap->force_bin == FORCE_BIN);
else
write_bin = buf->b_p_bin;
#ifdef FEAT_MBYTE
/*
* The BOM is written just after the encryption magic number.
* Skip it when appending and the file already existed, the BOM only makes
* sense at the start of the file.
*/
if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
{
write_info.bw_len = make_bom(buffer, fenc);
if (write_info.bw_len > 0)
{
/* don't convert, do encryption */
write_info.bw_flags = FIO_NOCONVERT | wb_flags;
if (buf_write_bytes(&write_info) == FAIL)
end = 0;
else
nchars += write_info.bw_len;
}
}
write_info.bw_start_lnum = start;
#endif
#ifdef FEAT_PERSISTENT_UNDO
write_undo_file = (buf->b_p_udf && overwriting && !append
&& !filtering && reset_changed);
if (write_undo_file)
/* Prepare for computing the hash value of the text. */
sha256_start(&sha_ctx);
#endif
write_info.bw_len = bufsize;
#ifdef HAS_BW_FLAGS
write_info.bw_flags = wb_flags;
#endif
fileformat = get_fileformat_force(buf, eap);
s = buffer;
len = 0;
for (lnum = start; lnum <= end; ++lnum)
{
/*
* The next while loop is done once for each character written.
* Keep it fast!
*/
ptr = ml_get_buf(buf, lnum, FALSE) - 1;
#ifdef FEAT_PERSISTENT_UNDO
if (write_undo_file)
sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
#endif
while ((c = *++ptr) != NUL)
{
if (c == NL)
*s = NUL; /* replace newlines with NULs */
else if (c == CAR && fileformat == EOL_MAC)
*s = NL; /* Mac: replace CRs with NLs */
else
*s = c;
++s;
if (++len != bufsize)
continue;
if (buf_write_bytes(&write_info) == FAIL)
{
end = 0; /* write error: break loop */
break;
}
nchars += bufsize;
s = buffer;
len = 0;
#ifdef FEAT_MBYTE
write_info.bw_start_lnum = lnum;
#endif
}
/* write failed or last line has no EOL: stop here */
if (end == 0
|| (lnum == end
&& (write_bin || !buf->b_p_fixeol)
&& (lnum == buf->b_no_eol_lnum
|| (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
{
++lnum; /* written the line, count it */
no_eol = TRUE;
break;
}
if (fileformat == EOL_UNIX)
*s++ = NL;
else
{
*s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
if (fileformat == EOL_DOS) /* write CR-NL */
{
if (++len == bufsize)
{
if (buf_write_bytes(&write_info) == FAIL)
{
end = 0; /* write error: break loop */
break;
}
nchars += bufsize;
s = buffer;
len = 0;
}
*s++ = NL;
}
}
if (++len == bufsize && end)
{
if (buf_write_bytes(&write_info) == FAIL)
{
end = 0; /* write error: break loop */
break;
}
nchars += bufsize;
s = buffer;
len = 0;
ui_breakcheck();
if (got_int)
{
end = 0; /* Interrupted, break loop */
break;
}
}
#ifdef VMS
/*
* On VMS there is a problem: newlines get added when writing blocks
* at a time. Fix it by writing a line at a time.
* This is much slower!
* Explanation: VAX/DECC RTL insists that records in some RMS
* structures end with a newline (carriage return) character, and if
* they don't it adds one.
* With other RMS structures it works perfect without this fix.
*/
if (buf->b_fab_rfm == FAB$C_VFC
|| ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
{
int b2write;
buf->b_fab_mrs = (buf->b_fab_mrs == 0
? MIN(4096, bufsize)
: MIN(buf->b_fab_mrs, bufsize));
b2write = len;
while (b2write > 0)
{
write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
if (buf_write_bytes(&write_info) == FAIL)
{
end = 0;
break;
}
b2write -= MIN(b2write, buf->b_fab_mrs);
}
write_info.bw_len = bufsize;
nchars += len;
s = buffer;
len = 0;
}
#endif
}
if (len > 0 && end > 0)
{
write_info.bw_len = len;
if (buf_write_bytes(&write_info) == FAIL)
end = 0; /* write error */
nchars += len;
}
#if defined(UNIX) && defined(HAVE_FSYNC)
/* On many journalling file systems there is a bug that causes both the
* original and the backup file to be lost when halting the system right
* after writing the file. That's because only the meta-data is
* journalled. Syncing the file slows down the system, but assures it has
* been written to disk and we don't lose it.
* For a device do try the fsync() but don't complain if it does not work
* (could be a pipe).
* If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
if (p_fs && fsync(fd) != 0 && !device)
{
errmsg = (char_u *)_("E667: Fsync failed");
end = 0;
}
#endif
#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
/* Probably need to set the security context. */
if (!backup_copy)
mch_copy_sec(backup, wfname);
#endif
#ifdef UNIX
/* When creating a new file, set its owner/group to that of the original
* file. Get the new device and inode number. */
if (backup != NULL && !backup_copy)
{
# ifdef HAVE_FCHOWN
stat_T st;
/* don't change the owner when it's already OK, some systems remove
* permission or ACL stuff */
if (mch_stat((char *)wfname, &st) < 0
|| st.st_uid != st_old.st_uid
|| st.st_gid != st_old.st_gid)
{
ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
if (perm >= 0) /* set permission again, may have changed */
(void)mch_setperm(wfname, perm);
}
# endif
buf_setino(buf);
}
else if (!buf->b_dev_valid)
/* Set the inode when creating a new file. */
buf_setino(buf);
#endif
if (close(fd) != 0)
{
errmsg = (char_u *)_("E512: Close failed");
end = 0;
}
#ifdef UNIX
if (made_writable)
perm &= ~0200; /* reset 'w' bit for security reasons */
#endif
if (perm >= 0) /* set perm. of new file same as old file */
(void)mch_setperm(wfname, perm);
#ifdef HAVE_ACL
/*
* Probably need to set the ACL before changing the user (can't set the
* ACL on a file the user doesn't own).
* On Solaris, with ZFS and the aclmode property set to "discard" (the
* default), chmod() discards all part of a file's ACL that don't represent
* the mode of the file. It's non-trivial for us to discover whether we're
* in that situation, so we simply always re-set the ACL.
*/
# ifndef HAVE_SOLARIS_ZFS_ACL
if (!backup_copy)
# endif
mch_set_acl(wfname, acl);
#endif
#ifdef FEAT_CRYPT
if (buf->b_cryptstate != NULL)
{
crypt_free_state(buf->b_cryptstate);
buf->b_cryptstate = NULL;
}
#endif
#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
if (wfname != fname)
{
/*
* The file was written to a temp file, now it needs to be converted
* with 'charconvert' to (overwrite) the output file.
*/
if (end != 0)
{
if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
wfname, fname) == FAIL)
{
write_info.bw_conv_error = TRUE;
end = 0;
}
}
mch_remove(wfname);
vim_free(wfname);
}
#endif
if (end == 0)
{
if (errmsg == NULL)
{
#ifdef FEAT_MBYTE
if (write_info.bw_conv_error)
{
if (write_info.bw_conv_error_lnum == 0)
errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
else
{
errmsg_allocated = TRUE;
errmsg = alloc(300);
vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
(long)write_info.bw_conv_error_lnum);
}
}
else
#endif
if (got_int)
errmsg = (char_u *)_(e_interr);
else
errmsg = (char_u *)_("E514: write error (file system full?)");
}
/*
* If we have a backup file, try to put it in place of the new file,
* because the new file is probably corrupt. This avoids losing the
* original file when trying to make a backup when writing the file a
* second time.
* When "backup_copy" is set we need to copy the backup over the new
* file. Otherwise rename the backup file.
* If this is OK, don't give the extra warning message.
*/
if (backup != NULL)
{
if (backup_copy)
{
/* This may take a while, if we were interrupted let the user
* know we got the message. */
if (got_int)
{
MSG(_(e_interr));
out_flush();
}
if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
{
if ((write_info.bw_fd = mch_open((char *)fname,
O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
perm & 0777)) >= 0)
{
/* copy the file. */
write_info.bw_buf = smallbuf;
#ifdef HAS_BW_FLAGS
write_info.bw_flags = FIO_NOCONVERT;
#endif
while ((write_info.bw_len = read_eintr(fd, smallbuf,
SMBUFSIZE)) > 0)
if (buf_write_bytes(&write_info) == FAIL)
break;
if (close(write_info.bw_fd) >= 0
&& write_info.bw_len == 0)
end = 1; /* success */
}
close(fd); /* ignore errors for closing read file */
}
}
else
{
if (vim_rename(backup, fname) == 0)
end = 1;
}
}
goto fail;
}
lnum -= start; /* compute number of written lines */
--no_wait_return; /* may wait for return now */
#if !(defined(UNIX) || defined(VMS))
fname = sfname; /* use shortname now, for the messages */
#endif
if (!filtering)
{
msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
c = FALSE;
#ifdef FEAT_MBYTE
if (write_info.bw_conv_error)
{
STRCAT(IObuff, _(" CONVERSION ERROR"));
c = TRUE;
if (write_info.bw_conv_error_lnum != 0)
vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
(long)write_info.bw_conv_error_lnum);
}
else if (notconverted)
{
STRCAT(IObuff, _("[NOT converted]"));
c = TRUE;
}
else if (converted)
{
STRCAT(IObuff, _("[converted]"));
c = TRUE;
}
#endif
if (device)
{
STRCAT(IObuff, _("[Device]"));
c = TRUE;
}
else if (newfile)
{
STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
c = TRUE;
}
if (no_eol)
{
msg_add_eol();
c = TRUE;
}
/* may add [unix/dos/mac] */
if (msg_add_fileformat(fileformat))
c = TRUE;
#ifdef FEAT_CRYPT
if (wb_flags & FIO_ENCRYPTED)
{
crypt_append_msg(buf);
c = TRUE;
}
#endif
msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
if (!shortmess(SHM_WRITE))
{
if (append)
STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
else
STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
}
set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
}
/* When written everything correctly: reset 'modified'. Unless not
* writing to the original file and '+' is not in 'cpoptions'. */
if (reset_changed && whole && !append
#ifdef FEAT_MBYTE
&& !write_info.bw_conv_error
#endif
&& (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
)
{
unchanged(buf, TRUE);
#ifdef FEAT_AUTOCMD
/* buf->b_changedtick is always incremented in unchanged() but that
* should not trigger a TextChanged event. */
if (last_changedtick + 1 == buf->b_changedtick
&& last_changedtick_buf == buf)
last_changedtick = buf->b_changedtick;
#endif
u_unchanged(buf);
u_update_save_nr(buf);
}
/*
* If written to the current file, update the timestamp of the swap file
* and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
*/
if (overwriting)
{
ml_timestamp(buf);
if (append)
buf->b_flags &= ~BF_NEW;
else
buf->b_flags &= ~BF_WRITE_MASK;
}
/*
* If we kept a backup until now, and we are in patch mode, then we make
* the backup file our 'original' file.
*/
if (*p_pm && dobackup)
{
char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
fname, p_pm, FALSE);
if (backup != NULL)
{
stat_T st;
/*
* If the original file does not exist yet
* the current backup file becomes the original file
*/
if (org == NULL)
EMSG(_("E205: Patchmode: can't save original file"));
else if (mch_stat(org, &st) < 0)
{
vim_rename(backup, (char_u *)org);
vim_free(backup); /* don't delete the file */
backup = NULL;
#ifdef UNIX
set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
#endif
}
}
/*
* If there is no backup file, remember that a (new) file was
* created.
*/
else
{
int empty_fd;
if (org == NULL
|| (empty_fd = mch_open(org,
O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
perm < 0 ? 0666 : (perm & 0777))) < 0)
EMSG(_("E206: patchmode: can't touch empty original file"));
else
close(empty_fd);
}
if (org != NULL)
{
mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
vim_free(org);
}
}
/*
* Remove the backup unless 'backup' option is set
*/
if (!p_bk && backup != NULL && mch_remove(backup) != 0)
EMSG(_("E207: Can't delete backup file"));
#ifdef FEAT_SUN_WORKSHOP
if (usingSunWorkShop)
workshop_file_saved((char *) ffname);
#endif
goto nofail;
/*
* Finish up. We get here either after failure or success.
*/
fail:
--no_wait_return; /* may wait for return now */
nofail:
/* Done saving, we accept changed buffer warnings again */
buf->b_saving = FALSE;
vim_free(backup);
if (buffer != smallbuf)
vim_free(buffer);
#ifdef FEAT_MBYTE
vim_free(fenc_tofree);
vim_free(write_info.bw_conv_buf);
# ifdef USE_ICONV
if (write_info.bw_iconv_fd != (iconv_t)-1)
{
iconv_close(write_info.bw_iconv_fd);
write_info.bw_iconv_fd = (iconv_t)-1;
}
# endif
#endif
#ifdef HAVE_ACL
mch_free_acl(acl);
#endif
if (errmsg != NULL)
{
int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
attr = hl_attr(HLF_E); /* set highlight for error messages */
msg_add_fname(buf,
#ifndef UNIX
sfname
#else
fname
#endif
); /* put file name in IObuff with quotes */
if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
/* If the error message has the form "is ...", put the error number in
* front of the file name. */
if (errnum != NULL)
{
STRMOVE(IObuff + numlen, IObuff);
mch_memmove(IObuff, errnum, (size_t)numlen);
}
STRCAT(IObuff, errmsg);
emsg(IObuff);
if (errmsg_allocated)
vim_free(errmsg);
retval = FAIL;
if (end == 0)
{
MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
attr | MSG_HIST);
MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
attr | MSG_HIST);
/* Update the timestamp to avoid an "overwrite changed file"
* prompt when writing again. */
if (mch_stat((char *)fname, &st_old) >= 0)
{
buf_store_time(buf, &st_old, fname);
buf->b_mtime_read = buf->b_mtime;
}
}
}
msg_scroll = msg_save;
#ifdef FEAT_PERSISTENT_UNDO
/*
* When writing the whole file and 'undofile' is set, also write the undo
* file.
*/
if (retval == OK && write_undo_file)
{
char_u hash[UNDO_HASH_SIZE];
sha256_finish(&sha_ctx, hash);
u_write_undo(NULL, FALSE, buf, hash);
}
#endif
#ifdef FEAT_AUTOCMD
#ifdef FEAT_EVAL
if (!should_abort(retval))
#else
if (!got_int)
#endif
{
aco_save_T aco;
curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
/*
* Apply POST autocommands.
* Careful: The autocommands may call buf_write() recursively!
*/
aucmd_prepbuf(&aco, buf);
if (append)
apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
FALSE, curbuf, eap);
else if (filtering)
apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
FALSE, curbuf, eap);
else if (reset_changed && whole)
apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
FALSE, curbuf, eap);
else
apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
FALSE, curbuf, eap);
/* restore curwin/curbuf and a few other things */
aucmd_restbuf(&aco);
#ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
retval = FALSE;
#endif
}
#endif
got_int |= prev_got_int;
#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
/* Update machine specific information. */
mch_post_buffer_write(buf);
#endif
return retval;
}
/*
* Set the name of the current buffer. Use when the buffer doesn't have a
* name and a ":r" or ":w" command with a file name is used.
*/
static int
set_rw_fname(char_u *fname, char_u *sfname)
{
#ifdef FEAT_AUTOCMD
buf_T *buf = curbuf;
/* It's like the unnamed buffer is deleted.... */
if (curbuf->b_p_bl)
apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
return FAIL;
# endif
if (curbuf != buf)
{
/* We are in another buffer now, don't do the renaming. */
EMSG(_(e_auchangedbuf));
return FAIL;
}
#endif
if (setfname(curbuf, fname, sfname, FALSE) == OK)
curbuf->b_flags |= BF_NOTEDITED;
#ifdef FEAT_AUTOCMD
/* ....and a new named one is created */
apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
if (curbuf->b_p_bl)
apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
# ifdef FEAT_EVAL
if (aborting()) /* autocmds may abort script processing */
return FAIL;
# endif
/* Do filetype detection now if 'filetype' is empty. */
if (*curbuf->b_p_ft == NUL)
{
if (au_has_group((char_u *)"filetypedetect"))
(void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
do_modelines(0);
}
#endif
return OK;
}
/*
* Put file name into IObuff with quotes.
*/
void
msg_add_fname(buf_T *buf, char_u *fname)
{
if (fname == NULL)
fname = (char_u *)"-stdin-";
home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
IObuff[0] = '"';
STRCAT(IObuff, "\" ");
}
/*
* Append message for text mode to IObuff.
* Return TRUE if something appended.
*/
static int
msg_add_fileformat(int eol_type)
{
#ifndef USE_CRNL
if (eol_type == EOL_DOS)
{
STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
return TRUE;
}
#endif
#ifndef USE_CR
if (eol_type == EOL_MAC)
{
STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
return TRUE;
}
#endif
#if defined(USE_CRNL) || defined(USE_CR)
if (eol_type == EOL_UNIX)
{
STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
return TRUE;
}
#endif
return FALSE;
}
/*
* Append line and character count to IObuff.
*/
void
msg_add_lines(
int insert_space,
long lnum,
off_T nchars)
{
char_u *p;
p = IObuff + STRLEN(IObuff);
if (insert_space)
*p++ = ' ';
if (shortmess(SHM_LINES))
vim_snprintf((char *)p, IOSIZE - (p - IObuff),
"%ldL, %lldC", lnum, (varnumber_T)nchars);
else
{
if (lnum == 1)
STRCPY(p, _("1 line, "));
else
sprintf((char *)p, _("%ld lines, "), lnum);
p += STRLEN(p);
if (nchars == 1)
STRCPY(p, _("1 character"));
else
vim_snprintf((char *)p, IOSIZE - (p - IObuff),
_("%lld characters"), (varnumber_T)nchars);
}
}
/*
* Append message for missing line separator to IObuff.
*/
static void
msg_add_eol(void)
{
STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
}
/*
* Check modification time of file, before writing to it.
* The size isn't checked, because using a tool like "gzip" takes care of
* using the same timestamp but can't set the size.
*/
static int
check_mtime(buf_T *buf, stat_T *st)
{
if (buf->b_mtime_read != 0
&& time_differs((long)st->st_mtime, buf->b_mtime_read))
{
msg_scroll = TRUE; /* don't overwrite messages here */
msg_silent = 0; /* must give this prompt */
/* don't use emsg() here, don't want to flush the buffers */
MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
hl_attr(HLF_E));
if (ask_yesno((char_u *)_("Do you really want to write to it"),
TRUE) == 'n')
return FAIL;
msg_scroll = FALSE; /* always overwrite the file message now */
}
return OK;
}
static int
time_differs(long t1, long t2)
{
#if defined(__linux__) || defined(MSWIN)
/* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
* the seconds. Since the roundoff is done when flushing the inode, the
* time may change unexpectedly by one second!!! */
return (t1 - t2 > 1 || t2 - t1 > 1);
#else
return (t1 != t2);
#endif
}
/*
* Call write() to write a number of bytes to the file.
* Handles encryption and 'encoding' conversion.
*
* Return FAIL for failure, OK otherwise.
*/
static int
buf_write_bytes(struct bw_info *ip)
{
int wlen;
char_u *buf = ip->bw_buf; /* data to write */
int len = ip->bw_len; /* length of data */
#ifdef HAS_BW_FLAGS
int flags = ip->bw_flags; /* extra flags */
#endif
#ifdef FEAT_MBYTE
/*
* Skip conversion when writing the crypt magic number or the BOM.
*/
if (!(flags & FIO_NOCONVERT))
{
char_u *p;
unsigned c;
int n;
if (flags & FIO_UTF8)
{
/*
* Convert latin1 in the buffer to UTF-8 in the file.
*/
p = ip->bw_conv_buf; /* translate to buffer */
for (wlen = 0; wlen < len; ++wlen)
p += utf_char2bytes(buf[wlen], p);
buf = ip->bw_conv_buf;
len = (int)(p - ip->bw_conv_buf);
}
else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
{
/*
* Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
* Latin1 chars in the file.
*/
if (flags & FIO_LATIN1)
p = buf; /* translate in-place (can only get shorter) */
else
p = ip->bw_conv_buf; /* translate to buffer */
for (wlen = 0; wlen < len; wlen += n)
{
if (wlen == 0 && ip->bw_restlen != 0)
{
int l;
/* Use remainder of previous call. Append the start of
* buf[] to get a full sequence. Might still be too
* short! */
l = CONV_RESTLEN - ip->bw_restlen;
if (l > len)
l = len;
mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
if (n > ip->bw_restlen + len)
{
/* We have an incomplete byte sequence at the end to
* be written. We can't convert it without the
* remaining bytes. Keep them for the next call. */
if (ip->bw_restlen + len > CONV_RESTLEN)
return FAIL;
ip->bw_restlen += len;
break;
}
if (n > 1)
c = utf_ptr2char(ip->bw_rest);
else
c = ip->bw_rest[0];
if (n >= ip->bw_restlen)
{
n -= ip->bw_restlen;
ip->bw_restlen = 0;
}
else
{
ip->bw_restlen -= n;
mch_memmove(ip->bw_rest, ip->bw_rest + n,
(size_t)ip->bw_restlen);
n = 0;
}
}
else
{
n = utf_ptr2len_len(buf + wlen, len - wlen);
if (n > len - wlen)
{
/* We have an incomplete byte sequence at the end to
* be written. We can't convert it without the
* remaining bytes. Keep them for the next call. */
if (len - wlen > CONV_RESTLEN)
return FAIL;
ip->bw_restlen = len - wlen;
mch_memmove(ip->bw_rest, buf + wlen,
(size_t)ip->bw_restlen);
break;
}
if (n > 1)
c = utf_ptr2char(buf + wlen);
else
c = buf[wlen];
}
if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
{
ip->bw_conv_error = TRUE;
ip->bw_conv_error_lnum = ip->bw_start_lnum;
}
if (c == NL)
++ip->bw_start_lnum;
}
if (flags & FIO_LATIN1)
len = (int)(p - buf);
else
{
buf = ip->bw_conv_buf;
len = (int)(p - ip->bw_conv_buf);
}
}
# ifdef WIN3264
else if (flags & FIO_CODEPAGE)
{
/*
* Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
* codepage.
*/
char_u *from;
size_t fromlen;
char_u *to;
int u8c;
BOOL bad = FALSE;
int needed;
if (ip->bw_restlen > 0)
{
/* Need to concatenate the remainder of the previous call and
* the bytes of the current call. Use the end of the
* conversion buffer for this. */
fromlen = len + ip->bw_restlen;
from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
}
else
{
from = buf;
fromlen = len;
}
to = ip->bw_conv_buf;
if (enc_utf8)
{
/* Convert from UTF-8 to UCS-2, to the start of the buffer.
* The buffer has been allocated to be big enough. */
while (fromlen > 0)
{
n = (int)utf_ptr2len_len(from, (int)fromlen);
if (n > (int)fromlen) /* incomplete byte sequence */
break;
u8c = utf_ptr2char(from);
*to++ = (u8c & 0xff);
*to++ = (u8c >> 8);
fromlen -= n;
from += n;
}
/* Copy remainder to ip->bw_rest[] to be used for the next
* call. */
if (fromlen > CONV_RESTLEN)
{
/* weird overlong sequence */
ip->bw_conv_error = TRUE;
return FAIL;
}
mch_memmove(ip->bw_rest, from, fromlen);
ip->bw_restlen = (int)fromlen;
}
else
{
/* Convert from enc_codepage to UCS-2, to the start of the
* buffer. The buffer has been allocated to be big enough. */
ip->bw_restlen = 0;
needed = MultiByteToWideChar(enc_codepage,
MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
NULL, 0);
if (needed == 0)
{
/* When conversion fails there may be a trailing byte. */
needed = MultiByteToWideChar(enc_codepage,
MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
NULL, 0);
if (needed == 0)
{
/* Conversion doesn't work. */
ip->bw_conv_error = TRUE;
return FAIL;
}
/* Save the trailing byte for the next call. */
ip->bw_rest[0] = from[fromlen - 1];
ip->bw_restlen = 1;
}
needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
(LPCSTR)from, (int)(fromlen - ip->bw_restlen),
(LPWSTR)to, needed);
if (needed == 0)
{
/* Safety check: Conversion doesn't work. */
ip->bw_conv_error = TRUE;
return FAIL;
}
to += needed * 2;
}
fromlen = to - ip->bw_conv_buf;
buf = to;
# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
if (FIO_GET_CP(flags) == CP_UTF8)
{
/* Convert from UCS-2 to UTF-8, using the remainder of the
* conversion buffer. Fails when out of space. */
for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
{
u8c = *from++;
u8c += (*from++ << 8);
to += utf_char2bytes(u8c, to);
if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
{
ip->bw_conv_error = TRUE;
return FAIL;
}
}
len = (int)(to - buf);
}
else
#endif
{
/* Convert from UCS-2 to the codepage, using the remainder of
* the conversion buffer. If the conversion uses the default
* character "0", the data doesn't fit in this encoding, so
* fail. */
len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
(LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
(LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
&bad);
if (bad)
{
ip->bw_conv_error = TRUE;
return FAIL;
}
}
}
# endif
# ifdef MACOS_CONVERT
else if (flags & FIO_MACROMAN)
{
/*
* Convert UTF-8 or latin1 to Apple MacRoman.
*/
char_u *from;
size_t fromlen;
if (ip->bw_restlen > 0)
{
/* Need to concatenate the remainder of the previous call and
* the bytes of the current call. Use the end of the
* conversion buffer for this. */
fromlen = len + ip->bw_restlen;
from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
}
else
{
from = buf;
fromlen = len;
}
if (enc2macroman(from, fromlen,
ip->bw_conv_buf, &len, ip->bw_conv_buflen,
ip->bw_rest, &ip->bw_restlen) == FAIL)
{
ip->bw_conv_error = TRUE;
return FAIL;
}
buf = ip->bw_conv_buf;
}
# endif
# ifdef USE_ICONV
if (ip->bw_iconv_fd != (iconv_t)-1)
{
const char *from;
size_t fromlen;
char *to;
size_t tolen;
/* Convert with iconv(). */
if (ip->bw_restlen > 0)
{
char *fp;
/* Need to concatenate the remainder of the previous call and
* the bytes of the current call. Use the end of the
* conversion buffer for this. */
fromlen = len + ip->bw_restlen;
fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
from = fp;
tolen = ip->bw_conv_buflen - fromlen;
}
else
{
from = (const char *)buf;
fromlen = len;
tolen = ip->bw_conv_buflen;
}
to = (char *)ip->bw_conv_buf;
if (ip->bw_first)
{
size_t save_len = tolen;
/* output the initial shift state sequence */
(void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
/* There is a bug in iconv() on Linux (which appears to be
* wide-spread) which sets "to" to NULL and messes up "tolen".
*/
if (to == NULL)
{
to = (char *)ip->bw_conv_buf;
tolen = save_len;
}
ip->bw_first = FALSE;
}
/*
* If iconv() has an error or there is not enough room, fail.
*/
if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
== (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
|| fromlen > CONV_RESTLEN)
{
ip->bw_conv_error = TRUE;
return FAIL;
}
/* copy remainder to ip->bw_rest[] to be used for the next call. */
if (fromlen > 0)
mch_memmove(ip->bw_rest, (void *)from, fromlen);
ip->bw_restlen = (int)fromlen;
buf = ip->bw_conv_buf;
len = (int)((char_u *)to - ip->bw_conv_buf);
}
# endif
}
#endif /* FEAT_MBYTE */
#ifdef FEAT_CRYPT
if (flags & FIO_ENCRYPTED)
{
/* Encrypt the data. Do it in-place if possible, otherwise use an
* allocated buffer. */
if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
{
crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
}
else
{
char_u *outbuf;
len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
if (len == 0)
return OK; /* Crypt layer is buffering, will flush later. */
wlen = write_eintr(ip->bw_fd, outbuf, len);
vim_free(outbuf);
return (wlen < len) ? FAIL : OK;
}
}
#endif
wlen = write_eintr(ip->bw_fd, buf, len);
return (wlen < len) ? FAIL : OK;
}
#ifdef FEAT_MBYTE
/*
* Convert a Unicode character to bytes.
* Return TRUE for an error, FALSE when it's OK.
*/
static int
ucs2bytes(
unsigned c, /* in: character */
char_u **pp, /* in/out: pointer to result */
int flags) /* FIO_ flags */
{
char_u *p = *pp;
int error = FALSE;
int cc;
if (flags & FIO_UCS4)
{
if (flags & FIO_ENDIAN_L)
{
*p++ = c;
*p++ = (c >> 8);
*p++ = (c >> 16);
*p++ = (c >> 24);
}
else
{
*p++ = (c >> 24);
*p++ = (c >> 16);
*p++ = (c >> 8);
*p++ = c;
}
}
else if (flags & (FIO_UCS2 | FIO_UTF16))
{
if (c >= 0x10000)
{
if (flags & FIO_UTF16)
{
/* Make two words, ten bits of the character in each. First
* word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
c -= 0x10000;
if (c >= 0x100000)
error = TRUE;
cc = ((c >> 10) & 0x3ff) + 0xd800;
if (flags & FIO_ENDIAN_L)
{
*p++ = cc;
*p++ = ((unsigned)cc >> 8);
}
else
{
*p++ = ((unsigned)cc >> 8);
*p++ = cc;
}
c = (c & 0x3ff) + 0xdc00;
}
else
error = TRUE;
}
if (flags & FIO_ENDIAN_L)
{
*p++ = c;
*p++ = (c >> 8);
}
else
{
*p++ = (c >> 8);
*p++ = c;
}
}
else /* Latin1 */
{
if (c >= 0x100)
{
error = TRUE;
*p++ = 0xBF;
}
else
*p++ = c;
}
*pp = p;
return error;
}
/*
* Return TRUE if file encoding "fenc" requires conversion from or to
* 'encoding'.
*/
static int
need_conversion(char_u *fenc)
{
int same_encoding;
int enc_flags;
int fenc_flags;
if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
{
same_encoding = TRUE;
fenc_flags = 0;
}
else
{
/* Ignore difference between "ansi" and "latin1", "ucs-4" and
* "ucs-4be", etc. */
enc_flags = get_fio_flags(p_enc);
fenc_flags = get_fio_flags(fenc);
same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
}
if (same_encoding)
{
/* Specified encoding matches with 'encoding'. This requires
* conversion when 'encoding' is Unicode but not UTF-8. */
return enc_unicode != 0;
}
/* Encodings differ. However, conversion is not needed when 'enc' is any
* Unicode encoding and the file is UTF-8. */
return !(enc_utf8 && fenc_flags == FIO_UTF8);
}
/*
* Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
* internal conversion.
* if "ptr" is an empty string, use 'encoding'.
*/
static int
get_fio_flags(char_u *ptr)
{
int prop;
if (*ptr == NUL)
ptr = p_enc;
prop = enc_canon_props(ptr);
if (prop & ENC_UNICODE)
{
if (prop & ENC_2BYTE)
{
if (prop & ENC_ENDIAN_L)
return FIO_UCS2 | FIO_ENDIAN_L;
return FIO_UCS2;
}
if (prop & ENC_4BYTE)
{
if (prop & ENC_ENDIAN_L)
return FIO_UCS4 | FIO_ENDIAN_L;
return FIO_UCS4;
}
if (prop & ENC_2WORD)
{
if (prop & ENC_ENDIAN_L)
return FIO_UTF16 | FIO_ENDIAN_L;
return FIO_UTF16;
}
return FIO_UTF8;
}
if (prop & ENC_LATIN1)
return FIO_LATIN1;
/* must be ENC_DBCS, requires iconv() */
return 0;
}
#ifdef WIN3264
/*
* Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
* for the conversion MS-Windows can do for us. Also accept "utf-8".
* Used for conversion between 'encoding' and 'fileencoding'.
*/
static int
get_win_fio_flags(char_u *ptr)
{
int cp;
/* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
if (!enc_utf8 && enc_codepage <= 0)
return 0;
cp = encname2codepage(ptr);
if (cp == 0)
{
# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
if (STRCMP(ptr, "utf-8") == 0)
cp = CP_UTF8;
else
# endif
return 0;
}
return FIO_PUT_CP(cp) | FIO_CODEPAGE;
}
#endif
#ifdef MACOS_X
/*
* Check "ptr" for a Carbon supported encoding and return the FIO_ flags
* needed for the internal conversion to/from utf-8 or latin1.
*/
static int
get_mac_fio_flags(char_u *ptr)
{
if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
&& (enc_canon_props(ptr) & ENC_MACROMAN))
return FIO_MACROMAN;
return 0;
}
#endif
/*
* Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
* "size" must be at least 2.
* Return the name of the encoding and set "*lenp" to the length.
* Returns NULL when no BOM found.
*/
static char_u *
check_for_bom(
char_u *p,
long size,
int *lenp,
int flags)
{
char *name = NULL;
int len = 2;
if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
&& (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
{
name = "utf-8"; /* EF BB BF */
len = 3;
}
else if (p[0] == 0xff && p[1] == 0xfe)
{
if (size >= 4 && p[2] == 0 && p[3] == 0
&& (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
{
name = "ucs-4le"; /* FF FE 00 00 */
len = 4;
}
else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
name = "ucs-2le"; /* FF FE */
else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
/* utf-16le is preferred, it also works for ucs-2le text */
name = "utf-16le"; /* FF FE */
}
else if (p[0] == 0xfe && p[1] == 0xff
&& (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
{
/* Default to utf-16, it works also for ucs-2 text. */
if (flags == FIO_UCS2)
name = "ucs-2"; /* FE FF */
else
name = "utf-16"; /* FE FF */
}
else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
&& p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
{
name = "ucs-4"; /* 00 00 FE FF */
len = 4;
}
*lenp = len;
return (char_u *)name;
}
/*
* Generate a BOM in "buf[4]" for encoding "name".
* Return the length of the BOM (zero when no BOM).
*/
static int
make_bom(char_u *buf, char_u *name)
{
int flags;
char_u *p;
flags = get_fio_flags(name);
/* Can't put a BOM in a non-Unicode file. */
if (flags == FIO_LATIN1 || flags == 0)
return 0;
if (flags == FIO_UTF8) /* UTF-8 */
{
buf[0] = 0xef;
buf[1] = 0xbb;
buf[2] = 0xbf;
return 3;
}
p = buf;
(void)ucs2bytes(0xfeff, &p, flags);
return (int)(p - buf);
}
#endif
#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
/*
* Try to find a shortname by comparing the fullname with the current
* directory.
* Returns "full_path" or pointer into "full_path" if shortened.
*/
char_u *
shorten_fname1(char_u *full_path)
{
char_u *dirname;
char_u *p = full_path;
dirname = alloc(MAXPATHL);
if (dirname == NULL)
return full_path;
if (mch_dirname(dirname, MAXPATHL) == OK)
{
p = shorten_fname(full_path, dirname);
if (p == NULL || *p == NUL)
p = full_path;
}
vim_free(dirname);
return p;
}
#endif
/*
* Try to find a shortname by comparing the fullname with the current
* directory.
* Returns NULL if not shorter name possible, pointer into "full_path"
* otherwise.
*/
char_u *
shorten_fname(char_u *full_path, char_u *dir_name)
{
int len;
char_u *p;
if (full_path == NULL)
return NULL;
len = (int)STRLEN(dir_name);
if (fnamencmp(dir_name, full_path, len) == 0)
{
p = full_path + len;
#if defined(MSWIN)
/*
* MSWIN: when a file is in the root directory, dir_name will end in a
* slash, since C: by itself does not define a specific dir. In this
* case p may already be correct. <negri>
*/
if (!((len > 2) && (*(p - 2) == ':')))
#endif
{
if (vim_ispathsep(*p))
++p;
#ifndef VMS /* the path separator is always part of the path */
else
p = NULL;
#endif
}
}
#if defined(MSWIN)
/*
* When using a file in the current drive, remove the drive name:
* "A:\dir\file" -> "\dir\file". This helps when moving a session file on
* a floppy from "A:\dir" to "B:\dir".
*/
else if (len > 3
&& TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
&& full_path[1] == ':'
&& vim_ispathsep(full_path[2]))
p = full_path + 2;
#endif
else
p = NULL;
return p;
}
/*
* Shorten filenames for all buffers.
* When "force" is TRUE: Use full path from now on for files currently being
* edited, both for file name and swap file name. Try to shorten the file
* names a bit, if safe to do so.
* When "force" is FALSE: Only try to shorten absolute file names.
* For buffers that have buftype "nofile" or "scratch": never change the file
* name.
*/
void
shorten_fnames(int force)
{
char_u dirname[MAXPATHL];
buf_T *buf;
char_u *p;
mch_dirname(dirname, MAXPATHL);
FOR_ALL_BUFFERS(buf)
{
if (buf->b_fname != NULL
#ifdef FEAT_QUICKFIX
&& !bt_nofile(buf)
#endif
&& !path_with_url(buf->b_fname)
&& (force
|| buf->b_sfname == NULL
|| mch_isFullName(buf->b_sfname)))
{
vim_free(buf->b_sfname);
buf->b_sfname = NULL;
p = shorten_fname(buf->b_ffname, dirname);
if (p != NULL)
{
buf->b_sfname = vim_strsave(p);
buf->b_fname = buf->b_sfname;
}
if (p == NULL || buf->b_fname == NULL)
buf->b_fname = buf->b_ffname;
}
/* Always make the swap file name a full path, a "nofile" buffer may
* also have a swap file. */
mf_fullname(buf->b_ml.ml_mfp);
}
#ifdef FEAT_WINDOWS
status_redraw_all();
redraw_tabline = TRUE;
#endif
}
#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
|| defined(FEAT_GUI_MSWIN) \
|| defined(FEAT_GUI_MAC) \
|| defined(PROTO)
/*
* Shorten all filenames in "fnames[count]" by current directory.
*/
void
shorten_filenames(char_u **fnames, int count)
{
int i;
char_u dirname[MAXPATHL];
char_u *p;
if (fnames == NULL || count < 1)
return;
mch_dirname(dirname, sizeof(dirname));
for (i = 0; i < count; ++i)
{
if ((p = shorten_fname(fnames[i], dirname)) != NULL)
{
/* shorten_fname() returns pointer in given "fnames[i]". If free
* "fnames[i]" first, "p" becomes invalid. So we need to copy
* "p" first then free fnames[i]. */
p = vim_strsave(p);
vim_free(fnames[i]);
fnames[i] = p;
}
}
}
#endif
/*
* add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
* fo_o_h.ext for MSDOS or when shortname option set.
*
* Assumed that fname is a valid name found in the filesystem we assure that
* the return value is a different name and ends in 'ext'.
* "ext" MUST be at most 4 characters long if it starts with a dot, 3
* characters otherwise.
* Space for the returned name is allocated, must be freed later.
* Returns NULL when out of memory.
*/
char_u *
modname(
char_u *fname,
char_u *ext,
int prepend_dot) /* may prepend a '.' to file name */
{
return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
fname, ext, prepend_dot);
}
char_u *
buf_modname(
int shortname, /* use 8.3 file name */
char_u *fname,
char_u *ext,
int prepend_dot) /* may prepend a '.' to file name */
{
char_u *retval;
char_u *s;
char_u *e;
char_u *ptr;
int fnamelen, extlen;
extlen = (int)STRLEN(ext);
/*
* If there is no file name we must get the name of the current directory
* (we need the full path in case :cd is used).
*/
if (fname == NULL || *fname == NUL)
{
retval = alloc((unsigned)(MAXPATHL + extlen + 3));
if (retval == NULL)
return NULL;
if (mch_dirname(retval, MAXPATHL) == FAIL ||
(fnamelen = (int)STRLEN(retval)) == 0)
{
vim_free(retval);
return NULL;
}
if (!after_pathsep(retval, retval + fnamelen))
{
retval[fnamelen++] = PATHSEP;
retval[fnamelen] = NUL;
}
prepend_dot = FALSE; /* nothing to prepend a dot to */
}
else
{
fnamelen = (int)STRLEN(fname);
retval = alloc((unsigned)(fnamelen + extlen + 3));
if (retval == NULL)
return NULL;
STRCPY(retval, fname);
#ifdef VMS
vms_remove_version(retval); /* we do not need versions here */
#endif
}
/*
* search backwards until we hit a '/', '\' or ':' replacing all '.'
* by '_' for MSDOS or when shortname option set and ext starts with a dot.
* Then truncate what is after the '/', '\' or ':' to 8 characters for
* MSDOS and 26 characters for AMIGA, a lot more for UNIX.
*/
for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
{
if (*ext == '.'
#ifdef USE_LONG_FNAME
&& (!USE_LONG_FNAME || shortname)
#else
&& shortname
#endif
)
if (*ptr == '.') /* replace '.' by '_' */
*ptr = '_';
if (vim_ispathsep(*ptr))
{
++ptr;
break;
}
}
/* the file name has at most BASENAMELEN characters. */
if (STRLEN(ptr) > (unsigned)BASENAMELEN)
ptr[BASENAMELEN] = '\0';
s = ptr + STRLEN(ptr);
/*
* For 8.3 file names we may have to reduce the length.
*/
#ifdef USE_LONG_FNAME
if (!USE_LONG_FNAME || shortname)
#else
if (shortname)
#endif
{
/*
* If there is no file name, or the file name ends in '/', and the
* extension starts with '.', put a '_' before the dot, because just
* ".ext" is invalid.
*/
if (fname == NULL || *fname == NUL
|| vim_ispathsep(fname[STRLEN(fname) - 1]))
{
if (*ext == '.')
*s++ = '_';
}
/*
* If the extension starts with '.', truncate the base name at 8
* characters
*/
else if (*ext == '.')
{
if ((size_t)(s - ptr) > (size_t)8)
{
s = ptr + 8;
*s = '\0';
}
}
/*
* If the extension doesn't start with '.', and the file name
* doesn't have an extension yet, append a '.'
*/
else if ((e = vim_strchr(ptr, '.')) == NULL)
*s++ = '.';
/*
* If the extension doesn't start with '.', and there already is an
* extension, it may need to be truncated
*/
else if ((int)STRLEN(e) + extlen > 4)
s = e + 4 - extlen;
}
#if defined(USE_LONG_FNAME) || defined(WIN3264)
/*
* If there is no file name, and the extension starts with '.', put a
* '_' before the dot, because just ".ext" may be invalid if it's on a
* FAT partition, and on HPFS it doesn't matter.
*/
else if ((fname == NULL || *fname == NUL) && *ext == '.')
*s++ = '_';
#endif
/*
* Append the extension.
* ext can start with '.' and cannot exceed 3 more characters.
*/
STRCPY(s, ext);
/*
* Prepend the dot.
*/
if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
#ifdef USE_LONG_FNAME
&& USE_LONG_FNAME
#endif
)
{
STRMOVE(e + 1, e);
*e = '.';
}
/*
* Check that, after appending the extension, the file name is really
* different.
*/
if (fname != NULL && STRCMP(fname, retval) == 0)
{
/* we search for a character that can be replaced by '_' */
while (--s >= ptr)
{
if (*s != '_')
{
*s = '_';
break;
}
}
if (s < ptr) /* fname was "________.<ext>", how tricky! */
*ptr = 'v';
}
return retval;
}
/*
* Like fgets(), but if the file line is too long, it is truncated and the
* rest of the line is thrown away. Returns TRUE for end-of-file.
*/
int
vim_fgets(char_u *buf, int size, FILE *fp)
{
char *eof;
#define FGETS_SIZE 200
char tbuf[FGETS_SIZE];
buf[size - 2] = NUL;
#ifdef USE_CR
eof = fgets_cr((char *)buf, size, fp);
#else
eof = fgets((char *)buf, size, fp);
#endif
if (buf[size - 2] != NUL && buf[size - 2] != '\n')
{
buf[size - 1] = NUL; /* Truncate the line */
/* Now throw away the rest of the line: */
do
{
tbuf[FGETS_SIZE - 2] = NUL;
#ifdef USE_CR
ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
#else
ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
#endif
} while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
}
return (eof == NULL);
}
#if defined(USE_CR) || defined(PROTO)
/*
* Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
* Returns TRUE for end-of-file.
* Only used for the Mac, because it's much slower than vim_fgets().
*/
int
tag_fgets(char_u *buf, int size, FILE *fp)
{
int i = 0;
int c;
int eof = FALSE;
for (;;)
{
c = fgetc(fp);
if (c == EOF)
{
eof = TRUE;
break;
}
if (c == '\r')
{
/* Always store a NL for end-of-line. */
if (i < size - 1)
buf[i++] = '\n';
c = fgetc(fp);
if (c != '\n') /* Macintosh format: single CR. */
ungetc(c, fp);
break;
}
if (i < size - 1)
buf[i++] = c;
if (c == '\n')
break;
}
buf[i] = NUL;
return eof;
}
#endif
/*
* rename() only works if both files are on the same file system, this
* function will (attempts to?) copy the file across if rename fails -- webb
* Return -1 for failure, 0 for success.
*/
int
vim_rename(char_u *from, char_u *to)
{
int fd_in;
int fd_out;
int n;
char *errmsg = NULL;
char *buffer;
#ifdef AMIGA
BPTR flock;
#endif
stat_T st;
long perm;
#ifdef HAVE_ACL
vim_acl_T acl; /* ACL from original file */
#endif
int use_tmp_file = FALSE;
/*
* When the names are identical, there is nothing to do. When they refer
* to the same file (ignoring case and slash/backslash differences) but
* the file name differs we need to go through a temp file.
*/
if (fnamecmp(from, to) == 0)
{
if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
use_tmp_file = TRUE;
else
return 0;
}
/*
* Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
*/
if (mch_stat((char *)from, &st) < 0)
return -1;
#ifdef UNIX
{
stat_T st_to;
/* It's possible for the source and destination to be the same file.
* This happens when "from" and "to" differ in case and are on a FAT32
* filesystem. In that case go through a temp file name. */
if (mch_stat((char *)to, &st_to) >= 0
&& st.st_dev == st_to.st_dev
&& st.st_ino == st_to.st_ino)
use_tmp_file = TRUE;
}
#endif
#ifdef WIN3264
{
BY_HANDLE_FILE_INFORMATION info1, info2;
/* It's possible for the source and destination to be the same file.
* In that case go through a temp file name. This makes rename("foo",
* "./foo") a no-op (in a complicated way). */
if (win32_fileinfo(from, &info1) == FILEINFO_OK
&& win32_fileinfo(to, &info2) == FILEINFO_OK
&& info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
&& info1.nFileIndexHigh == info2.nFileIndexHigh
&& info1.nFileIndexLow == info2.nFileIndexLow)
use_tmp_file = TRUE;
}
#endif
if (use_tmp_file)
{
char tempname[MAXPATHL + 1];
/*
* Find a name that doesn't exist and is in the same directory.
* Rename "from" to "tempname" and then rename "tempname" to "to".
*/
if (STRLEN(from) >= MAXPATHL - 5)
return -1;
STRCPY(tempname, from);
for (n = 123; n < 99999; ++n)
{
sprintf((char *)gettail((char_u *)tempname), "%d", n);
if (mch_stat(tempname, &st) < 0)
{
if (mch_rename((char *)from, tempname) == 0)
{
if (mch_rename(tempname, (char *)to) == 0)
return 0;
/* Strange, the second step failed. Try moving the
* file back and return failure. */
mch_rename(tempname, (char *)from);
return -1;
}
/* If it fails for one temp name it will most likely fail
* for any temp name, give up. */
return -1;
}
}
return -1;
}
/*
* Delete the "to" file, this is required on some systems to make the
* mch_rename() work, on other systems it makes sure that we don't have
* two files when the mch_rename() fails.
*/
#ifdef AMIGA
/*
* With MSDOS-compatible filesystems (crossdos, messydos) it is possible
* that the name of the "to" file is the same as the "from" file, even
* though the names are different. To avoid the chance of accidentally
* deleting the "from" file (horror!) we lock it during the remove.
*
* When used for making a backup before writing the file: This should not
* happen with ":w", because startscript() should detect this problem and
* set buf->b_shortname, causing modname() to return a correct ".bak" file
* name. This problem does exist with ":w filename", but then the
* original file will be somewhere else so the backup isn't really
* important. If autoscripting is off the rename may fail.
*/
flock = Lock((UBYTE *)from, (long)ACCESS_READ);
#endif
mch_remove(to);
#ifdef AMIGA
if (flock)
UnLock(flock);
#endif
/*
* First try a normal rename, return if it works.
*/
if (mch_rename((char *)from, (char *)to) == 0)
return 0;
/*
* Rename() failed, try copying the file.
*/
perm = mch_getperm(from);
#ifdef HAVE_ACL
/* For systems that support ACL: get the ACL from the original file. */
acl = mch_get_acl(from);
#endif
fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
if (fd_in == -1)
{
#ifdef HAVE_ACL
mch_free_acl(acl);
#endif
return -1;
}
/* Create the new file with same permissions as the original. */
fd_out = mch_open((char *)to,
O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
if (fd_out == -1)
{
close(fd_in);
#ifdef HAVE_ACL
mch_free_acl(acl);
#endif
return -1;
}
buffer = (char *)alloc(BUFSIZE);
if (buffer == NULL)
{
close(fd_out);
close(fd_in);
#ifdef HAVE_ACL
mch_free_acl(acl);
#endif
return -1;
}
while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
if (write_eintr(fd_out, buffer, n) != n)
{
errmsg = _("E208: Error writing to \"%s\"");
break;
}
vim_free(buffer);
close(fd_in);
if (close(fd_out) < 0)
errmsg = _("E209: Error closing \"%s\"");
if (n < 0)
{
errmsg = _("E210: Error reading \"%s\"");
to = from;
}
#ifndef UNIX /* for Unix mch_open() already set the permission */
mch_setperm(to, perm);
#endif
#ifdef HAVE_ACL
mch_set_acl(to, acl);
mch_free_acl(acl);
#endif
#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
mch_copy_sec(from, to);
#endif
if (errmsg != NULL)
{
EMSG2(errmsg, to);
return -1;
}
mch_remove(from);
return 0;
}
static int already_warned = FALSE;
/*
* Check if any not hidden buffer has been changed.
* Postpone the check if there are characters in the stuff buffer, a global
* command is being executed, a mapping is being executed or an autocommand is
* busy.
* Returns TRUE if some message was written (screen should be redrawn and
* cursor positioned).
*/
int
check_timestamps(
int focus) /* called for GUI focus event */
{
buf_T *buf;
int didit = 0;
int n;
/* Don't check timestamps while system() or another low-level function may
* cause us to lose and gain focus. */
if (no_check_timestamps > 0)
return FALSE;
/* Avoid doing a check twice. The OK/Reload dialog can cause a focus
* event and we would keep on checking if the file is steadily growing.
* Do check again after typing something. */
if (focus && did_check_timestamps)
{
need_check_timestamps = TRUE;
return FALSE;
}
if (!stuff_empty() || global_busy || !typebuf_typed()
#ifdef FEAT_AUTOCMD
|| autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
#endif
)
need_check_timestamps = TRUE; /* check later */
else
{
++no_wait_return;
did_check_timestamps = TRUE;
already_warned = FALSE;
FOR_ALL_BUFFERS(buf)
{
/* Only check buffers in a window. */
if (buf->b_nwindows > 0)
{
bufref_T bufref;
set_bufref(&bufref, buf);
n = buf_check_timestamp(buf, focus);
if (didit < n)
didit = n;
if (n > 0 && !bufref_valid(&bufref))
{
/* Autocommands have removed the buffer, start at the
* first one again. */
buf = firstbuf;
continue;
}
}
}
--no_wait_return;
need_check_timestamps = FALSE;
if (need_wait_return && didit == 2)
{
/* make sure msg isn't overwritten */
msg_puts((char_u *)"\n");
out_flush();
}
}
return didit;
}
/*
* Move all the lines from buffer "frombuf" to buffer "tobuf".
* Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
* empty.
*/
static int
move_lines(buf_T *frombuf, buf_T *tobuf)
{
buf_T *tbuf = curbuf;
int retval = OK;
linenr_T lnum;
char_u *p;
/* Copy the lines in "frombuf" to "tobuf". */
curbuf = tobuf;
for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
{
p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
{
vim_free(p);
retval = FAIL;
break;
}
vim_free(p);
}
/* Delete all the lines in "frombuf". */
if (retval != FAIL)
{
curbuf = frombuf;
for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
if (ml_delete(lnum, FALSE) == FAIL)
{
/* Oops! We could try putting back the saved lines, but that
* might fail again... */
retval = FAIL;
break;
}
}
curbuf = tbuf;
return retval;
}
/*
* Check if buffer "buf" has been changed.
* Also check if the file for a new buffer unexpectedly appeared.
* return 1 if a changed buffer was found.
* return 2 if a message has been displayed.
* return 0 otherwise.
*/
int
buf_check_timestamp(
buf_T *buf,
int focus UNUSED) /* called for GUI focus event */
{
stat_T st;
int stat_res;
int retval = 0;
char_u *path;
char_u *tbuf;
char *mesg = NULL;
char *mesg2 = "";
int helpmesg = FALSE;
int reload = FALSE;
char *reason;
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
int can_reload = FALSE;
#endif
off_T orig_size = buf->b_orig_size;
int orig_mode = buf->b_orig_mode;
#ifdef FEAT_GUI
int save_mouse_correct = need_mouse_correct;
#endif
#ifdef FEAT_AUTOCMD
static int busy = FALSE;
int n;
char_u *s;
bufref_T bufref;
set_bufref(&bufref, buf);
#endif
/* If there is no file name, the buffer is not loaded, 'buftype' is
* set, we are in the middle of a save or being called recursively: ignore
* this buffer. */
if (buf->b_ffname == NULL
|| buf->b_ml.ml_mfp == NULL
#if defined(FEAT_QUICKFIX)
|| *buf->b_p_bt != NUL
#endif
|| buf->b_saving
#ifdef FEAT_AUTOCMD
|| busy
#endif
#ifdef FEAT_NETBEANS_INTG
|| isNetbeansBuffer(buf)
#endif
)
return 0;
if ( !(buf->b_flags & BF_NOTEDITED)
&& buf->b_mtime != 0
&& ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
|| time_differs((long)st.st_mtime, buf->b_mtime)
|| st.st_size != buf->b_orig_size
#ifdef HAVE_ST_MODE
|| (int)st.st_mode != buf->b_orig_mode
#else
|| mch_getperm(buf->b_ffname) != buf->b_orig_mode
#endif
))
{
retval = 1;
/* set b_mtime to stop further warnings (e.g., when executing
* FileChangedShell autocmd) */
if (stat_res < 0)
{
buf->b_mtime = 0;
buf->b_orig_size = 0;
buf->b_orig_mode = 0;
}
else
buf_store_time(buf, &st, buf->b_ffname);
/* Don't do anything for a directory. Might contain the file
* explorer. */
if (mch_isdir(buf->b_fname))
;
/*
* If 'autoread' is set, the buffer has no changes and the file still
* exists, reload the buffer. Use the buffer-local option value if it
* was set, the global option value otherwise.
*/
else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
&& !bufIsChanged(buf) && stat_res >= 0)
reload = TRUE;
else
{
if (stat_res < 0)
reason = "deleted";
else if (bufIsChanged(buf))
reason = "conflict";
else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
reason = "changed";
else if (orig_mode != buf->b_orig_mode)
reason = "mode";
else
reason = "time";
#ifdef FEAT_AUTOCMD
/*
* Only give the warning if there are no FileChangedShell
* autocommands.
* Avoid being called recursively by setting "busy".
*/
busy = TRUE;
# ifdef FEAT_EVAL
set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
# endif
++allbuf_lock;
n = apply_autocmds(EVENT_FILECHANGEDSHELL,
buf->b_fname, buf->b_fname, FALSE, buf);
--allbuf_lock;
busy = FALSE;
if (n)
{
if (!bufref_valid(&bufref))
EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
# ifdef FEAT_EVAL
s = get_vim_var_str(VV_FCS_CHOICE);
if (STRCMP(s, "reload") == 0 && *reason != 'd')
reload = TRUE;
else if (STRCMP(s, "ask") == 0)
n = FALSE;
else
# endif
return 2;
}
if (!n)
#endif
{
if (*reason == 'd')
mesg = _("E211: File \"%s\" no longer available");
else
{
helpmesg = TRUE;
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
can_reload = TRUE;
#endif
/*
* Check if the file contents really changed to avoid
* giving a warning when only the timestamp was set (e.g.,
* checked out of CVS). Always warn when the buffer was
* changed.
*/
if (reason[2] == 'n')
{
mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
mesg2 = _("See \":help W12\" for more info.");
}
else if (reason[1] == 'h')
{
mesg = _("W11: Warning: File \"%s\" has changed since editing started");
mesg2 = _("See \":help W11\" for more info.");
}
else if (*reason == 'm')
{
mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
mesg2 = _("See \":help W16\" for more info.");
}
else
/* Only timestamp changed, store it to avoid a warning
* in check_mtime() later. */
buf->b_mtime_read = buf->b_mtime;
}
}
}
}
else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
&& vim_fexists(buf->b_ffname))
{
retval = 1;
mesg = _("W13: Warning: File \"%s\" has been created after editing started");
buf->b_flags |= BF_NEW_W;
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
can_reload = TRUE;
#endif
}
if (mesg != NULL)
{
path = home_replace_save(buf, buf->b_fname);
if (path != NULL)
{
if (!helpmesg)
mesg2 = "";
tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
+ STRLEN(mesg2) + 2));
sprintf((char *)tbuf, mesg, path);
#ifdef FEAT_EVAL
/* Set warningmsg here, before the unimportant and output-specific
* mesg2 has been appended. */
set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
#endif
#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
if (can_reload)
{
if (*mesg2 != NUL)
{
STRCAT(tbuf, "\n");
STRCAT(tbuf, mesg2);
}
if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
(char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
reload = TRUE;
}
else
#endif
if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
{
if (*mesg2 != NUL)
{
STRCAT(tbuf, "; ");
STRCAT(tbuf, mesg2);
}
EMSG(tbuf);
retval = 2;
}
else
{
# ifdef FEAT_AUTOCMD
if (!autocmd_busy)
# endif
{
msg_start();
msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
if (*mesg2 != NUL)
msg_puts_attr((char_u *)mesg2,
hl_attr(HLF_W) + MSG_HIST);
msg_clr_eos();
(void)msg_end();
if (emsg_silent == 0)
{
out_flush();
# ifdef FEAT_GUI
if (!focus)
# endif
/* give the user some time to think about it */
ui_delay(1000L, TRUE);
/* don't redraw and erase the message */
redraw_cmdline = FALSE;
}
}
already_warned = TRUE;
}
vim_free(path);
vim_free(tbuf);
}
}
if (reload)
{
/* Reload the buffer. */
buf_reload(buf, orig_mode);
#ifdef FEAT_PERSISTENT_UNDO
if (buf->b_p_udf && buf->b_ffname != NULL)
{
char_u hash[UNDO_HASH_SIZE];
buf_T *save_curbuf = curbuf;
/* Any existing undo file is unusable, write it now. */
curbuf = buf;
u_compute_hash(hash);
u_write_undo(NULL, FALSE, buf, hash);
curbuf = save_curbuf;
}
#endif
}
#ifdef FEAT_AUTOCMD
/* Trigger FileChangedShell when the file was changed in any way. */
if (bufref_valid(&bufref) && retval != 0)
(void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
buf->b_fname, buf->b_fname, FALSE, buf);
#endif
#ifdef FEAT_GUI
/* restore this in case an autocommand has set it; it would break
* 'mousefocus' */
need_mouse_correct = save_mouse_correct;
#endif
return retval;
}
/*
* Reload a buffer that is already loaded.
* Used when the file was changed outside of Vim.
* "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
* buf->b_orig_mode may have been reset already.
*/
void
buf_reload(buf_T *buf, int orig_mode)
{
exarg_T ea;
pos_T old_cursor;
linenr_T old_topline;
int old_ro = buf->b_p_ro;
buf_T *savebuf;
bufref_T bufref;
int saved = OK;
aco_save_T aco;
int flags = READ_NEW;
/* set curwin/curbuf for "buf" and save some things */
aucmd_prepbuf(&aco, buf);
/* We only want to read the text from the file, not reset the syntax
* highlighting, clear marks, diff status, etc. Force the fileformat
* and encoding to be the same. */
if (prep_exarg(&ea, buf) == OK)
{
old_cursor = curwin->w_cursor;
old_topline = curwin->w_topline;
if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
{
/* Save all the text, so that the reload can be undone.
* Sync first so that this is a separate undo-able action. */
u_sync(FALSE);
saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
flags |= READ_KEEP_UNDO;
}
/*
* To behave like when a new file is edited (matters for
* BufReadPost autocommands) we first need to delete the current
* buffer contents. But if reading the file fails we should keep
* the old contents. Can't use memory only, the file might be
* too big. Use a hidden buffer to move the buffer contents to.
*/
if (bufempty() || saved == FAIL)
savebuf = NULL;
else
{
/* Allocate a buffer without putting it in the buffer list. */
savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
set_bufref(&bufref, savebuf);
if (savebuf != NULL && buf == curbuf)
{
/* Open the memline. */
curbuf = savebuf;
curwin->w_buffer = savebuf;
saved = ml_open(curbuf);
curbuf = buf;
curwin->w_buffer = buf;
}
if (savebuf == NULL || saved == FAIL || buf != curbuf
|| move_lines(buf, savebuf) == FAIL)
{
EMSG2(_("E462: Could not prepare for reloading \"%s\""),
buf->b_fname);
saved = FAIL;
}
}
if (saved == OK)
{
curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
#ifdef FEAT_AUTOCMD
keep_filetype = TRUE; /* don't detect 'filetype' */
#endif
if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
(linenr_T)0,
(linenr_T)MAXLNUM, &ea, flags) != OK)
{
#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
if (!aborting())
#endif
EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
{
/* Put the text back from the save buffer. First
* delete any lines that readfile() added. */
while (!bufempty())
if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
break;
(void)move_lines(savebuf, buf);
}
}
else if (buf == curbuf) /* "buf" still valid */
{
/* Mark the buffer as unmodified and free undo info. */
unchanged(buf, TRUE);
if ((flags & READ_KEEP_UNDO) == 0)
{
u_blockfree(buf);
u_clearall(buf);
}
else
{
/* Mark all undo states as changed. */
u_unchanged(curbuf);
}
}
}
vim_free(ea.cmd);
if (savebuf != NULL && bufref_valid(&bufref))
wipe_buffer(savebuf, FALSE);
#ifdef FEAT_DIFF
/* Invalidate diff info if necessary. */
diff_invalidate(curbuf);
#endif
/* Restore the topline and cursor position and check it (lines may
* have been removed). */
if (old_topline > curbuf->b_ml.ml_line_count)
curwin->w_topline = curbuf->b_ml.ml_line_count;
else
curwin->w_topline = old_topline;
curwin->w_cursor = old_cursor;
check_cursor();
update_topline();
#ifdef FEAT_AUTOCMD
keep_filetype = FALSE;
#endif
#ifdef FEAT_FOLDING
{
win_T *wp;
tabpage_T *tp;
/* Update folds unless they are defined manually. */
FOR_ALL_TAB_WINDOWS(tp, wp)
if (wp->w_buffer == curwin->w_buffer
&& !foldmethodIsManual(wp))
foldUpdateAll(wp);
}
#endif
/* If the mode didn't change and 'readonly' was set, keep the old
* value; the user probably used the ":view" command. But don't
* reset it, might have had a read error. */
if (orig_mode == curbuf->b_orig_mode)
curbuf->b_p_ro |= old_ro;
/* Modelines must override settings done by autocommands. */
do_modelines(0);
}
/* restore curwin/curbuf and a few other things */
aucmd_restbuf(&aco);
/* Careful: autocommands may have made "buf" invalid! */
}
void
buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
{
buf->b_mtime = (long)st->st_mtime;
buf->b_orig_size = st->st_size;
#ifdef HAVE_ST_MODE
buf->b_orig_mode = (int)st->st_mode;
#else
buf->b_orig_mode = mch_getperm(fname);
#endif
}
/*
* Adjust the line with missing eol, used for the next write.
* Used for do_filter(), when the input lines for the filter are deleted.
*/
void
write_lnum_adjust(linenr_T offset)
{
if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
curbuf->b_no_eol_lnum += offset;
}
#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
/*
* Delete "name" and everything in it, recursively.
* return 0 for succes, -1 if some file was not deleted.
*/
int
delete_recursive(char_u *name)
{
int result = 0;
char_u **files;
int file_count;
int i;
char_u *exp;
/* A symbolic link to a directory itself is deleted, not the directory it
* points to. */
if (
# if defined(UNIX) || defined(WIN32)
mch_isrealdir(name)
# else
mch_isdir(name)
# endif
)
{
vim_snprintf((char *)NameBuff, MAXPATHL, "%s/*", name);
exp = vim_strsave(NameBuff);
if (exp == NULL)
return -1;
if (gen_expand_wildcards(1, &exp, &file_count, &files,
EW_DIR|EW_FILE|EW_SILENT|EW_ALLLINKS|EW_DODOT|EW_EMPTYOK) == OK)
{
for (i = 0; i < file_count; ++i)
if (delete_recursive(files[i]) != 0)
result = -1;
FreeWild(file_count, files);
}
else
result = -1;
vim_free(exp);
(void)mch_rmdir(name);
}
else
result = mch_remove(name) == 0 ? 0 : -1;
return result;
}
#endif
#if defined(TEMPDIRNAMES) || defined(PROTO)
static long temp_count = 0; /* Temp filename counter. */
/*
* Delete the temp directory and all files it contains.
*/
void
vim_deltempdir(void)
{
if (vim_tempdir != NULL)
{
/* remove the trailing path separator */
gettail(vim_tempdir)[-1] = NUL;
delete_recursive(vim_tempdir);
vim_free(vim_tempdir);
vim_tempdir = NULL;
}
}
/*
* Directory "tempdir" was created. Expand this name to a full path and put
* it in "vim_tempdir". This avoids that using ":cd" would confuse us.
* "tempdir" must be no longer than MAXPATHL.
*/
static void
vim_settempdir(char_u *tempdir)
{
char_u *buf;
buf = alloc((unsigned)MAXPATHL + 2);
if (buf != NULL)
{
if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
STRCPY(buf, tempdir);
add_pathsep(buf);
vim_tempdir = vim_strsave(buf);
vim_free(buf);
}
}
#endif
/*
* vim_tempname(): Return a unique name that can be used for a temp file.
*
* The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
* guaranteed to NOT be created.
*
* The returned pointer is to allocated memory.
* The returned pointer is NULL if no valid name was found.
*/
char_u *
vim_tempname(
int extra_char UNUSED, /* char to use in the name instead of '?' */
int keep UNUSED)
{
#ifdef USE_TMPNAM
char_u itmp[L_tmpnam]; /* use tmpnam() */
#else
char_u itmp[TEMPNAMELEN];
#endif
#ifdef TEMPDIRNAMES
static char *(tempdirs[]) = {TEMPDIRNAMES};
int i;
# ifndef EEXIST
stat_T st;
# endif
/*
* This will create a directory for private use by this instance of Vim.
* This is done once, and the same directory is used for all temp files.
* This method avoids security problems because of symlink attacks et al.
* It's also a bit faster, because we only need to check for an existing
* file when creating the directory and not for each temp file.
*/
if (vim_tempdir == NULL)
{
/*
* Try the entries in TEMPDIRNAMES to create the temp directory.
*/
for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
{
# ifndef HAVE_MKDTEMP
size_t itmplen;
long nr;
long off;
# endif
/* Expand $TMP, leave room for "/v1100000/999999999".
* Skip the directory check if the expansion fails. */
expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
if (itmp[0] != '$' && mch_isdir(itmp))
{
/* directory exists */
add_pathsep(itmp);
# ifdef HAVE_MKDTEMP
{
# if defined(UNIX) || defined(VMS)
/* Make sure the umask doesn't remove the executable bit.
* "repl" has been reported to use "177". */
mode_t umask_save = umask(077);
# endif
/* Leave room for filename */
STRCAT(itmp, "vXXXXXX");
if (mkdtemp((char *)itmp) != NULL)
vim_settempdir(itmp);
# if defined(UNIX) || defined(VMS)
(void)umask(umask_save);
# endif
}
# else
/* Get an arbitrary number of up to 6 digits. When it's
* unlikely that it already exists it will be faster,
* otherwise it doesn't matter. The use of mkdir() avoids any
* security problems because of the predictable number. */
nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
itmplen = STRLEN(itmp);
/* Try up to 10000 different values until we find a name that
* doesn't exist. */
for (off = 0; off < 10000L; ++off)
{
int r;
# if defined(UNIX) || defined(VMS)
mode_t umask_save;
# endif
sprintf((char *)itmp + itmplen, "v%ld", nr + off);
# ifndef EEXIST
/* If mkdir() does not set errno to EEXIST, check for
* existing file here. There is a race condition then,
* although it's fail-safe. */
if (mch_stat((char *)itmp, &st) >= 0)
continue;
# endif
# if defined(UNIX) || defined(VMS)
/* Make sure the umask doesn't remove the executable bit.
* "repl" has been reported to use "177". */
umask_save = umask(077);
# endif
r = vim_mkdir(itmp, 0700);
# if defined(UNIX) || defined(VMS)
(void)umask(umask_save);
# endif
if (r == 0)
{
vim_settempdir(itmp);
break;
}
# ifdef EEXIST
/* If the mkdir() didn't fail because the file/dir exists,
* we probably can't create any dir here, try another
* place. */
if (errno != EEXIST)
# endif
break;
}
# endif /* HAVE_MKDTEMP */
if (vim_tempdir != NULL)
break;
}
}
}
if (vim_tempdir != NULL)
{
/* There is no need to check if the file exists, because we own the
* directory and nobody else creates a file in it. */
sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
return vim_strsave(itmp);
}
return NULL;
#else /* TEMPDIRNAMES */
# ifdef WIN3264
char szTempFile[_MAX_PATH + 1];
char buf4[4];
char_u *retval;
char_u *p;
STRCPY(itmp, "");
if (GetTempPath(_MAX_PATH, szTempFile) == 0)
{
szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
szTempFile[1] = NUL;
}
strcpy(buf4, "VIM");
buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
if (GetTempFileName(szTempFile, buf4, 0, (LPSTR)itmp) == 0)
return NULL;
if (!keep)
/* GetTempFileName() will create the file, we don't want that */
(void)DeleteFile((LPSTR)itmp);
/* Backslashes in a temp file name cause problems when filtering with
* "sh". NOTE: This also checks 'shellcmdflag' to help those people who
* didn't set 'shellslash'. */
retval = vim_strsave(itmp);
if (*p_shcf == '-' || p_ssl)
for (p = retval; *p; ++p)
if (*p == '\\')
*p = '/';
return retval;
# else /* WIN3264 */
# ifdef USE_TMPNAM
char_u *p;
/* tmpnam() will make its own name */
p = tmpnam((char *)itmp);
if (p == NULL || *p == NUL)
return NULL;
# else
char_u *p;
# ifdef VMS_TEMPNAM
/* mktemp() is not working on VMS. It seems to be
* a do-nothing function. Therefore we use tempnam().
*/
sprintf((char *)itmp, "VIM%c", extra_char);
p = (char_u *)tempnam("tmp:", (char *)itmp);
if (p != NULL)
{
/* VMS will use '.LIS' if we don't explicitly specify an extension,
* and VIM will then be unable to find the file later */
STRCPY(itmp, p);
STRCAT(itmp, ".txt");
free(p);
}
else
return NULL;
# else
STRCPY(itmp, TEMPNAME);
if ((p = vim_strchr(itmp, '?')) != NULL)
*p = extra_char;
if (mktemp((char *)itmp) == NULL)
return NULL;
# endif
# endif
return vim_strsave(itmp);
# endif /* WIN3264 */
#endif /* TEMPDIRNAMES */
}
#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
/*
* Convert all backslashes in fname to forward slashes in-place, unless when
* it looks like a URL.
*/
void
forward_slash(char_u *fname)
{
char_u *p;
if (path_with_url(fname))
return;
for (p = fname; *p != NUL; ++p)
# ifdef FEAT_MBYTE
/* The Big5 encoding can have '\' in the trail byte. */
if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
++p;
else
# endif
if (*p == '\\')
*p = '/';
}
#endif
/*
* Code for automatic commands.
*
* Only included when "FEAT_AUTOCMD" has been defined.
*/
#if defined(FEAT_AUTOCMD) || defined(PROTO)
/*
* The autocommands are stored in a list for each event.
* Autocommands for the same pattern, that are consecutive, are joined
* together, to avoid having to match the pattern too often.
* The result is an array of Autopat lists, which point to AutoCmd lists:
*
* first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
* Autopat.cmds Autopat.cmds
* | |
* V V
* AutoCmd.next AutoCmd.next
* | |
* V V
* AutoCmd.next NULL
* |
* V
* NULL
*
* first_autopat[1] --> Autopat.next --> NULL
* Autopat.cmds
* |
* V
* AutoCmd.next
* |
* V
* NULL
* etc.
*
* The order of AutoCmds is important, this is the order in which they were
* defined and will have to be executed.
*/
typedef struct AutoCmd
{
char_u *cmd; /* The command to be executed (NULL
when command has been removed) */
char nested; /* If autocommands nest here */
char last; /* last command in list */
#ifdef FEAT_EVAL
scid_T scriptID; /* script ID where defined */
#endif
struct AutoCmd *next; /* Next AutoCmd in list */
} AutoCmd;
typedef struct AutoPat
{
char_u *pat; /* pattern as typed (NULL when pattern
has been removed) */
regprog_T *reg_prog; /* compiled regprog for pattern */
AutoCmd *cmds; /* list of commands to do */
struct AutoPat *next; /* next AutoPat in AutoPat list */
int group; /* group ID */
int patlen; /* strlen() of pat */
int buflocal_nr; /* !=0 for buffer-local AutoPat */
char allow_dirs; /* Pattern may match whole path */
char last; /* last pattern for apply_autocmds() */
} AutoPat;
static struct event_name
{
char *name; /* event name */
event_T event; /* event number */
} event_names[] =
{
{"BufAdd", EVENT_BUFADD},
{"BufCreate", EVENT_BUFADD},
{"BufDelete", EVENT_BUFDELETE},
{"BufEnter", EVENT_BUFENTER},
{"BufFilePost", EVENT_BUFFILEPOST},
{"BufFilePre", EVENT_BUFFILEPRE},
{"BufHidden", EVENT_BUFHIDDEN},
{"BufLeave", EVENT_BUFLEAVE},
{"BufNew", EVENT_BUFNEW},
{"BufNewFile", EVENT_BUFNEWFILE},
{"BufRead", EVENT_BUFREADPOST},
{"BufReadCmd", EVENT_BUFREADCMD},
{"BufReadPost", EVENT_BUFREADPOST},
{"BufReadPre", EVENT_BUFREADPRE},
{"BufUnload", EVENT_BUFUNLOAD},
{"BufWinEnter", EVENT_BUFWINENTER},
{"BufWinLeave", EVENT_BUFWINLEAVE},
{"BufWipeout", EVENT_BUFWIPEOUT},
{"BufWrite", EVENT_BUFWRITEPRE},
{"BufWritePost", EVENT_BUFWRITEPOST},
{"BufWritePre", EVENT_BUFWRITEPRE},
{"BufWriteCmd", EVENT_BUFWRITECMD},
{"CmdwinEnter", EVENT_CMDWINENTER},
{"CmdwinLeave", EVENT_CMDWINLEAVE},
{"CmdUndefined", EVENT_CMDUNDEFINED},
{"ColorScheme", EVENT_COLORSCHEME},
{"CompleteDone", EVENT_COMPLETEDONE},
{"CursorHold", EVENT_CURSORHOLD},
{"CursorHoldI", EVENT_CURSORHOLDI},
{"CursorMoved", EVENT_CURSORMOVED},
{"CursorMovedI", EVENT_CURSORMOVEDI},
{"EncodingChanged", EVENT_ENCODINGCHANGED},
{"FileEncoding", EVENT_ENCODINGCHANGED},
{"FileAppendPost", EVENT_FILEAPPENDPOST},
{"FileAppendPre", EVENT_FILEAPPENDPRE},
{"FileAppendCmd", EVENT_FILEAPPENDCMD},
{"FileChangedShell",EVENT_FILECHANGEDSHELL},
{"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
{"FileChangedRO", EVENT_FILECHANGEDRO},
{"FileReadPost", EVENT_FILEREADPOST},
{"FileReadPre", EVENT_FILEREADPRE},
{"FileReadCmd", EVENT_FILEREADCMD},
{"FileType", EVENT_FILETYPE},
{"FileWritePost", EVENT_FILEWRITEPOST},
{"FileWritePre", EVENT_FILEWRITEPRE},
{"FileWriteCmd", EVENT_FILEWRITECMD},
{"FilterReadPost", EVENT_FILTERREADPOST},
{"FilterReadPre", EVENT_FILTERREADPRE},
{"FilterWritePost", EVENT_FILTERWRITEPOST},
{"FilterWritePre", EVENT_FILTERWRITEPRE},
{"FocusGained", EVENT_FOCUSGAINED},
{"FocusLost", EVENT_FOCUSLOST},
{"FuncUndefined", EVENT_FUNCUNDEFINED},
{"GUIEnter", EVENT_GUIENTER},
{"GUIFailed", EVENT_GUIFAILED},
{"InsertChange", EVENT_INSERTCHANGE},
{"InsertEnter", EVENT_INSERTENTER},
{"InsertLeave", EVENT_INSERTLEAVE},
{"InsertCharPre", EVENT_INSERTCHARPRE},
{"MenuPopup", EVENT_MENUPOPUP},
{"OptionSet", EVENT_OPTIONSET},
{"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
{"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
{"QuitPre", EVENT_QUITPRE},
{"RemoteReply", EVENT_REMOTEREPLY},
{"SessionLoadPost", EVENT_SESSIONLOADPOST},
{"ShellCmdPost", EVENT_SHELLCMDPOST},
{"ShellFilterPost", EVENT_SHELLFILTERPOST},
{"SourcePre", EVENT_SOURCEPRE},
{"SourceCmd", EVENT_SOURCECMD},
{"SpellFileMissing",EVENT_SPELLFILEMISSING},
{"StdinReadPost", EVENT_STDINREADPOST},
{"StdinReadPre", EVENT_STDINREADPRE},
{"SwapExists", EVENT_SWAPEXISTS},
{"Syntax", EVENT_SYNTAX},
{"TabNew", EVENT_TABNEW},
{"TabClosed", EVENT_TABCLOSED},
{"TabEnter", EVENT_TABENTER},
{"TabLeave", EVENT_TABLEAVE},
{"TermChanged", EVENT_TERMCHANGED},
{"TermResponse", EVENT_TERMRESPONSE},
{"TextChanged", EVENT_TEXTCHANGED},
{"TextChangedI", EVENT_TEXTCHANGEDI},
{"User", EVENT_USER},
{"VimEnter", EVENT_VIMENTER},
{"VimLeave", EVENT_VIMLEAVE},
{"VimLeavePre", EVENT_VIMLEAVEPRE},
{"WinNew", EVENT_WINNEW},
{"WinEnter", EVENT_WINENTER},
{"WinLeave", EVENT_WINLEAVE},
{"VimResized", EVENT_VIMRESIZED},
{NULL, (event_T)0}
};
static AutoPat *first_autopat[NUM_EVENTS] =
{
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};
/*
* struct used to keep status while executing autocommands for an event.
*/
typedef struct AutoPatCmd
{
AutoPat *curpat; /* next AutoPat to examine */
AutoCmd *nextcmd; /* next AutoCmd to execute */
int group; /* group being used */
char_u *fname; /* fname to match with */
char_u *sfname; /* sfname to match with */
char_u *tail; /* tail of fname */
event_T event; /* current event */
int arg_bufnr; /* initially equal to <abuf>, set to zero when
buf is deleted */
struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
} AutoPatCmd;
static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
/*
* augroups stores a list of autocmd group names.
*/
static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
/* use get_deleted_augroup() to get this */
static char_u *deleted_augroup = NULL;
/*
* The ID of the current group. Group 0 is the default one.
*/
static int current_augroup = AUGROUP_DEFAULT;
static int au_need_clean = FALSE; /* need to delete marked patterns */
static void show_autocmd(AutoPat *ap, event_T event);
static void au_remove_pat(AutoPat *ap);
static void au_remove_cmds(AutoPat *ap);
static void au_cleanup(void);
static int au_new_group(char_u *name);
static void au_del_group(char_u *name);
static event_T event_name2nr(char_u *start, char_u **end);
static char_u *event_nr2name(event_T event);
static char_u *find_end_event(char_u *arg, int have_group);
static int event_ignored(event_T event);
static int au_get_grouparg(char_u **argp);
static int do_autocmd_event(event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group);
static int apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap);
static void auto_next_pat(AutoPatCmd *apc, int stop_at_last);
#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN)
static int match_file_pat(char_u *pattern, regprog_T **prog, char_u *fname, char_u *sfname, char_u *tail, int allow_dirs);
#endif
static event_T last_event;
static int last_group;
static int autocmd_blocked = 0; /* block all autocmds */
static char_u *
get_deleted_augroup(void)
{
if (deleted_augroup == NULL)
deleted_augroup = (char_u *)_("--Deleted--");
return deleted_augroup;
}
/*
* Show the autocommands for one AutoPat.
*/
static void
show_autocmd(AutoPat *ap, event_T event)
{
AutoCmd *ac;
/* Check for "got_int" (here and at various places below), which is set
* when "q" has been hit for the "--more--" prompt */
if (got_int)
return;
if (ap->pat == NULL) /* pattern has been removed */
return;
msg_putchar('\n');
if (got_int)
return;
if (event != last_event || ap->group != last_group)
{
if (ap->group != AUGROUP_DEFAULT)
{
if (AUGROUP_NAME(ap->group) == NULL)
msg_puts_attr(get_deleted_augroup(), hl_attr(HLF_E));
else
msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
msg_puts((char_u *)" ");
}
msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
last_event = event;
last_group = ap->group;
msg_putchar('\n');
if (got_int)
return;
}
msg_col = 4;
msg_outtrans(ap->pat);
for (ac = ap->cmds; ac != NULL; ac = ac->next)
{
if (ac->cmd != NULL) /* skip removed commands */
{
if (msg_col >= 14)
msg_putchar('\n');
msg_col = 14;
if (got_int)
return;
msg_outtrans(ac->cmd);
#ifdef FEAT_EVAL
if (p_verbose > 0)
last_set_msg(ac->scriptID);
#endif
if (got_int)
return;
if (ac->next != NULL)
{
msg_putchar('\n');
if (got_int)
return;
}
}
}
}
/*
* Mark an autocommand pattern for deletion.
*/
static void
au_remove_pat(AutoPat *ap)
{
vim_free(ap->pat);
ap->pat = NULL;
ap->buflocal_nr = -1;
au_need_clean = TRUE;
}
/*
* Mark all commands for a pattern for deletion.
*/
static void
au_remove_cmds(AutoPat *ap)
{
AutoCmd *ac;
for (ac = ap->cmds; ac != NULL; ac = ac->next)
{
vim_free(ac->cmd);
ac->cmd = NULL;
}
au_need_clean = TRUE;
}
/*
* Cleanup autocommands and patterns that have been deleted.
* This is only done when not executing autocommands.
*/
static void
au_cleanup(void)
{
AutoPat *ap, **prev_ap;
AutoCmd *ac, **prev_ac;
event_T event;
if (autocmd_busy || !au_need_clean)
return;
/* loop over all events */
for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
event = (event_T)((int)event + 1))
{
/* loop over all autocommand patterns */
prev_ap = &(first_autopat[(int)event]);
for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
{
/* loop over all commands for this pattern */
prev_ac = &(ap->cmds);
for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
{
/* remove the command if the pattern is to be deleted or when
* the command has been marked for deletion */
if (ap->pat == NULL || ac->cmd == NULL)
{
*prev_ac = ac->next;
vim_free(ac->cmd);
vim_free(ac);
}
else
prev_ac = &(ac->next);
}
/* remove the pattern if it has been marked for deletion */
if (ap->pat == NULL)
{
*prev_ap = ap->next;
vim_regfree(ap->reg_prog);
vim_free(ap);
}
else
prev_ap = &(ap->next);
}
}
au_need_clean = FALSE;
}
/*
* Called when buffer is freed, to remove/invalidate related buffer-local
* autocmds.
*/
void
aubuflocal_remove(buf_T *buf)
{
AutoPat *ap;
event_T event;
AutoPatCmd *apc;
/* invalidate currently executing autocommands */
for (apc = active_apc_list; apc; apc = apc->next)
if (buf->b_fnum == apc->arg_bufnr)
apc->arg_bufnr = 0;
/* invalidate buflocals looping through events */
for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
event = (event_T)((int)event + 1))
/* loop over all autocommand patterns */
for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
if (ap->buflocal_nr == buf->b_fnum)
{
au_remove_pat(ap);
if (p_verbose >= 6)
{
verbose_enter();
smsg((char_u *)
_("auto-removing autocommand: %s <buffer=%d>"),
event_nr2name(event), buf->b_fnum);
verbose_leave();
}
}
au_cleanup();
}
/*
* Add an autocmd group name.
* Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
*/
static int
au_new_group(char_u *name)
{
int i;
i = au_find_group(name);
if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
{
/* First try using a free entry. */
for (i = 0; i < augroups.ga_len; ++i)
if (AUGROUP_NAME(i) == NULL)
break;
if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
return AUGROUP_ERROR;
AUGROUP_NAME(i) = vim_strsave(name);
if (AUGROUP_NAME(i) == NULL)
return AUGROUP_ERROR;
if (i == augroups.ga_len)
++augroups.ga_len;
}
return i;
}
static void
au_del_group(char_u *name)
{
int i;
i = au_find_group(name);
if (i == AUGROUP_ERROR) /* the group doesn't exist */
EMSG2(_("E367: No such group: \"%s\""), name);
else if (i == current_augroup)
EMSG(_("E936: Cannot delete the current group"));
else
{
event_T event;
AutoPat *ap;
int in_use = FALSE;
for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
event = (event_T)((int)event + 1))
{
for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
if (ap->group == i && ap->pat != NULL)
{
give_warning((char_u *)_("W19: Deleting augroup that is still in use"), TRUE);
in_use = TRUE;
event = NUM_EVENTS;
break;
}
}
vim_free(AUGROUP_NAME(i));
if (in_use)
{
AUGROUP_NAME(i) = get_deleted_augroup();
}
else
AUGROUP_NAME(i) = NULL;
}
}
/*
* Find the ID of an autocmd group name.
* Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
*/
static int
au_find_group(char_u *name)
{
int i;
for (i = 0; i < augroups.ga_len; ++i)
if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
&& STRCMP(AUGROUP_NAME(i), name) == 0)
return i;
return AUGROUP_ERROR;
}
/*
* Return TRUE if augroup "name" exists.
*/
int
au_has_group(char_u *name)
{
return au_find_group(name) != AUGROUP_ERROR;
}
/*
* ":augroup {name}".
*/
void
do_augroup(char_u *arg, int del_group)
{
int i;
if (del_group)
{
if (*arg == NUL)
EMSG(_(e_argreq));
else
au_del_group(arg);
}
else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
current_augroup = AUGROUP_DEFAULT;
else if (*arg) /* ":aug xxx": switch to group xxx */
{
i = au_new_group(arg);
if (i != AUGROUP_ERROR)
current_augroup = i;
}
else /* ":aug": list the group names */
{
msg_start();
for (i = 0; i < augroups.ga_len; ++i)
{
if (AUGROUP_NAME(i) != NULL)
{
msg_puts(AUGROUP_NAME(i));
msg_puts((char_u *)" ");
}
}
msg_clr_eos();
msg_end();
}
}
#if defined(EXITFREE) || defined(PROTO)
void
free_all_autocmds(void)
{
int i;
char_u *s;
for (current_augroup = -1; current_augroup < augroups.ga_len;
++current_augroup)
do_autocmd((char_u *)"", TRUE);
for (i = 0; i < augroups.ga_len; ++i)
{
s = ((char_u **)(augroups.ga_data))[i];
if (s != get_deleted_augroup())
vim_free(s);
}
ga_clear(&augroups);
}
#endif
/*
* Return the event number for event name "start".
* Return NUM_EVENTS if the event name was not found.
* Return a pointer to the next event name in "end".
*/
static event_T
event_name2nr(char_u *start, char_u **end)
{
char_u *p;
int i;
int len;
/* the event name ends with end of line, '|', a blank or a comma */
for (p = start; *p && !vim_iswhite(*p) && *p != ',' && *p != '|'; ++p)
;
for (i = 0; event_names[i].name != NULL; ++i)
{
len = (int)STRLEN(event_names[i].name);
if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
break;
}
if (*p == ',')
++p;
*end = p;
if (event_names[i].name == NULL)
return NUM_EVENTS;
return event_names[i].event;
}
/*
* Return the name for event "event".
*/
static char_u *
event_nr2name(event_T event)
{
int i;
for (i = 0; event_names[i].name != NULL; ++i)
if (event_names[i].event == event)
return (char_u *)event_names[i].name;
return (char_u *)"Unknown";
}
/*
* Scan over the events. "*" stands for all events.
*/
static char_u *
find_end_event(
char_u *arg,
int have_group) /* TRUE when group name was found */
{
char_u *pat;
char_u *p;
if (*arg == '*')
{
if (arg[1] && !vim_iswhite(arg[1]))
{
EMSG2(_("E215: Illegal character after *: %s"), arg);
return NULL;
}
pat = arg + 1;
}
else
{
for (pat = arg; *pat && *pat != '|' && !vim_iswhite(*pat); pat = p)
{
if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
{
if (have_group)
EMSG2(_("E216: No such event: %s"), pat);
else
EMSG2(_("E216: No such group or event: %s"), pat);
return NULL;
}
}
}
return pat;
}
/*
* Return TRUE if "event" is included in 'eventignore'.
*/
static int
event_ignored(event_T event)
{
char_u *p = p_ei;
while (*p != NUL)
{
if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
return TRUE;
if (event_name2nr(p, &p) == event)
return TRUE;
}
return FALSE;
}
/*
* Return OK when the contents of p_ei is valid, FAIL otherwise.
*/
int
check_ei(void)
{
char_u *p = p_ei;
while (*p)
{
if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
{
p += 3;
if (*p == ',')
++p;
}
else if (event_name2nr(p, &p) == NUM_EVENTS)
return FAIL;
}
return OK;
}
# if defined(FEAT_SYN_HL) || defined(PROTO)
/*
* Add "what" to 'eventignore' to skip loading syntax highlighting for every
* buffer loaded into the window. "what" must start with a comma.
* Returns the old value of 'eventignore' in allocated memory.
*/
char_u *
au_event_disable(char *what)
{
char_u *new_ei;
char_u *save_ei;
save_ei = vim_strsave(p_ei);
if (save_ei != NULL)
{
new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
if (new_ei != NULL)
{
if (*what == ',' && *p_ei == NUL)
STRCPY(new_ei, what + 1);
else
STRCAT(new_ei, what);
set_string_option_direct((char_u *)"ei", -1, new_ei,
OPT_FREE, SID_NONE);
vim_free(new_ei);
}
}
return save_ei;
}
void
au_event_restore(char_u *old_ei)
{
if (old_ei != NULL)
{
set_string_option_direct((char_u *)"ei", -1, old_ei,
OPT_FREE, SID_NONE);
vim_free(old_ei);
}
}
# endif /* FEAT_SYN_HL */
/*
* do_autocmd() -- implements the :autocmd command. Can be used in the
* following ways:
*
* :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
* will be automatically executed for <event>
* when editing a file matching <pat>, in
* the current group.
* :autocmd <event> <pat> Show the auto-commands associated with
* <event> and <pat>.
* :autocmd <event> Show the auto-commands associated with
* <event>.
* :autocmd Show all auto-commands.
* :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
* <event> and <pat>, and add the command
* <cmd>, for the current group.
* :autocmd! <event> <pat> Remove all auto-commands associated with
* <event> and <pat> for the current group.
* :autocmd! <event> Remove all auto-commands associated with
* <event> for the current group.
* :autocmd! Remove ALL auto-commands for the current
* group.
*
* Multiple events and patterns may be given separated by commas. Here are
* some examples:
* :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
* :autocmd bufleave * set tw=79 nosmartindent ic infercase
*
* :autocmd * *.c show all autocommands for *.c files.
*
* Mostly a {group} argument can optionally appear before <event>.
*/
void
do_autocmd(char_u *arg_in, int forceit)
{
char_u *arg = arg_in;
char_u *pat;
char_u *envpat = NULL;
char_u *cmd;
event_T event;
int need_free = FALSE;
int nested = FALSE;
int group;
if (*arg == '|')
{
arg = (char_u *)"";
group = AUGROUP_ALL; /* no argument, use all groups */
}
else
{
/*
* Check for a legal group name. If not, use AUGROUP_ALL.
*/
group = au_get_grouparg(&arg);
if (arg == NULL) /* out of memory */
return;
}
/*
* Scan over the events.
* If we find an illegal name, return here, don't do anything.
*/
pat = find_end_event(arg, group != AUGROUP_ALL);
if (pat == NULL)
return;
pat = skipwhite(pat);
if (*pat == '|')
{
pat = (char_u *)"";
cmd = (char_u *)"";
}
else
{
/*
* Scan over the pattern. Put a NUL at the end.
*/
cmd = pat;
while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
cmd++;
if (*cmd)
*cmd++ = NUL;
/* Expand environment variables in the pattern. Set 'shellslash', we want
* forward slashes here. */
if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
{
#ifdef BACKSLASH_IN_FILENAME
int p_ssl_save = p_ssl;
p_ssl = TRUE;
#endif
envpat = expand_env_save(pat);
#ifdef BACKSLASH_IN_FILENAME
p_ssl = p_ssl_save;
#endif
if (envpat != NULL)
pat = envpat;
}
/*
* Check for "nested" flag.
*/
cmd = skipwhite(cmd);
if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
{
nested = TRUE;
cmd = skipwhite(cmd + 6);
}
/*
* Find the start of the commands.
* Expand <sfile> in it.
*/
if (*cmd != NUL)
{
cmd = expand_sfile(cmd);
if (cmd == NULL) /* some error */
return;
need_free = TRUE;
}
}
/*
* Print header when showing autocommands.
*/
if (!forceit && *cmd == NUL)
{
/* Highlight title */
MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
}
/*
* Loop over the events.
*/
last_event = (event_T)-1; /* for listing the event name */
last_group = AUGROUP_ERROR; /* for listing the group name */
if (*arg == '*' || *arg == NUL || *arg == '|')
{
for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
event = (event_T)((int)event + 1))
if (do_autocmd_event(event, pat,
nested, cmd, forceit, group) == FAIL)
break;
}
else
{
while (*arg && *arg != '|' && !vim_iswhite(*arg))
if (do_autocmd_event(event_name2nr(arg, &arg), pat,
nested, cmd, forceit, group) == FAIL)
break;
}
if (need_free)
vim_free(cmd);
vim_free(envpat);
}
/*
* Find the group ID in a ":autocmd" or ":doautocmd" argument.
* The "argp" argument is advanced to the following argument.
*
* Returns the group ID, AUGROUP_ERROR for error (out of memory).
*/
static int
au_get_grouparg(char_u **argp)
{
char_u *group_name;
char_u *p;
char_u *arg = *argp;
int group = AUGROUP_ALL;
for (p = arg; *p && !vim_iswhite(*p) && *p != '|'; ++p)
;
if (p > arg)
{
group_name = vim_strnsave(arg, (int)(p - arg));
if (group_name == NULL) /* out of memory */
return AUGROUP_ERROR;
group = au_find_group(group_name);
if (group == AUGROUP_ERROR)
group = AUGROUP_ALL; /* no match, use all groups */
else
*argp = skipwhite(p); /* match, skip over group name */
vim_free(group_name);
}
return group;
}
/*
* do_autocmd() for one event.
* If *pat == NUL do for all patterns.
* If *cmd == NUL show entries.
* If forceit == TRUE delete entries.
* If group is not AUGROUP_ALL, only use this group.
*/
static int
do_autocmd_event(
event_T event,
char_u *pat,
int nested,
char_u *cmd,
int forceit,
int group)
{
AutoPat *ap;
AutoPat **prev_ap;
AutoCmd *ac;
AutoCmd **prev_ac;
int brace_level;
char_u *endpat;
int findgroup;
int allgroups;
int patlen;
int is_buflocal;
int buflocal_nr;
char_u buflocal_pat[25]; /* for "<buffer=X>" */
if (group == AUGROUP_ALL)
findgroup = current_augroup;
else
findgroup = group;
allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
/*
* Show or delete all patterns for an event.
*/
if (*pat == NUL)
{
for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
{
if (forceit) /* delete the AutoPat, if it's in the current group */
{
if (ap->group == findgroup)
au_remove_pat(ap);
}
else if (group == AUGROUP_ALL || ap->group == group)
show_autocmd(ap, event);
}
}
/*
* Loop through all the specified patterns.
*/
for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
{
/*
* Find end of the pattern.
* Watch out for a comma in braces, like "*.\{obj,o\}".
*/
brace_level = 0;
for (endpat = pat; *endpat && (*endpat != ',' || brace_level
|| (endpat > pat && endpat[-1] == '\\')); ++endpat)
{
if (*endpat == '{')
brace_level++;
else if (*endpat == '}')
brace_level--;
}
if (pat == endpat) /* ignore single comma */
continue;
patlen = (int)(endpat - pat);
/*
* detect special <buflocal[=X]> buffer-local patterns
*/
is_buflocal = FALSE;
buflocal_nr = 0;
if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
&& pat[patlen - 1] == '>')
{
/* "<buffer...>": Error will be printed only for addition.
* printing and removing will proceed silently. */
is_buflocal = TRUE;
if (patlen == 8)
/* "<buffer>" */
buflocal_nr = curbuf->b_fnum;
else if (patlen > 9 && pat[7] == '=')
{
if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0)
/* "<buffer=abuf>" */
buflocal_nr = autocmd_bufnr;
else if (skipdigits(pat + 8) == pat + patlen - 1)
/* "<buffer=123>" */
buflocal_nr = atoi((char *)pat + 8);
}
}
if (is_buflocal)
{
/* normalize pat into standard "<buffer>#N" form */
sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
pat = buflocal_pat; /* can modify pat and patlen */
patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
}
/*
* Find AutoPat entries with this pattern.
*/
prev_ap = &first_autopat[(int)event];
while ((ap = *prev_ap) != NULL)
{
if (ap->pat != NULL)
{
/* Accept a pattern when:
* - a group was specified and it's that group, or a group was
* not specified and it's the current group, or a group was
* not specified and we are listing
* - the length of the pattern matches
* - the pattern matches.
* For <buffer[=X]>, this condition works because we normalize
* all buffer-local patterns.
*/
if ((allgroups || ap->group == findgroup)
&& ap->patlen == patlen
&& STRNCMP(pat, ap->pat, patlen) == 0)
{
/*
* Remove existing autocommands.
* If adding any new autocmd's for this AutoPat, don't
* delete the pattern from the autopat list, append to
* this list.
*/
if (forceit)
{
if (*cmd != NUL && ap->next == NULL)
{
au_remove_cmds(ap);
break;
}
au_remove_pat(ap);
}
/*
* Show autocmd's for this autopat, or buflocals <buffer=X>
*/
else if (*cmd == NUL)
show_autocmd(ap, event);
/*
* Add autocmd to this autopat, if it's the last one.
*/
else if (ap->next == NULL)
break;
}
}
prev_ap = &ap->next;
}
/*
* Add a new command.
*/
if (*cmd != NUL)
{
/*
* If the pattern we want to add a command to does appear at the
* end of the list (or not is not in the list at all), add the
* pattern at the end of the list.
*/
if (ap == NULL)
{
/* refuse to add buffer-local ap if buffer number is invalid */
if (is_buflocal && (buflocal_nr == 0
|| buflist_findnr(buflocal_nr) == NULL))
{
EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
buflocal_nr);
return FAIL;
}
ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
if (ap == NULL)
return FAIL;
ap->pat = vim_strnsave(pat, patlen);
ap->patlen = patlen;
if (ap->pat == NULL)
{
vim_free(ap);
return FAIL;
}
if (is_buflocal)
{
ap->buflocal_nr = buflocal_nr;
ap->reg_prog = NULL;
}
else
{
char_u *reg_pat;
ap->buflocal_nr = 0;
reg_pat = file_pat_to_reg_pat(pat, endpat,
&ap->allow_dirs, TRUE);
if (reg_pat != NULL)
ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
vim_free(reg_pat);
if (reg_pat == NULL || ap->reg_prog == NULL)
{
vim_free(ap->pat);
vim_free(ap);
return FAIL;
}
}
ap->cmds = NULL;
*prev_ap = ap;
ap->next = NULL;
if (group == AUGROUP_ALL)
ap->group = current_augroup;
else
ap->group = group;
}
/*
* Add the autocmd at the end of the AutoCmd list.
*/
prev_ac = &(ap->cmds);
while ((ac = *prev_ac) != NULL)
prev_ac = &ac->next;
ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
if (ac == NULL)
return FAIL;
ac->cmd = vim_strsave(cmd);
#ifdef FEAT_EVAL
ac->scriptID = current_SID;
#endif
if (ac->cmd == NULL)
{
vim_free(ac);
return FAIL;
}
ac->next = NULL;
*prev_ac = ac;
ac->nested = nested;
}
}
au_cleanup(); /* may really delete removed patterns/commands now */
return OK;
}
/*
* Implementation of ":doautocmd [group] event [fname]".
* Return OK for success, FAIL for failure;
*/
int
do_doautocmd(
char_u *arg,
int do_msg, /* give message for no matching autocmds? */
int *did_something)
{
char_u *fname;
int nothing_done = TRUE;
int group;
if (did_something != NULL)
*did_something = FALSE;
/*
* Check for a legal group name. If not, use AUGROUP_ALL.
*/
group = au_get_grouparg(&arg);
if (arg == NULL) /* out of memory */
return FAIL;
if (*arg == '*')
{
EMSG(_("E217: Can't execute autocommands for ALL events"));
return FAIL;
}
/*
* Scan over the events.
* If we find an illegal name, return here, don't do anything.
*/
fname = find_end_event(arg, group != AUGROUP_ALL);
if (fname == NULL)
return FAIL;
fname = skipwhite(fname);
/*
* Loop over the events.
*/
while (*arg && !ends_excmd(*arg) && !vim_iswhite(*arg))
if (apply_autocmds_group(event_name2nr(arg, &arg),
fname, NULL, TRUE, group, curbuf, NULL))
nothing_done = FALSE;
if (nothing_done && do_msg)
MSG(_("No matching autocommands"));
if (did_something != NULL)
*did_something = !nothing_done;
#ifdef FEAT_EVAL
return aborting() ? FAIL : OK;
#else
return OK;
#endif
}
/*
* ":doautoall": execute autocommands for each loaded buffer.
*/
void
ex_doautoall(exarg_T *eap)
{
int retval;
aco_save_T aco;
buf_T *buf;
bufref_T bufref;
char_u *arg = eap->arg;
int call_do_modelines = check_nomodeline(&arg);
int did_aucmd;
/*
* This is a bit tricky: For some commands curwin->w_buffer needs to be
* equal to curbuf, but for some buffers there may not be a window.
* So we change the buffer for the current window for a moment. This
* gives problems when the autocommands make changes to the list of
* buffers or windows...
*/
FOR_ALL_BUFFERS(buf)
{
if (buf->b_ml.ml_mfp != NULL)
{
/* find a window for this buffer and save some values */
aucmd_prepbuf(&aco, buf);
set_bufref(&bufref, buf);
/* execute the autocommands for this buffer */
retval = do_doautocmd(arg, FALSE, &did_aucmd);
if (call_do_modelines && did_aucmd)
{
/* Execute the modeline settings, but don't set window-local
* options if we are using the current window for another
* buffer. */
do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
}
/* restore the current window */
aucmd_restbuf(&aco);
/* stop if there is some error or buffer was deleted */
if (retval == FAIL || !bufref_valid(&bufref))
break;
}
}
check_cursor(); /* just in case lines got deleted */
}
/*
* Check *argp for <nomodeline>. When it is present return FALSE, otherwise
* return TRUE and advance *argp to after it.
* Thus return TRUE when do_modelines() should be called.
*/
int
check_nomodeline(char_u **argp)
{
if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
{
*argp = skipwhite(*argp + 12);
return FALSE;
}
return TRUE;
}
/*
* Prepare for executing autocommands for (hidden) buffer "buf".
* Search for a visible window containing the current buffer. If there isn't
* one then use "aucmd_win".
* Set "curbuf" and "curwin" to match "buf".
* When FEAT_AUTOCMD is not defined another version is used, see below.
*/
void
aucmd_prepbuf(
aco_save_T *aco, /* structure to save values in */
buf_T *buf) /* new curbuf */
{
win_T *win;
#ifdef FEAT_WINDOWS
int save_ea;
#endif
#ifdef FEAT_AUTOCHDIR
int save_acd;
#endif
/* Find a window that is for the new buffer */
if (buf == curbuf) /* be quick when buf is curbuf */
win = curwin;
else
#ifdef FEAT_WINDOWS
FOR_ALL_WINDOWS(win)
if (win->w_buffer == buf)
break;
#else
win = NULL;
#endif
/* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
* back to using the current window. */
if (win == NULL && aucmd_win == NULL)
{
win_alloc_aucmd_win();
if (aucmd_win == NULL)
win = curwin;
}
if (win == NULL && aucmd_win_used)
/* Strange recursive autocommand, fall back to using the current
* window. Expect a few side effects... */
win = curwin;
aco->save_curwin = curwin;
aco->save_curbuf = curbuf;
if (win != NULL)
{
/* There is a window for "buf" in the current tab page, make it the
* curwin. This is preferred, it has the least side effects (esp. if
* "buf" is curbuf). */
aco->use_aucmd_win = FALSE;
curwin = win;
}
else
{
/* There is no window for "buf", use "aucmd_win". To minimize the side
* effects, insert it in the current tab page.
* Anything related to a window (e.g., setting folds) may have
* unexpected results. */
aco->use_aucmd_win = TRUE;
aucmd_win_used = TRUE;
aucmd_win->w_buffer = buf;
aucmd_win->w_s = &buf->b_s;
++buf->b_nwindows;
win_init_empty(aucmd_win); /* set cursor and topline to safe values */
/* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
* win_enter_ext(). */
vim_free(aucmd_win->w_localdir);
aucmd_win->w_localdir = NULL;
aco->globaldir = globaldir;
globaldir = NULL;
#ifdef FEAT_WINDOWS
/* Split the current window, put the aucmd_win in the upper half.
* We don't want the BufEnter or WinEnter autocommands. */
block_autocmds();
make_snapshot(SNAP_AUCMD_IDX);
save_ea = p_ea;
p_ea = FALSE;
# ifdef FEAT_AUTOCHDIR
/* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
save_acd = p_acd;
p_acd = FALSE;
# endif
(void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
(void)win_comp_pos(); /* recompute window positions */
p_ea = save_ea;
# ifdef FEAT_AUTOCHDIR
p_acd = save_acd;
# endif
unblock_autocmds();
#endif
curwin = aucmd_win;
}
curbuf = buf;
aco->new_curwin = curwin;
set_bufref(&aco->new_curbuf, curbuf);
}
/*
* Cleanup after executing autocommands for a (hidden) buffer.
* Restore the window as it was (if possible).
* When FEAT_AUTOCMD is not defined another version is used, see below.
*/
void
aucmd_restbuf(
aco_save_T *aco) /* structure holding saved values */
{
#ifdef FEAT_WINDOWS
int dummy;
#endif
if (aco->use_aucmd_win)
{
--curbuf->b_nwindows;
#ifdef FEAT_WINDOWS
/* Find "aucmd_win", it can't be closed, but it may be in another tab
* page. Do not trigger autocommands here. */
block_autocmds();
if (curwin != aucmd_win)
{
tabpage_T *tp;
win_T *wp;
FOR_ALL_TAB_WINDOWS(tp, wp)
{
if (wp == aucmd_win)
{
if (tp != curtab)
goto_tabpage_tp(tp, TRUE, TRUE);
win_goto(aucmd_win);
goto win_found;
}
}
}
win_found:
/* Remove the window and frame from the tree of frames. */
(void)winframe_remove(curwin, &dummy, NULL);
win_remove(curwin, NULL);
aucmd_win_used = FALSE;
last_status(FALSE); /* may need to remove last status line */
restore_snapshot(SNAP_AUCMD_IDX, FALSE);
(void)win_comp_pos(); /* recompute window positions */
unblock_autocmds();
if (win_valid(aco->save_curwin))
curwin = aco->save_curwin;
else
/* Hmm, original window disappeared. Just use the first one. */
curwin = firstwin;
# ifdef FEAT_EVAL
vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
# endif
#else
curwin = aco->save_curwin;
#endif
curbuf = curwin->w_buffer;
vim_free(globaldir);
globaldir = aco->globaldir;
/* the buffer contents may have changed */
check_cursor();
if (curwin->w_topline > curbuf->b_ml.ml_line_count)
{
curwin->w_topline = curbuf->b_ml.ml_line_count;
#ifdef FEAT_DIFF
curwin->w_topfill = 0;
#endif
}
#if defined(FEAT_GUI)
/* Hide the scrollbars from the aucmd_win and update. */
gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
gui_may_update_scrollbars();
#endif
}
else
{
/* restore curwin */
#ifdef FEAT_WINDOWS
if (win_valid(aco->save_curwin))
#endif
{
/* Restore the buffer which was previously edited by curwin, if
* it was changed, we are still the same window and the buffer is
* valid. */
if (curwin == aco->new_curwin
&& curbuf != aco->new_curbuf.br_buf
&& bufref_valid(&aco->new_curbuf)
&& aco->new_curbuf.br_buf->b_ml.ml_mfp != NULL)
{
# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
if (curwin->w_s == &curbuf->b_s)
curwin->w_s = &aco->new_curbuf.br_buf->b_s;
# endif
--curbuf->b_nwindows;
curbuf = aco->new_curbuf.br_buf;
curwin->w_buffer = curbuf;
++curbuf->b_nwindows;
}
curwin = aco->save_curwin;
curbuf = curwin->w_buffer;
/* In case the autocommand move the cursor to a position that that
* not exist in curbuf. */
check_cursor();
}
}
}
static int autocmd_nested = FALSE;
/*
* Execute autocommands for "event" and file name "fname".
* Return TRUE if some commands were executed.
*/
int
apply_autocmds(
event_T event,
char_u *fname, /* NULL or empty means use actual file name */
char_u *fname_io, /* fname to use for <afile> on cmdline */
int force, /* when TRUE, ignore autocmd_busy */
buf_T *buf) /* buffer for <abuf> */
{
return apply_autocmds_group(event, fname, fname_io, force,
AUGROUP_ALL, buf, NULL);
}
/*
* Like apply_autocmds(), but with extra "eap" argument. This takes care of
* setting v:filearg.
*/
static int
apply_autocmds_exarg(
event_T event,
char_u *fname,
char_u *fname_io,
int force,
buf_T *buf,
exarg_T *eap)
{
return apply_autocmds_group(event, fname, fname_io, force,
AUGROUP_ALL, buf, eap);
}
/*
* Like apply_autocmds(), but handles the caller's retval. If the script
* processing is being aborted or if retval is FAIL when inside a try
* conditional, no autocommands are executed. If otherwise the autocommands
* cause the script to be aborted, retval is set to FAIL.
*/
int
apply_autocmds_retval(
event_T event,
char_u *fname, /* NULL or empty means use actual file name */
char_u *fname_io, /* fname to use for <afile> on cmdline */
int force, /* when TRUE, ignore autocmd_busy */
buf_T *buf, /* buffer for <abuf> */
int *retval) /* pointer to caller's retval */
{
int did_cmd;
#ifdef FEAT_EVAL
if (should_abort(*retval))
return FALSE;
#endif
did_cmd = apply_autocmds_group(event, fname, fname_io, force,
AUGROUP_ALL, buf, NULL);
if (did_cmd
#ifdef FEAT_EVAL
&& aborting()
#endif
)
*retval = FAIL;
return did_cmd;
}
/*
* Return TRUE when there is a CursorHold autocommand defined.
*/
int
has_cursorhold(void)
{
return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
}
/*
* Return TRUE if the CursorHold event can be triggered.
*/
int
trigger_cursorhold(void)
{
int state;
if (!did_cursorhold
&& has_cursorhold()
&& !Recording
&& typebuf.tb_len == 0
#ifdef FEAT_INS_EXPAND
&& !ins_compl_active()
#endif
)
{
state = get_real_state();
if (state == NORMAL_BUSY || (state & INSERT) != 0)
return TRUE;
}
return FALSE;
}
/*
* Return TRUE when there is a CursorMoved autocommand defined.
*/
int
has_cursormoved(void)
{
return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
}
/*
* Return TRUE when there is a CursorMovedI autocommand defined.
*/
int
has_cursormovedI(void)
{
return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
}
/*
* Return TRUE when there is a TextChanged autocommand defined.
*/
int
has_textchanged(void)
{
return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
}
/*
* Return TRUE when there is a TextChangedI autocommand defined.
*/
int
has_textchangedI(void)
{
return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
}
/*
* Return TRUE when there is an InsertCharPre autocommand defined.
*/
int
has_insertcharpre(void)
{
return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
}
/*
* Return TRUE when there is an CmdUndefined autocommand defined.
*/
int
has_cmdundefined(void)
{
return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
}
/*
* Return TRUE when there is an FuncUndefined autocommand defined.
*/
int
has_funcundefined(void)
{
return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
}
/*
* Execute autocommands for "event" and file name "fname".
* Return TRUE if some commands were executed.
*/
static int
apply_autocmds_group(
event_T event,
char_u *fname, /* NULL or empty means use actual file name */
char_u *fname_io, /* fname to use for <afile> on cmdline, NULL means
use fname */
int force, /* when TRUE, ignore autocmd_busy */
int group, /* group ID, or AUGROUP_ALL */
buf_T *buf, /* buffer for <abuf> */
exarg_T *eap) /* command arguments */
{
char_u *sfname = NULL; /* short file name */
char_u *tail;
int save_changed;
buf_T *old_curbuf;
int retval = FALSE;
char_u *save_sourcing_name;
linenr_T save_sourcing_lnum;
char_u *save_autocmd_fname;
int save_autocmd_fname_full;
int save_autocmd_bufnr;
char_u *save_autocmd_match;
int save_autocmd_busy;
int save_autocmd_nested;
static int nesting = 0;
AutoPatCmd patcmd;
AutoPat *ap;
#ifdef FEAT_EVAL
scid_T save_current_SID;
void *save_funccalp;
char_u *save_cmdarg;
long save_cmdbang;
#endif
static int filechangeshell_busy = FALSE;
#ifdef FEAT_PROFILE
proftime_T wait_time;
#endif
int did_save_redobuff = FALSE;
/*
* Quickly return if there are no autocommands for this event or
* autocommands are blocked.
*/
if (event == NUM_EVENTS || first_autopat[(int)event] == NULL
|| autocmd_blocked > 0)
goto BYPASS_AU;
/*
* When autocommands are busy, new autocommands are only executed when
* explicitly enabled with the "nested" flag.
*/
if (autocmd_busy && !(force || autocmd_nested))
goto BYPASS_AU;
#ifdef FEAT_EVAL
/*
* Quickly return when immediately aborting on error, or when an interrupt
* occurred or an exception was thrown but not caught.
*/
if (aborting())
goto BYPASS_AU;
#endif
/*
* FileChangedShell never nests, because it can create an endless loop.
*/
if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
|| event == EVENT_FILECHANGEDSHELLPOST))
goto BYPASS_AU;
/*
* Ignore events in 'eventignore'.
*/
if (event_ignored(event))
goto BYPASS_AU;
/*
* Allow nesting of autocommands, but restrict the depth, because it's
* possible to create an endless loop.
*/
if (nesting == 10)
{
EMSG(_("E218: autocommand nesting too deep"));
goto BYPASS_AU;
}
/*
* Check if these autocommands are disabled. Used when doing ":all" or
* ":ball".
*/
if ( (autocmd_no_enter
&& (event == EVENT_WINENTER || event == EVENT_BUFENTER))
|| (autocmd_no_leave
&& (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
goto BYPASS_AU;
/*
* Save the autocmd_* variables and info about the current buffer.
*/
save_autocmd_fname = autocmd_fname;
save_autocmd_fname_full = autocmd_fname_full;
save_autocmd_bufnr = autocmd_bufnr;
save_autocmd_match = autocmd_match;
save_autocmd_busy = autocmd_busy;
save_autocmd_nested = autocmd_nested;
save_changed = curbuf->b_changed;
old_curbuf = curbuf;
/*
* Set the file name to be used for <afile>.
* Make a copy to avoid that changing a buffer name or directory makes it
* invalid.
*/
if (fname_io == NULL)
{
if (event == EVENT_COLORSCHEME || event == EVENT_OPTIONSET)
autocmd_fname = NULL;
else if (fname != NULL && !ends_excmd(*fname))
autocmd_fname = fname;
else if (buf != NULL)
autocmd_fname = buf->b_ffname;
else
autocmd_fname = NULL;
}
else
autocmd_fname = fname_io;
if (autocmd_fname != NULL)
autocmd_fname = vim_strsave(autocmd_fname);
autocmd_fname_full = FALSE; /* call FullName_save() later */
/*
* Set the buffer number to be used for <abuf>.
*/
if (buf == NULL)
autocmd_bufnr = 0;
else
autocmd_bufnr = buf->b_fnum;
/*
* When the file name is NULL or empty, use the file name of buffer "buf".
* Always use the full path of the file name to match with, in case
* "allow_dirs" is set.
*/
if (fname == NULL || *fname == NUL)
{
if (buf == NULL)
fname = NULL;
else
{
#ifdef FEAT_SYN_HL
if (event == EVENT_SYNTAX)
fname = buf->b_p_syn;
else
#endif
if (event == EVENT_FILETYPE)
fname = buf->b_p_ft;
else
{
if (buf->b_sfname != NULL)
sfname = vim_strsave(buf->b_sfname);
fname = buf->b_ffname;
}
}
if (fname == NULL)
fname = (char_u *)"";
fname = vim_strsave(fname); /* make a copy, so we can change it */
}
else
{
sfname = vim_strsave(fname);
/* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
* ColorScheme or QuickFixCmd* */
if (event == EVENT_FILETYPE
|| event == EVENT_SYNTAX
|| event == EVENT_FUNCUNDEFINED
|| event == EVENT_REMOTEREPLY
|| event == EVENT_SPELLFILEMISSING
|| event == EVENT_QUICKFIXCMDPRE
|| event == EVENT_COLORSCHEME
|| event == EVENT_OPTIONSET
|| event == EVENT_QUICKFIXCMDPOST)
fname = vim_strsave(fname);
else
fname = FullName_save(fname, FALSE);
}
if (fname == NULL) /* out of memory */
{
vim_free(sfname);
retval = FALSE;
goto BYPASS_AU;
}
#ifdef BACKSLASH_IN_FILENAME
/*
* Replace all backslashes with forward slashes. This makes the
* autocommand patterns portable between Unix and MS-DOS.
*/
if (sfname != NULL)
forward_slash(sfname);
forward_slash(fname);
#endif
#ifdef VMS
/* remove version for correct match */
if (sfname != NULL)
vms_remove_version(sfname);
vms_remove_version(fname);
#endif
/*
* Set the name to be used for <amatch>.
*/
autocmd_match = fname;
/* Don't redraw while doing auto commands. */
++RedrawingDisabled;
save_sourcing_name = sourcing_name;
sourcing_name = NULL; /* don't free this one */
save_sourcing_lnum = sourcing_lnum;
sourcing_lnum = 0; /* no line number here */
#ifdef FEAT_EVAL
save_current_SID = current_SID;
# ifdef FEAT_PROFILE
if (do_profiling == PROF_YES)
prof_child_enter(&wait_time); /* doesn't count for the caller itself */
# endif
/* Don't use local function variables, if called from a function */
save_funccalp = save_funccal();
#endif
/*
* When starting to execute autocommands, save the search patterns.
*/
if (!autocmd_busy)
{
save_search_patterns();
#ifdef FEAT_INS_EXPAND
if (!ins_compl_active())
#endif
{
saveRedobuff();
did_save_redobuff = TRUE;
}
did_filetype = keep_filetype;
}
/*
* Note that we are applying autocmds. Some commands need to know.
*/
autocmd_busy = TRUE;
filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
++nesting; /* see matching decrement below */
/* Remember that FileType was triggered. Used for did_filetype(). */
if (event == EVENT_FILETYPE)
did_filetype = TRUE;
tail = gettail(fname);
/* Find first autocommand that matches */
patcmd.curpat = first_autopat[(int)event];
patcmd.nextcmd = NULL;
patcmd.group = group;
patcmd.fname = fname;
patcmd.sfname = sfname;
patcmd.tail = tail;
patcmd.event = event;
patcmd.arg_bufnr = autocmd_bufnr;
patcmd.next = NULL;
auto_next_pat(&patcmd, FALSE);
/* found one, start executing the autocommands */
if (patcmd.curpat != NULL)
{
/* add to active_apc_list */
patcmd.next = active_apc_list;
active_apc_list = &patcmd;
#ifdef FEAT_EVAL
/* set v:cmdarg (only when there is a matching pattern) */
save_cmdbang = (long)get_vim_var_nr(VV_CMDBANG);
if (eap != NULL)
{
save_cmdarg = set_cmdarg(eap, NULL);
set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
}
else
save_cmdarg = NULL; /* avoid gcc warning */
#endif
retval = TRUE;
/* mark the last pattern, to avoid an endless loop when more patterns
* are added when executing autocommands */
for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
ap->last = FALSE;
ap->last = TRUE;
check_lnums(TRUE); /* make sure cursor and topline are valid */
do_cmdline(NULL, getnextac, (void *)&patcmd,
DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
#ifdef FEAT_EVAL
if (eap != NULL)
{
(void)set_cmdarg(NULL, save_cmdarg);
set_vim_var_nr(VV_CMDBANG, save_cmdbang);
}
#endif
/* delete from active_apc_list */
if (active_apc_list == &patcmd) /* just in case */
active_apc_list = patcmd.next;
}
--RedrawingDisabled;
autocmd_busy = save_autocmd_busy;
filechangeshell_busy = FALSE;
autocmd_nested = save_autocmd_nested;
vim_free(sourcing_name);
sourcing_name = save_sourcing_name;
sourcing_lnum = save_sourcing_lnum;
vim_free(autocmd_fname);
autocmd_fname = save_autocmd_fname;
autocmd_fname_full = save_autocmd_fname_full;
autocmd_bufnr = save_autocmd_bufnr;
autocmd_match = save_autocmd_match;
#ifdef FEAT_EVAL
current_SID = save_current_SID;
restore_funccal(save_funccalp);
# ifdef FEAT_PROFILE
if (do_profiling == PROF_YES)
prof_child_exit(&wait_time);
# endif
#endif
vim_free(fname);
vim_free(sfname);
--nesting; /* see matching increment above */
/*
* When stopping to execute autocommands, restore the search patterns and
* the redo buffer. Free any buffers in the au_pending_free_buf list and
* free any windows in the au_pending_free_win list.
*/
if (!autocmd_busy)
{
restore_search_patterns();
if (did_save_redobuff)
restoreRedobuff();
did_filetype = FALSE;
while (au_pending_free_buf != NULL)
{
buf_T *b = au_pending_free_buf->b_next;
vim_free(au_pending_free_buf);
au_pending_free_buf = b;
}
while (au_pending_free_win != NULL)
{
win_T *w = au_pending_free_win->w_next;
vim_free(au_pending_free_win);
au_pending_free_win = w;
}
}
/*
* Some events don't set or reset the Changed flag.
* Check if still in the same buffer!
*/
if (curbuf == old_curbuf
&& (event == EVENT_BUFREADPOST
|| event == EVENT_BUFWRITEPOST
|| event == EVENT_FILEAPPENDPOST
|| event == EVENT_VIMLEAVE
|| event == EVENT_VIMLEAVEPRE))
{
#ifdef FEAT_TITLE
if (curbuf->b_changed != save_changed)
need_maketitle = TRUE;
#endif
curbuf->b_changed = save_changed;
}
au_cleanup(); /* may really delete removed patterns/commands now */
BYPASS_AU:
/* When wiping out a buffer make sure all its buffer-local autocommands
* are deleted. */
if (event == EVENT_BUFWIPEOUT && buf != NULL)
aubuflocal_remove(buf);
if (retval == OK && event == EVENT_FILETYPE)
au_did_filetype = TRUE;
return retval;
}
# ifdef FEAT_EVAL
static char_u *old_termresponse = NULL;
# endif
/*
* Block triggering autocommands until unblock_autocmd() is called.
* Can be used recursively, so long as it's symmetric.
*/
void
block_autocmds(void)
{
# ifdef FEAT_EVAL
/* Remember the value of v:termresponse. */
if (autocmd_blocked == 0)
old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
# endif
++autocmd_blocked;
}
void
unblock_autocmds(void)
{
--autocmd_blocked;
# ifdef FEAT_EVAL
/* When v:termresponse was set while autocommands were blocked, trigger
* the autocommands now. Esp. useful when executing a shell command
* during startup (vimdiff). */
if (autocmd_blocked == 0
&& get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
# endif
}
int
is_autocmd_blocked(void)
{
return autocmd_blocked != 0;
}
/*
* Find next autocommand pattern that matches.
*/
static void
auto_next_pat(
AutoPatCmd *apc,
int stop_at_last) /* stop when 'last' flag is set */
{
AutoPat *ap;
AutoCmd *cp;
char_u *name;
char *s;
vim_free(sourcing_name);
sourcing_name = NULL;
for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
{
apc->curpat = NULL;
/* Only use a pattern when it has not been removed, has commands and
* the group matches. For buffer-local autocommands only check the
* buffer number. */
if (ap->pat != NULL && ap->cmds != NULL
&& (apc->group == AUGROUP_ALL || apc->group == ap->group))
{
/* execution-condition */
if (ap->buflocal_nr == 0
? (match_file_pat(NULL, &ap->reg_prog, apc->fname,
apc->sfname, apc->tail, ap->allow_dirs))
: ap->buflocal_nr == apc->arg_bufnr)
{
name = event_nr2name(apc->event);
s = _("%s Auto commands for \"%s\"");
sourcing_name = alloc((unsigned)(STRLEN(s)
+ STRLEN(name) + ap->patlen + 1));
if (sourcing_name != NULL)
{
sprintf((char *)sourcing_name, s,
(char *)name, (char *)ap->pat);
if (p_verbose >= 8)
{
verbose_enter();
smsg((char_u *)_("Executing %s"), sourcing_name);
verbose_leave();
}
}
apc->curpat = ap;
apc->nextcmd = ap->cmds;
/* mark last command */
for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
cp->last = FALSE;
cp->last = TRUE;
}
line_breakcheck();
if (apc->curpat != NULL) /* found a match */
break;
}
if (stop_at_last && ap->last)
break;
}
}
/*
* Get next autocommand command.
* Called by do_cmdline() to get the next line for ":if".
* Returns allocated string, or NULL for end of autocommands.
*/
char_u *
getnextac(int c UNUSED, void *cookie, int indent UNUSED)
{
AutoPatCmd *acp = (AutoPatCmd *)cookie;
char_u *retval;
AutoCmd *ac;
/* Can be called again after returning the last line. */
if (acp->curpat == NULL)
return NULL;
/* repeat until we find an autocommand to execute */
for (;;)
{
/* skip removed commands */
while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
if (acp->nextcmd->last)
acp->nextcmd = NULL;
else
acp->nextcmd = acp->nextcmd->next;
if (acp->nextcmd != NULL)
break;
/* at end of commands, find next pattern that matches */
if (acp->curpat->last)
acp->curpat = NULL;
else
acp->curpat = acp->curpat->next;
if (acp->curpat != NULL)
auto_next_pat(acp, TRUE);
if (acp->curpat == NULL)
return NULL;
}
ac = acp->nextcmd;
if (p_verbose >= 9)
{
verbose_enter_scroll();
smsg((char_u *)_("autocommand %s"), ac->cmd);
msg_puts((char_u *)"\n"); /* don't overwrite this either */
verbose_leave_scroll();
}
retval = vim_strsave(ac->cmd);
autocmd_nested = ac->nested;
#ifdef FEAT_EVAL
current_SID = ac->scriptID;
#endif
if (ac->last)
acp->nextcmd = NULL;
else
acp->nextcmd = ac->next;
return retval;
}
/*
* Return TRUE if there is a matching autocommand for "fname".
* To account for buffer-local autocommands, function needs to know
* in which buffer the file will be opened.
*/
int
has_autocmd(event_T event, char_u *sfname, buf_T *buf)
{
AutoPat *ap;
char_u *fname;
char_u *tail = gettail(sfname);
int retval = FALSE;
fname = FullName_save(sfname, FALSE);
if (fname == NULL)
return FALSE;
#ifdef BACKSLASH_IN_FILENAME
/*
* Replace all backslashes with forward slashes. This makes the
* autocommand patterns portable between Unix and MS-DOS.
*/
sfname = vim_strsave(sfname);
if (sfname != NULL)
forward_slash(sfname);
forward_slash(fname);
#endif
for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
if (ap->pat != NULL && ap->cmds != NULL
&& (ap->buflocal_nr == 0
? match_file_pat(NULL, &ap->reg_prog,
fname, sfname, tail, ap->allow_dirs)
: buf != NULL && ap->buflocal_nr == buf->b_fnum
))
{
retval = TRUE;
break;
}
vim_free(fname);
#ifdef BACKSLASH_IN_FILENAME
vim_free(sfname);
#endif
return retval;
}
#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
/*
* Function given to ExpandGeneric() to obtain the list of autocommand group
* names.
*/
char_u *
get_augroup_name(expand_T *xp UNUSED, int idx)
{
if (idx == augroups.ga_len) /* add "END" add the end */
return (char_u *)"END";
if (idx >= augroups.ga_len) /* end of list */
return NULL;
if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup())
/* skip deleted entries */
return (char_u *)"";
return AUGROUP_NAME(idx); /* return a name */
}
static int include_groups = FALSE;
char_u *
set_context_in_autocmd(
expand_T *xp,
char_u *arg,
int doautocmd) /* TRUE for :doauto*, FALSE for :autocmd */
{
char_u *p;
int group;
/* check for a group name, skip it if present */
include_groups = FALSE;
p = arg;
group = au_get_grouparg(&arg);
if (group == AUGROUP_ERROR)
return NULL;
/* If there only is a group name that's what we expand. */
if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
{
arg = p;
group = AUGROUP_ALL;
}
/* skip over event name */
for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
if (*p == ',')
arg = p + 1;
if (*p == NUL)
{
if (group == AUGROUP_ALL)
include_groups = TRUE;
xp->xp_context = EXPAND_EVENTS; /* expand event name */
xp->xp_pattern = arg;
return NULL;
}
/* skip over pattern */
arg = skipwhite(p);
while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
arg++;
if (*arg)
return arg; /* expand (next) command */
if (doautocmd)
xp->xp_context = EXPAND_FILES; /* expand file names */
else
xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
return NULL;
}
/*
* Function given to ExpandGeneric() to obtain the list of event names.
*/
char_u *
get_event_name(expand_T *xp UNUSED, int idx)
{
if (idx < augroups.ga_len) /* First list group names, if wanted */
{
if (!include_groups || AUGROUP_NAME(idx) == NULL
|| AUGROUP_NAME(idx) == get_deleted_augroup())
return (char_u *)""; /* skip deleted entries */
return AUGROUP_NAME(idx); /* return a name */
}
return (char_u *)event_names[idx - augroups.ga_len].name;
}
#endif /* FEAT_CMDL_COMPL */
/*
* Return TRUE if autocmd is supported.
*/
int
autocmd_supported(char_u *name)
{
char_u *p;
return (event_name2nr(name, &p) != NUM_EVENTS);
}
/*
* Return TRUE if an autocommand is defined for a group, event and
* pattern: The group can be omitted to accept any group. "event" and "pattern"
* can be NULL to accept any event and pattern. "pattern" can be NULL to accept
* any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
* Used for:
* exists("#Group") or
* exists("#Group#Event") or
* exists("#Group#Event#pat") or
* exists("#Event") or
* exists("#Event#pat")
*/
int
au_exists(char_u *arg)
{
char_u *arg_save;
char_u *pattern = NULL;
char_u *event_name;
char_u *p;
event_T event;
AutoPat *ap;
buf_T *buflocal_buf = NULL;
int group;
int retval = FALSE;
/* Make a copy so that we can change the '#' chars to a NUL. */
arg_save = vim_strsave(arg);
if (arg_save == NULL)
return FALSE;
p = vim_strchr(arg_save, '#');
if (p != NULL)
*p++ = NUL;
/* First, look for an autocmd group name */
group = au_find_group(arg_save);
if (group == AUGROUP_ERROR)
{
/* Didn't match a group name, assume the first argument is an event. */
group = AUGROUP_ALL;
event_name = arg_save;
}
else
{
if (p == NULL)
{
/* "Group": group name is present and it's recognized */
retval = TRUE;
goto theend;
}
/* Must be "Group#Event" or "Group#Event#pat". */
event_name = p;
p = vim_strchr(event_name, '#');
if (p != NULL)
*p++ = NUL; /* "Group#Event#pat" */
}
pattern = p; /* "pattern" is NULL when there is no pattern */
/* find the index (enum) for the event name */
event = event_name2nr(event_name, &p);
/* return FALSE if the event name is not recognized */
if (event == NUM_EVENTS)
goto theend;
/* Find the first autocommand for this event.
* If there isn't any, return FALSE;
* If there is one and no pattern given, return TRUE; */
ap = first_autopat[(int)event];
if (ap == NULL)
goto theend;
/* if pattern is "<buffer>", special handling is needed which uses curbuf */
/* for pattern "<buffer=N>, fnamecmp() will work fine */
if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
buflocal_buf = curbuf;
/* Check if there is an autocommand with the given pattern. */
for ( ; ap != NULL; ap = ap->next)
/* only use a pattern when it has not been removed and has commands. */
/* For buffer-local autocommands, fnamecmp() works fine. */
if (ap->pat != NULL && ap->cmds != NULL
&& (group == AUGROUP_ALL || ap->group == group)
&& (pattern == NULL
|| (buflocal_buf == NULL
? fnamecmp(ap->pat, pattern) == 0
: ap->buflocal_nr == buflocal_buf->b_fnum)))
{
retval = TRUE;
break;
}
theend:
vim_free(arg_save);
return retval;
}
#else /* FEAT_AUTOCMD */
/*
* Prepare for executing commands for (hidden) buffer "buf".
* This is the non-autocommand version, it simply saves "curbuf" and sets
* "curbuf" and "curwin" to match "buf".
*/
void
aucmd_prepbuf(
aco_save_T *aco, /* structure to save values in */
buf_T *buf) /* new curbuf */
{
aco->save_curbuf = curbuf;
--curbuf->b_nwindows;
curbuf = buf;
curwin->w_buffer = buf;
++curbuf->b_nwindows;
}
/*
* Restore after executing commands for a (hidden) buffer.
* This is the non-autocommand version.
*/
void
aucmd_restbuf(
aco_save_T *aco) /* structure holding saved values */
{
--curbuf->b_nwindows;
curbuf = aco->save_curbuf;
curwin->w_buffer = curbuf;
++curbuf->b_nwindows;
}
#endif /* FEAT_AUTOCMD */
#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
/*
* Try matching a filename with a "pattern" ("prog" is NULL), or use the
* precompiled regprog "prog" ("pattern" is NULL). That avoids calling
* vim_regcomp() often.
* Used for autocommands and 'wildignore'.
* Returns TRUE if there is a match, FALSE otherwise.
*/
static int
match_file_pat(
char_u *pattern, /* pattern to match with */
regprog_T **prog, /* pre-compiled regprog or NULL */
char_u *fname, /* full path of file name */
char_u *sfname, /* short file name or NULL */
char_u *tail, /* tail of path */
int allow_dirs) /* allow matching with dir */
{
regmatch_T regmatch;
int result = FALSE;
regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
if (prog != NULL)
regmatch.regprog = *prog;
else
regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
/*
* Try for a match with the pattern with:
* 1. the full file name, when the pattern has a '/'.
* 2. the short file name, when the pattern has a '/'.
* 3. the tail of the file name, when the pattern has no '/'.
*/
if (regmatch.regprog != NULL
&& ((allow_dirs
&& (vim_regexec(®match, fname, (colnr_T)0)
|| (sfname != NULL
&& vim_regexec(®match, sfname, (colnr_T)0))))
|| (!allow_dirs && vim_regexec(®match, tail, (colnr_T)0))))
result = TRUE;
if (prog != NULL)
*prog = regmatch.regprog;
else
vim_regfree(regmatch.regprog);
return result;
}
#endif
#if defined(FEAT_WILDIGN) || defined(PROTO)
/*
* Return TRUE if a file matches with a pattern in "list".
* "list" is a comma-separated list of patterns, like 'wildignore'.
* "sfname" is the short file name or NULL, "ffname" the long file name.
*/
int
match_file_list(char_u *list, char_u *sfname, char_u *ffname)
{
char_u buf[100];
char_u *tail;
char_u *regpat;
char allow_dirs;
int match;
char_u *p;
tail = gettail(sfname);
/* try all patterns in 'wildignore' */
p = list;
while (*p)
{
copy_option_part(&p, buf, 100, ",");
regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
if (regpat == NULL)
break;
match = match_file_pat(regpat, NULL, ffname, sfname,
tail, (int)allow_dirs);
vim_free(regpat);
if (match)
return TRUE;
}
return FALSE;
}
#endif
/*
* Convert the given pattern "pat" which has shell style wildcards in it, into
* a regular expression, and return the result in allocated memory. If there
* is a directory path separator to be matched, then TRUE is put in
* allow_dirs, otherwise FALSE is put there -- webb.
* Handle backslashes before special characters, like "\*" and "\ ".
*
* Returns NULL when out of memory.
*/
char_u *
file_pat_to_reg_pat(
char_u *pat,
char_u *pat_end, /* first char after pattern or NULL */
char *allow_dirs, /* Result passed back out in here */
int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
{
int size = 2; /* '^' at start, '$' at end */
char_u *endp;
char_u *reg_pat;
char_u *p;
int i;
int nested = 0;
int add_dollar = TRUE;
if (allow_dirs != NULL)
*allow_dirs = FALSE;
if (pat_end == NULL)
pat_end = pat + STRLEN(pat);
for (p = pat; p < pat_end; p++)
{
switch (*p)
{
case '*':
case '.':
case ',':
case '{':
case '}':
case '~':
size += 2; /* extra backslash */
break;
#ifdef BACKSLASH_IN_FILENAME
case '\\':
case '/':
size += 4; /* could become "[\/]" */
break;
#endif
default:
size++;
# ifdef FEAT_MBYTE
if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
{
++p;
++size;
}
# endif
break;
}
}
reg_pat = alloc(size + 1);
if (reg_pat == NULL)
return NULL;
i = 0;
if (pat[0] == '*')
while (pat[0] == '*' && pat < pat_end - 1)
pat++;
else
reg_pat[i++] = '^';
endp = pat_end - 1;
if (endp >= pat && *endp == '*')
{
while (endp - pat > 0 && *endp == '*')
endp--;
add_dollar = FALSE;
}
for (p = pat; *p && nested >= 0 && p <= endp; p++)
{
switch (*p)
{
case '*':
reg_pat[i++] = '.';
reg_pat[i++] = '*';
while (p[1] == '*') /* "**" matches like "*" */
++p;
break;
case '.':
case '~':
reg_pat[i++] = '\\';
reg_pat[i++] = *p;
break;
case '?':
reg_pat[i++] = '.';
break;
case '\\':
if (p[1] == NUL)
break;
#ifdef BACKSLASH_IN_FILENAME
if (!no_bslash)
{
/* translate:
* "\x" to "\\x" e.g., "dir\file"
* "\*" to "\\.*" e.g., "dir\*.c"
* "\?" to "\\." e.g., "dir\??.c"
* "\+" to "\+" e.g., "fileX\+.c"
*/
if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
&& p[1] != '+')
{
reg_pat[i++] = '[';
reg_pat[i++] = '\\';
reg_pat[i++] = '/';
reg_pat[i++] = ']';
if (allow_dirs != NULL)
*allow_dirs = TRUE;
break;
}
}
#endif
/* Undo escaping from ExpandEscape():
* foo\?bar -> foo?bar
* foo\%bar -> foo%bar
* foo\,bar -> foo,bar
* foo\ bar -> foo bar
* Don't unescape \, * and others that are also special in a
* regexp.
* An escaped { must be unescaped since we use magic not
* verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
*/
if (*++p == '?'
#ifdef BACKSLASH_IN_FILENAME
&& no_bslash
#endif
)
reg_pat[i++] = '?';
else
if (*p == ',' || *p == '%' || *p == '#'
|| vim_isspace(*p) || *p == '{' || *p == '}')
reg_pat[i++] = *p;
else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
{
reg_pat[i++] = '\\';
reg_pat[i++] = '{';
p += 2;
}
else
{
if (allow_dirs != NULL && vim_ispathsep(*p)
#ifdef BACKSLASH_IN_FILENAME
&& (!no_bslash || *p != '\\')
#endif
)
*allow_dirs = TRUE;
reg_pat[i++] = '\\';
reg_pat[i++] = *p;
}
break;
#ifdef BACKSLASH_IN_FILENAME
case '/':
reg_pat[i++] = '[';
reg_pat[i++] = '\\';
reg_pat[i++] = '/';
reg_pat[i++] = ']';
if (allow_dirs != NULL)
*allow_dirs = TRUE;
break;
#endif
case '{':
reg_pat[i++] = '\\';
reg_pat[i++] = '(';
nested++;
break;
case '}':
reg_pat[i++] = '\\';
reg_pat[i++] = ')';
--nested;
break;
case ',':
if (nested)
{
reg_pat[i++] = '\\';
reg_pat[i++] = '|';
}
else
reg_pat[i++] = ',';
break;
default:
# ifdef FEAT_MBYTE
if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
reg_pat[i++] = *p++;
else
# endif
if (allow_dirs != NULL && vim_ispathsep(*p))
*allow_dirs = TRUE;
reg_pat[i++] = *p;
break;
}
}
if (add_dollar)
reg_pat[i++] = '$';
reg_pat[i] = NUL;
if (nested != 0)
{
if (nested < 0)
EMSG(_("E219: Missing {."));
else
EMSG(_("E220: Missing }."));
vim_free(reg_pat);
reg_pat = NULL;
}
return reg_pat;
}
#if defined(EINTR) || defined(PROTO)
/*
* Version of read() that retries when interrupted by EINTR (possibly
* by a SIGWINCH).
*/
long
read_eintr(int fd, void *buf, size_t bufsize)
{
long ret;
for (;;)
{
ret = vim_read(fd, buf, bufsize);
if (ret >= 0 || errno != EINTR)
break;
}
return ret;
}
/*
* Version of write() that retries when interrupted by EINTR (possibly
* by a SIGWINCH).
*/
long
write_eintr(int fd, void *buf, size_t bufsize)
{
long ret = 0;
long wlen;
/* Repeat the write() so long it didn't fail, other than being interrupted
* by a signal. */
while (ret < (long)bufsize)
{
wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
if (wlen < 0)
{
if (errno != EINTR)
break;
}
else
ret += wlen;
}
return ret;
}
#endif
|