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
|
*lua.txt* Nvim
NVIM REFERENCE MANUAL
Lua engine *lua* *Lua*
Type |gO| to see the table of contents.
==============================================================================
INTRODUCTION *lua-intro*
The Lua 5.1 script engine is builtin and always available. Try this command to
get an idea of what lurks beneath: >vim
:lua vim.print(package.loaded)
Nvim includes a "standard library" |lua-stdlib| for Lua. It complements the
"editor stdlib" (|builtin-functions| and |Ex-commands|) and the |API|, all of
which can be used from Lua code (|lua-vimscript| |vim.api|). Together these
"namespaces" form the Nvim programming interface.
Lua plugins and user config are automatically discovered and loaded, just like
Vimscript. See |lua-guide| for practical guidance.
You can also run Lua scripts from your shell using the |-l| argument: >
nvim -l foo.lua [args...]
<
*lua-compat*
Lua 5.1 is the permanent interface for Nvim Lua. Plugins need only consider
Lua 5.1, not worry about forward-compatibility with future Lua versions. If
Nvim ever ships with Lua 5.4+, a Lua 5.1 compatibility shim will be provided
so that old plugins continue to work transparently.
*lua-luajit*
On supported platforms, Nvim is built with LuaJIT, which provides extra
functionality (compared to PUC Lua) such as "bit" and various utilities (see
|lua-profile|). Lua code in |init.lua| and plugins can assume its presence on
many platforms, but for maximum compatibility should check the `jit` global
variable: >lua
if jit then
-- code for luajit
else
-- code for plain lua 5.1
end
<
*lua-bit*
The LuaJIT "bit" extension module is _always_ available: when built with PUC
Lua, Nvim includes a fallback implementation which provides `require("bit")`.
*lua-profile*
To profile Lua code (with LuaJIT-enabled Nvim), the basic steps are: >lua
-- Start a profiling session:
require('jit.p').start('ri1', '/tmp/profile')
-- Perform arbitrary tasks (use plugins, scripts, etc.) ...
-- Stop the session. Profile is written to /tmp/profile.
require('jit.p').stop()
See https://luajit.org/ext_profiler.html or the "p.lua" source for details: >
:lua vim.cmd.edit(package.searchpath('jit.p', package.path))
==============================================================================
LUA CONCEPTS AND IDIOMS *lua-concepts*
Lua is very simple: this means that, while there are some quirks, once you
internalize those quirks, everything works the same everywhere. Scopes
(closures) in particular are very consistent, unlike JavaScript or most other
languages.
Lua has three fundamental mechanisms—one for "each major aspect of
programming": tables, closures, and coroutines.
https://www.lua.org/doc/cacm2018.pdf
- Tables are the "object" or container datastructure: they represent both
lists and maps, you can extend them to represent your own datatypes and
change their behavior using |metatable|s (like Python's "datamodel").
- EVERY scope in Lua is a closure: a function is a closure, a module is
a closure, a `do` block (|lua-do|) is a closure--and they all work the same.
A Lua module is literally just a big closure discovered on the "path"
(where your modules are found: |package.cpath|).
- Stackful coroutines enable cooperative multithreading, generators, and
versatile control for both Lua and its host (Nvim).
*iterator*
An iterator is just a function that can be called repeatedly to get the "next"
value of a collection (or any other |iterable|). This interface is expected by
|for-in| loops, produced by |pairs()|, supported by |vim.iter|, etc.
https://www.lua.org/pil/7.1.html
*iterable*
An "iterable" is anything that |vim.iter()| can consume: tables, dicts, lists,
iterator functions, tables implementing the |__call()| metamethod, and
|vim.iter()| objects.
*list-iterator*
Iterators on |lua-list| tables have a "middle" and "end", whereas iterators in
general may be logically infinite. Therefore some |vim.iter| operations (e.g.
|Iter:rev()|) make sense only on list-like tables (which are finite by
definition).
*lua-function-call*
Lua functions can be called in multiple ways. Consider the function: >lua
local foo = function(a, b)
print("A: ", a)
print("B: ", b)
end
The first way to call this function is: >lua
foo(1, 2)
-- ==== Result ====
-- A: 1
-- B: 2
This way of calling a function is familiar from most scripting languages. In
Lua, any missing arguments are passed as `nil`, and extra parameters are
silently discarded. Example: >lua
foo(1)
-- ==== Result ====
-- A: 1
-- B: nil
<
*kwargs*
When calling a function, you can omit the parentheses if the function takes
exactly one string literal (`"foo"`) or table literal (`{1,2,3}`). The latter
is often used to mimic "named parameters" ("kwargs" or "keyword args") as in
languages like Python and C#. Example: >lua
local func_with_opts = function(opts)
local will_do_foo = opts.foo
local filename = opts.filename
...
end
func_with_opts { foo = true, filename = "hello.world" }
<
There's nothing special going on here except that parentheses are implicitly
added. But visually, this small bit of sugar gets reasonably close to a
"keyword args" interface.
*lua-regex*
Lua intentionally does not support regular expressions, instead it has limited
|lua-patterns| which avoid the performance pitfalls of extended regex. Lua
scripts can also use Vim regex via |vim.regex()|.
Examples: >lua
print(string.match("foo123bar123", "%d+"))
-- 123
print(string.match("foo123bar123", "[^%d]+"))
-- foo
print(string.match("foo123bar123", "[abc]+"))
-- ba
print(string.match("foo.bar", "%.bar"))
-- .bar
==============================================================================
IMPORTING LUA MODULES *lua-module-load*
Modules are searched for under the directories specified in 'runtimepath', in
the order they appear. Any "." in the module name is treated as a directory
separator when searching. For a module `foo.bar`, each directory is searched
for `lua/foo/bar.lua`, then `lua/foo/bar/init.lua`. If no files are found,
the directories are searched again for a shared library with a name matching
`lua/foo/bar.?`, where `?` is a list of suffixes (such as `so` or `dll`) derived from
the initial value of |package.cpath|. If still no files are found, Nvim falls
back to Lua's default search mechanism. The first script found is run and
`require()` returns the value returned by the script if any, else `true`.
The return value is cached after the first call to `require()` for each module,
with subsequent calls returning the cached value without searching for, or
executing any script. For further details see |require()|.
For example, if 'runtimepath' is `foo,bar` and |package.cpath| was
`./?.so;./?.dll` at startup, `require('mod')` searches these paths in order
and loads the first module found ("first wins"): >
foo/lua/mod.lua
foo/lua/mod/init.lua
bar/lua/mod.lua
bar/lua/mod/init.lua
foo/lua/mod.so
foo/lua/mod.dll
bar/lua/mod.so
bar/lua/mod.dll
<
*lua-package-path*
Nvim automatically adjusts |package.path| and |package.cpath| according to the
effective 'runtimepath' value. Adjustment happens whenever 'runtimepath' is
changed. `package.path` is adjusted by simply appending `/lua/?.lua` and
`/lua/?/init.lua` to each directory from 'runtimepath' (`/` is actually the
first character of `package.config`).
Similarly to |package.path|, modified directories from 'runtimepath' are also
added to |package.cpath|. In this case, instead of appending `/lua/?.lua` and
`/lua/?/init.lua` to each runtimepath, all unique `?`-containing suffixes of
the existing |package.cpath| are used. Example:
- 1. Given that
- 'runtimepath' contains `/foo/bar,/xxx;yyy/baz,/abc`;
- initial |package.cpath| (defined at compile-time or derived from
`$LUA_CPATH` / `$LUA_INIT`) contains `./?.so;/def/ghi/a?d/j/g.elf;/def/?.so`.
- 2. It finds `?`-containing suffixes `/?.so`, `/a?d/j/g.elf` and `/?.so`, in
order: parts of the path starting from the first path component containing
question mark and preceding path separator.
- 3. The suffix of `/def/?.so`, namely `/?.so` is not unique, as it’s the same
as the suffix of the first path from |package.path| (i.e. `./?.so`). Which
leaves `/?.so` and `/a?d/j/g.elf`, in this order.
- 4. 'runtimepath' has three paths: `/foo/bar`, `/xxx;yyy/baz` and `/abc`. The
second one contains a semicolon which is a paths separator so it is out,
leaving only `/foo/bar` and `/abc`, in order.
- 5. The cartesian product of paths from 4. and suffixes from 3. is taken,
giving four variants. In each variant a `/lua` path segment is inserted
between path and suffix, leaving:
- `/foo/bar/lua/?.so`
- `/foo/bar/lua/a?d/j/g.elf`
- `/abc/lua/?.so`
- `/abc/lua/a?d/j/g.elf`
- 6. New paths are prepended to the original |package.cpath|.
The result will look like this: >
/foo/bar,/xxx;yyy/baz,/abc ('runtimepath')
× ./?.so;/def/ghi/a?d/j/g.elf;/def/?.so (package.cpath)
= /foo/bar/lua/?.so;/foo/bar/lua/a?d/j/g.elf;/abc/lua/?.so;/abc/lua/a?d/j/g.elf;./?.so;/def/ghi/a?d/j/g.elf;/def/?.so
Note:
- To track 'runtimepath' updates, paths added at previous update are
remembered and removed at the next update, while all paths derived from the
new 'runtimepath' are prepended as described above. This allows removing
paths when path is removed from 'runtimepath', adding paths when they are
added and reordering |package.path|/|package.cpath| content if 'runtimepath'
was reordered.
- Although adjustments happen automatically, Nvim does not track current
values of |package.path| or |package.cpath|. If you happen to delete some
paths from there you can set 'runtimepath' to trigger an update: >vim
let &runtimepath = &runtimepath
- Skipping paths from 'runtimepath' which contain semicolons applies both to
|package.path| and |package.cpath|. Given that there are some badly written
plugins using shell, which will not work with paths containing semicolons,
it is better to not have them in 'runtimepath' at all.
==============================================================================
COMMANDS *lua-commands*
These commands execute a Lua chunk from either the command line (:lua, :luado)
or a file (:luafile) on the given line [range]. As always in Lua, each chunk
has its own scope (closure), so only global variables are shared between
command calls. The |lua-stdlib| modules, user modules, and anything else on
|package.path| are available.
The Lua print() function redirects its output to the Nvim message area, with
arguments separated by " " (space) instead of "\t" (tab).
*:lua=* *:lua*
:lua {chunk}
Executes Lua chunk {chunk}. If {chunk} starts with "=" the rest of the
chunk is evaluated as an expression and printed. `:lua =expr` and `:=expr`
are equivalent to `:lua vim.print(expr)`.
Examples: >vim
:lua vim.api.nvim_command('echo "Hello, Nvim!"')
< To see the Lua version: >vim
:lua print(_VERSION)
< To see the LuaJIT version: >vim
:lua =jit.version
<
:{range}lua
Executes buffer lines in {range} as Lua code. Unlike |:source|, this
always treats the lines as Lua code.
Example: select the following code and type ":lua<Enter>" to execute it: >lua
print(string.format(
'unix time: %s', os.time()))
<
*:lua-heredoc*
:lua << [trim] [{endmarker}]
{script}
{endmarker}
Executes Lua script {script} from within Vimscript. You can omit
[endmarker] after the "<<" and use a dot "." after {script} (similar to
|:append|, |:insert|). Refer to |:let-heredoc| for more information.
Example: >vim
function! CurrentLineInfo()
lua << EOF
local linenr = vim.api.nvim_win_get_cursor(0)[1]
local curline = vim.api.nvim_buf_get_lines(0, linenr - 1, linenr, false)[1]
print(string.format('Line [%d] has %d bytes', linenr, #curline))
EOF
endfunction
<
Note that the `local` variables will disappear when the block finishes.
But not globals.
*:luado*
:[range]luado {body}
Executes Lua chunk "function(line, linenr) {body} end" for each buffer
line in [range], where `line` is the current line text (without <EOL>),
and `linenr` is the current line number. If the function returns a string
that becomes the text of the corresponding buffer line. Default [range] is
the whole file: "1,$".
Examples: >vim
:luado return string.format("%s\t%d", line:reverse(), #line)
:lua require"lpeg"
:lua -- balanced parenthesis grammar:
:lua bp = lpeg.P{ "(" * ((1 - lpeg.S"()") + lpeg.V(1))^0 * ")" }
:luado if bp:match(line) then return "=>\t" .. line end
<
*:luafile*
:luafile {file}
Execute Lua script in {file}.
The whole argument is used as the filename (like |:edit|), spaces do not
need to be escaped. Alternatively you can |:source| Lua files.
Examples: >vim
:luafile script.lua
:luafile %
<
==============================================================================
luaeval() *lua-eval*
The (dual) equivalent of "vim.eval" for passing Lua values to Nvim is
"luaeval". "luaeval" takes an expression string and an optional argument used
for _A inside expression and returns the result of the expression. It is
semantically equivalent in Lua to: >lua
local chunkheader = "local _A = select(1, ...) return "
function luaeval (expstr, arg)
local chunk = assert(loadstring(chunkheader .. expstr, "luaeval"))
return chunk(arg) -- return typval
end
<
Lua nils, numbers, strings, tables and booleans are converted to their
respective Vimscript types. If a Lua string contains a NUL byte, it will be
converted to a |Blob|. Conversion of other Lua types is an error.
The magic global "_A" contains the second argument to luaeval().
Example: >vim
:echo luaeval('_A[1] + _A[2]', [40, 2])
" 42
:echo luaeval('string.match(_A, "[a-z]+")', 'XYXfoo123')
" foo
<
*lua-table-ambiguous*
Lua tables are used as both dictionaries and lists, so it is impossible to
determine whether empty table is meant to be empty list or empty dictionary.
Additionally Lua does not have integer numbers. To distinguish between these
cases there is the following agreement:
*lua-list*
0. Empty table is empty list.
1. Table with N consecutive integer indices starting from 1 and ending with
N is considered a list. See also |list-iterator|.
*lua-dict*
2. Table with string keys, none of which contains NUL byte, is considered to
be a dictionary.
3. Table with string keys, at least one of which contains NUL byte, is also
considered to be a dictionary, but this time it is converted to
a |msgpack-special-map|.
*lua-special-tbl*
4. Table with `vim.type_idx` key may be a dictionary, a list or floating-point
value:
- `{[vim.type_idx]=vim.types.float, [vim.val_idx]=1}` is converted to
a floating-point 1.0. Note that by default integral Lua numbers are
converted to |Number|s, non-integral are converted to |Float|s. This
variant allows integral |Float|s.
- `{[vim.type_idx]=vim.types.dictionary}` is converted to an empty
dictionary, `{[vim.type_idx]=vim.types.dictionary, [42]=1, a=2}` is
converted to a dictionary `{'a': 42}`: non-string keys are ignored.
Without `vim.type_idx` key tables with keys not fitting in 1., 2. or 3.
are errors.
- `{[vim.type_idx]=vim.types.array}` is converted to an empty list. As well
as `{[vim.type_idx]=vim.types.array, [42]=1}`: integral keys that do not
form a 1-step sequence from 1 to N are ignored, as well as all
non-integral keys.
Examples: >vim
:echo luaeval('math.pi')
:function Rand(x,y) " random uniform between x and y
: return luaeval('(_A.y-_A.x)*math.random()+_A.x', {'x':a:x,'y':a:y})
: endfunction
:echo Rand(1,10)
<
Note: Second argument to `luaeval` is converted ("marshalled") from Vimscript
to Lua, so changes to Lua containers do not affect values in Vimscript. Return
value is also always converted. When converting, |msgpack-special-dict|s are
treated specially.
==============================================================================
Vimscript v:lua interface *v:lua-call*
From Vimscript the special `v:lua` prefix can be used to call Lua functions
which are global or accessible from global tables. The expression >vim
call v:lua.func(arg1, arg2)
is equivalent to the Lua chunk >lua
return func(...)
where the args are converted to Lua values. The expression >vim
call v:lua.somemod.func(args)
is equivalent to the Lua chunk >lua
return somemod.func(...)
In addition, functions of packages can be accessed like >vim
call v:lua.require'mypack'.func(arg1, arg2)
call v:lua.require'mypack.submod'.func(arg1, arg2)
Note: Only single quote form without parens is allowed. Using
`require"mypack"` or `require('mypack')` as prefixes do NOT work (the latter
is still valid as a function call of itself, in case require returns a useful
value).
The `v:lua` prefix may be used to call Lua functions as |method|s. For
example: >vim
:eval arg1->v:lua.somemod.func(arg2)
<
You can use `v:lua` in "func" options like 'tagfunc', 'omnifunc', etc.
For example consider the following Lua omnifunc handler: >lua
function mymod.omnifunc(findstart, base)
if findstart == 1 then
return 0
else
return {'stuff', 'steam', 'strange things'}
end
end
vim.bo[buf].omnifunc = 'v:lua.mymod.omnifunc'
Note: The module ("mymod" in the above example) must either be a Lua global,
or use require() as shown above to access it from a package.
Note: `v:lua` without a call is not allowed in a Vimscript expression:
|Funcref|s cannot represent Lua functions. The following are errors: >vim
let g:Myvar = v:lua.myfunc " Error
call SomeFunc(v:lua.mycallback) " Error
let g:foo = v:lua " Error
let g:foo = v:['lua'] " Error
<
==============================================================================
Lua standard modules *lua-stdlib*
The Nvim Lua "standard library" (stdlib) is the `vim` module, which exposes
various functions and sub-modules. It is always loaded, thus `require("vim")`
is unnecessary.
You can peek at the module properties: >vim
:lua vim.print(vim)
Result is something like this: >
{
_os_proc_children = <function 1>,
_os_proc_info = <function 2>,
...
api = {
nvim__id = <function 5>,
nvim__id_array = <function 6>,
...
},
deepcopy = <function 106>,
gsplit = <function 107>,
...
}
To find documentation on e.g. the "deepcopy" function: >vim
:help vim.deepcopy()
Note that underscore-prefixed functions (e.g. "_os_proc_children") are
internal/private and must not be used by plugins.
------------------------------------------------------------------------------
VIM.UV *lua-loop* *vim.uv*
`vim.uv` exposes the "luv" Lua bindings for the libUV library that Nvim uses
for networking, filesystem, and process management, see |luvref.txt|.
In particular, it allows interacting with the main Nvim |luv-event-loop|.
*E5560* *lua-loop-callbacks*
It is an error to directly invoke `vim.api` functions (except |api-fast|) in
`vim.uv` callbacks. For example, this is an error: >lua
local timer = vim.uv.new_timer()
timer:start(1000, 0, function()
vim.api.nvim_command('echomsg "test"')
end)
<
To avoid the error use |vim.schedule_wrap()| to defer the callback: >lua
local timer = vim.uv.new_timer()
timer:start(1000, 0, vim.schedule_wrap(function()
vim.api.nvim_command('echomsg "test"')
end))
<
(For one-shot timers, see |vim.defer_fn()|, which automatically adds the
wrapping.)
Example: repeating timer
1. Save this code to a file.
2. Execute it with ":luafile %". >lua
-- Create a timer handle (implementation detail: uv_timer_t).
local timer = vim.uv.new_timer()
local i = 0
-- Waits 1000ms, then repeats every 750ms until timer:close().
timer:start(1000, 750, function()
print('timer invoked! i='..tostring(i))
if i > 4 then
timer:close() -- Always close handles to avoid leaks.
end
i = i + 1
end)
print('sleeping');
<
Example: File-change detection *watch-file*
1. Save this code to a file.
2. Execute it with ":luafile %".
3. Use ":Watch %" to watch any file.
4. Try editing the file from another text editor.
5. Observe that the file reloads in Nvim (because on_change() calls
|:checktime|). >lua
local w = vim.uv.new_fs_event()
local function on_change(err, fname, status)
-- Do work...
vim.api.nvim_command('checktime')
-- Debounce: stop/start.
w:stop()
watch_file(fname)
end
function watch_file(fname)
local fullpath = vim.api.nvim_call_function(
'fnamemodify', {fname, ':p'})
w:start(fullpath, {}, vim.schedule_wrap(function(...)
on_change(...) end))
end
vim.api.nvim_command(
"command! -nargs=1 Watch call luaeval('watch_file(_A)', expand('<args>'))")
<
*fswatch-limitations*
When on Linux and using fswatch, you may need to increase the maximum number
of `inotify` watches and queued events as the default limit can be too low. To
increase the limit, run: >sh
sysctl fs.inotify.max_user_watches=100000
sysctl fs.inotify.max_queued_events=100000
<
This will increase the limit to 100000 watches and queued events. These lines
can be added to `/etc/sysctl.conf` to make the changes persistent.
Example: TCP echo-server *tcp-server*
1. Save this code to a file.
2. Execute it with ":luafile %".
3. Note the port number.
4. Connect from any TCP client (e.g. "nc 0.0.0.0 36795"): >lua
local function create_server(host, port, on_connect)
local server = vim.uv.new_tcp()
server:bind(host, port)
server:listen(128, function(err)
assert(not err, err) -- Check for errors.
local sock = vim.uv.new_tcp()
server:accept(sock) -- Accept client connection.
on_connect(sock) -- Start reading messages.
end)
return server
end
local server = create_server('0.0.0.0', 0, function(sock)
sock:read_start(function(err, chunk)
assert(not err, err) -- Check for errors.
if chunk then
sock:write(chunk) -- Echo received messages to the channel.
else -- EOF (stream closed).
sock:close() -- Always close handles to avoid leaks.
end
end)
end)
print('TCP echo-server listening on port: '..server:getsockname().port)
<
Multithreading *lua-loop-threading*
Plugins can perform work in separate (os-level) threads using the threading
APIs in luv, for instance `vim.uv.new_thread`. Note that every thread
gets its own separate Lua interpreter state, with no access to Lua globals
in the main thread. Neither can the state of the editor (buffers, windows,
etc) be directly accessed from threads.
A subset of the `vim.*` API is available in threads. This includes:
- `vim.uv` with a separate event loop per thread.
- `vim.mpack` and `vim.json` (useful for serializing messages between threads)
- `require` in threads can use Lua packages from the global |package.path|
- `print()` and `vim.inspect`
- `vim.diff`
- most utility functions in `vim.*` for working with pure Lua values
like `vim.split`, `vim.tbl_*`, `vim.list_*`, and so on.
- `vim.is_thread()` returns true from a non-main thread.
==============================================================================
VIM.HIGHLIGHT *vim.highlight*
vim.highlight.on_yank({opts}) *vim.highlight.on_yank()*
Highlight the yanked text during a |TextYankPost| event.
Add the following to your `init.vim`: >vim
autocmd TextYankPost * silent! lua vim.highlight.on_yank {higroup='Visual', timeout=300}
<
Parameters: ~
• {opts} (`table?`) Optional parameters
• higroup highlight group for yanked region (default
"IncSearch")
• timeout time in ms before highlight is cleared (default 150)
• on_macro highlight when executing macro (default false)
• on_visual highlight when yanking visual selection (default
true)
• event event structure (default vim.v.event)
• priority integer priority (default
|vim.highlight.priorities|`.user`)
vim.highlight.priorities *vim.highlight.priorities*
Table with default priorities used for highlighting:
• `syntax`: `50`, used for standard syntax highlighting
• `treesitter`: `100`, used for treesitter-based highlighting
• `semantic_tokens`: `125`, used for LSP semantic token highlighting
• `diagnostics`: `150`, used for code analysis such as diagnostics
• `user`: `200`, used for user-triggered highlights such as LSP document
symbols or `on_yank` autocommands
*vim.highlight.range()*
vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {opts})
Apply highlight group to range of text.
Parameters: ~
• {bufnr} (`integer`) Buffer number to apply highlighting to
• {ns} (`integer`) Namespace to add highlight to
• {higroup} (`string`) Highlight group to use for highlighting
• {start} (`integer[]|string`) Start of region as a (line, column)
tuple or string accepted by |getpos()|
• {finish} (`integer[]|string`) End of region as a (line, column)
tuple or string accepted by |getpos()|
• {opts} (`table?`) A table with the following fields:
• {regtype}? (`string`, default: `'charwise'`) Type of
range. See |setreg()|
• {inclusive}? (`boolean`, default: `false`) Indicates
whether the range is end-inclusive
• {priority}? (`integer`, default:
`vim.highlight.priorities.user`) Indicates priority of
highlight
==============================================================================
VIM.DIFF *vim.diff*
vim.diff({a}, {b}, {opts}) *vim.diff()*
Run diff on strings {a} and {b}. Any indices returned by this function,
either directly or via callback arguments, are 1-based.
Examples: >lua
vim.diff('a\n', 'b\nc\n')
-- =>
-- @@ -1 +1,2 @@
-- -a
-- +b
-- +c
vim.diff('a\n', 'b\nc\n', {result_type = 'indices'})
-- =>
-- {
-- {1, 1, 1, 2}
-- }
<
Parameters: ~
• {a} (`string`) First string to compare
• {b} (`string`) Second string to compare
• {opts} (`table?`) Optional parameters:
• {on_hunk}?
(`fun(start_a: integer, count_a: integer, start_b: integer, count_b: integer): integer`)
Invoked for each hunk in the diff. Return a negative number
to cancel the callback for any remaining hunks. Arguments:
• `start_a` (`integer`): Start line of hunk in {a}.
• `count_a` (`integer`): Hunk size in {a}.
• `start_b` (`integer`): Start line of hunk in {b}.
• `count_b` (`integer`): Hunk size in {b}.
• {result_type}? (`'unified'|'indices'`, default: `'unified'`)
Form of the returned diff:
• `unified`: String in unified format.
• `indices`: Array of hunk locations. Note: This option is
ignored if `on_hunk` is used.
• {linematch}? (`boolean|integer`) Run linematch on the
resulting hunks from xdiff. When integer, only hunks upto
this size in lines are run through linematch. Requires
`result_type = indices`, ignored otherwise.
• {algorithm}? (`'myers'|'minimal'|'patience'|'histogram'`,
default: `'myers'`) Diff algorithm to use. Values:
• `myers`: the default algorithm
• `minimal`: spend extra time to generate the smallest
possible diff
• `patience`: patience diff algorithm
• `histogram`: histogram diff algorithm
• {ctxlen}? (`integer`) Context length
• {interhunkctxlen}? (`integer`) Inter hunk context length
• {ignore_whitespace}? (`boolean`) Ignore whitespace
• {ignore_whitespace_change}? (`boolean`) Ignore whitespace
change
• {ignore_whitespace_change_at_eol}? (`boolean`) Ignore
whitespace change at end-of-line.
• {ignore_cr_at_eol}? (`boolean`) Ignore carriage return at
end-of-line
• {ignore_blank_lines}? (`boolean`) Ignore blank lines
• {indent_heuristic}? (`boolean`) Use the indent heuristic for
the internal diff library.
Return: ~
(`string|integer[]`) See {opts.result_type}. `nil` if {opts.on_hunk}
is given.
==============================================================================
VIM.MPACK *vim.mpack*
This module provides encoding and decoding of Lua objects to and from
msgpack-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
vim.mpack.decode({str}) *vim.mpack.decode()*
Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object.
Parameters: ~
• {str} (`string`)
Return: ~
(`any`)
vim.mpack.encode({obj}) *vim.mpack.encode()*
Encodes (or "packs") Lua object {obj} as msgpack in a Lua string.
Parameters: ~
• {obj} (`any`)
Return: ~
(`string`)
==============================================================================
VIM.JSON *vim.json*
This module provides encoding and decoding of Lua objects to and from
JSON-encoded strings. Supports |vim.NIL| and |vim.empty_dict()|.
vim.json.decode({str}, {opts}) *vim.json.decode()*
Decodes (or "unpacks") the JSON-encoded {str} to a Lua object.
• Decodes JSON "null" as |vim.NIL| (controllable by {opts}, see below).
• Decodes empty object as |vim.empty_dict()|.
• Decodes empty array as `{}` (empty Lua table).
Example: >lua
vim.print(vim.json.decode('{"bar":[],"foo":{},"zub":null}'))
-- { bar = {}, foo = vim.empty_dict(), zub = vim.NIL }
<
Parameters: ~
• {str} (`string`) Stringified JSON data.
• {opts} (`table<string,any>?`) Options table with keys:
• luanil: (table) Table with keys:
• object: (boolean) When true, converts `null` in JSON
objects to Lua `nil` instead of |vim.NIL|.
• array: (boolean) When true, converts `null` in JSON arrays
to Lua `nil` instead of |vim.NIL|.
Return: ~
(`any`)
vim.json.encode({obj}) *vim.json.encode()*
Encodes (or "packs") Lua object {obj} as JSON in a Lua string.
Parameters: ~
• {obj} (`any`)
Return: ~
(`string`)
==============================================================================
VIM.BASE64 *vim.base64*
vim.base64.decode({str}) *vim.base64.decode()*
Decode a Base64 encoded string.
Parameters: ~
• {str} (`string`) Base64 encoded string
Return: ~
(`string`) Decoded string
vim.base64.encode({str}) *vim.base64.encode()*
Encode {str} using Base64.
Parameters: ~
• {str} (`string`) String to encode
Return: ~
(`string`) Encoded string
==============================================================================
VIM.SPELL *vim.spell*
vim.spell.check({str}) *vim.spell.check()*
Check {str} for spelling errors. Similar to the Vimscript function
|spellbadword()|.
Note: The behaviour of this function is dependent on: 'spelllang',
'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local to
the buffer. Consider calling this with |nvim_buf_call()|.
Example: >lua
vim.spell.check("the quik brown fox")
-- =>
-- {
-- {'quik', 'bad', 5}
-- }
<
Parameters: ~
• {str} (`string`)
Return: ~
(`{[1]: string, [2]: 'bad'|'rare'|'local'|'caps', [3]: integer}[]`)
List of tuples with three items:
• The badly spelled word.
• The type of the spelling error: "bad" spelling mistake "rare" rare
word "local" word only valid in another region "caps" word should
start with Capital
• The position in {str} where the word begins.
==============================================================================
VIM *vim.builtin*
vim.api.{func}({...}) *vim.api*
Invokes Nvim |API| function {func} with arguments {...}.
Example: call the "nvim_get_current_line()" API function: >lua
print(tostring(vim.api.nvim_get_current_line()))
vim.NIL *vim.NIL*
Special value representing NIL in |RPC| and |v:null| in Vimscript
conversion, and similar cases. Lua `nil` cannot be used as part of a Lua
table representing a Dictionary or Array, because it is treated as
missing: `{"foo", nil}` is the same as `{"foo"}`.
vim.type_idx *vim.type_idx*
Type index for use in |lua-special-tbl|. Specifying one of the values from
|vim.types| allows typing the empty table (it is unclear whether empty Lua
table represents empty list or empty array) and forcing integral numbers
to be |Float|. See |lua-special-tbl| for more details.
vim.val_idx *vim.val_idx*
Value index for tables representing |Float|s. A table representing
floating-point value 1.0 looks like this: >lua
{
[vim.type_idx] = vim.types.float,
[vim.val_idx] = 1.0,
}
< See also |vim.type_idx| and |lua-special-tbl|.
vim.types *vim.types*
Table with possible values for |vim.type_idx|. Contains two sets of
key-value pairs: first maps possible values for |vim.type_idx| to
human-readable strings, second maps human-readable type names to values
for |vim.type_idx|. Currently contains pairs for `float`, `array` and
`dictionary` types.
Note: One must expect that values corresponding to `vim.types.float`,
`vim.types.array` and `vim.types.dictionary` fall under only two following
assumptions:
1. Value may serve both as a key and as a value in a table. Given the
properties of Lua tables this basically means “value is not `nil`”.
2. For each value in `vim.types` table `vim.types[vim.types[value]]` is the
same as `value`.
No other restrictions are put on types, and it is not guaranteed that
values corresponding to `vim.types.float`, `vim.types.array` and
`vim.types.dictionary` will not change or that `vim.types` table will only
contain values for these three types.
*log_levels* *vim.log.levels*
Log levels are one of the values defined in `vim.log.levels`:
vim.log.levels.DEBUG
vim.log.levels.ERROR
vim.log.levels.INFO
vim.log.levels.TRACE
vim.log.levels.WARN
vim.log.levels.OFF
vim.empty_dict() *vim.empty_dict()*
Creates a special empty table (marked with a metatable), which Nvim
converts to an empty dictionary when translating Lua values to Vimscript
or API types. Nvim by default converts an empty table `{}` without this
metatable to an list/array.
Note: If numeric keys are present in the table, Nvim ignores the metatable
marker and converts the dict to a list/array anyway.
Return: ~
(`table`)
vim.iconv({str}, {from}, {to}) *vim.iconv()*
The result is a String, which is the text {str} converted from encoding
{from} to encoding {to}. When the conversion fails `nil` is returned. When
some characters could not be converted they are replaced with "?". The
encoding names are whatever the iconv() library function can accept, see
":Man 3 iconv".
Parameters: ~
• {str} (`string`) Text to convert
• {from} (`string`) Encoding of {str}
• {to} (`string`) Target encoding
Return: ~
(`string?`) Converted string if conversion succeeds, `nil` otherwise.
vim.in_fast_event() *vim.in_fast_event()*
Returns true if the code is executing as part of a "fast" event handler,
where most of the API is disabled. These are low-level events (e.g.
|lua-loop-callbacks|) which can be invoked whenever Nvim polls for input.
When this is `false` most API functions are callable (but may be subject
to other restrictions such as |textlock|).
vim.rpcnotify({channel}, {method}, {...}) *vim.rpcnotify()*
Sends {event} to {channel} via |RPC| and returns immediately. If {channel}
is 0, the event is broadcast to all channels.
This function also works in a fast callback |lua-loop-callbacks|.
Parameters: ~
• {channel} (`integer`)
• {method} (`string`)
• {...} (`any?`)
vim.rpcrequest({channel}, {method}, {...}) *vim.rpcrequest()*
Sends a request to {channel} to invoke {method} via |RPC| and blocks until
a response is received.
Note: NIL values as part of the return value is represented as |vim.NIL|
special value
Parameters: ~
• {channel} (`integer`)
• {method} (`string`)
• {...} (`any?`)
vim.schedule({fn}) *vim.schedule()*
Schedules {fn} to be invoked soon by the main event-loop. Useful to avoid
|textlock| or other temporary restrictions.
Parameters: ~
• {fn} (`fun()`)
vim.str_byteindex({str}, {index}, {use_utf16}) *vim.str_byteindex()*
Convert UTF-32 or UTF-16 {index} to byte index. If {use_utf16} is not
supplied, it defaults to false (use UTF-32). Returns the byte index.
Invalid UTF-8 and NUL is treated like in |vim.str_utfindex()|. An {index}
in the middle of a UTF-16 sequence is rounded upwards to the end of that
sequence.
Parameters: ~
• {str} (`string`)
• {index} (`integer`)
• {use_utf16} (`boolean?`)
vim.str_utf_end({str}, {index}) *vim.str_utf_end()*
Gets the distance (in bytes) from the last byte of the codepoint
(character) that {index} points to.
Examples: >lua
-- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
-- Returns 0 because the index is pointing at the last byte of a character
vim.str_utf_end('æ', 2)
-- Returns 1 because the index is pointing at the penultimate byte of a character
vim.str_utf_end('æ', 1)
<
Parameters: ~
• {str} (`string`)
• {index} (`integer`)
Return: ~
(`integer`)
vim.str_utf_pos({str}) *vim.str_utf_pos()*
Gets a list of the starting byte positions of each UTF-8 codepoint in the
given string.
Embedded NUL bytes are treated as terminating the string.
Parameters: ~
• {str} (`string`)
Return: ~
(`integer[]`)
vim.str_utf_start({str}, {index}) *vim.str_utf_start()*
Gets the distance (in bytes) from the starting byte of the codepoint
(character) that {index} points to.
The result can be added to {index} to get the starting byte of a
character.
Examples: >lua
-- The character 'æ' is stored as the bytes '\xc3\xa6' (using UTF-8)
-- Returns 0 because the index is pointing at the first byte of a character
vim.str_utf_start('æ', 1)
-- Returns -1 because the index is pointing at the second byte of a character
vim.str_utf_start('æ', 2)
<
Parameters: ~
• {str} (`string`)
• {index} (`integer`)
Return: ~
(`integer`)
vim.str_utfindex({str}, {index}) *vim.str_utfindex()*
Convert byte index to UTF-32 and UTF-16 indices. If {index} is not
supplied, the length of the string is used. All indices are zero-based.
Embedded NUL bytes are treated as terminating the string. Invalid UTF-8
bytes, and embedded surrogates are counted as one code point each. An
{index} in the middle of a UTF-8 sequence is rounded upwards to the end of
that sequence.
Parameters: ~
• {str} (`string`)
• {index} (`integer?`)
Return (multiple): ~
(`integer`) UTF-32 index
(`integer`) UTF-16 index
vim.stricmp({a}, {b}) *vim.stricmp()*
Compares strings case-insensitively.
Parameters: ~
• {a} (`string`)
• {b} (`string`)
Return: ~
(`0|1|-1`) if strings are equal, {a} is greater than {b} or {a} is
lesser than {b}, respectively.
vim.ui_attach({ns}, {options}, {callback}) *vim.ui_attach()*
Attach to ui events, similar to |nvim_ui_attach()| but receive events as
Lua callback. Can be used to implement screen elements like popupmenu or
message handling in Lua.
{options} should be a dictionary-like table, where `ext_...` options
should be set to true to receive events for the respective external
element.
{callback} receives event name plus additional parameters. See
|ui-popupmenu| and the sections below for event format for respective
events.
WARNING: This api is considered experimental. Usability will vary for
different screen elements. In particular `ext_messages` behavior is
subject to further changes and usability improvements. This is expected to
be used to handle messages when setting 'cmdheight' to zero (which is
likewise experimental).
Example (stub for a |ui-popupmenu| implementation): >lua
ns = vim.api.nvim_create_namespace('my_fancy_pum')
vim.ui_attach(ns, {ext_popupmenu=true}, function(event, ...)
if event == "popupmenu_show" then
local items, selected, row, col, grid = ...
print("display pum ", #items)
elseif event == "popupmenu_select" then
local selected = ...
print("selected", selected)
elseif event == "popupmenu_hide" then
print("FIN")
end
end)
<
Parameters: ~
• {ns} (`integer`)
• {options} (`table<string, any>`)
• {callback} (`fun()`)
vim.ui_detach({ns}) *vim.ui_detach()*
Detach a callback previously attached with |vim.ui_attach()| for the given
namespace {ns}.
Parameters: ~
• {ns} (`integer`)
vim.wait({time}, {callback}, {interval}, {fast_only}) *vim.wait()*
Wait for {time} in milliseconds until {callback} returns `true`.
Executes {callback} immediately and at approximately {interval}
milliseconds (default 200). Nvim still processes other events during this
time.
Cannot be called while in an |api-fast| event.
Examples: >lua
---
-- Wait for 100 ms, allowing other events to process
vim.wait(100, function() end)
---
-- Wait for 100 ms or until global variable set.
vim.wait(100, function() return vim.g.waiting_for_var end)
---
-- Wait for 1 second or until global variable set, checking every ~500 ms
vim.wait(1000, function() return vim.g.waiting_for_var end, 500)
---
-- Schedule a function to set a value in 100ms
vim.defer_fn(function() vim.g.timer_result = true end, 100)
-- Would wait ten seconds if results blocked. Actually only waits 100 ms
if vim.wait(10000, function() return vim.g.timer_result end) then
print('Only waiting a little bit of time!')
end
<
Parameters: ~
• {time} (`integer`) Number of milliseconds to wait
• {callback} (`fun(): boolean?`) Optional callback. Waits until
{callback} returns true
• {interval} (`integer?`) (Approximate) number of milliseconds to wait
between polls
• {fast_only} (`boolean?`) If true, only |api-fast| events will be
processed.
Return (multiple): ~
(`boolean`)
(`-1|-2?`)
• If {callback} returns `true` during the {time}: `true, nil`
• If {callback} never returns `true` during the {time}: `false, -1`
• If {callback} is interrupted during the {time}: `false, -2`
• If {callback} errors, the error is raised.
==============================================================================
LUA-VIMSCRIPT BRIDGE *lua-vimscript*
Nvim Lua provides an interface or "bridge" to Vimscript variables and
functions, and editor commands and options.
Objects passed over this bridge are COPIED (marshalled): there are no
"references". |lua-guide-variables| For example, using `vim.fn.remove()` on a
Lua list copies the list object to Vimscript and does NOT modify the Lua list: >lua
local list = { 1, 2, 3 }
vim.fn.remove(list, 0)
vim.print(list) --> "{ 1, 2, 3 }"
<
vim.call({func}, {...}) *vim.call()*
Invokes |vim-function| or |user-function| {func} with arguments {...}.
See also |vim.fn|.
Equivalent to: >lua
vim.fn[func]({...})
<
vim.cmd({command})
See |vim.cmd()|.
vim.fn.{func}({...}) *vim.fn*
Invokes |vim-function| or |user-function| {func} with arguments {...}.
To call autoload functions, use the syntax: >lua
vim.fn['some#function']({...})
<
Unlike vim.api.|nvim_call_function()| this converts directly between Vim
objects and Lua objects. If the Vim function returns a float, it will be
represented directly as a Lua number. Empty lists and dictionaries both
are represented by an empty table.
Note: |v:null| values as part of the return value is represented as
|vim.NIL| special value
Note: vim.fn keys are generated lazily, thus `pairs(vim.fn)` only
enumerates functions that were called at least once.
Note: The majority of functions cannot run in |api-fast| callbacks with some
undocumented exceptions which are allowed.
*lua-vim-variables*
The Vim editor global dictionaries |g:| |w:| |b:| |t:| |v:| can be accessed
from Lua conveniently and idiomatically by referencing the `vim.*` Lua tables
described below. In this way you can easily read and modify global Vimscript
variables from Lua.
Example: >lua
vim.g.foo = 5 -- Set the g:foo Vimscript variable.
print(vim.g.foo) -- Get and print the g:foo Vimscript variable.
vim.g.foo = nil -- Delete (:unlet) the Vimscript variable.
vim.b[2].foo = 6 -- Set b:foo for buffer 2
<
Note that setting dictionary fields directly will not write them back into
Nvim. This is because the index into the namespace simply returns a copy.
Instead the whole dictionary must be written as one. This can be achieved by
creating a short-lived temporary.
Example: >lua
vim.g.my_dict.field1 = 'value' -- Does not work
local my_dict = vim.g.my_dict --
my_dict.field1 = 'value' -- Instead do
vim.g.my_dict = my_dict --
vim.g *vim.g*
Global (|g:|) editor variables.
Key with no value returns `nil`.
vim.b *vim.b*
Buffer-scoped (|b:|) variables for the current buffer.
Invalid or unset key returns `nil`. Can be indexed with
an integer to access variables for a specific buffer.
vim.w *vim.w*
Window-scoped (|w:|) variables for the current window.
Invalid or unset key returns `nil`. Can be indexed with
an integer to access variables for a specific window.
vim.t *vim.t*
Tabpage-scoped (|t:|) variables for the current tabpage.
Invalid or unset key returns `nil`. Can be indexed with
an integer to access variables for a specific tabpage.
vim.v *vim.v*
|v:| variables.
Invalid or unset key returns `nil`.
*lua-options*
*lua-vim-options*
*lua-vim-set*
*lua-vim-setlocal*
Vim options can be accessed through |vim.o|, which behaves like Vimscript
|:set|.
Examples: ~
To set a boolean toggle:
Vimscript: `set number`
Lua: `vim.o.number = true`
To set a string value:
Vimscript: `set wildignore=*.o,*.a,__pycache__`
Lua: `vim.o.wildignore = '*.o,*.a,__pycache__'`
Similarly, there is |vim.bo| and |vim.wo| for setting buffer-scoped and
window-scoped options. Note that this must NOT be confused with
|local-options| and |:setlocal|. There is also |vim.go| that only accesses the
global value of a |global-local| option, see |:setglobal|.
*vim.opt_local*
*vim.opt_global*
*vim.opt*
A special interface |vim.opt| exists for conveniently interacting with list-
and map-style option from Lua: It allows accessing them as Lua tables and
offers object-oriented method for adding and removing entries.
Examples: ~
The following methods of setting a list-style option are equivalent:
In Vimscript: >vim
set wildignore=*.o,*.a,__pycache__
<
In Lua using `vim.o`: >lua
vim.o.wildignore = '*.o,*.a,__pycache__'
<
In Lua using `vim.opt`: >lua
vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }
<
To replicate the behavior of |:set+=|, use: >lua
vim.opt.wildignore:append { "*.pyc", "node_modules" }
<
To replicate the behavior of |:set^=|, use: >lua
vim.opt.wildignore:prepend { "new_first_value" }
<
To replicate the behavior of |:set-=|, use: >lua
vim.opt.wildignore:remove { "node_modules" }
<
The following methods of setting a map-style option are equivalent:
In Vimscript: >vim
set listchars=space:_,tab:>~
<
In Lua using `vim.o`: >lua
vim.o.listchars = 'space:_,tab:>~'
<
In Lua using `vim.opt`: >lua
vim.opt.listchars = { space = '_', tab = '>~' }
<
Note that |vim.opt| returns an `Option` object, not the value of the option,
which is accessed through |vim.opt:get()|:
Examples: ~
The following methods of getting a list-style option are equivalent:
In Vimscript: >vim
echo wildignore
<
In Lua using `vim.o`: >lua
print(vim.o.wildignore)
<
In Lua using `vim.opt`: >lua
vim.print(vim.opt.wildignore:get())
<
In any of the above examples, to replicate the behavior |:setlocal|, use
`vim.opt_local`. Additionally, to replicate the behavior of |:setglobal|, use
`vim.opt_global`.
Option:append({value}) *vim.opt:append()*
Append a value to string-style options. See |:set+=|
These are equivalent: >lua
vim.opt.formatoptions:append('j')
vim.opt.formatoptions = vim.opt.formatoptions + 'j'
<
Parameters: ~
• {value} (`string`) Value to append
Option:get() *vim.opt:get()*
Returns a Lua-representation of the option. Boolean, number and string
values will be returned in exactly the same fashion.
For values that are comma-separated lists, an array will be returned with
the values as entries in the array: >lua
vim.cmd [[set wildignore=*.pyc,*.o]]
vim.print(vim.opt.wildignore:get())
-- { "*.pyc", "*.o", }
for _, ignore_pattern in ipairs(vim.opt.wildignore:get()) do
print("Will ignore:", ignore_pattern)
end
-- Will ignore: *.pyc
-- Will ignore: *.o
<
For values that are comma-separated maps, a table will be returned with
the names as keys and the values as entries: >lua
vim.cmd [[set listchars=space:_,tab:>~]]
vim.print(vim.opt.listchars:get())
-- { space = "_", tab = ">~", }
for char, representation in pairs(vim.opt.listchars:get()) do
print(char, "=>", representation)
end
<
For values that are lists of flags, a set will be returned with the flags
as keys and `true` as entries. >lua
vim.cmd [[set formatoptions=njtcroql]]
vim.print(vim.opt.formatoptions:get())
-- { n = true, j = true, c = true, ... }
local format_opts = vim.opt.formatoptions:get()
if format_opts.j then
print("J is enabled!")
end
<
Return: ~
(`string|integer|boolean?`) value of option
Option:prepend({value}) *vim.opt:prepend()*
Prepend a value to string-style options. See |:set^=|
These are equivalent: >lua
vim.opt.wildignore:prepend('*.o')
vim.opt.wildignore = vim.opt.wildignore ^ '*.o'
<
Parameters: ~
• {value} (`string`) Value to prepend
Option:remove({value}) *vim.opt:remove()*
Remove a value from string-style options. See |:set-=|
These are equivalent: >lua
vim.opt.wildignore:remove('*.pyc')
vim.opt.wildignore = vim.opt.wildignore - '*.pyc'
<
Parameters: ~
• {value} (`string`) Value to remove
vim.bo[{bufnr}] *vim.bo*
Get or set buffer-scoped |options| for the buffer with number {bufnr}.
Like `:setlocal`. If {bufnr} is omitted then the current buffer is used.
Invalid {bufnr} or key is an error.
Example: >lua
local bufnr = vim.api.nvim_get_current_buf()
vim.bo[bufnr].buflisted = true -- same as vim.bo.buflisted = true
print(vim.bo.comments)
print(vim.bo.baz) -- error: invalid key
<
vim.env *vim.env*
Environment variables defined in the editor session. See |expand-env| and
|:let-environment| for the Vimscript behavior. Invalid or unset key
returns `nil`.
Example: >lua
vim.env.FOO = 'bar'
print(vim.env.TERM)
<
vim.go *vim.go*
Get or set global |options|. Like `:setglobal`. Invalid key is an error.
Note: this is different from |vim.o| because this accesses the global
option value and thus is mostly useful for use with |global-local|
options.
Example: >lua
vim.go.cmdheight = 4
print(vim.go.columns)
print(vim.go.bar) -- error: invalid key
<
vim.o *vim.o*
Get or set |options|. Like `:set`. Invalid key is an error.
Note: this works on both buffer-scoped and window-scoped options using the
current buffer and window.
Example: >lua
vim.o.cmdheight = 4
print(vim.o.columns)
print(vim.o.foo) -- error: invalid key
<
vim.wo[{winid}][{bufnr}] *vim.wo*
Get or set window-scoped |options| for the window with handle {winid} and
buffer with number {bufnr}. Like `:setlocal` if setting a |global-local|
option or if {bufnr} is provided, like `:set` otherwise. If {winid} is
omitted then the current window is used. Invalid {winid}, {bufnr} or key
is an error.
Note: only {bufnr} with value `0` (the current buffer in the window) is
supported.
Example: >lua
local winid = vim.api.nvim_get_current_win()
vim.wo[winid].number = true -- same as vim.wo.number = true
print(vim.wo.foldmarker)
print(vim.wo.quux) -- error: invalid key
vim.wo[winid][0].spell = false -- like ':setlocal nospell'
<
==============================================================================
Lua module: vim *lua-vim*
vim.cmd({command}) *vim.cmd()*
Executes Vim script commands.
Note that `vim.cmd` can be indexed with a command name to return a
callable function to the command.
Example: >lua
vim.cmd('echo 42')
vim.cmd([[
augroup My_group
autocmd!
autocmd FileType c setlocal cindent
augroup END
]])
-- Ex command :echo "foo"
-- Note string literals need to be double quoted.
vim.cmd('echo "foo"')
vim.cmd { cmd = 'echo', args = { '"foo"' } }
vim.cmd.echo({ args = { '"foo"' } })
vim.cmd.echo('"foo"')
-- Ex command :write! myfile.txt
vim.cmd('write! myfile.txt')
vim.cmd { cmd = 'write', args = { "myfile.txt" }, bang = true }
vim.cmd.write { args = { "myfile.txt" }, bang = true }
vim.cmd.write { "myfile.txt", bang = true }
-- Ex command :colorscheme blue
vim.cmd('colorscheme blue')
vim.cmd.colorscheme('blue')
<
Parameters: ~
• {command} (`string|table`) Command(s) to execute. If a string,
executes multiple lines of Vim script at once. In this
case, it is an alias to |nvim_exec2()|, where `opts.output`
is set to false. Thus it works identical to |:source|. If a
table, executes a single command. In this case, it is an
alias to |nvim_cmd()| where `opts` is empty.
See also: ~
• |ex-cmd-index|
vim.defer_fn({fn}, {timeout}) *vim.defer_fn()*
Defers calling {fn} until {timeout} ms passes.
Use to do a one-shot timer that calls {fn} Note: The {fn} is
|vim.schedule_wrap()|ped automatically, so API functions are safe to call.
Parameters: ~
• {fn} (`function`) Callback to call once `timeout` expires
• {timeout} (`integer`) Number of milliseconds to wait before calling
`fn`
Return: ~
(`table`) timer luv timer object
*vim.deprecate()*
vim.deprecate({name}, {alternative}, {version}, {plugin}, {backtrace})
Shows a deprecation message to the user.
Parameters: ~
• {name} (`string`) Deprecated feature (function, API, etc.).
• {alternative} (`string?`) Suggested alternative feature.
• {version} (`string`) Version when the deprecated function will be
removed.
• {plugin} (`string?`) Name of the plugin that owns the deprecated
feature. Defaults to "Nvim".
• {backtrace} (`boolean?`) Prints backtrace. Defaults to true.
Return: ~
(`string?`) Deprecated message, or nil if no message was shown.
vim.inspect() *vim.inspect()*
Gets a human-readable representation of the given object.
Return: ~
(`string`)
See also: ~
• |vim.print()|
• https://github.com/kikito/inspect.lua
• https://github.com/mpeterv/vinspect
vim.keycode({str}) *vim.keycode()*
Translates keycodes.
Example: >lua
local k = vim.keycode
vim.g.mapleader = k'<bs>'
<
Parameters: ~
• {str} (`string`) String to be converted.
Return: ~
(`string`)
See also: ~
• |nvim_replace_termcodes()|
vim.lua_omnifunc({find_start}) *vim.lua_omnifunc()*
Omnifunc for completing Lua values from the runtime Lua interpreter,
similar to the builtin completion for the `:lua` command.
Activate using `set omnifunc=v:lua.vim.lua_omnifunc` in a Lua buffer.
Parameters: ~
• {find_start} (`1|0`)
vim.notify({msg}, {level}, {opts}) *vim.notify()*
Displays a notification to the user.
This function can be overridden by plugins to display notifications using
a custom provider (such as the system notification provider). By default,
writes to |:messages|.
Parameters: ~
• {msg} (`string`) Content of the notification to show to the user.
• {level} (`integer?`) One of the values from |vim.log.levels|.
• {opts} (`table?`) Optional parameters. Unused by default.
vim.notify_once({msg}, {level}, {opts}) *vim.notify_once()*
Displays a notification only one time.
Like |vim.notify()|, but subsequent calls with the same message will not
display a notification.
Parameters: ~
• {msg} (`string`) Content of the notification to show to the user.
• {level} (`integer?`) One of the values from |vim.log.levels|.
• {opts} (`table?`) Optional parameters. Unused by default.
Return: ~
(`boolean`) true if message was displayed, else false
vim.on_key({fn}, {ns_id}) *vim.on_key()*
Adds Lua function {fn} with namespace id {ns_id} as a listener to every,
yes every, input key.
The Nvim command-line option |-w| is related but does not support
callbacks and cannot be toggled dynamically.
Note: ~
• {fn} will be removed on error.
• {fn} will not be cleared by |nvim_buf_clear_namespace()|
Parameters: ~
• {fn} (`fun(key: string, typed: string)?`) Function invoked for
every input key, after mappings have been applied but before
further processing. Arguments {key} and {typed} are raw
keycodes, where {key} is the key after mappings are applied,
and {typed} is the key(s) before mappings are applied.
{typed} may be empty if {key} is produced by non-typed key(s)
or by the same typed key(s) that produced a previous {key}.
When {fn} is `nil` and {ns_id} is specified, the callback
associated with namespace {ns_id} is removed.
• {ns_id} (`integer?`) Namespace ID. If nil or 0, generates and returns
a new |nvim_create_namespace()| id.
Return: ~
(`integer`) Namespace id associated with {fn}. Or count of all
callbacks if on_key() is called without arguments.
See also: ~
• |keytrans()|
vim.paste({lines}, {phase}) *vim.paste()*
Paste handler, invoked by |nvim_paste()| when a conforming UI (such as the
|TUI|) pastes text into the editor.
Example: To remove ANSI color codes when pasting: >lua
vim.paste = (function(overridden)
return function(lines, phase)
for i,line in ipairs(lines) do
-- Scrub ANSI color codes from paste input.
lines[i] = line:gsub('\27%[[0-9;mK]+', '')
end
overridden(lines, phase)
end
end)(vim.paste)
<
Parameters: ~
• {lines} (`string[]`) |readfile()|-style list of lines to paste.
|channel-lines|
• {phase} (`-1|1|2|3`) -1: "non-streaming" paste: the call contains all
lines. If paste is "streamed", `phase` indicates the stream
state:
• 1: starts the paste (exactly once)
• 2: continues the paste (zero or more times)
• 3: ends the paste (exactly once)
Return: ~
(`boolean`) result false if client should cancel the paste.
See also: ~
• |paste|
vim.print({...}) *vim.print()*
"Pretty prints" the given arguments and returns them unmodified.
Example: >lua
local hl_normal = vim.print(vim.api.nvim_get_hl(0, { name = 'Normal' }))
<
Parameters: ~
• {...} (`any`)
Return: ~
(`any`) given arguments.
See also: ~
• |vim.inspect()|
• |:=|
*vim.region()*
vim.region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive})
Gets a dict of line segment ("chunk") positions for the region from `pos1`
to `pos2`.
Input and output positions are byte positions, (0,0)-indexed. "End of
line" column position (for example, |linewise| visual selection) is
returned as |v:maxcol| (big number).
Parameters: ~
• {bufnr} (`integer`) Buffer number, or 0 for current buffer
• {pos1} (`integer[]|string`) Start of region as a (line, column)
tuple or |getpos()|-compatible string
• {pos2} (`integer[]|string`) End of region as a (line, column)
tuple or |getpos()|-compatible string
• {regtype} (`string`) |setreg()|-style selection type
• {inclusive} (`boolean`) Controls whether the ending column is
inclusive (see also 'selection').
Return: ~
(`table`) region Dict of the form `{linenr = {startcol,endcol}}`.
`endcol` is exclusive, and whole lines are returned as
`{startcol,endcol} = {0,-1}`.
vim.schedule_wrap({fn}) *vim.schedule_wrap()*
Returns a function which calls {fn} via |vim.schedule()|.
The returned function passes all arguments to {fn}.
Example: >lua
function notify_readable(_err, readable)
vim.notify("readable? " .. tostring(readable))
end
vim.uv.fs_access(vim.fn.stdpath("config"), "R", vim.schedule_wrap(notify_readable))
<
Parameters: ~
• {fn} (`function`)
Return: ~
(`function`)
See also: ~
• |lua-loop-callbacks|
• |vim.schedule()|
• |vim.in_fast_event()|
vim.system({cmd}, {opts}, {on_exit}) *vim.system()*
Runs a system command or throws an error if {cmd} cannot be run.
Examples: >lua
local on_exit = function(obj)
print(obj.code)
print(obj.signal)
print(obj.stdout)
print(obj.stderr)
end
-- Runs asynchronously:
vim.system({'echo', 'hello'}, { text = true }, on_exit)
-- Runs synchronously:
local obj = vim.system({'echo', 'hello'}, { text = true }):wait()
-- { code = 0, signal = 0, stdout = 'hello', stderr = '' }
<
See |uv.spawn()| for more details. Note: unlike |uv.spawn()|, vim.system
throws an error if {cmd} cannot be run.
Parameters: ~
• {cmd} (`string[]`) Command to execute
• {opts} (`vim.SystemOpts?`) Options:
• cwd: (string) Set the current working directory for the
sub-process.
• env: table<string,string> Set environment variables for
the new process. Inherits the current environment with
`NVIM` set to |v:servername|.
• clear_env: (boolean) `env` defines the job environment
exactly, instead of merging current environment.
• stdin: (string|string[]|boolean) If `true`, then a pipe
to stdin is opened and can be written to via the
`write()` method to SystemObj. If string or string[] then
will be written to stdin and closed. Defaults to `false`.
• stdout: (boolean|function) Handle output from stdout.
When passed as a function must have the signature
`fun(err: string, data: string)`. Defaults to `true`
• stderr: (boolean|function) Handle output from stderr.
When passed as a function must have the signature
`fun(err: string, data: string)`. Defaults to `true`.
• text: (boolean) Handle stdout and stderr as text.
Replaces `\r\n` with `\n`.
• timeout: (integer) Run the command with a time limit.
Upon timeout the process is sent the TERM signal (15) and
the exit code is set to 124.
• detach: (boolean) If true, spawn the child process in a
detached state - this will make it a process group
leader, and will effectively enable the child to keep
running after the parent exits. Note that the child
process will still keep the parent's event loop alive
unless the parent process calls |uv.unref()| on the
child's process handle.
• {on_exit} (`fun(out: vim.SystemCompleted)?`) Called when subprocess
exits. When provided, the command runs asynchronously.
Receives SystemCompleted object, see return of
SystemObj:wait().
Return: ~
(`vim.SystemObj`) Object with the fields:
• cmd (string[]) Command name and args
• pid (integer) Process ID
• wait (fun(timeout: integer|nil): SystemCompleted) Wait for the
process to complete. Upon timeout the process is sent the KILL
signal (9) and the exit code is set to 124. Cannot be called in
|api-fast|.
• SystemCompleted is an object with the fields:
• code: (integer)
• signal: (integer)
• stdout: (string), nil if stdout argument is passed
• stderr: (string), nil if stderr argument is passed
• kill (fun(signal: integer|string))
• write (fun(data: string|nil)) Requires `stdin=true`. Pass `nil` to
close the stream.
• is_closing (fun(): boolean)
==============================================================================
Lua module: vim.inspector *vim.inspector*
vim.inspect_pos({bufnr}, {row}, {col}, {filter}) *vim.inspect_pos()*
Get all the items at a given buffer position.
Can also be pretty-printed with `:Inspect!`. *:Inspect!*
Parameters: ~
• {bufnr} (`integer?`) defaults to the current buffer
• {row} (`integer?`) row to inspect, 0-based. Defaults to the row of
the current cursor
• {col} (`integer?`) col to inspect, 0-based. Defaults to the col of
the current cursor
• {filter} (`table?`) Table with key-value pairs to filter the items
• {syntax} (`boolean`, default: `true`) Include syntax based
highlight groups.
• {treesitter} (`boolean`, default: `true`) Include
treesitter based highlight groups.
• {extmarks} (`boolean|"all"`, default: true) Include
extmarks. When `all`, then extmarks without a `hl_group`
will also be included.
• {semantic_tokens} (`boolean`, default: true) Include
semantic token highlights.
Return: ~
(`table`) a table with the following key-value pairs. Items are in
"traversal order":
• treesitter: a list of treesitter captures
• syntax: a list of syntax groups
• semantic_tokens: a list of semantic tokens
• extmarks: a list of extmarks
• buffer: the buffer used to get the items
• row: the row used to get the items
• col: the col used to get the items
vim.show_pos({bufnr}, {row}, {col}, {filter}) *vim.show_pos()*
Show all the items at a given buffer position.
Can also be shown with `:Inspect`. *:Inspect*
Parameters: ~
• {bufnr} (`integer?`) defaults to the current buffer
• {row} (`integer?`) row to inspect, 0-based. Defaults to the row of
the current cursor
• {col} (`integer?`) col to inspect, 0-based. Defaults to the col of
the current cursor
• {filter} (`table?`) A table with the following fields:
• {syntax} (`boolean`, default: `true`) Include syntax based
highlight groups.
• {treesitter} (`boolean`, default: `true`) Include
treesitter based highlight groups.
• {extmarks} (`boolean|"all"`, default: true) Include
extmarks. When `all`, then extmarks without a `hl_group`
will also be included.
• {semantic_tokens} (`boolean`, default: true) Include
semantic token highlights.
*vim.Ringbuf*
Fields: ~
• {clear} (`fun()`) Clear all items
• {push} (`fun(item: T)`) Adds an item, overriding the oldest item if
the buffer is full.
• {pop} (`fun(): T?`) Removes and returns the first unread item
• {peek} (`fun(): T?`) Returns the first unread item without removing
it
Ringbuf:clear() *Ringbuf:clear()*
Clear all items
Ringbuf:peek() *Ringbuf:peek()*
Returns the first unread item without removing it
Return: ~
(`any?`)
Ringbuf:pop() *Ringbuf:pop()*
Removes and returns the first unread item
Return: ~
(`any?`)
Ringbuf:push({item}) *Ringbuf:push()*
Adds an item, overriding the oldest item if the buffer is full.
Parameters: ~
• {item} (`any`)
vim.deep_equal({a}, {b}) *vim.deep_equal()*
Deep compare values for equality
Tables are compared recursively unless they both provide the `eq`
metamethod. All other types are compared using the equality `==` operator.
Parameters: ~
• {a} (`any`) First value
• {b} (`any`) Second value
Return: ~
(`boolean`) `true` if values are equals, else `false`
vim.deepcopy({orig}, {noref}) *vim.deepcopy()*
Returns a deep copy of the given object. Non-table objects are copied as
in a typical Lua assignment, whereas table objects are copied recursively.
Functions are naively copied, so functions in the copied table point to
the same functions as those in the input table. Userdata and threads are
not copied and will throw an error.
Note: `noref=true` is much more performant on tables with unique table
fields, while `noref=false` is more performant on tables that reuse table
fields.
Parameters: ~
• {orig} (`table`) Table to copy
• {noref} (`boolean?`) When `false` (default) a contained table is only
copied once and all references point to this single copy.
When `true` every occurrence of a table results in a new
copy. This also means that a cyclic reference can cause
`deepcopy()` to fail.
Return: ~
(`table`) Table of copied keys and (nested) values.
vim.defaulttable({createfn}) *vim.defaulttable()*
Creates a table whose missing keys are provided by {createfn} (like
Python's "defaultdict").
If {createfn} is `nil` it defaults to defaulttable() itself, so accessing
nested keys creates nested tables: >lua
local a = vim.defaulttable()
a.b.c = 1
<
Parameters: ~
• {createfn} (`fun(key:any):any?`) Provides the value for a missing
`key`.
Return: ~
(`table`) Empty table with `__index` metamethod.
vim.endswith({s}, {suffix}) *vim.endswith()*
Tests if `s` ends with `suffix`.
Parameters: ~
• {s} (`string`) String
• {suffix} (`string`) Suffix to match
Return: ~
(`boolean`) `true` if `suffix` is a suffix of `s`
vim.gsplit({s}, {sep}, {opts}) *vim.gsplit()*
Gets an |iterator| that splits a string at each instance of a separator,
in "lazy" fashion (as opposed to |vim.split()| which is "eager").
Example: >lua
for s in vim.gsplit(':aa::b:', ':', {plain=true}) do
print(s)
end
<
If you want to also inspect the separator itself (instead of discarding
it), use |string.gmatch()|. Example: >lua
for word, num in ('foo111bar222'):gmatch('([^0-9]*)(%d*)') do
print(('word: %s num: %s'):format(word, num))
end
<
Parameters: ~
• {s} (`string`) String to split
• {sep} (`string`) Separator or pattern
• {opts} (`table?`) Keyword arguments |kwargs|:
• {plain}? (`boolean`) Use `sep` literally (as in
string.find).
• {trimempty}? (`boolean`) Discard empty segments at start and
end of the sequence.
Return: ~
(`fun():string?`) Iterator over the split components
See also: ~
• |string.gmatch()|
• |vim.split()|
• |lua-patterns|
• https://www.lua.org/pil/20.2.html
• http://lua-users.org/wiki/StringLibraryTutorial
vim.is_callable({f}) *vim.is_callable()*
Returns true if object `f` can be called as a function.
Parameters: ~
• {f} (`any`) Any object
Return: ~
(`boolean`) `true` if `f` is callable, else `false`
vim.isarray({t}) *vim.isarray()*
Tests if `t` is an "array": a table indexed only by integers (potentially
non-contiguous).
If the indexes start from 1 and are contiguous then the array is also a
list. |vim.islist()|
Empty table `{}` is an array, unless it was created by |vim.empty_dict()|
or returned as a dict-like |API| or Vimscript result, for example from
|rpcrequest()| or |vim.fn|.
Parameters: ~
• {t} (`table?`)
Return: ~
(`boolean`) `true` if array-like table, else `false`.
See also: ~
• https://github.com/openresty/luajit2#tableisarray
vim.islist({t}) *vim.islist()*
Tests if `t` is a "list": a table indexed only by contiguous integers
starting from 1 (what |lua-length| calls a "regular array").
Empty table `{}` is a list, unless it was created by |vim.empty_dict()| or
returned as a dict-like |API| or Vimscript result, for example from
|rpcrequest()| or |vim.fn|.
Parameters: ~
• {t} (`table?`)
Return: ~
(`boolean`) `true` if list-like table, else `false`.
See also: ~
• |vim.isarray()|
vim.list_contains({t}, {value}) *vim.list_contains()*
Checks if a list-like table (integer keys without gaps) contains `value`.
Parameters: ~
• {t} (`table`) Table to check (must be list-like, not validated)
• {value} (`any`) Value to compare
Return: ~
(`boolean`) `true` if `t` contains `value`
See also: ~
• |vim.tbl_contains()| for checking values in general tables
vim.list_extend({dst}, {src}, {start}, {finish}) *vim.list_extend()*
Extends a list-like table with the values of another list-like table.
NOTE: This mutates dst!
Parameters: ~
• {dst} (`table`) List which will be modified and appended to
• {src} (`table`) List from which values will be inserted
• {start} (`integer?`) Start index on src. Defaults to 1
• {finish} (`integer?`) Final index on src. Defaults to `#src`
Return: ~
(`table`) dst
See also: ~
• |vim.tbl_extend()|
vim.list_slice({list}, {start}, {finish}) *vim.list_slice()*
Creates a copy of a table containing only elements from start to end
(inclusive)
Parameters: ~
• {list} (`any[]`) Table
• {start} (`integer?`) Start range of slice
• {finish} (`integer?`) End range of slice
Return: ~
(`any[]`) Copy of table sliced from start to finish (inclusive)
vim.pesc({s}) *vim.pesc()*
Escapes magic chars in |lua-patterns|.
Parameters: ~
• {s} (`string`) String to escape
Return: ~
(`string`) %-escaped pattern string
See also: ~
• https://github.com/rxi/lume
vim.ringbuf({size}) *vim.ringbuf()*
Create a ring buffer limited to a maximal number of items. Once the buffer
is full, adding a new entry overrides the oldest entry. >lua
local ringbuf = vim.ringbuf(4)
ringbuf:push("a")
ringbuf:push("b")
ringbuf:push("c")
ringbuf:push("d")
ringbuf:push("e") -- overrides "a"
print(ringbuf:pop()) -- returns "b"
print(ringbuf:pop()) -- returns "c"
-- Can be used as iterator. Pops remaining items:
for val in ringbuf do
print(val)
end
<
Returns a Ringbuf instance with the following methods:
• |Ringbuf:push()|
• |Ringbuf:pop()|
• |Ringbuf:peek()|
• |Ringbuf:clear()|
Parameters: ~
• {size} (`integer`)
Return: ~
(`vim.Ringbuf`) ringbuf See |vim.Ringbuf|.
vim.spairs({t}) *vim.spairs()*
Enumerates key-value pairs of a table, ordered by key.
Parameters: ~
• {t} (`table`) Dict-like table
Return (multiple): ~
(`fun(table: table<K, V>, index?: K):K, V`) |for-in| iterator over
sorted keys and their values
(`table`)
See also: ~
• Based on
https://github.com/premake/premake-core/blob/master/src/base/table.lua
vim.split({s}, {sep}, {opts}) *vim.split()*
Splits a string at each instance of a separator and returns the result as
a table (unlike |vim.gsplit()|).
Examples: >lua
split(":aa::b:", ":") --> {'','aa','','b',''}
split("axaby", "ab?") --> {'','x','y'}
split("x*yz*o", "*", {plain=true}) --> {'x','yz','o'}
split("|x|y|z|", "|", {trimempty=true}) --> {'x', 'y', 'z'}
<
Parameters: ~
• {s} (`string`) String to split
• {sep} (`string`) Separator or pattern
• {opts} (`table?`) Keyword arguments |kwargs|:
• {plain}? (`boolean`) Use `sep` literally (as in
string.find).
• {trimempty}? (`boolean`) Discard empty segments at start and
end of the sequence.
Return: ~
(`string[]`) List of split components
See also: ~
• |vim.gsplit()|
• |string.gmatch()|
vim.startswith({s}, {prefix}) *vim.startswith()*
Tests if `s` starts with `prefix`.
Parameters: ~
• {s} (`string`) String
• {prefix} (`string`) Prefix to match
Return: ~
(`boolean`) `true` if `prefix` is a prefix of `s`
vim.tbl_contains({t}, {value}, {opts}) *vim.tbl_contains()*
Checks if a table contains a given value, specified either directly or via
a predicate that is checked for each value.
Example: >lua
vim.tbl_contains({ 'a', { 'b', 'c' } }, function(v)
return vim.deep_equal(v, { 'b', 'c' })
end, { predicate = true })
-- true
<
Parameters: ~
• {t} (`table`) Table to check
• {value} (`any`) Value to compare or predicate function reference
• {opts} (`table?`) Keyword arguments |kwargs|:
• {predicate}? (`boolean`) `value` is a function reference to
be checked (default false)
Return: ~
(`boolean`) `true` if `t` contains `value`
See also: ~
• |vim.list_contains()| for checking values in list-like tables
vim.tbl_count({t}) *vim.tbl_count()*
Counts the number of non-nil values in table `t`. >lua
vim.tbl_count({ a=1, b=2 }) --> 2
vim.tbl_count({ 1, 2 }) --> 2
<
Parameters: ~
• {t} (`table`) Table
Return: ~
(`integer`) Number of non-nil values in table
See also: ~
• https://github.com/Tieske/Penlight/blob/master/lua/pl/tablex.lua
vim.tbl_deep_extend({behavior}, {...}) *vim.tbl_deep_extend()*
Merges recursively two or more tables.
Parameters: ~
• {behavior} (`'error'|'keep'|'force'`) Decides what to do if a key is
found in more than one map:
• "error": raise an error
• "keep": use value from the leftmost map
• "force": use value from the rightmost map
• {...} (`table`) Two or more tables
Return: ~
(`table`) Merged table
See also: ~
• |vim.tbl_extend()|
vim.tbl_extend({behavior}, {...}) *vim.tbl_extend()*
Merges two or more tables.
Parameters: ~
• {behavior} (`'error'|'keep'|'force'`) Decides what to do if a key is
found in more than one map:
• "error": raise an error
• "keep": use value from the leftmost map
• "force": use value from the rightmost map
• {...} (`table`) Two or more tables
Return: ~
(`table`) Merged table
See also: ~
• |extend()|
vim.tbl_filter({func}, {t}) *vim.tbl_filter()*
Filter a table using a predicate function
Parameters: ~
• {func} (`function`) Function
• {t} (`table`) Table
Return: ~
(`any[]`) Table of filtered values
vim.tbl_get({o}, {...}) *vim.tbl_get()*
Index into a table (first argument) via string keys passed as subsequent
arguments. Return `nil` if the key does not exist.
Examples: >lua
vim.tbl_get({ key = { nested_key = true }}, 'key', 'nested_key') == true
vim.tbl_get({ key = {}}, 'key', 'nested_key') == nil
<
Parameters: ~
• {o} (`table`) Table to index
• {...} (`any`) Optional keys (0 or more, variadic) via which to index
the table
Return: ~
(`any`) Nested value indexed by key (if it exists), else nil
vim.tbl_isempty({t}) *vim.tbl_isempty()*
Checks if a table is empty.
Parameters: ~
• {t} (`table`) Table to check
Return: ~
(`boolean`) `true` if `t` is empty
See also: ~
• https://github.com/premake/premake-core/blob/master/src/base/table.lua
vim.tbl_keys({t}) *vim.tbl_keys()*
Return a list of all keys used in a table. However, the order of the
return table of keys is not guaranteed.
Parameters: ~
• {t} (`table`) Table
Return: ~
(`any[]`) List of keys
See also: ~
• From
https://github.com/premake/premake-core/blob/master/src/base/table.lua
vim.tbl_map({func}, {t}) *vim.tbl_map()*
Apply a function to all values of a table.
Parameters: ~
• {func} (`fun(value: T): any`) Function
• {t} (`table<any, T>`) Table
Return: ~
(`table`) Table of transformed values
vim.tbl_values({t}) *vim.tbl_values()*
Return a list of all values used in a table. However, the order of the
return table of values is not guaranteed.
Parameters: ~
• {t} (`table`) Table
Return: ~
(`any[]`) List of values
vim.trim({s}) *vim.trim()*
Trim whitespace (Lua pattern "%s") from both sides of a string.
Parameters: ~
• {s} (`string`) String to trim
Return: ~
(`string`) String with whitespace removed from its beginning and end
See also: ~
• |lua-patterns|
• https://www.lua.org/pil/20.2.html
vim.validate({opt}) *vim.validate()*
Validates a parameter specification (types and values). Specs are
evaluated in alphanumeric order, until the first failure.
Usage example: >lua
function user.new(name, age, hobbies)
vim.validate{
name={name, 'string'},
age={age, 'number'},
hobbies={hobbies, 'table'},
}
...
end
<
Examples with explicit argument values (can be run directly): >lua
vim.validate{arg1={{'foo'}, 'table'}, arg2={'foo', 'string'}}
--> NOP (success)
vim.validate{arg1={1, 'table'}}
--> error('arg1: expected table, got number')
vim.validate{arg1={3, function(a) return (a % 2) == 0 end, 'even number'}}
--> error('arg1: expected even number, got 3')
<
If multiple types are valid they can be given as a list. >lua
vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
-- NOP (success)
vim.validate{arg1={1, {'string', 'table'}}}
-- error('arg1: expected string|table, got number')
<
Parameters: ~
• {opt} (`table`) Names of parameters to validate. Each key is a
parameter name; each value is a tuple in one of these forms:
1. (arg_value, type_name, optional)
• arg_value: argument value
• type_name: string|table type name, one of: ("table", "t",
"string", "s", "number", "n", "boolean", "b", "function",
"f", "nil", "thread", "userdata") or list of them.
• optional: (optional) boolean, if true, `nil` is valid
2. (arg_value, fn, msg)
• arg_value: argument value
• fn: any function accepting one argument, returns true if
and only if the argument is valid. Can optionally return
an additional informative error message as the second
returned value.
• msg: (optional) error string if validation fails
==============================================================================
Lua module: vim.loader *vim.loader*
vim.loader.disable() *vim.loader.disable()*
Disables the experimental Lua module loader:
• removes the loaders
• adds the default Nvim loader
vim.loader.enable() *vim.loader.enable()*
Enables the experimental Lua module loader:
• overrides loadfile
• adds the Lua loader using the byte-compilation cache
• adds the libs loader
• removes the default Nvim loader
vim.loader.find({modname}, {opts}) *vim.loader.find()*
Finds Lua modules for the given module name.
Parameters: ~
• {modname} (`string`) Module name, or `"*"` to find the top-level
modules instead
• {opts} (`table?`) Options for finding a module:
• {rtp}? (`boolean`, default: `true`) Search for modname in
the runtime path.
• {paths}? (`string[]`, default: `{}`) Extra paths to
search for modname
• {patterns}? (`string[]`, default:
`{"/init.lua", ".lua"}`) List of patterns to use when
searching for modules. A pattern is a string added to the
basename of the Lua module being searched.
• {all}? (`boolean`, default: `false`) Search for all
matches.
Return: ~
(`table[]`) A list of objects with the following fields:
• {modpath} (`string`) Path of the module
• {modname} (`string`) Name of the module
• {stat}? (`uv.uv_fs_t`) The fs_stat of the module path. Won't be
returned for `modname="*"`
vim.loader.reset({path}) *vim.loader.reset()*
Resets the cache for the path, or all the paths if path is nil.
Parameters: ~
• {path} (`string?`) path to reset
==============================================================================
Lua module: vim.uri *vim.uri*
vim.uri_decode({str}) *vim.uri_decode()*
URI-decodes a string containing percent escapes.
Parameters: ~
• {str} (`string`) string to decode
Return: ~
(`string`) decoded string
vim.uri_encode({str}, {rfc}) *vim.uri_encode()*
URI-encodes a string using percent escapes.
Parameters: ~
• {str} (`string`) string to encode
• {rfc} (`"rfc2396"|"rfc2732"|"rfc3986"?`)
Return: ~
(`string`) encoded string
vim.uri_from_bufnr({bufnr}) *vim.uri_from_bufnr()*
Gets a URI from a bufnr.
Parameters: ~
• {bufnr} (`integer`)
Return: ~
(`string`) URI
vim.uri_from_fname({path}) *vim.uri_from_fname()*
Gets a URI from a file path.
Parameters: ~
• {path} (`string`) Path to file
Return: ~
(`string`) URI
vim.uri_to_bufnr({uri}) *vim.uri_to_bufnr()*
Gets the buffer for a uri. Creates a new unloaded buffer if no buffer for
the uri already exists.
Parameters: ~
• {uri} (`string`)
Return: ~
(`integer`) bufnr
vim.uri_to_fname({uri}) *vim.uri_to_fname()*
Gets a filename from a URI.
Parameters: ~
• {uri} (`string`)
Return: ~
(`string`) filename or unchanged URI for non-file URIs
==============================================================================
Lua module: vim.ui *vim.ui*
vim.ui.input({opts}, {on_confirm}) *vim.ui.input()*
Prompts the user for input, allowing arbitrary (potentially asynchronous)
work until `on_confirm`.
Example: >lua
vim.ui.input({ prompt = 'Enter value for shiftwidth: ' }, function(input)
vim.o.shiftwidth = tonumber(input)
end)
<
Parameters: ~
• {opts} (`table?`) Additional options. See |input()|
• prompt (string|nil) Text of the prompt
• default (string|nil) Default reply to the input
• completion (string|nil) Specifies type of completion
supported for input. Supported types are the same that
can be supplied to a user-defined command using the
"-complete=" argument. See |:command-completion|
• highlight (function) Function that will be used for
highlighting user inputs.
• {on_confirm} (`function`) ((input|nil) -> ()) Called once the user
confirms or abort the input. `input` is what the user
typed (it might be an empty string if nothing was
entered), or `nil` if the user aborted the dialog.
vim.ui.open({path}) *vim.ui.open()*
Opens `path` with the system default handler (macOS `open`, Windows
`explorer.exe`, Linux `xdg-open`, …), or returns (but does not show) an
error message on failure.
Expands "~/" and environment variables in filesystem paths.
Examples: >lua
-- Asynchronous.
vim.ui.open("https://neovim.io/")
vim.ui.open("~/path/to/file")
-- Synchronous (wait until the process exits).
local cmd, err = vim.ui.open("$VIMRUNTIME")
if cmd then
cmd:wait()
end
<
Parameters: ~
• {path} (`string`) Path or URL to open
Return (multiple): ~
(`vim.SystemObj?`) Command object, or nil if not found.
(`string?`) Error message on failure, or nil on success.
See also: ~
• |vim.system()|
vim.ui.select({items}, {opts}, {on_choice}) *vim.ui.select()*
Prompts the user to pick from a list of items, allowing arbitrary
(potentially asynchronous) work until `on_choice`.
Example: >lua
vim.ui.select({ 'tabs', 'spaces' }, {
prompt = 'Select tabs or spaces:',
format_item = function(item)
return "I'd like to choose " .. item
end,
}, function(choice)
if choice == 'spaces' then
vim.o.expandtab = true
else
vim.o.expandtab = false
end
end)
<
Parameters: ~
• {items} (`any[]`) Arbitrary items
• {opts} (`table`) Additional options
• prompt (string|nil) Text of the prompt. Defaults to
`Select one of:`
• format_item (function item -> text) Function to format
an individual item from `items`. Defaults to
`tostring`.
• kind (string|nil) Arbitrary hint string indicating the
item shape. Plugins reimplementing `vim.ui.select` may
wish to use this to infer the structure or semantics of
`items`, or the context in which select() was called.
• {on_choice} (`fun(item: any?, idx: integer?)`) Called once the user
made a choice. `idx` is the 1-based index of `item`
within `items`. `nil` if the user aborted the dialog.
==============================================================================
Lua module: vim.filetype *vim.filetype*
vim.filetype.add({filetypes}) *vim.filetype.add()*
Add new filetype mappings.
Filetype mappings can be added either by extension or by filename (either
the "tail" or the full file path). The full file path is checked first,
followed by the file name. If a match is not found using the filename,
then the filename is matched against the list of |lua-patterns| (sorted by
priority) until a match is found. Lastly, if pattern matching does not
find a filetype, then the file extension is used.
The filetype can be either a string (in which case it is used as the
filetype directly) or a function. If a function, it takes the full path
and buffer number of the file as arguments (along with captures from the
matched pattern, if any) and should return a string that will be used as
the buffer's filetype. Optionally, the function can return a second
function value which, when called, modifies the state of the buffer. This
can be used to, for example, set filetype-specific buffer variables. This
function will be called by Nvim before setting the buffer's filetype.
Filename patterns can specify an optional priority to resolve cases when a
file path matches multiple patterns. Higher priorities are matched first.
When omitted, the priority defaults to 0. A pattern can contain
environment variables of the form "${SOME_VAR}" that will be automatically
expanded. If the environment variable is not set, the pattern won't be
matched.
See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
Example: >lua
vim.filetype.add({
extension = {
foo = 'fooscript',
bar = function(path, bufnr)
if some_condition() then
return 'barscript', function(bufnr)
-- Set a buffer variable
vim.b[bufnr].barscript_version = 2
end
end
return 'bar'
end,
},
filename = {
['.foorc'] = 'toml',
['/etc/foo/config'] = 'toml',
},
pattern = {
['.*/etc/foo/.*'] = 'fooscript',
-- Using an optional priority
['.*/etc/foo/.*%.conf'] = { 'dosini', { priority = 10 } },
-- A pattern containing an environment variable
['${XDG_CONFIG_HOME}/foo/git'] = 'git',
['README.(%a+)$'] = function(path, bufnr, ext)
if ext == 'md' then
return 'markdown'
elseif ext == 'rst' then
return 'rst'
end
end,
},
})
<
To add a fallback match on contents, use >lua
vim.filetype.add {
pattern = {
['.*'] = {
function(path, bufnr)
local content = vim.api.nvim_buf_get_lines(bufnr, 0, 1, false)[1] or ''
if vim.regex([[^#!.*\\<mine\\>]]):match_str(content) ~= nil then
return 'mine'
elseif vim.regex([[\\<drawing\\>]]):match_str(content) ~= nil then
return 'drawing'
end
end,
{ priority = -math.huge },
},
},
}
<
Parameters: ~
• {filetypes} (`table`) A table containing new filetype maps (see
example).
• {pattern}? (`vim.filetype.mapping`)
• {extension}? (`vim.filetype.mapping`)
• {filename}? (`vim.filetype.mapping`)
*vim.filetype.get_option()*
vim.filetype.get_option({filetype}, {option})
Get the default option value for a {filetype}.
The returned value is what would be set in a new buffer after 'filetype'
is set, meaning it should respect all FileType autocmds and ftplugin
files.
Example: >lua
vim.filetype.get_option('vim', 'commentstring')
<
Note: this uses |nvim_get_option_value()| but caches the result. This
means |ftplugin| and |FileType| autocommands are only triggered once and
may not reflect later changes.
Parameters: ~
• {filetype} (`string`) Filetype
• {option} (`string`) Option name
Return: ~
(`string|boolean|integer`) Option value
vim.filetype.match({args}) *vim.filetype.match()*
Perform filetype detection.
The filetype can be detected using one of three methods:
1. Using an existing buffer
2. Using only a file name
3. Using only file contents
Of these, option 1 provides the most accurate result as it uses both the
buffer's filename and (optionally) the buffer contents. Options 2 and 3
can be used without an existing buffer, but may not always provide a match
in cases where the filename (or contents) cannot unambiguously determine
the filetype.
Each of the three options is specified using a key to the single argument
of this function. Example: >lua
-- Using a buffer number
vim.filetype.match({ buf = 42 })
-- Override the filename of the given buffer
vim.filetype.match({ buf = 42, filename = 'foo.c' })
-- Using a filename without a buffer
vim.filetype.match({ filename = 'main.lua' })
-- Using file contents
vim.filetype.match({ contents = {'#!/usr/bin/env bash'} })
<
Parameters: ~
• {args} (`table`) Table specifying which matching strategy to use.
Accepted keys are:
• {buf}? (`integer`) Buffer number to use for matching.
Mutually exclusive with {contents}
• {filename}? (`string`) Filename to use for matching. When
{buf} is given, defaults to the filename of the given buffer
number. The file need not actually exist in the filesystem.
When used without {buf} only the name of the file is used
for filetype matching. This may result in failure to detect
the filetype in cases where the filename alone is not enough
to disambiguate the filetype.
• {contents}? (`string[]`) An array of lines representing file
contents to use for matching. Can be used with {filename}.
Mutually exclusive with {buf}.
Return (multiple): ~
(`string?`) If a match was found, the matched filetype.
(`function?`) A function that modifies buffer state when called (for
example, to set some filetype specific buffer variables). The function
accepts a buffer number as its only argument.
==============================================================================
Lua module: vim.keymap *vim.keymap*
vim.keymap.del({modes}, {lhs}, {opts}) *vim.keymap.del()*
Remove an existing mapping. Examples: >lua
vim.keymap.del('n', 'lhs')
vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
<
Parameters: ~
• {modes} (`string|string[]`)
• {lhs} (`string`)
• {opts} (`table?`) A table with the following fields:
• {buffer}? (`integer|boolean`) Remove a mapping from the
given buffer. When `0` or `true`, use the current buffer.
See also: ~
• |vim.keymap.set()|
vim.keymap.set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
Adds a new |mapping|. Examples: >lua
-- Map to a Lua function:
vim.keymap.set('n', 'lhs', function() print("real lua function") end)
-- Map to multiple modes:
vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer = true })
-- Buffer-local mapping:
vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 })
-- Expr mapping:
vim.keymap.set('i', '<Tab>', function()
return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
end, { expr = true })
-- <Plug> mapping:
vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)')
<
Parameters: ~
• {mode} (`string|string[]`) Mode short-name, see |nvim_set_keymap()|.
Can also be list of modes to create mapping on multiple modes.
• {lhs} (`string`) Left-hand side |{lhs}| of the mapping.
• {rhs} (`string|function`) Right-hand side |{rhs}| of the mapping,
can be a Lua function.
• {opts} (`table?`) Table of |:map-arguments|. Same as
|nvim_set_keymap()| {opts}, except:
• {replace_keycodes} defaults to `true` if "expr" is `true`.
Also accepts:
• {buffer}? (`integer|boolean`) Creates buffer-local mapping,
`0` or `true` for current buffer.
• {remap}? (`boolean`, default: `false`) Make the mapping
recursive. Inverse of {noremap}.
See also: ~
• |nvim_set_keymap()|
• |maparg()|
• |mapcheck()|
• |mapset()|
==============================================================================
Lua module: vim.fs *vim.fs*
vim.fs.basename({file}) *vim.fs.basename()*
Return the basename of the given path
Parameters: ~
• {file} (`string?`) Path
Return: ~
(`string?`) Basename of {file}
vim.fs.dir({path}, {opts}) *vim.fs.dir()*
Return an iterator over the items located in {path}
Parameters: ~
• {path} (`string`) An absolute or relative path to the directory to
iterate over. The path is first normalized
|vim.fs.normalize()|.
• {opts} (`table?`) Optional keyword arguments:
• depth: integer|nil How deep the traverse (default 1)
• skip: (fun(dir_name: string): boolean)|nil Predicate to
control traversal. Return false to stop searching the
current directory. Only useful when depth > 1
Return: ~
(`Iterator`) over items in {path}. Each iteration yields two values:
"name" and "type". "name" is the basename of the item relative to
{path}. "type" is one of the following: "file", "directory", "link",
"fifo", "socket", "char", "block", "unknown".
vim.fs.dirname({file}) *vim.fs.dirname()*
Return the parent directory of the given path
Parameters: ~
• {file} (`string?`) Path
Return: ~
(`string?`) Parent directory of {file}
vim.fs.find({names}, {opts}) *vim.fs.find()*
Find files or directories (or other items as specified by `opts.type`) in
the given path.
Finds items given in {names} starting from {path}. If {upward} is "true"
then the search traverses upward through parent directories; otherwise,
the search traverses downward. Note that downward searches are recursive
and may search through many directories! If {stop} is non-nil, then the
search stops when the directory given in {stop} is reached. The search
terminates when {limit} (default 1) matches are found. You can set {type}
to "file", "directory", "link", "socket", "char", "block", or "fifo" to
narrow the search to find only that type.
Examples: >lua
-- list all test directories under the runtime directory
local test_dirs = vim.fs.find(
{'test', 'tst', 'testdir'},
{limit = math.huge, type = 'directory', path = './runtime/'}
)
-- get all files ending with .cpp or .hpp inside lib/
local cpp_hpp = vim.fs.find(function(name, path)
return name:match('.*%.[ch]pp$') and path:match('[/\\\\]lib$')
end, {limit = math.huge, type = 'file'})
<
Parameters: ~
• {names} (`string|string[]|fun(name: string, path: string): boolean`)
Names of the items to find. Must be base names, paths and
globs are not supported when {names} is a string or a table.
If {names} is a function, it is called for each traversed
item with args:
• name: base name of the current item
• path: full path of the current item The function should
return `true` if the given item is considered a match.
• {opts} (`table`) Optional keyword arguments:
• {path}? (`string`) Path to begin searching from. If
omitted, the |current-directory| is used.
• {upward}? (`boolean`, default: `false`) Search upward
through parent directories. Otherwise, search through child
directories (recursively).
• {stop}? (`string`) Stop searching when this directory is
reached. The directory itself is not searched.
• {type}? (`string`) Find only items of the given type. If
omitted, all items that match {names} are included.
• {limit}? (`number`, default: `1`) Stop the search after
finding this many matches. Use `math.huge` to place no
limit on the number of matches.
Return: ~
(`string[]`) Normalized paths |vim.fs.normalize()| of all matching
items
vim.fs.joinpath({...}) *vim.fs.joinpath()*
Concatenate directories and/or file paths into a single path with
normalization (e.g., `"foo/"` and `"bar"` get joined to `"foo/bar"`)
Parameters: ~
• {...} (`string`)
Return: ~
(`string`)
vim.fs.normalize({path}, {opts}) *vim.fs.normalize()*
Normalize a path to a standard format. A tilde (~) character at the
beginning of the path is expanded to the user's home directory and
environment variables are also expanded. "." and ".." components are also
resolved, except when the path is relative and trying to resolve it would
result in an absolute path.
• "." as the only part in a relative path:
• "." => "."
• "././" => "."
• ".." when it leads outside the current directory
• "foo/../../bar" => "../bar"
• "../../foo" => "../../foo"
• ".." in the root directory returns the root directory.
• "/../../" => "/"
On Windows, backslash (\) characters are converted to forward slashes (/).
Examples: >lua
[[C:\Users\jdoe]] => "C:/Users/jdoe"
"~/src/neovim" => "/home/jdoe/src/neovim"
"$XDG_CONFIG_HOME/nvim/init.vim" => "/Users/jdoe/.config/nvim/init.vim"
"~/src/nvim/api/../tui/./tui.c" => "/home/jdoe/src/nvim/tui/tui.c"
"./foo/bar" => "foo/bar"
"foo/../../../bar" => "../../bar"
"/home/jdoe/../../../bar" => "/bar"
"C:foo/../../baz" => "C:../baz"
"C:/foo/../../baz" => "C:/baz"
[[\\?\UNC\server\share\foo\..\..\..\bar]] => "//?/UNC/server/share/bar"
<
Parameters: ~
• {path} (`string`) Path to normalize
• {opts} (`table?`) A table with the following fields:
• {expand_env}? (`boolean`, default: `true`) Expand
environment variables.
• {win}? (`boolean`, default: `true` in Windows, `false`
otherwise) Path is a Windows path.
Return: ~
(`string`) Normalized path
vim.fs.parents({start}) *vim.fs.parents()*
Iterate over all the parents of the given path.
Example: >lua
local root_dir
for dir in vim.fs.parents(vim.api.nvim_buf_get_name(0)) do
if vim.fn.isdirectory(dir .. "/.git") == 1 then
root_dir = dir
break
end
end
if root_dir then
print("Found git repository at", root_dir)
end
<
Parameters: ~
• {start} (`string`) Initial path.
Return (multiple): ~
(`fun(_, dir: string): string?`) Iterator
(`nil`)
(`string?`)
vim.fs.root({source}, {marker}) *vim.fs.root()*
Find the first parent directory containing a specific "marker", relative
to a file path or buffer.
If the buffer is unnamed (has no backing file) or has a non-empty
'buftype' then the search begins from Nvim's |current-directory|.
Example: >lua
-- Find the root of a Python project, starting from file 'main.py'
vim.fs.root(vim.fs.joinpath(vim.env.PWD, 'main.py'), {'pyproject.toml', 'setup.py' })
-- Find the root of a git repository
vim.fs.root(0, '.git')
-- Find the parent directory containing any file with a .csproj extension
vim.fs.root(0, function(name, path)
return name:match('%.csproj$') ~= nil
end)
<
Parameters: ~
• {source} (`integer|string`) Buffer number (0 for current buffer) or
file path (absolute or relative to the |current-directory|)
to begin the search from.
• {marker} (`string|string[]|fun(name: string, path: string): boolean`)
A marker, or list of markers, to search for. If a function,
the function is called for each evaluated item and should
return true if {name} and {path} are a match.
Return: ~
(`string?`) Directory path containing one of the given markers, or nil
if no directory was found.
==============================================================================
Lua module: vim.glob *vim.glob*
vim.glob.to_lpeg({pattern}) *vim.glob.to_lpeg()*
Parses a raw glob into an |lua-lpeg| pattern.
This uses glob semantics from LSP 3.17.0:
https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#pattern
Glob patterns can have the following syntax:
• `*` to match one or more characters in a path segment
• `?` to match on one character in a path segment
• `**` to match any number of path segments, including none
• `{}` to group conditions (e.g. `*.{ts,js}` matches TypeScript and
JavaScript files)
• `[]` to declare a range of characters to match in a path segment (e.g.,
`example.[0-9]` to match on `example.0`, `example.1`, …)
• `[!...]` to negate a range of characters to match in a path segment
(e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not
`example.0`)
Parameters: ~
• {pattern} (`string`) The raw glob pattern
Return: ~
(`vim.lpeg.Pattern`) pattern An |lua-lpeg| representation of the
pattern
==============================================================================
VIM.LPEG *vim.lpeg*
LPeg is a pattern-matching library for Lua, based on Parsing Expression
Grammars (PEGs). https://bford.info/packrat/
*lua-lpeg* *vim.lpeg.Pattern*
The LPeg library for parsing expression grammars is included as `vim.lpeg`
(https://www.inf.puc-rio.br/~roberto/lpeg/).
In addition, its regex-like interface is available as |vim.re|
(https://www.inf.puc-rio.br/~roberto/lpeg/re.html).
Pattern:match({subject}, {init}, {...}) *Pattern:match()*
Matches the given `pattern` against the `subject` string. If the match
succeeds, returns the index in the subject of the first character after
the match, or the captured values (if the pattern captured any value). An
optional numeric argument `init` makes the match start at that position in
the subject string. As usual in Lua libraries, a negative value counts
from the end. Unlike typical pattern-matching functions, `match` works
only in anchored mode; that is, it tries to match the pattern with a
prefix of the given subject string (at position `init`), not with an
arbitrary substring of the subject. So, if we want to find a pattern
anywhere in a string, we must either write a loop in Lua or write a
pattern that matches anywhere.
Example: >lua
local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
assert(lpeg.match(pattern, 'hello') == 6)
assert(pattern:match('1 hello') == nil)
<
Parameters: ~
• {subject} (`string`)
• {init} (`integer?`)
• {...} (`any`)
Return: ~
(`any`) ...
vim.lpeg.B({pattern}) *vim.lpeg.B()*
Returns a pattern that matches only if the input string at the current
position is preceded by `patt`. Pattern `patt` must match only strings
with some fixed length, and it cannot contain captures. Like the `and`
predicate, this pattern never consumes any input, independently of success
or failure.
Parameters: ~
• {pattern} (`vim.lpeg.Pattern|string|integer|boolean|table`)
Return: ~
(`vim.lpeg.Pattern`)
vim.lpeg.C({patt}) *vim.lpeg.C()*
Creates a simple capture, which captures the substring of the subject that
matches `patt`. The captured value is a string. If `patt` has other
captures, their values are returned after this one.
Example: >lua
local function split (s, sep)
sep = lpeg.P(sep)
local elem = lpeg.C((1 - sep) ^ 0)
local p = elem * (sep * elem) ^ 0
return lpeg.match(p, s)
end
local a, b, c = split('a,b,c', ',')
assert(a == 'a')
assert(b == 'b')
assert(c == 'c')
<
Parameters: ~
• {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Carg({n}) *vim.lpeg.Carg()*
Creates an argument capture. This pattern matches the empty string and
produces the value given as the nth extra argument given in the call to
`lpeg.match`.
Parameters: ~
• {n} (`integer`)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Cb({name}) *vim.lpeg.Cb()*
Creates a back capture. This pattern matches the empty string and produces
the values produced by the most recent group capture named `name` (where
`name` can be any Lua value). Most recent means the last complete
outermost group capture with the given name. A Complete capture means that
the entire pattern corresponding to the capture has matched. An Outermost
capture means that the capture is not inside another complete capture. In
the same way that LPeg does not specify when it evaluates captures, it
does not specify whether it reuses values previously produced by the group
or re-evaluates them.
Parameters: ~
• {name} (`any`)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Cc({...}) *vim.lpeg.Cc()*
Creates a constant capture. This pattern matches the empty string and
produces all given values as its captured values.
Parameters: ~
• {...} (`any`)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Cf({patt}, {func}) *vim.lpeg.Cf()*
Creates a fold capture. If `patt` produces a list of captures C1 C2 ...
Cn, this capture will produce the value
`func(...func(func(C1, C2), C3)...,Cn)`, that is, it will fold (or
accumulate, or reduce) the captures from `patt` using function `func`.
This capture assumes that `patt` should produce at least one capture with
at least one value (of any type), which becomes the initial value of an
accumulator. (If you need a specific initial value, you may prefix a
constant capture to `patt`.) For each subsequent capture, LPeg calls
`func` with this accumulator as the first argument and all values produced
by the capture as extra arguments; the first result from this call becomes
the new value for the accumulator. The final value of the accumulator
becomes the captured value.
Example: >lua
local number = lpeg.R('09') ^ 1 / tonumber
local list = number * (',' * number) ^ 0
local function add(acc, newvalue) return acc + newvalue end
local sum = lpeg.Cf(list, add)
assert(sum:match('10,30,43') == 83)
<
Parameters: ~
• {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
• {func} (`fun(acc, newvalue)`)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Cg({patt}, {name}) *vim.lpeg.Cg()*
Creates a group capture. It groups all values returned by `patt` into a
single capture. The group may be anonymous (if no name is given) or named
with the given name (which can be any non-nil Lua value).
Parameters: ~
• {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
• {name} (`string?`)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Cmt({patt}, {fn}) *vim.lpeg.Cmt()*
Creates a match-time capture. Unlike all other captures, this one is
evaluated immediately when a match occurs (even if it is part of a larger
pattern that fails later). It forces the immediate evaluation of all its
nested captures and then calls `function`. The given function gets as
arguments the entire subject, the current position (after the match of
`patt`), plus any capture values produced by `patt`. The first value
returned by `function` defines how the match happens. If the call returns
a number, the match succeeds and the returned number becomes the new
current position. (Assuming a subject sand current position `i`, the
returned number must be in the range `[i, len(s) + 1]`.) If the call
returns `true`, the match succeeds without consuming any input (so, to
return true is equivalent to return `i`). If the call returns `false`,
`nil`, or no value, the match fails. Any extra values returned by the
function become the values produced by the capture.
Parameters: ~
• {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
• {fn} (`fun(s: string, i: integer, ...: any)`) (position:
boolean|integer, ...: any)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Cp() *vim.lpeg.Cp()*
Creates a position capture. It matches the empty string and captures the
position in the subject where the match occurs. The captured value is a
number.
Example: >lua
local I = lpeg.Cp()
local function anywhere(p) return lpeg.P({I * p * I + 1 * lpeg.V(1)}) end
local match_start, match_end = anywhere('world'):match('hello world!')
assert(match_start == 7)
assert(match_end == 12)
<
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Cs({patt}) *vim.lpeg.Cs()*
Creates a substitution capture. This function creates a substitution
capture, which captures the substring of the subject that matches `patt`,
with substitutions. For any capture inside `patt` with a value, the
substring that matched the capture is replaced by the capture value (which
should be a string). The final captured value is the string resulting from
all replacements.
Example: >lua
local function gsub (s, patt, repl)
patt = lpeg.P(patt)
patt = lpeg.Cs((patt / repl + 1) ^ 0)
return lpeg.match(patt, s)
end
assert(gsub('Hello, xxx!', 'xxx', 'World') == 'Hello, World!')
<
Parameters: ~
• {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.Ct({patt}) *vim.lpeg.Ct()*
Creates a table capture. This capture returns a table with all values from
all anonymous captures made by `patt` inside this table in successive
integer keys, starting at 1. Moreover, for each named capture group
created by `patt`, the first value of the group is put into the table with
the group name as its key. The captured value is only the table.
Parameters: ~
• {patt} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
Return: ~
(`vim.lpeg.Capture`)
vim.lpeg.locale({tab}) *vim.lpeg.locale()*
Returns a table with patterns for matching some character classes
according to the current locale. The table has fields named `alnum`,
`alpha`, `cntrl`, `digit`, `graph`, `lower`, `print`, `punct`, `space`,
`upper`, and `xdigit`, each one containing a correspondent pattern. Each
pattern matches any single character that belongs to its class. If called
with an argument `table`, then it creates those fields inside the given
table and returns that table.
Example: >lua
lpeg.locale(lpeg)
local space = lpeg.space ^ 0
local name = lpeg.C(lpeg.alpha ^ 1) * space
local sep = lpeg.S(',;') * space
local pair = lpeg.Cg(name * '=' * space * name) * sep ^ -1
local list = lpeg.Cf(lpeg.Ct('') * pair ^ 0, rawset)
local t = list:match('a=b, c = hi; next = pi')
assert(t.a == 'b')
assert(t.c == 'hi')
assert(t.next == 'pi')
local locale = lpeg.locale()
assert(type(locale.digit) == 'userdata')
<
Parameters: ~
• {tab} (`table?`)
Return: ~
(`vim.lpeg.Locale`)
vim.lpeg.match({pattern}, {subject}, {init}, {...}) *vim.lpeg.match()*
Matches the given `pattern` against the `subject` string. If the match
succeeds, returns the index in the subject of the first character after
the match, or the captured values (if the pattern captured any value). An
optional numeric argument `init` makes the match start at that position in
the subject string. As usual in Lua libraries, a negative value counts
from the end. Unlike typical pattern-matching functions, `match` works
only in anchored mode; that is, it tries to match the pattern with a
prefix of the given subject string (at position `init`), not with an
arbitrary substring of the subject. So, if we want to find a pattern
anywhere in a string, we must either write a loop in Lua or write a
pattern that matches anywhere.
Example: >lua
local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
assert(lpeg.match(pattern, 'hello') == 6)
assert(pattern:match('1 hello') == nil)
<
Parameters: ~
• {pattern} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
• {subject} (`string`)
• {init} (`integer?`)
• {...} (`any`)
Return: ~
(`any`) ...
vim.lpeg.P({value}) *vim.lpeg.P()*
Converts the given value into a proper pattern. The following rules are
applied:
• If the argument is a pattern, it is returned unmodified.
• If the argument is a string, it is translated to a pattern that matches
the string literally.
• If the argument is a non-negative number `n`, the result is a pattern
that matches exactly `n` characters.
• If the argument is a negative number `-n`, the result is a pattern that
succeeds only if the input string has less than `n` characters left:
`lpeg.P(-n)` is equivalent to `-lpeg.P(n)` (see the unary minus
operation).
• If the argument is a boolean, the result is a pattern that always
succeeds or always fails (according to the boolean value), without
consuming any input.
• If the argument is a table, it is interpreted as a grammar (see
Grammars).
• If the argument is a function, returns a pattern equivalent to a
match-time capture over the empty string.
Parameters: ~
• {value} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
Return: ~
(`vim.lpeg.Pattern`)
vim.lpeg.R({...}) *vim.lpeg.R()*
Returns a pattern that matches any single character belonging to one of
the given ranges. Each `range` is a string `xy` of length 2, representing
all characters with code between the codes of `x` and `y` (both
inclusive). As an example, the pattern `lpeg.R('09')` matches any digit,
and `lpeg.R('az', 'AZ')` matches any ASCII letter.
Example: >lua
local pattern = lpeg.R('az') ^ 1 * -1
assert(pattern:match('hello') == 6)
<
Parameters: ~
• {...} (`string`)
Return: ~
(`vim.lpeg.Pattern`)
vim.lpeg.S({string}) *vim.lpeg.S()*
Returns a pattern that matches any single character that appears in the
given string (the `S` stands for Set). As an example, the pattern
`lpeg.S('+-*/')` matches any arithmetic operator. Note that, if `s` is a
character (that is, a string of length 1), then `lpeg.P(s)` is equivalent
to `lpeg.S(s)` which is equivalent to `lpeg.R(s..s)`. Note also that both
`lpeg.S('')` and `lpeg.R()` are patterns that always fail.
Parameters: ~
• {string} (`string`)
Return: ~
(`vim.lpeg.Pattern`)
vim.lpeg.setmaxstack({max}) *vim.lpeg.setmaxstack()*
Sets a limit for the size of the backtrack stack used by LPeg to track
calls and choices. The default limit is `400`. Most well-written patterns
need little backtrack levels and therefore you seldom need to change this
limit; before changing it you should try to rewrite your pattern to avoid
the need for extra space. Nevertheless, a few useful patterns may
overflow. Also, with recursive grammars, subjects with deep recursion may
also need larger limits.
Parameters: ~
• {max} (`integer`)
vim.lpeg.type({value}) *vim.lpeg.type()*
Returns the string `"pattern"` if the given value is a pattern, otherwise
`nil`.
Parameters: ~
• {value} (`vim.lpeg.Pattern|string|integer|boolean|table|function`)
Return: ~
(`"pattern"?`)
vim.lpeg.V({v}) *vim.lpeg.V()*
Creates a non-terminal (a variable) for a grammar. This operation creates
a non-terminal (a variable) for a grammar. The created non-terminal refers
to the rule indexed by `v` in the enclosing grammar.
Example: >lua
local b = lpeg.P({'(' * ((1 - lpeg.S '()') + lpeg.V(1)) ^ 0 * ')'})
assert(b:match('((string))') == 11)
assert(b:match('(') == nil)
<
Parameters: ~
• {v} (`boolean|string|number|function|table|thread|userdata|lightuserdata`)
Return: ~
(`vim.lpeg.Pattern`)
vim.lpeg.version() *vim.lpeg.version()*
Returns a string with the running version of LPeg.
Return: ~
(`string`)
==============================================================================
VIM.RE *vim.re*
The `vim.re` module provides a conventional regex-like syntax for pattern
usage within LPeg |vim.lpeg|. (Unrelated to |vim.regex| which provides Vim
|regexp| from Lua.)
See https://www.inf.puc-rio.br/~roberto/lpeg/re.html for the original
documentation including regex syntax and examples.
vim.re.compile({string}, {defs}) *vim.re.compile()*
Compiles the given {string} and returns an equivalent LPeg pattern. The
given string may define either an expression or a grammar. The optional
{defs} table provides extra Lua values to be used by the pattern.
Parameters: ~
• {string} (`string`)
• {defs} (`table?`)
Return: ~
(`vim.lpeg.Pattern`)
vim.re.find({subject}, {pattern}, {init}) *vim.re.find()*
Searches the given {pattern} in the given {subject}. If it finds a match,
returns the index where this occurrence starts and the index where it
ends. Otherwise, returns nil.
An optional numeric argument {init} makes the search starts at that
position in the subject string. As usual in Lua libraries, a negative
value counts from the end.
Parameters: ~
• {subject} (`string`)
• {pattern} (`vim.lpeg.Pattern|string`)
• {init} (`integer?`)
Return (multiple): ~
(`integer?`) the index where the occurrence starts, nil if no match
(`integer?`) the index where the occurrence ends, nil if no match
vim.re.gsub({subject}, {pattern}, {replacement}) *vim.re.gsub()*
Does a global substitution, replacing all occurrences of {pattern} in the
given {subject} by {replacement}.
Parameters: ~
• {subject} (`string`)
• {pattern} (`vim.lpeg.Pattern|string`)
• {replacement} (`string`)
Return: ~
(`string`)
vim.re.match({subject}, {pattern}, {init}) *vim.re.match()*
Matches the given {pattern} against the given {subject}, returning all
captures.
Parameters: ~
• {subject} (`string`)
• {pattern} (`vim.lpeg.Pattern|string`)
• {init} (`integer?`)
Return: ~
(`integer|vim.lpeg.Capture?`)
See also: ~
• vim.lpeg.match()
vim.re.updatelocale() *vim.re.updatelocale()*
Updates the pre-defined character classes to the current locale.
==============================================================================
VIM.REGEX *vim.regex*
Vim regexes can be used directly from Lua. Currently they only allow matching
within a single line.
*regex:match_line()*
regex:match_line({bufnr}, {line_idx}, {start}, {end_})
Match line {line_idx} (zero-based) in buffer {bufnr}. If {start} and {end}
are supplied, match only this byte index range. Otherwise see
|regex:match_str()|. If {start} is used, then the returned byte indices
will be relative {start}.
Parameters: ~
• {bufnr} (`integer`)
• {line_idx} (`integer`)
• {start} (`integer?`)
• {end_} (`integer?`)
regex:match_str({str}) *regex:match_str()*
Match the string against the regex. If the string should match the regex
precisely, surround the regex with `^` and `$`. If there was a match, the
byte indices for the beginning and end of the match are returned. When
there is no match, `nil` is returned. Because any integer is "truthy",
`regex:match_str()` can be directly used as a condition in an
if-statement.
Parameters: ~
• {str} (`string`)
vim.regex({re}) *vim.regex()*
Parse the Vim regex {re} and return a regex object. Regexes are "magic"
and case-sensitive by default, regardless of 'magic' and 'ignorecase'.
They can be controlled with flags, see |/magic| and |/ignorecase|.
Parameters: ~
• {re} (`string`)
Return: ~
(`vim.regex`)
==============================================================================
Lua module: vim.secure *vim.secure*
vim.secure.read({path}) *vim.secure.read()*
Attempt to read the file at {path} prompting the user if the file should
be trusted. The user's choice is persisted in a trust database at
$XDG_STATE_HOME/nvim/trust.
Parameters: ~
• {path} (`string`) Path to a file to read.
Return: ~
(`string?`) The contents of the given file if it exists and is
trusted, or nil otherwise.
See also: ~
• |:trust|
vim.secure.trust({opts}) *vim.secure.trust()*
Manage the trust database.
The trust database is located at |$XDG_STATE_HOME|/nvim/trust.
Parameters: ~
• {opts} (`table`) A table with the following fields:
• {action} (`'allow'|'deny'|'remove'`) - `'allow'` to add a
file to the trust database and trust it,
• `'deny'` to add a file to the trust database and deny it,
• `'remove'` to remove file from the trust database
• {path}? (`string`) Path to a file to update. Mutually
exclusive with {bufnr}. Cannot be used when {action} is
"allow".
• {bufnr}? (`integer`) Buffer number to update. Mutually
exclusive with {path}.
Return (multiple): ~
(`boolean`) success true if operation was successful
(`string`) msg full path if operation was successful, else error
message
==============================================================================
Lua module: vim.version *vim.version*
The `vim.version` module provides functions for comparing versions and ranges
conforming to the https://semver.org spec. Plugins, and plugin managers, can
use this to check available tools and dependencies on the current system.
Example: >lua
local v = vim.version.parse(vim.fn.system({'tmux', '-V'}), {strict=false})
if vim.version.gt(v, {3, 2, 0}) then
-- ...
end
<
*vim.version()* returns the version of the current Nvim process.
VERSION RANGE SPEC *version-range*
A version "range spec" defines a semantic version range which can be tested
against a version, using |vim.version.range()|.
Supported range specs are shown in the following table. Note: suffixed
versions (1.2.3-rc1) are not matched. >
1.2.3 is 1.2.3
=1.2.3 is 1.2.3
>1.2.3 greater than 1.2.3
<1.2.3 before 1.2.3
>=1.2.3 at least 1.2.3
~1.2.3 is >=1.2.3 <1.3.0 "reasonably close to 1.2.3"
^1.2.3 is >=1.2.3 <2.0.0 "compatible with 1.2.3"
^0.2.3 is >=0.2.3 <0.3.0 (0.x.x is special)
^0.0.1 is =0.0.1 (0.0.x is special)
^1.2 is >=1.2.0 <2.0.0 (like ^1.2.0)
~1.2 is >=1.2.0 <1.3.0 (like ~1.2.0)
^1 is >=1.0.0 <2.0.0 "compatible with 1"
~1 same "reasonably close to 1"
1.x same
1.* same
1 same
* any version
x same
1.2.3 - 2.3.4 is >=1.2.3 <=2.3.4
Partial right: missing pieces treated as x (2.3 => 2.3.x).
1.2.3 - 2.3 is >=1.2.3 <2.4.0
1.2.3 - 2 is >=1.2.3 <3.0.0
Partial left: missing pieces treated as 0 (1.2 => 1.2.0).
1.2 - 2.3.0 is 1.2.0 - 2.3.0
<
vim.version.cmp({v1}, {v2}) *vim.version.cmp()*
Parses and compares two version objects (the result of
|vim.version.parse()|, or specified literally as a `{major, minor, patch}`
tuple, e.g. `{1, 0, 3}`).
Example: >lua
if vim.version.cmp({1,0,3}, {0,2,1}) == 0 then
-- ...
end
local v1 = vim.version.parse('1.0.3-pre')
local v2 = vim.version.parse('0.2.1')
if vim.version.cmp(v1, v2) == 0 then
-- ...
end
<
Note: ~
• Per semver, build metadata is ignored when comparing two
otherwise-equivalent versions.
Parameters: ~
• {v1} (`vim.Version|number[]|string`) Version object.
• {v2} (`vim.Version|number[]|string`) Version to compare with `v1`.
Return: ~
(`integer`) -1 if `v1 < v2`, 0 if `v1 == v2`, 1 if `v1 > v2`.
vim.version.eq({v1}, {v2}) *vim.version.eq()*
Returns `true` if the given versions are equal. See |vim.version.cmp()|
for usage.
Parameters: ~
• {v1} (`vim.Version|number[]|string`)
• {v2} (`vim.Version|number[]|string`)
Return: ~
(`boolean`)
vim.version.ge({v1}, {v2}) *vim.version.ge()*
Returns `true` if `v1 >= v2`. See |vim.version.cmp()| for usage.
Parameters: ~
• {v1} (`vim.Version|number[]|string`)
• {v2} (`vim.Version|number[]|string`)
Return: ~
(`boolean`)
vim.version.gt({v1}, {v2}) *vim.version.gt()*
Returns `true` if `v1 > v2`. See |vim.version.cmp()| for usage.
Parameters: ~
• {v1} (`vim.Version|number[]|string`)
• {v2} (`vim.Version|number[]|string`)
Return: ~
(`boolean`)
vim.version.last({versions}) *vim.version.last()*
TODO: generalize this, move to func.lua
Parameters: ~
• {versions} (`vim.Version[]`)
Return: ~
(`vim.Version?`)
vim.version.le({v1}, {v2}) *vim.version.le()*
Returns `true` if `v1 <= v2`. See |vim.version.cmp()| for usage.
Parameters: ~
• {v1} (`vim.Version|number[]|string`)
• {v2} (`vim.Version|number[]|string`)
Return: ~
(`boolean`)
vim.version.lt({v1}, {v2}) *vim.version.lt()*
Returns `true` if `v1 < v2`. See |vim.version.cmp()| for usage.
Parameters: ~
• {v1} (`vim.Version|number[]|string`)
• {v2} (`vim.Version|number[]|string`)
Return: ~
(`boolean`)
vim.version.parse({version}, {opts}) *vim.version.parse()*
Parses a semantic version string and returns a version object which can be
used with other `vim.version` functions. For example "1.0.1-rc1+build.2"
returns: >
{ major = 1, minor = 0, patch = 1, prerelease = "rc1", build = "build.2" }
<
Parameters: ~
• {version} (`string`) Version string to parse.
• {opts} (`table?`) Optional keyword arguments:
• strict (boolean): Default false. If `true`, no coercion
is attempted on input not conforming to semver v2.0.0. If
`false`, `parse()` attempts to coerce input such as
"1.0", "0-x", "tmux 3.2a" into valid versions.
Return: ~
(`vim.Version?`) parsed_version Version object or `nil` if input is
invalid.
See also: ~
• https://semver.org/spec/v2.0.0.html
vim.version.range({spec}) *vim.version.range()*
Parses a semver |version-range| "spec" and returns a range object: >
{
from: Version
to: Version
has(v: string|Version)
}
<
`:has()` checks if a version is in the range (inclusive `from`, exclusive
`to`).
Example: >lua
local r = vim.version.range('1.0.0 - 2.0.0')
print(r:has('1.9.9')) -- true
print(r:has('2.0.0')) -- false
print(r:has(vim.version())) -- check against current Nvim version
<
Or use cmp(), le(), lt(), ge(), gt(), and/or eq() to compare a version
against `.to` and `.from` directly: >lua
local r = vim.version.range('1.0.0 - 2.0.0') -- >=1.0, <2.0
print(vim.version.ge({1,0,3}, r.from) and vim.version.lt({1,0,3}, r.to))
<
Parameters: ~
• {spec} (`string`) Version range "spec"
Return: ~
(`table?`) A table with the following fields:
• {from} (`vim.Version`)
• {to}? (`vim.Version`)
See also: ~
• https://github.com/npm/node-semver#ranges
==============================================================================
Lua module: vim.iter *vim.iter*
*vim.iter()* is an interface for |iterable|s: it wraps a table or function
argument into an *Iter* object with methods (such as |Iter:filter()| and
|Iter:map()|) that transform the underlying source data. These methods can be
chained to create iterator "pipelines": the output of each pipeline stage is
input to the next stage. The first stage depends on the type passed to
`vim.iter()`:
• List tables (arrays, |lua-list|) yield only the value of each element.
• Use |Iter:enumerate()| to also pass the index to the next stage.
• Or initialize with ipairs(): `vim.iter(ipairs(…))`.
• Non-list tables (|lua-dict|) yield both the key and value of each element.
• Function |iterator|s yield all values returned by the underlying function.
• Tables with a |__call()| metamethod are treated as function iterators.
The iterator pipeline terminates when the underlying |iterable| is exhausted
(for function iterators this means it returned nil).
Note: `vim.iter()` scans table input to decide if it is a list or a dict; to
avoid this cost you can wrap the table with an iterator e.g.
`vim.iter(ipairs({…}))`, but that precludes the use of |list-iterator|
operations such as |Iter:rev()|).
Examples: >lua
local it = vim.iter({ 1, 2, 3, 4, 5 })
it:map(function(v)
return v * 3
end)
it:rev()
it:skip(2)
it:totable()
-- { 9, 6, 3 }
-- ipairs() is a function iterator which returns both the index (i) and the value (v)
vim.iter(ipairs({ 1, 2, 3, 4, 5 })):map(function(i, v)
if i > 2 then return v end
end):totable()
-- { 3, 4, 5 }
local it = vim.iter(vim.gsplit('1,2,3,4,5', ','))
it:map(function(s) return tonumber(s) end)
for i, d in it:enumerate() do
print(string.format("Column %d is %d", i, d))
end
-- Column 1 is 1
-- Column 2 is 2
-- Column 3 is 3
-- Column 4 is 4
-- Column 5 is 5
vim.iter({ a = 1, b = 2, c = 3, z = 26 }):any(function(k, v)
return k == 'z'
end)
-- true
local rb = vim.ringbuf(3)
rb:push("a")
rb:push("b")
vim.iter(rb):totable()
-- { "a", "b" }
<
Iter:all({pred}) *Iter:all()*
Returns true if all items in the iterator match the given predicate.
Parameters: ~
• {pred} (`fun(...):boolean`) Predicate function. Takes all values
returned from the previous stage in the pipeline as arguments
and returns true if the predicate matches.
Iter:any({pred}) *Iter:any()*
Returns true if any of the items in the iterator match the given
predicate.
Parameters: ~
• {pred} (`fun(...):boolean`) Predicate function. Takes all values
returned from the previous stage in the pipeline as arguments
and returns true if the predicate matches.
Iter:each({f}) *Iter:each()*
Calls a function once for each item in the pipeline, draining the
iterator.
For functions with side effects. To modify the values in the iterator, use
|Iter:map()|.
Parameters: ~
• {f} (`fun(...)`) Function to execute for each item in the pipeline.
Takes all of the values returned by the previous stage in the
pipeline as arguments.
Iter:enumerate() *Iter:enumerate()*
Yields the item index (count) and value for each item of an iterator
pipeline.
For list tables, this is more efficient: >lua
vim.iter(ipairs(t))
<
instead of: >lua
vim.iter(t):enumerate()
<
Example: >lua
local it = vim.iter(vim.gsplit('abc', '')):enumerate()
it:next()
-- 1 'a'
it:next()
-- 2 'b'
it:next()
-- 3 'c'
<
Return: ~
(`Iter`)
Iter:filter({f}) *Iter:filter()*
Filters an iterator pipeline.
Example: >lua
local bufs = vim.iter(vim.api.nvim_list_bufs()):filter(vim.api.nvim_buf_is_loaded)
<
Parameters: ~
• {f} (`fun(...):boolean`) Takes all values returned from the previous
stage in the pipeline and returns false or nil if the current
iterator element should be removed.
Return: ~
(`Iter`)
Iter:find({f}) *Iter:find()*
Find the first value in the iterator that satisfies the given predicate.
Advances the iterator. Returns nil and drains the iterator if no value is
found.
Examples: >lua
local it = vim.iter({ 3, 6, 9, 12 })
it:find(12)
-- 12
local it = vim.iter({ 3, 6, 9, 12 })
it:find(20)
-- nil
local it = vim.iter({ 3, 6, 9, 12 })
it:find(function(v) return v % 4 == 0 end)
-- 12
<
Parameters: ~
• {f} (`any`)
Return: ~
(`any`)
Iter:flatten({depth}) *Iter:flatten()*
Flattens a |list-iterator|, un-nesting nested values up to the given
{depth}. Errors if it attempts to flatten a dict-like value.
Examples: >lua
vim.iter({ 1, { 2 }, { { 3 } } }):flatten():totable()
-- { 1, 2, { 3 } }
vim.iter({1, { { a = 2 } }, { 3 } }):flatten():totable()
-- { 1, { a = 2 }, 3 }
vim.iter({ 1, { { a = 2 } }, { 3 } }):flatten(math.huge):totable()
-- error: attempt to flatten a dict-like table
<
Parameters: ~
• {depth} (`number?`) Depth to which |list-iterator| should be
flattened (defaults to 1)
Return: ~
(`Iter`)
Iter:fold({init}, {f}) *Iter:fold()*
Folds ("reduces") an iterator into a single value. *Iter:reduce()*
Examples: >lua
-- Create a new table with only even values
vim.iter({ a = 1, b = 2, c = 3, d = 4 })
:filter(function(k, v) return v % 2 == 0 end)
:fold({}, function(acc, k, v)
acc[k] = v
return acc
end) --> { b = 2, d = 4 }
-- Get the "maximum" item of an iterable.
vim.iter({ -99, -4, 3, 42, 0, 0, 7 })
:fold({}, function(acc, v)
acc.max = math.max(v, acc.max or v)
return acc
end) --> { max = 42 }
<
Parameters: ~
• {init} (`any`) Initial value of the accumulator.
• {f} (`fun(acc:A, ...):A`) Accumulation function.
Return: ~
(`any`)
Iter:join({delim}) *Iter:join()*
Collect the iterator into a delimited string.
Each element in the iterator is joined into a string separated by {delim}.
Consumes the iterator.
Parameters: ~
• {delim} (`string`) Delimiter
Return: ~
(`string`)
Iter:last() *Iter:last()*
Drains the iterator and returns the last item.
Example: >lua
local it = vim.iter(vim.gsplit('abcdefg', ''))
it:last()
-- 'g'
local it = vim.iter({ 3, 6, 9, 12, 15 })
it:last()
-- 15
<
Return: ~
(`any`)
See also: ~
• Iter.rpeek
Iter:map({f}) *Iter:map()*
Maps the items of an iterator pipeline to the values returned by `f`.
If the map function returns nil, the value is filtered from the iterator.
Example: >lua
local it = vim.iter({ 1, 2, 3, 4 }):map(function(v)
if v % 2 == 0 then
return v * 3
end
end)
it:totable()
-- { 6, 12 }
<
Parameters: ~
• {f} (`fun(...):any`) Mapping function. Takes all values returned from
the previous stage in the pipeline as arguments and returns one
or more new values, which are used in the next pipeline stage.
Nil return values are filtered from the output.
Return: ~
(`Iter`)
Iter:next() *Iter:next()*
Gets the next value from the iterator.
Example: >lua
local it = vim.iter(string.gmatch('1 2 3', '%d+')):map(tonumber)
it:next()
-- 1
it:next()
-- 2
it:next()
-- 3
<
Return: ~
(`any`)
Iter:nth({n}) *Iter:nth()*
Gets the nth value of an iterator (and advances to it).
If `n` is negative, offsets from the end of a |list-iterator|.
Example: >lua
local it = vim.iter({ 3, 6, 9, 12 })
it:nth(2)
-- 6
it:nth(2)
-- 12
local it2 = vim.iter({ 3, 6, 9, 12 })
it2:nth(-2)
-- 9
it2:nth(-2)
-- 3
<
Parameters: ~
• {n} (`number`) Index of the value to return. May be negative if the
source is a |list-iterator|.
Return: ~
(`any`)
Iter:peek() *Iter:peek()*
Gets the next value in a |list-iterator| without consuming it.
Example: >lua
local it = vim.iter({ 3, 6, 9, 12 })
it:peek()
-- 3
it:peek()
-- 3
it:next()
-- 3
<
Return: ~
(`any`)
Iter:pop() *Iter:pop()*
"Pops" a value from a |list-iterator| (gets the last value and decrements
the tail).
Example: >lua
local it = vim.iter({1, 2, 3, 4})
it:pop()
-- 4
it:pop()
-- 3
<
Return: ~
(`any`)
Iter:rev() *Iter:rev()*
Reverses a |list-iterator| pipeline.
Example: >lua
local it = vim.iter({ 3, 6, 9, 12 }):rev()
it:totable()
-- { 12, 9, 6, 3 }
<
Return: ~
(`Iter`)
Iter:rfind({f}) *Iter:rfind()*
Gets the first value satisfying a predicate, from the end of a
|list-iterator|.
Advances the iterator. Returns nil and drains the iterator if no value is
found.
Examples: >lua
local it = vim.iter({ 1, 2, 3, 2, 1 }):enumerate()
it:rfind(1)
-- 5 1
it:rfind(1)
-- 1 1
<
Parameters: ~
• {f} (`any`)
Return: ~
(`any`)
See also: ~
• Iter.find
Iter:rpeek() *Iter:rpeek()*
Gets the last value of a |list-iterator| without consuming it.
Example: >lua
local it = vim.iter({1, 2, 3, 4})
it:rpeek()
-- 4
it:rpeek()
-- 4
it:pop()
-- 4
<
Return: ~
(`any`)
See also: ~
• Iter.last
Iter:rskip({n}) *Iter:rskip()*
Discards `n` values from the end of a |list-iterator| pipeline.
Example: >lua
local it = vim.iter({ 1, 2, 3, 4, 5 }):rskip(2)
it:next()
-- 1
it:pop()
-- 3
<
Parameters: ~
• {n} (`number`) Number of values to skip.
Return: ~
(`Iter`)
Iter:skip({n}) *Iter:skip()*
Skips `n` values of an iterator pipeline.
Example: >lua
local it = vim.iter({ 3, 6, 9, 12 }):skip(2)
it:next()
-- 9
<
Parameters: ~
• {n} (`number`) Number of values to skip.
Return: ~
(`Iter`)
Iter:slice({first}, {last}) *Iter:slice()*
Sets the start and end of a |list-iterator| pipeline.
Equivalent to `:skip(first - 1):rskip(len - last + 1)`.
Parameters: ~
• {first} (`number`)
• {last} (`number`)
Return: ~
(`Iter`)
Iter:take({n}) *Iter:take()*
Transforms an iterator to yield only the first n values.
Example: >lua
local it = vim.iter({ 1, 2, 3, 4 }):take(2)
it:next()
-- 1
it:next()
-- 2
it:next()
-- nil
<
Parameters: ~
• {n} (`integer`)
Return: ~
(`Iter`)
Iter:totable() *Iter:totable()*
Collect the iterator into a table.
The resulting table depends on the initial source in the iterator
pipeline. List-like tables and function iterators will be collected into a
list-like table. If multiple values are returned from the final stage in
the iterator pipeline, each value will be included in a table.
Examples: >lua
vim.iter(string.gmatch('100 20 50', '%d+')):map(tonumber):totable()
-- { 100, 20, 50 }
vim.iter({ 1, 2, 3 }):map(function(v) return v, 2 * v end):totable()
-- { { 1, 2 }, { 2, 4 }, { 3, 6 } }
vim.iter({ a = 1, b = 2, c = 3 }):filter(function(k, v) return v % 2 ~= 0 end):totable()
-- { { 'a', 1 }, { 'c', 3 } }
<
The generated table is a list-like table with consecutive, numeric
indices. To create a map-like table with arbitrary keys, use
|Iter:fold()|.
Return: ~
(`table`)
==============================================================================
Lua module: vim.snippet *vim.snippet*
*vim.snippet.ActiveFilter*
Fields: ~
• {direction} (`vim.snippet.Direction`) Navigation direction. -1 for
previous, 1 for next.
vim.snippet.active({filter}) *vim.snippet.active()*
Returns `true` if there's an active snippet in the current buffer,
applying the given filter if provided.
You can use this function to navigate a snippet as follows: >lua
vim.keymap.set({ 'i', 's' }, '<Tab>', function()
if vim.snippet.active({ direction = 1 }) then
return '<cmd>lua vim.snippet.jump(1)<cr>'
else
return '<Tab>'
end
end, { expr = true })
<
Parameters: ~
• {filter} (`vim.snippet.ActiveFilter?`) Filter to constrain the search
with:
• `direction` (vim.snippet.Direction): Navigation direction.
Will return `true` if the snippet can be jumped in the
given direction. See |vim.snippet.ActiveFilter|.
Return: ~
(`boolean`)
vim.snippet.expand({input}) *vim.snippet.expand()*
Expands the given snippet text. Refer to
https://microsoft.github.io/language-server-protocol/specification/#snippet_syntax
for the specification of valid input.
Tabstops are highlighted with |hl-SnippetTabstop|.
Parameters: ~
• {input} (`string`)
vim.snippet.jump({direction}) *vim.snippet.jump()*
Jumps to the next (or previous) placeholder in the current snippet, if
possible.
For example, map `<Tab>` to jump while a snippet is active: >lua
vim.keymap.set({ 'i', 's' }, '<Tab>', function()
if vim.snippet.active({ direction = 1 }) then
return '<cmd>lua vim.snippet.jump(1)<cr>'
else
return '<Tab>'
end
end, { expr = true })
<
Parameters: ~
• {direction} (`vim.snippet.Direction`) Navigation direction. -1 for
previous, 1 for next.
vim.snippet.stop() *vim.snippet.stop()*
Exits the current snippet.
==============================================================================
Lua module: vim.text *vim.text*
vim.text.hexdecode({enc}) *vim.text.hexdecode()*
Hex decode a string.
Parameters: ~
• {enc} (`string`) String to decode
Return (multiple): ~
(`string?`) Decoded string
(`string?`) Error message, if any
vim.text.hexencode({str}) *vim.text.hexencode()*
Hex encode a string.
Parameters: ~
• {str} (`string`) String to encode
Return: ~
(`string`) Hex encoded string
==============================================================================
Lua module: tohtml *vim.tohtml*
:[range]TOhtml {file} *:TOhtml*
Converts the buffer shown in the current window to HTML, opens the generated
HTML in a new split window, and saves its contents to {file}. If {file} is not
given, a temporary file (created by |tempname()|) is used.
tohtml.tohtml({winid}, {opt}) *tohtml.tohtml.tohtml()*
Converts the buffer shown in the window {winid} to HTML and returns the
output as a list of string.
Parameters: ~
• {winid} (`integer?`) Window to convert (defaults to current window)
• {opt} (`table?`) Optional parameters.
• {title}? (`string|false`, default: buffer name) Title tag
to set in the generated HTML code.
• {number_lines}? (`boolean`, default: `false`) Show line
numbers.
• {font}? (`string[]|string`, default: `guifont`) Fonts to
use.
• {width}? (`integer`, default: 'textwidth' if non-zero or
window width otherwise) Width used for items which are
either right aligned or repeat a character infinitely.
• {range}? (`integer[]`, default: entire buffer) Range of
rows to use.
Return: ~
(`string[]`)
vim:tw=78:ts=8:sw=4:sts=4:et:ft=help:norl:
|