Source

slimv-newlisp / ftplugin / slimv.vim

Full commit
   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
" slimv.vim:    The Superior Lisp Interaction Mode for VIM
" Version:      0.8.6
" Last Change:  25 Aug 2011
" Maintainer:   Tamas Kovacs <kovisoft at gmail dot com>
" License:      This file is placed in the public domain.
"               No warranty, express or implied.
"               *** ***   Use At-Your-Own-Risk!   *** ***
"
" =====================================================================
"
"  Load Once:
if &cp || exists( 'g:slimv_loaded' )
    finish
endif

let g:slimv_loaded = 1

let g:slimv_windows = 0
let g:slimv_cygwin  = 0
let g:slimv_osx     = 0

if has( 'win32' ) || has( 'win95' ) || has( 'win64' ) || has( 'win16' )
    let g:slimv_windows = 1
elseif has( 'win32unix' )
    let g:slimv_cygwin = 1
elseif has( 'macunix' )
    let g:slimv_osx = 1
endif


" =====================================================================
"  Functions used by global variable definitions
" =====================================================================

" Try to autodetect Python executable
function! SlimvAutodetectPython()
    if !g:slimv_cygwin && executable( 'python' )
        return 'python'
    endif

    if g:slimv_windows || g:slimv_cygwin
        " Try to find Python on the standard installation places
        " For Cygwin we need to use the Windows Python instead of the Cygwin Python
        let pythons = split( globpath( 'c:/python*,c:/Program Files/python*', 'python.exe' ), '\n' )
        if len( pythons ) == 0
            " Go deeper in subdirectories
            let pythons = split( globpath( 'c:/python*/**,c:/Program Files/python*/**', 'python.exe' ), '\n' )
            if len( pythons ) == 0
                return ''
            endif
        endif
        let pycmd = pythons[0]
        if match( pycmd, ' ' ) >= 0
            " Convert Python command to short 8.3 format if path contains spaces
            let pycmd = fnamemodify( pycmd, ':8' )
        endif
        return pycmd
    else
        return ''
    endif
endfunction

" Build the command to start the client
function! SlimvMakeClientCommand()
    if g:slimv_python == '' || g:slimv_lisp == ''
        " We don't have enough information to build client command
        return ''
    endif

    " Start with the Python path
    let cmd = g:slimv_python

    " Add path of Slimv script, enclose it in double quotes if path contains spaces
    if g:slimv_path[0] != '"' && match( g:slimv_path, ' ' ) >= 0
        let cmd = cmd . ' "' . g:slimv_path . '"'
    else
        let cmd = cmd . ' ' . g:slimv_path
    endif

    " Add port number if different from default
    if g:slimv_port != 5151
        let cmd = cmd . ' -p ' . g:slimv_port
    endif

    " Add Lisp path
    if g:slimv_lisp[0] != '"' && match( g:slimv_lisp, ' ' ) >= 0
        let cmd = cmd . ' -l "' . g:slimv_lisp . '"'
    else
        let cmd = cmd . ' -l ' . g:slimv_lisp
    endif

    return cmd
endfunction

function! SlimvClientCommand()
    if g:slimv_client == ''
        " No command to start client, we are clueless, ask user for assistance
        if g:slimv_python == ''
            let g:slimv_python = input( 'Enter Python path (or fill g:slimv_python in your vimrc): ', '', 'file' )
        endif
        if g:slimv_lisp == ''
            let g:slimv_lisp = input( 'Enter Lisp path (or fill g:slimv_lisp in your vimrc): ', '', 'file' )
        endif
        let g:slimv_client = SlimvMakeClientCommand()
    endif
endfunction

" Convert Cygwin path to Windows path, if needed
function! s:Cygpath( path )
    let path = a:path
    if g:slimv_cygwin
        let path = system( 'cygpath -w ' . path )
        let path = substitute( path, "\n", "", "g" )
        let path = substitute( path, "\\", "/", "g" )
    endif
    return path
endfunction

" Find slimv.py in the Vim ftplugin directory (if not given in vimrc)
if !exists( 'g:slimv_path' )
    let plugins = split( globpath( &runtimepath, 'ftplugin/**/slimv.py'), '\n' )
    if len( plugins ) > 0
        let g:slimv_path = s:Cygpath( plugins[0] )
    else
        let g:slimv_path = 'slimv.py'
    endif
endif

" Get the filetype (Lisp dialect) used by Slimv
function! SlimvGetFiletype()
    if &ft != ''
        " Return Vim filetype if defined
        return &ft
    endif

    if match( tolower( g:slimv_lisp ), 'clojure' ) >= 0 || match( tolower( g:slimv_lisp ), 'clj' ) >= 0
        " Must be Clojure
        return 'clojure'
    endif

    " We have no clue, guess its lisp
    return 'lisp'
endfunction

" Try to autodetect SWANK and build the command to start the SWANK server
function! SlimvSwankCommand()
    if exists( 'g:slimv_swank_clojure' ) && SlimvGetFiletype() == 'clojure'
        return g:slimv_swank_clojure
    endif
    if exists( 'g:slimv_swank_scheme' ) && SlimvGetFiletype() == 'scheme'
        return g:slimv_swank_scheme
    endif
    if exists( 'g:slimv_swank_cmd' )
        return g:slimv_swank_cmd
    endif

    let cmd = ''
    if SlimvGetFiletype() == 'clojure'
        " First autodetect Leiningen and Cake
        if executable( 'lein' )
            let cmd = '"lein swank"'
        elseif executable( 'cake' )
            let cmd = '"cake swank"'
        else
            " Check if swank-clojure is bundled with Slimv
            let swanks = split( globpath( &runtimepath, 'swank-clojure/swank/swank.clj'), '\n' )
            if len( swanks ) == 0
                return ''
            endif
            let sclj = substitute( swanks[0], '\', '/', "g" )
            let cmd = g:slimv_lisp . ' -i "' . sclj . '" -e "(swank.swank/start-repl)" -r'
        endif
    elseif SlimvGetFiletype() == 'scheme'
        let swanks = split( globpath( &runtimepath, 'slime/contrib/swank-mit-scheme.scm'), '\n' )
        if len( swanks ) == 0
            return ''
        endif
        if b:SlimvImplementation() == 'mit'
            let cmd = '"' . g:slimv_lisp . '" --load "' . swanks[0] . '"'
        endif
    else
        " First check if SWANK is bundled with Slimv
        let swanks = split( globpath( &runtimepath, 'slime/start-swank.lisp'), '\n' )
        if len( swanks ) == 0
            " Try to find SWANK in the standard SLIME installation locations
            if g:slimv_windows || g:slimv_cygwin
                let swanks = split( globpath( 'c:/slime/,c:/*lisp*/slime/,c:/*lisp*/site/lisp/slime/,c:/Program Files/*lisp*/site/lisp/slime/', 'start-swank.lisp' ), '\n' )
            else
                let swanks = split( globpath( '/usr/share/common-lisp/source/slime/', 'start-swank.lisp' ), '\n' )
            endif
        endif
        if len( swanks ) == 0
            return ''
        endif

        " Build proper SWANK start command for the Lisp implementation used
        if b:SlimvImplementation() == 'sbcl'
            let cmd = '"' . g:slimv_lisp . '" --load "' . swanks[0] . '"'
        elseif b:SlimvImplementation() == 'clisp'
            let cmd = '"' . g:slimv_lisp . '" -i "' . swanks[0] . '"'
        elseif b:SlimvImplementation() == 'allegro'
            let cmd = '"' . g:slimv_lisp . '" -L "' . swanks[0] . '"'
        elseif b:SlimvImplementation() == 'cmu'
            let cmd = '"' . g:slimv_lisp . '" -load "' . swanks[0] . '"'
        else
            let cmd = '"' . g:slimv_lisp . '" -l "' . swanks[0] . '"'
        endif
    endif
    if cmd != ''
        if g:slimv_windows || g:slimv_cygwin
            return '!start /MIN ' . cmd
        elseif g:slimv_osx
            return '!osascript -e "tell application \"Terminal\" to do script \"' . cmd . '\""'
        else
            return '! xterm -iconic -e ' . cmd . ' &'
        endif
    endif
    return ''
endfunction

" =====================================================================
"  Global variable definitions
" =====================================================================

" Use SWANK server
if !exists( 'g:slimv_swank' )
    let g:slimv_swank = 1
endif

" Host name or IP address of the SWANK server
if !exists( 'g:swank_host' )
    let g:swank_host = 'localhost'
endif

" TCP port number to use for the SWANK server
if !exists( 'g:swank_port' )
    let g:swank_port = 4005
endif

" TCP port number to use for the Slimv server
if !exists( 'g:slimv_port' )
    let g:slimv_port = 5151
endif

" Find Python (if not given in vimrc)
if !exists( 'g:slimv_python' )
    let g:slimv_python = SlimvAutodetectPython()
endif

" Find Lisp (if not given in vimrc)
if !exists( 'g:slimv_lisp' )
    let lisp = b:SlimvAutodetect()
    let g:slimv_lisp = lisp[0]
    if !exists( 'g:slimv_impl' )
        let g:slimv_impl = lisp[1]
    endif
endif

" Try to find out the Lisp implementation
" if not autodetected and not given in vimrc
if !exists( 'g:slimv_impl' )
    let g:slimv_impl = b:SlimvImplementation()
endif

" Open a REPL buffer inside Vim?
if !exists( 'g:slimv_repl_open' )
    let g:slimv_repl_open = 1
endif

" Directory name for the REPL buffer file
if !exists( 'g:slimv_repl_dir' )
    if g:slimv_windows
        let g:slimv_repl_dir = matchstr( tempname(), '.*\\' )
    else
        let g:slimv_repl_dir = s:Cygpath( '/tmp/' )
    endif
endif

" Filename for the REPL buffer file
if !exists( 'g:slimv_repl_file' )
    let g:slimv_repl_file = b:SlimvREPLFile()
endif

" Shall we open REPL buffer in split window?
if !exists( 'g:slimv_repl_split' )
    let g:slimv_repl_split = 1
endif

" Wrap long lines in REPL buffer
if !exists( 'g:slimv_repl_wrap' )
    let g:slimv_repl_wrap = 1
endif

" Maximum number of lines echoed from the evaluated form
if !exists( 'g:slimv_echolines' )
    let g:slimv_echolines = 4
endif

" Syntax highlighting for the REPL buffer
if !exists( 'g:slimv_repl_syntax' )
    let g:slimv_repl_syntax = 0
endif

" Alternative value (in msec) for 'updatetime' while the REPL buffer is changing
if !exists( 'g:slimv_updatetime' )
    let g:slimv_updatetime = 500
endif

" Build client command (if not given in vimrc)
if !exists( 'g:slimv_client' )
    let g:slimv_client = SlimvMakeClientCommand()
endif

" Slimv keybinding set (0 = no keybindings)
if !exists( 'g:slimv_keybindings' )
    let g:slimv_keybindings = 1
endif

" Append Slimv menu to the global menu (0 = no menu)
if !exists( 'g:slimv_menu' )
    let g:slimv_menu = 1
endif

" Build the ctags command capable of generating lisp tags file
" The command can be run with execute 'silent !' . g:slimv_ctags
if !exists( 'g:slimv_ctags' )
    let ctags = split( globpath( '$vim,$vimruntime', 'ctags.exe' ), '\n' )
    if len( ctags ) > 0
        " Remove -a option to regenerate every time
        let g:slimv_ctags = '"' . ctags[0] . '" -a --language-force=lisp *.lisp *.clj'
    endif
endif

" Package/namespace handling
if !exists( 'g:slimv_package' )
    let g:slimv_package = 1
endif

" General timeout for various startup and connection events (seconds)
if !exists( 'g:slimv_timeout' )
    let g:slimv_timeout = 20
endif

" Use balloonexpr to display symbol description
if !exists( 'g:slimv_balloon' )
    let g:slimv_balloon = 1
endif

" Shall we use simple or fuzzy completion?
if !exists( 'g:slimv_simple_compl' )
    let g:slimv_simple_compl = 0
endif

" Custom <Leader> for the Slimv plugin
if !exists( 'g:slimv_leader' )
    if exists( 'mapleader' )
        let g:slimv_leader = mapleader
    else
        let g:slimv_leader = ','
    endif
endif


" =====================================================================
"  Template definitions
" =====================================================================

if !exists( 'g:slimv_template_pprint' )
    if SlimvGetFiletype() == 'clojure'
        let g:slimv_template_pprint = '(doseq [o %1] (println o))'
    else
        let g:slimv_template_pprint = '(dolist (o %1) (pprint o))'
    endif
endif

if !exists( 'g:slimv_template_undefine' )
    if SlimvGetFiletype() == 'clojure'
        let g:slimv_template_undefine = "(ns-unmap 'user '" . "%1)"
    else
        let g:slimv_template_undefine = '(fmakunbound (read-from-string "%1"))'
    endif
endif

if !exists( 'g:slimv_template_describe' )
    let g:slimv_template_describe = '(describe (read-from-string "%1"))'
endif

if !exists( 'g:slimv_template_trace' )
    let g:slimv_template_trace = '(trace %1)'
endif

if !exists( 'g:slimv_template_untrace' )
    let g:slimv_template_untrace = '(untrace %1)'
endif

if !exists( 'g:slimv_template_profile' )
    if b:SlimvImplementation() == 'sbcl'
        let g:slimv_template_profile = '(sb-profile:profile %1)'
    else
        let g:slimv_template_profile = '(mon:monitor %1)'
    endif
endif

if !exists( 'g:slimv_template_unprofile' )
    if b:SlimvImplementation() == 'sbcl'
        let g:slimv_template_unprofile = '(sb-profile:unprofile %1)'
    else
        let g:slimv_template_unprofile = '(mon:unmonitor %1)'
    endif
endif

if !exists( 'g:slimv_template_unprofile_all' )
    if b:SlimvImplementation() == 'sbcl'
        let g:slimv_template_unprofile_all = '(sb-profile:unprofile)'
    else
        let g:slimv_template_unprofile_all = '(mon:unmonitor)'
    endif
endif

if !exists( 'g:slimv_template_show_profiled' )
    if b:SlimvImplementation() == 'sbcl'
        let g:slimv_template_show_profiled = '(sb-profile:profile)'
    else
        let g:slimv_template_show_profiled = '(pprint mon:*monitored-functions*)'
    endif
endif

if !exists( 'g:slimv_template_profile_report' )
    if b:SlimvImplementation() == 'sbcl'
        let g:slimv_template_profile_report = '(sb-profile:report)'
    else
        let g:slimv_template_profile_report = '(mon:report-monitoring)'
    endif
endif

if !exists( 'g:slimv_template_profile_reset' )
    if b:SlimvImplementation() == 'sbcl'
        let g:slimv_template_profile_reset = '(sb-profile:reset)'
    else
        let g:slimv_template_profile_reset = '(mon:reset-all-monitoring)'
    endif
endif

if !exists( 'g:slimv_template_disassemble' )
    let g:slimv_template_disassemble = "(disassemble #'%1)"
endif

if !exists( 'g:slimv_template_inspect' )
    if SlimvGetFiletype() == 'clojure'
        let g:slimv_template_inspect = "(print-doc #'" . "%1)"
    else
        let g:slimv_template_inspect = '(inspect %1)'
    endif
endif

if !exists( 'g:slimv_template_apropos' )
    if SlimvGetFiletype() == 'clojure'
        let g:slimv_template_apropos = '(find-doc "%1")'
    else
        let g:slimv_template_apropos = '(apropos "%1")'
    endif
endif

if !exists( 'g:slimv_template_macroexpand' )
    if SlimvGetFiletype() == 'clojure'
        let g:slimv_template_macroexpand = '%1'
    else
        let g:slimv_template_macroexpand = '(pprint %1)'
    endif
endif

if !exists( 'g:slimv_template_macroexpand_all' )
    if SlimvGetFiletype() == 'clojure'
        let g:slimv_template_macroexpand_all = '%1'
    else
        let g:slimv_template_macroexpand_all = '(pprint %1)'
    endif
endif

if !exists( 'g:slimv_template_compile_file' )
"    let g:slimv_template_compile_file = '(compile-file "%1")'
    let g:slimv_template_compile_file =
    \ '(let ((fasl-file (compile-file "%1")))' .
    \ '  (when (and %2 fasl-file) (load fasl-file)))'
endif

if !exists( 'g:slimv_template_compile_string' )
    let g:slimv_template_compile_string = 
    \ '(funcall (compile nil (read-from-string (format nil "(~S () ~A)" ' . "'" . 'lambda "%1"))))'
endif


" =====================================================================
"  Other non-global script variables
" =====================================================================

let s:repl_name = g:slimv_repl_dir . g:slimv_repl_file    " Name of the REPL buffer inside Vim
let s:prompt = ''                                         " Lisp prompt in the last line
let s:indent = ''                                         " Most recent indentation info
let s:last_update = 0                                     " The last update time for the REPL buffer
let s:last_size = 0                                       " The last size of the REPL buffer
let s:save_updatetime = &updatetime                       " The original value for 'updatetime'
let s:save_showmode = &showmode                           " The original value for 'showmode'
let s:python_initialized = 0                              " Is the embedded Python initialized?
let s:swank_connected = 0                                 " Is the SWANK server connected?
let s:swank_package = ''                                  " Package to use at the next SWANK eval
let s:swank_form = ''                                     " Form to send to SWANK
let s:refresh_disabled = 0                                " Set this variable temporarily to avoid recursive REPL rehresh calls
let s:debug_activated = 0                                 " Are we in the SWANK debugger?
let s:debug_move_cursor = 0                               " Move cursor to Restarts when debug activated
let s:compiled_file = ''                                  " Name of the compiled file
let s:au_curhold_set = 0                                  " Whether the autocommand has been set
let s:skip_sc = 'synIDattr(synID(line("."), col("."), 0), "name") =~ "[Ss]tring\\|[Cc]omment"'
                                                          " Skip matches inside string or comment 

" =====================================================================
"  General utility functions
" =====================================================================

" Display an error message
function! SlimvError( msg )
    echohl ErrorMsg
    echo a:msg
    echohl None
endfunction 

" Display an error message and a question, return user response
function! SlimvErrorAsk( msg, question )
    echohl ErrorMsg
    let answer = input( a:msg . a:question )
    echo ""
    echohl None
    return answer
endfunction 

" Display an error message and wait for ENTER
function! SlimvErrorWait( msg )
    call SlimvErrorAsk( a:msg, " Press ENTER to continue." )
endfunction 

" Shorten long messages to fit status line
function! SlimvShortEcho( msg )
    let saved=&shortmess
    set shortmess+=T
    exe "normal :echomsg a:msg\n"
    let &shortmess=saved
endfunction

" Position the cursor at the end of the REPL buffer
" Optionally mark this position in Vim mark 's'
function! SlimvEndOfReplBuffer()
    if !g:slimv_repl_open
        " User does not want to display REPL in Vim
        return
    endif
    normal! G$
endfunction

" Remember the end of the REPL buffer: user may enter commands here
" Also remember the prompt, because the user may overwrite it
function! SlimvMarkBufferEnd()
    call setpos( "'s", [0, line('$'), col('$'), 0] )
    let s:prompt = getline( "'s" )
endfunction

" Handle response coming from the SWANK listener
function! SlimvSwankResponse()
    let s:refresh_disabled = 1
    call SlimvCommand( 'python swank_output()' )
    let s:refresh_disabled = 0
    let msg = ''
    redir => msg
    silent execute 'python swank_response("")'
    redir END

    if s:swank_action != '' && msg != ''
        if s:swank_action == ':describe-symbol'
            echo msg
            echo input('Press ENTER to continue.')
        endif
    endif
    if s:swank_actions_pending == 0
        " All SWANK output handled
        let &updatetime = s:save_updatetime
    endif
endfunction

" Execute the given command and write its output at the end of the REPL buffer
function! SlimvCommand( cmd )
    " Execute the command with output redirected to variable
    let msg = ''
    redir => msg
    silent execute a:cmd
    redir END

    let repl_buf = bufnr( g:slimv_repl_file )
    if repl_buf == -1
        " REPL buffer not loaded
        return
    endif
    let repl_win = bufwinnr( repl_buf )
    let this_win = winnr()

    if msg == ''
        " No new REPL output since the last refresh
        if g:slimv_updatetime > 0 && s:last_update < localtime() - 1
            let &updatetime = s:save_updatetime
        endif
        return
    endif
    let this_buf = bufnr( "%" )
    if repl_buf != this_buf
        " Switch to the REPL buffer/window
        try
            if g:slimv_repl_split && repl_win != -1
                if this_win != repl_win
                    execute repl_win . "wincmd w"
                endif
            else
                execute "buf " . repl_buf
            endif
        catch /.*/
            " Some Vim versions give an E303 error here
            " but we don't need a swapfile for the REPL buffer anyway
        endtry
    endif

    if g:slimv_updatetime > 0
        let &updatetime = g:slimv_updatetime
    endif

    let lines = split( msg, '\n', 1 )
    if lines[0] == ''
        " For some reason Python output redirection sometimes adds a newline at the beginning
        let lines = lines[1:]
    endif
    set noreadonly
    let lastline = getline( '$' ) . lines[0]
    call setline( '$', lastline )
    call append( '$', lines[1:] )
    set readonly
    set nomodified
    let s:last_update = localtime()

    if !g:slimv_repl_syntax
        set syntax=
    endif
    if g:slimv_swank
        setlocal buftype=nofile
        setlocal noswapfile
    else
        setlocal autoread
    endif
    call SlimvEndOfReplBuffer()
    call SlimvMarkBufferEnd()
    if s:debug_activated && s:debug_move_cursor
        call search( '^Restarts:', 'bW' )
        let s:debug_move_cursor = 0
        stopinsert
    endif

    if repl_buf != this_buf && repl_win != -1 && !s:debug_activated
        " Switch back to the caller buffer/window
        if g:slimv_repl_split
            if this_win != repl_win
                execute this_win . "wincmd w"
            endif
        else
            execute "buf " . this_buf
        endif
    endif
endfunction

" Execute the given SWANK command, wait for and return the response
function! SlimvCommandGetResponse( name, cmd )
    let s:refresh_disabled = 1
    call SlimvCommand( a:cmd )
    let msg = ''
    let s:swank_action = ''
    let starttime = localtime()
    let cmd_timeout = 3
    while s:swank_action == '' && localtime()-starttime < cmd_timeout
        python swank_output()
        redir => msg
        silent execute 'python swank_response("' . a:name . '")'
        redir END
    endwhile
    let s:refresh_disabled = 0
    return msg
endfunction

" Reload the contents of the REPL buffer from the output file if changed
function! SlimvRefreshReplBuffer()
    if s:refresh_disabled
        " Refresh is unwanted at the moment, probably another refresh is going on
        return
    endif

"    if !g:slimv_repl_open || !g:slimv_repl_split
    if !g:slimv_repl_open
        " User does not want to display REPL in Vim
        " or does not display it in a split window
        return
    endif

    let repl_buf = bufnr( g:slimv_repl_file )
    if repl_buf == -1
        " REPL buffer not loaded
        return
    endif
    let repl_win = bufwinnr( repl_buf )
    let this_win = winnr()

    if g:slimv_swank && s:swank_connected
        call SlimvSwankResponse()
        return
    endif

    let size = getfsize( s:repl_name )
    if size == s:last_size
        " REPL output file did not change since the last refresh
        if g:slimv_updatetime > 0 && s:last_update < localtime() - 1
            let &updatetime = s:save_updatetime
        endif
        return
    endif
    let this_buf = bufnr( "%" )
    if repl_buf != this_buf
        " Switch to the REPL buffer/window
        try
            if g:slimv_repl_split && repl_win != -1
                if this_win != repl_win
                    execute repl_win . "wincmd w"
                endif
            else
                execute "buf " . repl_buf
            endif
        catch /.*/
            " Some Vim versions give an E303 error here
            " but we don't need a swapfile for the REPL buffer anyway
        endtry
    endif

    if g:slimv_updatetime > 0
        let &updatetime = g:slimv_updatetime
    endif

    try
        execute "silent view! " . s:repl_name
        let s:last_size = size
        let s:last_update = localtime()
    catch /.*/
        " Oops, something went wrong, the buffer will not be refreshed this time
    endtry
    syntax on
    if !g:slimv_repl_syntax
        set syntax=
    endif
    if g:slimv_swank
        setlocal buftype=nofile
        setlocal noswapfile
    else
        setlocal autoread
    endif
    call SlimvEndOfReplBuffer()
    call SlimvMarkBufferEnd()
    set nomodified

    if repl_buf != this_buf && repl_win != -1 && !s:debug_activated
        " Switch back to the caller buffer/window
        if g:slimv_repl_split
            if this_win != repl_win
                execute this_win . "wincmd w"
            endif
        else
            execute "buf " . this_buf
        endif
    endif
endfunction

" This function re-triggers the CursorHold event
" after refreshing the REPL buffer
function! SlimvTimer()
    call SlimvRefreshReplBuffer()
    if g:slimv_repl_open
        if mode() == 'i' || mode() == 'I'
            " Put '<Insert>' twice into the typeahead buffer, which should not do anything
            " just switch to overwrite mode then back to insert mode
            call feedkeys("\<insert>\<insert>")
        else
            " Put an incomplete 'f' command and an Esc into the typeahead buffer
            call feedkeys("f\e")
        endif
    endif
endfunction

" Switch refresh mode on:
" refresh REPL buffer on frequent Vim events
function! SlimvRefreshModeOn()
    set readonly
    if g:slimv_swank
        setlocal buftype=nofile
        setlocal noswapfile
    else
        setlocal autoread
    endif
    if ! g:slimv_swank
        execute "au CursorMoved  * :call SlimvRefreshReplBuffer()"
        execute "au CursorMovedI * :call SlimvRefreshReplBuffer()"
    endif
    if ! s:au_curhold_set
        let s:au_curhold_set = 1
        execute "au CursorHold   * :call SlimvTimer()"
        execute "au CursorHoldI  * :call SlimvTimer()"
    endif
    call SlimvRefreshReplBuffer()
endfunction

" Switch refresh mode off
function! SlimvRefreshModeOff()
    if ! g:slimv_swank
        execute "au! CursorMoved"
        execute "au! CursorMovedI"
    endif
    execute "au! CursorHold"
    execute "au! CursorHoldI"
    let s:au_curhold_set = 0
    set noreadonly
endfunction

" Called when entering REPL buffer
function! SlimvReplEnter()
    call SlimvAddReplMenu()
    execute "au FileChangedRO " . g:slimv_repl_file . " :call SlimvRefreshModeOff()"
    call SlimvRefreshModeOn()
endfunction

" Called when leaving REPL buffer
function! SlimvReplLeave()
    try
        " Check if REPL menu exists, then remove it
        aunmenu REPL
        execute ':unmap ' . g:slimv_leader . '\'
    catch /.*/
        " REPL menu not found, we cannot remove it
    endtry
    if g:slimv_repl_split
        call SlimvRefreshModeOn()
    else
        call SlimvRefreshModeOff()
    endif
endfunction

" View the given file in a top/bottom/left/right split window
function! s:SplitView( filename )
    if g:slimv_repl_split == 1
        execute "silent topleft sview! " . a:filename
    elseif g:slimv_repl_split == 2
        execute "silent botright sview! " . a:filename
    elseif g:slimv_repl_split == 3
        execute "silent topleft vertical sview! " . a:filename
    elseif g:slimv_repl_split == 4
        execute "silent botright vertical sview! " . a:filename
    else
        execute "silent view! " . a:filename
    endif
endfunction

" Open a new REPL buffer or switch to the existing one
function! SlimvOpenReplBuffer()
    let repl_buf = bufnr( g:slimv_repl_file )
    if repl_buf == -1
        " Create a new REPL buffer
        call s:SplitView( s:repl_name )
    else
        if g:slimv_repl_split
            " REPL buffer is already created. Check if it is open in a window
            let repl_win = bufwinnr( repl_buf )
            if repl_win == -1
                " Create windows
                call s:SplitView( s:repl_name )
            else
                " Switch to the REPL window
                if winnr() != repl_win
                    execute repl_win . "wincmd w"
                endif
            endif
        else
            execute "buffer " . repl_buf
        endif
    endif

    " Add keybindings valid only for the REPL buffer
    if g:slimv_swank
        inoremap <buffer> <silent>    <CR>   <C-R>=pumvisible() ? "\<lt>CR>" : "\<lt>End>\<lt>C-O>:call SlimvSendCommand(0)\<lt>CR>"<CR>
        inoremap <buffer> <silent>    <C-CR> <End><C-O>:call SlimvSendCommand(1)<CR>
    else
        inoremap <buffer> <silent>    <CR>   <C-R>=pumvisible() ? "\<lt>CR>" : "\<lt>End>\<lt>CR>\<lt>C-O>:call SlimvSendCommand(0)\<lt>CR>"<CR>
        inoremap <buffer> <silent>    <C-CR> <End><CR><C-O>:call SlimvSendCommand(1)<CR>
    endif
    inoremap <buffer> <silent>        <Up>   <C-R>=pumvisible() ? "\<lt>Up>" : "\<lt>C-O>:call SlimvHandleUp()\<lt>CR>"<CR>
    inoremap <buffer> <silent>        <Down> <C-R>=pumvisible() ? "\<lt>Down>" : "\<lt>C-O>:call SlimvHandleDown()\<lt>CR>"<CR>
    noremap  <buffer> <silent>        <CR>   :call SlimvHandleEnter()<CR>
    inoremap <buffer> <silent>        <C-C>  <C-O>:call SlimvInterrupt()<CR>

    if exists( 'g:paredit_loaded' )
        inoremap <buffer> <silent> <expr> <BS>   PareditBackspace(1)
    else
        inoremap <buffer> <silent> <expr> <BS>   SlimvHandleBS()
    endif

    if g:slimv_keybindings == 1
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'.      :call SlimvSendCommand(0)<CR>'
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'/      :call SlimvSendCommand(1)<CR>'
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'<Up>   :call SlimvPreviousCommand()<CR>'
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'<Down> :call SlimvNextCommand()<CR>'
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'z      :call SlimvRefresh()<CR>'
    elseif g:slimv_keybindings == 2
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'rs     :call SlimvSendCommand(0)<CR>'
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'ro     :call SlimvSendCommand(1)<CR>'
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'rp     :call SlimvPreviousCommand()<CR>'
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'rn     :call SlimvNextCommand()<CR>'
        execute 'noremap <buffer> <silent> ' . g:slimv_leader.'rr     :call SlimvRefresh()<CR>'
    endif

    if g:slimv_repl_wrap
        inoremap <buffer> <silent>        <Home> <C-O>g<Home>
        inoremap <buffer> <silent>        <End>  <C-O>g<End>
        noremap  <buffer> <silent>        <Up>   gk
        noremap  <buffer> <silent>        <Down> gj
        noremap  <buffer> <silent>        <Home> g<Home>
        noremap  <buffer> <silent>        <End>  g<End>
        noremap  <buffer> <silent>        k      gk
        noremap  <buffer> <silent>        j      gj
        noremap  <buffer> <silent>        0      g0
        noremap  <buffer> <silent>        $      g$
        set wrap
    endif

    hi SlimvNormal term=none cterm=none gui=none
    hi SlimvCursor term=reverse cterm=reverse gui=reverse

    " Add autocommands specific to the REPL buffer
    execute "au FileChangedShell " . g:slimv_repl_file . " :call SlimvRefreshReplBuffer()"
    execute "au FocusGained "      . g:slimv_repl_file . " :call SlimvRefreshReplBuffer()"
    execute "au BufEnter "         . g:slimv_repl_file . " :call SlimvReplEnter()"
    execute "au BufLeave "         . g:slimv_repl_file . " :call SlimvReplLeave()"

    filetype on
    if g:slimv_swank
        setlocal buftype=nofile
        setlocal noswapfile
    else
        setlocal autoread
    endif
    redraw
    let s:last_size = 0

    call SlimvRefreshReplBuffer()
endfunction

" Set 'iskeyword' option depending on file type
function! s:SetKeyword()
    if SlimvGetFiletype() == 'clojure'
        setlocal iskeyword+=~,#,&,\|,!,?
    else
        setlocal iskeyword+=~,#,&,\|,{,},[,],!,?
    endif
endfunction

" Select symbol under cursor and return it
function! SlimvSelectSymbol()
    call s:SetKeyword()
    let symbol = expand('<cword>')
    return symbol
endfunction

" Select symbol with possible prefixes under cursor and return it
function! SlimvSelectSymbolExt()
    let save_iskeyword = &iskeyword
    if SlimvGetFiletype() == 'clojure'
        setlocal iskeyword+=~,#,&,\|,!,?,'
    else
        setlocal iskeyword+=~,#,&,\|,{,},[,],!,?,'
    endif
    let symbol = expand('<cword>')
    let &iskeyword = save_iskeyword
    return symbol
endfunction

" Select bottom level form the cursor is inside and copy it to register 's'
function! SlimvSelectForm()
    " Search the opening '(' if we are standing on a special form prefix character
    let c = col( '.' ) - 1
    while c < len( getline( '.' ) ) && match( "'`#", getline( '.' )[c] ) >= 0
        normal! l
        let c = c + 1
    endwhile
    normal! va(o
    " Handle '() or #'() etc. type special syntax forms
    let c = col( '.' ) - 2
    while c >= 0 && match( ' \t()', getline( '.' )[c] ) < 0
        normal! h
        let c = c - 1
    endwhile
    silent normal! "sy
    let sel = SlimvGetSelection()
    if sel == ''
        call SlimvError( "Form is empty." )
        return 0
    elseif sel == '(' || sel == '[' || sel == '{'
        call SlimvError( "Form is unbalanced." )
        return 0
    else
        return 1
    endif
endfunction

" Find starting '(' of a top level form
function! SlimvFindDefunStart()
    let l = line( '.' )
    let matchb = max( [l-100, 1] )
    while searchpair( '(', '', ')', 'bW', s:skip_sc, matchb )
    endwhile
endfunction

" Select top level form the cursor is inside and copy it to register 's'
function! SlimvSelectDefun()
    call SlimvFindDefunStart()
    return SlimvSelectForm()
endfunction

" Return the contents of register 's'
function! SlimvGetSelection()
    return getreg( '"s' )
endfunction

" Find the given string backwards and put it in front of the current selection
" if it is a valid Lisp form (i.e. not inside comment or string)
function! SlimvFindAddSel( string )
    let found = 0
    let searching = search( '(\s*' . a:string . '\s', 'bcW' )
    while searching
        " Search for the previos occurrence
        if synIDattr( synID( line('.'), col('.'), 0), 'name' ) !~ '[Ss]tring\|[Cc]omment'
            " It is not inside a comment or string
            let found = 1
            break
        endif
        let searching = search( '(\s*' . a:string . '\s', 'bW' )
    endwhile
    if found
        if g:slimv_swank
            silent normal! ww
            let l:packagename_tokens = split(expand('<cWORD>'),')\|\s')
            if l:packagename_tokens != []
                let s:swank_package = l:packagename_tokens[0]
            else
                let s:swank_package = ''
            endif
        else
            " Put the form just found at the beginning of the selection
            let sel = SlimvGetSelection()
            silent normal! v%"sy
            call setreg( '"s', SlimvGetSelection() . "\n" . sel )
        endif
    endif
endfunction

" Find and add language specific package/namespace definition before the
" cursor position and if exists then add it in front of the current selection
function! SlimvFindPackage()
    if !g:slimv_package || SlimvGetFiletype() == 'scheme'
        return
    endif
    if SlimvGetFiletype() == 'clojure'
        call SlimvFindAddSel( 'in-ns' )
    else
        call SlimvFindAddSel( '\(cl:\|common-lisp:\|\)in-package' )
    endif
endfunction

" Execute the given SWANK command with current package defined
function! SlimvCommandUsePackage( cmd )
    let oldpos = getpos( '.' ) 
    call SlimvFindPackage()
    let s:refresh_disabled = 1
    call SlimvCommand( a:cmd )
    let s:swank_package = ''
    call setpos( '.', oldpos ) 
    let s:refresh_disabled = 0
    call SlimvRefreshReplBuffer()
endfunction

" Initialize embedded Python and connect to SWANK server
function! SlimvConnectSwank()
    if !s:python_initialized
        if ! has('python')
            call SlimvErrorWait( 'Vim is compiled without the Python feature. Switching off SWANK client.' )
            let g:slimv_swank = 0
            return 0
        endif
        if g:slimv_windows || g:slimv_cygwin
            " Verify that Vim is compiled with Python and Python is properly installed
            let v = ''
            redir => v
            silent ver
            redir END
            let pydll = matchstr( v, '\cpython..\.dll' )
            if ! executable( pydll )
                call SlimvErrorWait( pydll . ' not found. Switching off SWANK client.' )
                let g:slimv_swank = 0
                return 0
            endif
        endif
        python import vim
        execute 'pyfile ' . substitute( g:slimv_path, "slimv.py", "swank.py", "g" )
        let s:python_initialized = 1
    endif

    if !s:swank_connected
        let s:swank_version = ''
        let s:lisp_version = ''
        if g:swank_host == ''
            let g:swank_host = input( 'Swank server host name: ', 'localhost' )
        endif
        execute 'python swank_connect("' . g:swank_host . '", ' . g:swank_port . ', "result" )'
        if result != '' && ( g:swank_host == 'localhost' || g:swank_host == '127.0.0.1' )
            " SWANK server is not running, start server if possible
            let swank = SlimvSwankCommand()
            if swank != ''
                redraw
                echon "\rStarting SWANK server..."
                silent execute swank
                let starttime = localtime()
                while result != '' && localtime()-starttime < g:slimv_timeout
                    sleep 500m
                    execute 'python swank_connect("' . g:swank_host . '", ' . g:swank_port . ', "result" )'
                endwhile
                redraw!
            endif
        endif
        if result == ''
            " Connected to SWANK server
            redraw
            echon "\rGetting SWANK connection info..."
            let starttime = localtime()
            while s:swank_version == '' && localtime()-starttime < g:slimv_timeout
                call SlimvSwankResponse()
            endwhile
            if s:swank_version >= '2008-12-23'
                call SlimvCommandGetResponse( ':create-repl', 'python swank_create_repl()' )
            endif
            let s:swank_connected = 1
            if g:slimv_simple_compl == 0
                python swank_require('swank-fuzzy')
                call SlimvSwankResponse()
            endif
            redraw
            echon "\rConnected to SWANK server on port " . g:swank_port . "."
	    if exists( "*b:SlimvReplInit" )
		" Perform implementation specific REPL initialization if supplied
                call b:SlimvReplInit( s:lisp_version )
            endif
        else
            " Display connection error message
            let answer = SlimvErrorAsk( result, " Switch off SWANK client [Y/n]?" )
            if answer[0] != 'n' && answer[0] != 'N'
                let g:slimv_swank = 0
            endif
        endif
    endif
    return s:swank_connected
endfunction

" Send argument to Lisp server for evaluation
function! SlimvSend( args, open_buffer, echoing )
    call SlimvClientCommand()
    if g:slimv_client == ''
        return
    endif

    let repl_buf = bufnr( g:slimv_repl_file )
    let repl_win = bufwinnr( repl_buf )

    if a:open_buffer && ( repl_buf == -1 || ( g:slimv_repl_split && repl_win == -1 ) )
        call SlimvOpenReplBuffer()
    endif

    if g:slimv_swank
        call SlimvConnectSwank()
    endif
    if g:slimv_swank && !s:swank_connected
        return
    endif

    " Send the lines to the client for evaluation
    let text = join( a:args, "\n" ) . "\n"

    if g:slimv_swank
        let s:refresh_disabled = 1
        let s:swank_form = text
        if a:echoing && g:slimv_echolines != 0
            if g:slimv_echolines > 0
                let nlpos = match( s:swank_form, "\n", 0, g:slimv_echolines )
                if nlpos > 0
                    " Echo only the first g:slimv_echolines number of lines
                    let trimmed = strpart( s:swank_form, nlpos )
                    let s:swank_form = strpart( s:swank_form, 0, nlpos )
                    let ending = s:CloseForm( [s:swank_form] )
                    if ending != 'ERROR'
                        if substitute( trimmed, '\s\|\n', '', 'g' ) == ''
                            " Only whitespaces are trimmed
                            let s:swank_form = s:swank_form . ending . "\n"
                        else
                            " Valuable characters trimmed, indicate it by printing "..."
                            let s:swank_form = s:swank_form . " ..." . ending . "\n"
                        endif
                    endif
                endif
            endif
            call SlimvCommand( 'echo "\n" . s:swank_form' )
            let s:swank_form = text
        else
            " Open a new line for the output
            call SlimvCommand( 'echo "\n"' )
        endif
        call SlimvCommand( 'python swank_input("s:swank_form")' )
        let s:swank_package = ''
        let s:refresh_disabled = 0
        call SlimvRefreshReplBuffer()
    else
        let result = system( g:slimv_client . ' -o ' . s:repl_name, text )
        if result != ''
            " Treat any output as error message
            call SlimvErrorWait( result )
        endif
    endif

    if a:open_buffer
        " Refresh REPL buffer then return to the caller buffer/window
        call SlimvRefreshReplBuffer()
        if g:slimv_repl_split && repl_win == -1
            execute "normal! \<C-w>p"
        endif
    endif
endfunction

" Eval arguments in Lisp REPL
function! SlimvEval( args )
    call SlimvSend( a:args, g:slimv_repl_open, 1 )
endfunction

" Set command line after the prompt
function! SlimvSetCommandLine( cmd )
    let line = getline( "." )
    if line( "." ) == line( "'s" )
        " The prompt is in the line marked with 's
        let promptlen = len( s:prompt )
    else
        let promptlen = 0
    endif
    if len( line ) > promptlen
        let line = strpart( line, 0, promptlen )
    endif
    let line = line . a:cmd
    call setline( ".", line )
    call SlimvEndOfReplBuffer()
    set nomodified
endfunction

" Add command list to the command history
function! SlimvAddHistory( cmd )
    if !exists( 'g:slimv_cmdhistory' )
        let g:slimv_cmdhistory = []
    endif
    let i = 0
    while i < len( a:cmd )
        " Trim trailing whitespaces from the command
        let command = substitute( a:cmd[i], "\\(.*[^ ]\\)\\s*", "\\1", "g" )
        if len( a:cmd ) > 1 || len( g:slimv_cmdhistory ) == 0 || command != g:slimv_cmdhistory[-1]
            " Add command only if differs from the last one
            call add( g:slimv_cmdhistory, command )
        endif
        let i = i + 1
    endwhile
    let g:slimv_cmdhistorypos = len( g:slimv_cmdhistory )
endfunction

" Recall command from the command history at the marked position
function! SlimvRecallHistory()
    if g:slimv_cmdhistorypos >= 0 && g:slimv_cmdhistorypos < len( g:slimv_cmdhistory )
        call SlimvSetCommandLine( g:slimv_cmdhistory[g:slimv_cmdhistorypos] )
    else
        call SlimvSetCommandLine( "" )
    endif
endfunction

" Return missing parens, double quotes, etc to properly close form
function! s:CloseForm( lines )
    let form = join( a:lines, "\n" )
    let end = ''
    let i = 0
    while i < len( form )
        if form[i] == '"'
            " Inside a string
            let end = '"' . end
            let i += 1
            while i < len( form )
                if form[i] == '\'
                    " Ignore next character
                    let i += 2
                elseif form[i] == '"'
                    let end = end[1:]
                    break
                else
                    let i += 1
                endif
            endwhile
        elseif form[i] == ';'
            " Inside a comment
            let end = "\n" . end
            let cend = match(form, "\n", i)
            if cend == -1
                break
            endif
            let i = cend
            let end = end[1:]
        else
            " We are outside of strings and comments, now we shall count parens
            if form[i] == '('
                let end = ')' . end
            elseif form[i] == '[' && SlimvGetFiletype() == 'clojure'
                let end = ']' . end
            elseif form[i] == '{' && SlimvGetFiletype() == 'clojure'
                let end = '}' . end
            elseif form[i] == ')' || ((form[i] == ']' || form[i] == '}') && SlimvGetFiletype() == 'clojure')
                if len( end ) == 0 || end[0] != form[i]
                    " Oops, too many closing parens or invalid closing paren
                    return 'ERROR'
                endif
                let end = end[1:]
            endif
        endif
        let i += 1
    endwhile
    return end
endfunction

" Return Lisp source code indentation at the given line
function! SlimvIndent( lnum )
    if a:lnum <= 1
        " Start of the file
        return 0
    endif
    let pnum = prevnonblank(a:lnum - 1)
    if pnum == 0
        " Hit the start of the file, use zero indent.
        return 0
    endif
    " Find start of current form
    let [l, c] = searchpairpos( '(', '', ')', 'nbW', s:skip_sc, pnum )
    if l == pnum
        let line = getline( l )
        let parent = strpart( line, 0, c )
        if match( parent, '\c(\s*\(flet\|labels\|macrolet\)\s*(\s*(\s*$' ) >= 0
            " Handle special indentation style for flet, labels, etc.
            return c + 1
        endif
        " Found opening paren in the previous line, let's find out the function name
        let func = matchstr( line, '\<\k*\>', c )
        " If it's a keyword, keep the indentation straight
        if strpart(func, 0, 1) == ':'
            return c
        endif
        if SlimvGetFiletype() == 'clojure' && match( func, 'defn$' ) >= 0
            " Fix clojure specific indentation issues not handled by the default lisp.vim
            return c + 1
        endif
        " Remove package specification
        let func = substitute(func, '^.*:', '', '')
        if func != '' && g:slimv_swank && s:swank_connected
            let s:indent = ''
            silent execute 'python get_indent_info("' . func . '")'
            if s:indent >= '0' && s:indent <= '9'
                " Function has &body argument, so indent by 2 spaces from the opening '('
                return c + 1
            endif
        endif
    endif

    " Use default Lisp indening
    set lisp
    let li = lispindent(a:lnum)
    set nolisp
    return li
endfunction 

" Send command line to REPL buffer
" Arguments: close = add missing closing parens
function! SlimvSendCommand( close )
    call SlimvRefreshModeOn()
    let lastline = line( "'s" )
    let lastcol  =  col( "'s" )
    if lastline > 0
        if line( "." ) >= lastline
            " Trim the prompt from the beginning of the command line
            " The user might have overwritten some parts of the prompt
            let cmdline = getline( lastline )
            let c = 0
            while c < lastcol - 1 && cmdline[c] == s:prompt[c]
                let c = c + 1
            endwhile
            let cmd = [ strpart( getline( lastline ), c ) ]

            " Build a possible multi-line command
            let l = lastline + 1
            while l <= line("$")
                call add( cmd, strpart( getline( l ), 0) )
                let l = l + 1
            endwhile

            " Count the number of opening and closing braces
            let end = s:CloseForm( cmd )
            if end == 'ERROR'
                " Too many closing parens
                call SlimvErrorWait( "Too many or invalid closing parens found." )
                return
            endif
            let echoing = 0
            if a:close && end != ''
                " Close form if necessary and evaluate it
                let cmd[len(cmd)-1] = cmd[len(cmd)-1] . end
                let end = ''
                let echoing = 1
            endif
            if end == ''
                " Expression finished, let's evaluate it
                " but first add it to the history
                call SlimvAddHistory( cmd )
                " Evaluate, but echo only when form is actually closed here
                call SlimvSend( cmd, g:slimv_repl_open, echoing )
            else
                " Expression is not finished yet, indent properly and wait for completion
                " Indentation works only if lisp indentation is switched on
                let l = line('.') + 1
                call append( '.', '' )
                call setline( l, repeat( ' ', SlimvIndent(l) ) )
                normal! j$
            endif
        endif
    else
        call append( '$', "Slimv error: previous EOF mark not found, re-enter last form:" )
        call append( '$', "" )
        call SlimvEndOfReplBuffer()
        call SlimvMarkBufferEnd()
        set nomodified
    endif
endfunction

" Close current top level form by adding the missing parens
function! SlimvCloseForm()
    let l2 = line( '.' )
    call SlimvFindDefunStart()
    let l1 = line( '.' )
    let form = []
    let l = l1
    while l <= l2
        call add( form, getline( l ) )
        let l = l + 1
    endwhile
    let end = s:CloseForm( form )
    if end == 'ERROR'
        " Too many closing parens
        call SlimvErrorWait( "Too many or invalid closing parens found." )
    elseif end != ''
        " Add missing parens
        if end[0] == "\n"
            call append( l2, end[1:] )
        else
            call setline( l2, getline( l2 ) . end )
        endif
    endif
    normal! %
endfunction

" Handle insert mode 'Backspace' keypress in the REPL buffer
function! SlimvHandleBS()
    if line( "." ) == line( "'s" ) && col( "." ) <= col( "'s" )
        " No BS allowed before the previous EOF mark
        return ""
    else
        return "\<BS>"
    endif
endfunction

" Recall previous command from command history
function! s:PreviousCommand()
    if exists( 'g:slimv_cmdhistory' ) && g:slimv_cmdhistorypos > 0
        let g:slimv_cmdhistorypos = g:slimv_cmdhistorypos - 1
        call SlimvRecallHistory()
    endif
endfunction

" Recall next command from command history
function! s:NextCommand()
    if exists( 'g:slimv_cmdhistory' ) && g:slimv_cmdhistorypos < len( g:slimv_cmdhistory )
        let g:slimv_cmdhistorypos = g:slimv_cmdhistorypos + 1
        call SlimvRecallHistory()
    else
        call SlimvSetCommandLine( "" )
    endif
endfunction

" Handle insert mode 'Up' keypress in the REPL buffer
function! SlimvHandleUp()
    if line( "." ) >= line( "'s" )
        if exists( 'g:slimv_cmdhistory' ) && g:slimv_cmdhistorypos == len( g:slimv_cmdhistory )
            call SlimvRefresh()
            call SlimvEndOfReplBuffer()
            call SlimvMarkBufferEnd()
            startinsert!
        endif
        call s:PreviousCommand()
    else
        normal! gk
    endif
endfunction

" Handle insert mode 'Down' keypress in the REPL buffer
function! SlimvHandleDown()
    if line( "." ) >= line( "'s" )
        call s:NextCommand()
    else
        normal! gj
    endif
endfunction

" Handle normal mode 'Enter' keypress in the REPL buffer
function! SlimvHandleEnter()
    let line = getline('.')
    if s:debug_activated
        " Check if Enter was pressed in a section printed by the SWANK debugger
        let item = matchstr( line, '\d\+' )
        if item != ''
            let section = getline( line('.') - item - 1 )
            if section[0:8] == 'Restarts:'
                " Apply item-th restart
                call SlimvEval( [item] )
                return
            endif
            if section[0:9] == 'Backtrace:'
                " Display item-th frame, we signal frames by prefixing with '#'
                call SlimvEval( ['#' . item] )
                return
            endif
        endif
    endif
    if line[0:9] == 'Inspecting'
        " Reload inspected item
        call SlimvEval( ['[0]'] )
        return
    endif

    if line[0] == '['
        if line[0:3] == '[<<]'
            " Pop back up in the inspector
            let item = '-1'
        else
            " Inspect n-th part
            let item = matchstr( line, '\d\+' )
        endif
        if item != ''
            call SlimvEval( ['[' . item . ']'] )
            return
        endif
    endif

    if line[0] == '<'
        " Inspector n-th action
        let item = matchstr( line, '\d\+' )
        if item != ''
            call SlimvEval( ['<' . item . '>'] )
            return
        endif
    endif

    " No special treatment, perform the original function
    execute "normal! \<CR>"
endfunction

" Go to command line and recall previous command from command history
function! SlimvPreviousCommand()
    call SlimvEndOfReplBuffer()
    if line( "." ) >= line( "'s" )
        call s:PreviousCommand()
    endif
endfunction

" Go to command line and recall next command from command history
function! SlimvNextCommand()
    call SlimvEndOfReplBuffer()
    if line( "." ) >= line( "'s" )
        call s:NextCommand()
    endif
endfunction

" Handle interrupt (Ctrl-C) keypress in the REPL buffer
function! SlimvInterrupt()
    if g:slimv_swank
        call SlimvCommand( 'python swank_interrupt()' )
    else
        call SlimvSend( ['SLIMV::INTERRUPT'], 0, 1 )
    endif
    call SlimvRefreshReplBuffer()
endfunction

" Select a specific restart in debugger
function! SlimvDebugCommand( cmd )
    if g:slimv_swank
        if s:swank_connected
            if s:debug_activated
                call SlimvCommand( 'python ' . a:cmd . '()' )
                call SlimvRefreshReplBuffer()
            else
                call SlimvError( "Debugger is not activated." )
            endif
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    endif
endfunction

" List current Lisp threads
function! SlimvListThreads()
    if g:slimv_swank
        if s:swank_connected
            call SlimvCommand( 'python swank_list_threads()' )
            call SlimvRefreshReplBuffer()
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    endif
endfunction

" Kill thread selected from the Thread List
function! SlimvKillThread()
    if g:slimv_swank
        if s:swank_connected
            let line = getline('.')
            let item = matchstr( line, '\d\+' )
            let item = input( 'Thread to kill: ', item )
            if item != ''
                call SlimvCommand( 'python swank_debug_thread(' . item . ')' )
                call SlimvRefreshReplBuffer()
            endif
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    endif
endfunction

" Debug thread selected from the Thread List
function! SlimvDebugThread()
    if g:slimv_swank
        if s:swank_connected
            let line = getline('.')
            let item = matchstr( line, '\d\+' )
            let item = input( 'Thread to debug: ', item )
            if item != ''
                call SlimvCommand( 'python swank_debug_thread(' . item . ')' )
                call SlimvRefreshReplBuffer()
            endif
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    endif
endfunction

" Display function argument list
function! SlimvArglist()
    let l = line('.')
    let c = col('.') - 1
    let line = getline('.')
    call s:SetKeyword()
    if s:swank_connected && c > 1 && line[c-2] =~ '\k'
        let save_ve = &virtualedit
        set virtualedit=onemore
        " Display only if entering the first space after a keyword
        let matchb = max( [l-100, 1] )
        let [l0, c0] = searchpairpos( '(', '', ')', 'nbW', s:skip_sc, matchb )
        if l0 > 0
            " Found opening paren, let's find out the function name
            let arg = matchstr( line, '\<\k*\>', c0 )
            if arg != ''
                " Ask function argument list from SWANK
                let msg = SlimvCommandGetResponse( ':operator-arglist', 'python swank_op_arglist("' . arg . '")' )
                if msg != ''
                    " Print argument list in status line with newlines removed.
                    " Disable showmode until the next ESC to prevent
                    " immeditate overwriting by the "-- INSERT --" text.
                    let s:save_showmode = &showmode
                    set noshowmode
                    let msg = substitute( msg, "\n", "", "g" )
                    redraw
                    if match( msg, arg ) != 1
                        " Function name is not received from REPL
                        call SlimvShortEcho( "(" . arg . ' ' . msg[1:] )
                    else
                        call SlimvShortEcho( msg )
                    endif
                endif
            endif
        endif
        let &virtualedit=save_ve
    endif

    " Return empty string because this function is called from an insert mode mapping
    return ''
endfunction

" Start and connect slimv server
" This is a quite dummy function that just evaluates the empty string
function! SlimvConnectServer()
    if g:slimv_swank
        let repl_buf = bufnr( g:slimv_repl_file )
        let repl_win = bufwinnr( repl_buf )
        if g:slimv_repl_open && ( repl_buf == -1 || ( g:slimv_repl_split && repl_win == -1 ) )
            call SlimvOpenReplBuffer()
        endif 
        if s:swank_connected
            python swank_disconnect()
            let s:swank_connected = 0
        endif 
        call SlimvConnectSwank()
    endif
    if !g:slimv_swank
        call SlimvSend( ['SLIMV::OUTPUT::' . s:repl_name ], g:slimv_repl_open, 1 )
    endif
endfunction

" Refresh REPL buffer continuously
function! SlimvRefresh()
    if bufnr( g:slimv_repl_file ) == -1 || g:slimv_swank
        " REPL not opened, no need to refresh
        return
    endif
    if bufnr( g:slimv_repl_file ) != bufnr( "%" )
        " REPL is not the current window, activate it
        call SlimvOpenReplBuffer()
    else
        try
            execute "silent view! " . s:repl_name
            let s:last_size = getfsize( s:repl_name )
            let s:last_update = localtime()
        catch /.*/
            " Oops, something went wrong, the buffer will not be refreshed this time
        endtry
    endif
endfunction

" Get the last region (visual block)
function! SlimvGetRegion() range
    let oldpos = getpos( '.' ) 
    if mode() == 'v' || mode() == 'V'
        let lines = getline( a:firstline, a:lastline )
        let firstcol = col( a:firstline ) - 1
        let lastcol  = col( a:lastline  ) - 2
    else
        let lines = getline( "'<", "'>" )
        let firstcol = col( "'<" ) - 1
        let lastcol  = col( "'>" ) - 2
    endif
    if lastcol >= 0
        let lines[len(lines)-1] = lines[len(lines)-1][ : lastcol]
    else
        let lines[len(lines)-1] = ''
    endif
    let lines[0] = lines[0][firstcol : ]

    " Find and add package/namespace definition in front of the region
    if g:slimv_package
        call setreg( '"s', '' )
        call SlimvFindPackage()
        let sel = SlimvGetSelection()
        if sel != ''
            let lines = [sel] + lines
        endif
    endif
    call setpos( '.', oldpos ) 
    return lines
endfunction

" Eval buffer lines in the given range
function! SlimvEvalRegion() range
    let lines = SlimvGetRegion()
    call SlimvEval( lines )
endfunction

" Eval contents of the 's' register
function! SlimvEvalSelection()
    let lines = [SlimvGetSelection()]
    call SlimvEval( lines )
endfunction

" Eval Lisp form.
" Form given in the template is passed to Lisp without modification.
function! SlimvEvalForm( template )
    let lines = [a:template]
    call SlimvEval( lines )
endfunction

" Eval Lisp form, with the given parameter substituted in the template.
" %1 string is substituted with par1
function! SlimvEvalForm1( template, par1 )
    let p1 = escape( a:par1, '&' )
    let temp1 = substitute( a:template, '%1', p1, 'g' )
    let lines = [temp1]
    call SlimvEval( lines )
endfunction

" Eval Lisp form, with the given parameters substituted in the template.
" %1 string is substituted with par1
" %2 string is substituted with par2
function! SlimvEvalForm2( template, par1, par2 )
    let p1 = escape( a:par1, '&' )
    let p2 = escape( a:par2, '&' )
    let temp1 = substitute( a:template, '%1', p1, 'g' )
    let temp2 = substitute( temp1,      '%2', p2, 'g' )
    let lines = [temp2]
    call SlimvEval( lines )
endfunction


" =====================================================================
"  Special functions
" =====================================================================

" Evaluate top level form at the cursor pos
function! SlimvEvalDefun()
    let oldpos = getpos( '.' ) 
    if !SlimvSelectDefun()
        return
    endif
    call SlimvFindPackage()
    call setpos( '.', oldpos ) 
    call SlimvEvalSelection()
endfunction

" Evaluate the whole buffer
function! SlimvEvalBuffer()
    let lines = getline( 1, '$' )
    call SlimvEval( lines )
endfunction

" Return frame number if we are in the Backtrace section of the debugger
function! s:DebugFrame()
    if g:slimv_swank && s:swank_connected && s:debug_activated
        " Check if we are in SLDB
        let repl_buf = bufnr( g:slimv_repl_file )
        if repl_buf != -1 && repl_buf == bufnr( "%" )
            let line = getline('.')
            let item = matchstr( line, '\d\+' )
            if item != ''
                let section = getline( line('.') - item - 1 )
                if section[0:9] == 'Backtrace:'
                    return item
                endif
            endif
        endif
    endif
    return ''
endfunction

" Evaluate current s-expression at the cursor pos
function! SlimvEvalExp()
    let oldpos = getpos( '.' ) 
    if !SlimvSelectForm()
        return
    endif
    call SlimvFindPackage()
    call setpos( '.', oldpos ) 
    call SlimvEvalSelection()
endfunction

" Evaluate and pretty print current s-expression
function! SlimvPprintEvalExp()
    let oldpos = getpos( '.' ) 
    if !SlimvSelectForm()
        return
    endif
    call SlimvFindPackage()
    call setpos( '.', oldpos ) 
    call SlimvEvalForm1( g:slimv_template_pprint, SlimvGetSelection() )
endfunction

" Evaluate expression entered interactively
function! SlimvInteractiveEval()
    let frame = s:DebugFrame()
    if frame != ''
        " We are in the debugger, eval expression in the frame the cursor stands on
        let e = input( 'Eval in frame: ' )
        if e != ''
            let result = SlimvCommandGetResponse( ':eval-string-in-frame', 'python swank_eval_in_frame("' . e . '", ' . frame . ')' )
            if result != ''
                redraw
                echo result
            endif
        endif
    else
        let e = input( 'Eval: ' )
        if e != ''
            call SlimvEval([e])
        endif
    endif
endfunction

" Undefine function
function! SlimvUndefineFunction()
    if g:slimv_swank
        if s:swank_connected
            call SlimvCommand( 'python swank_undefine_function("' . SlimvSelectSymbol() . '")' )
            call SlimvRefreshReplBuffer()
        endif
    else
        call SlimvEvalForm1( g:slimv_template_undefine, SlimvSelectSymbol() )
    endif
endfunction

" ---------------------------------------------------------------------

" General part of the various macroexpand functions
function! SlimvMacroexpandGeneral( command )
    call SlimvFindDefunStart()
    let line = getline( "." )
    if match( line, '(\s*defmacro\s' ) < 0
        " The form does not contain 'defmacro', put it in a macroexpand block
        if !SlimvSelectForm()
            return
        endif
        let m = "(" . a:command . " '" . SlimvGetSelection() . ")"
    else
        " The form is a 'defmacro', so do a macroexpand from the macro name and parameters
        if SlimvGetFiletype() == 'clojure'
            " Some Vim configs (e.g. matchit.vim) include the trailing ']' after '%' in Visual mode
            silent normal! vt[%ht]"sy
        else
            silent normal! vt(])"sy
        endif
        let m = SlimvGetSelection() . '))'
        let m = substitute( m, "defmacro\\s*", a:command . " '(", 'g' )
        if SlimvGetFiletype() == 'clojure'
            " Remove opening bracket from the parameter list
            " TODO: fix this for multi-line macro header
            let m = substitute( m, "\\[\\(.*\\)", "\\1", 'g' )
        else
            " Remove opening brace from the parameter list
            " The nice regular expression below says: remove the third '('
            " ( + something + ( + something + ( + something -> ( + something + ( + something + something
            " TODO: fix this for multi-line macro header
            let m = substitute( m, "\\(([^()]*([^()]*\\)(\\(.*\\)", "\\1\\2", 'g' )
        endif
    endif
    return m
endfunction

" Macroexpand-1 the current top level form
function! SlimvMacroexpand()
    if g:slimv_swank
        if s:swank_connected
            if !SlimvSelectForm()
                return
            endif
            let s:swank_form = SlimvGetSelection()
            call SlimvCommandUsePackage( 'python swank_macroexpand("s:swank_form")' )
        endif
    else
        let oldpos = getpos( '.' ) 
        let m = SlimvMacroexpandGeneral( "macroexpand-1" )
        call SlimvEvalForm1( g:slimv_template_macroexpand, m )
        call setpos( '.', oldpos ) 
    endif
endfunction

" Macroexpand the current top level form
function! SlimvMacroexpandAll()
    if g:slimv_swank
        if s:swank_connected
            if !SlimvSelectForm()
                return
            endif
            let s:swank_form = SlimvGetSelection()
            call SlimvCommandUsePackage( 'python swank_macroexpand_all("s:swank_form")' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        let oldpos = getpos( '.' ) 
        let m = SlimvMacroexpandGeneral( "macroexpand" )
        call SlimvEvalForm1( g:slimv_template_macroexpand_all, m )
        call setpos( '.', oldpos ) 
    endif
endfunction

" Switch trace on for the selected function (toggle for swank)
function! SlimvTrace()
    if g:slimv_swank
        if s:swank_connected
            let s = input( '(Un)trace: ', SlimvSelectSymbol() )
            if s != ''
                call SlimvCommandUsePackage( 'python swank_toggle_trace("' . s . '")' )
                redraw!
            endif
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        let s = input( 'Trace: ', SlimvSelectSymbol() )
        echo s
        if s != ''
            call SlimvEvalForm1( g:slimv_template_trace, s )
        endif
    endif
endfunction

" Switch trace off for the selected function (or all functions for swank)
function! SlimvUntrace()
    if g:slimv_swank
        if s:swank_connected
            let s:refresh_disabled = 1
            call SlimvCommand( 'python swank_untrace_all()' )
            let s:refresh_disabled = 0
            call SlimvRefreshReplBuffer()
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        let s = input( 'Untrace: ', SlimvSelectSymbol() )
        if s != ''
            call SlimvEvalForm1( g:slimv_template_untrace, s )
        endif
    endif
endfunction

" Disassemble the selected function
function! SlimvDisassemble()
    let s = input( 'Disassemble: ', SlimvSelectSymbol() )
    if s != ''
        if g:slimv_swank
            if s:swank_connected
                call SlimvCommandUsePackage( 'python swank_disassemble("' . s . '")' )
            else
                call SlimvError( "Not connected to SWANK server." )
            endif
        else
            call SlimvEvalForm1( g:slimv_template_disassemble, s )
        endif
    endif
endfunction

" Inspect symbol under cursor
function! SlimvInspect()
    let frame = s:DebugFrame()
    if frame != ''
        " Inspect selected for a frame in the debugger's Backtrace section
        let s = input( 'Inspect in frame ' . frame . ': ' )
        call SlimvCommand( 'python swank_inspect_in_frame("' . s . '", ' . frame . ')' )
        call SlimvRefreshReplBuffer()
        return
    else
        let s = input( 'Inspect: ', SlimvSelectSymbolExt() )
        if s != ''
            if g:slimv_swank
                if s:swank_connected
                    call SlimvCommandUsePackage( 'python swank_inspect("' . s . '")' )
                else
                    call SlimvError( "Not connected to SWANK server." )
                endif
            else
                call SlimvEvalForm1( g:slimv_template_inspect, s )
            endif
        endif
    endif
endfunction

" Cross reference: who calls
function! SlimvXrefBase( text, cmd )
    if g:slimv_swank
        if s:swank_connected
            let s = input( a:text, SlimvSelectSymbol() )
            if s != ''
                call SlimvCommandUsePackage( 'python swank_xref("' . s . '", "' . a:cmd . '")' )
            endif
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        call SlimvError( "SWANK is switched off." )
    endif
endfunction

" Cross reference: who calls
function! SlimvXrefCalls()
    call SlimvXrefBase( 'Who calls: ', ':calls' )
endfunction

" Cross reference: who references
function! SlimvXrefReferences()
    call SlimvXrefBase( 'Who references: ', ':references' )
endfunction

" Cross reference: who sets
function! SlimvXrefSets()
    call SlimvXrefBase( 'Who sets: ', ':sets' )
endfunction

" Cross reference: who binds
function! SlimvXrefBinds()
    call SlimvXrefBase( 'Who binds: ', ':binds' )
endfunction

" Cross reference: who macroexpands
function! SlimvXrefMacroexpands()
    call SlimvXrefBase( 'Who macroexpands: ', ':macroexpands' )
endfunction

" Cross reference: who specializes
function! SlimvXrefSpecializes()
    call SlimvXrefBase( 'Who specializes: ', ':specializes' )
endfunction

" Cross reference: list callers
function! SlimvXrefCallers()
    call SlimvXrefBase( 'List callers: ', ':callers' )
endfunction

" Cross reference: list callees
function! SlimvXrefCallees()
    call SlimvXrefBase( 'List callees: ', ':callees' )
endfunction

" ---------------------------------------------------------------------

" Compile and load profiler
function! SlimvLoadProfiler()
    if SlimvGetFiletype() == 'clojure'
        call SlimvError( "No profiler support for Clojure." )
    elseif b:SlimvImplementation() == 'sbcl'
        call SlimvError( "SBCL has a built-in profiler, no need to load it." )
    else
        let profiler = split( globpath( &runtimepath, 'slime/metering.lisp'), '\n' )
        if len( profiler ) == 0
            let profiler = split( globpath( &runtimepath, 'ftplugin/**/metering.lisp'), '\n' )
        endif
        if len( profiler ) > 0
            let filename = profiler[0]
            let filename = substitute( filename, '\\', '/', 'g' )
            call SlimvEvalForm2( g:slimv_template_compile_file, filename, 'T' )
        else
            call SlimvError( "metering.lisp is not found in the Vim ftplugin directory or below." )
        endif
    endif
endfunction

" Switch or toggle profiling on for the selected function
function! SlimvProfile()
    if g:slimv_swank
        if s:swank_connected
            let s = input( '(Un)profile: ', SlimvSelectSymbol() )
            if s != ''
                call SlimvCommandUsePackage( 'python swank_toggle_profile("' . s . '")' )
                redraw!
            endif
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        if SlimvGetFiletype() == 'clojure'
            call SlimvError( "No profiler support for Clojure." )
        else
            let s = input( 'Profile: ', SlimvSelectSymbol() )
            if s != ''
                call SlimvEvalForm1( g:slimv_template_profile, s )
            endif
        endif
    endif
endfunction

" Switch profiling on based on substring
function! SlimvProfileSubstring()
    if s:swank_connected
        let s = input( 'Profile by matching substring: ', SlimvSelectSymbol() )
        if s != ''
            let p = input( 'Package (RET for all packages): ' )
            call SlimvCommandUsePackage( 'python swank_profile_substring("' . s . '","' . p . '")' )
            redraw!
        endif
    else
        call SlimvError( "Not connected to SWANK server." )
    endif
endfunction

" Switch profiling off for the selected function
function! SlimvUnprofile()
    if SlimvGetFiletype() == 'clojure'
        call SlimvError( "No profiler support for Clojure." )
    else
        let s = input( 'Unprofile: ', SlimvSelectSymbol() )
        if s != ''
            call SlimvEvalForm1( g:slimv_template_unprofile, s )
        endif
    endif
endfunction

" Switch profiling completely off
function! SlimvUnprofileAll()
    if g:slimv_swank
        if s:swank_connected
            call SlimvCommandUsePackage( 'python swank_unprofile_all()' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        if SlimvGetFiletype() == 'clojure'
            call SlimvError( "No profiler support for Clojure." )
        else
            call SlimvEvalForm( g:slimv_template_unprofile_all )
        endif
    endif
endfunction

" Display list of profiled functions
function! SlimvShowProfiled()
    if g:slimv_swank
        if s:swank_connected
            call SlimvCommandUsePackage( 'python swank_profiled_functions()' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        if SlimvGetFiletype() == 'clojure'
            call SlimvError( "No profiler support for Clojure." )
        else
            call SlimvEvalForm( g:slimv_template_show_profiled )
        endif
    endif
endfunction

" Report profiling results
function! SlimvProfileReport()
    if g:slimv_swank
        if s:swank_connected
            call SlimvCommandUsePackage( 'python swank_profile_report()' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        if SlimvGetFiletype() == 'clojure'
            call SlimvError( "No profiler support for Clojure." )
        else
            call SlimvEvalForm( g:slimv_template_profile_report )
        endif
    endif
endfunction

" Reset profiling counters
function! SlimvProfileReset()
    if g:slimv_swank
        if s:swank_connected
            call SlimvCommandUsePackage( 'python swank_profile_reset()' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        if SlimvGetFiletype() == 'clojure'
            call SlimvError( "No profiler support for Clojure." )
        else
            call SlimvEvalForm( g:slimv_template_profile_reset )
        endif
    endif
endfunction

" ---------------------------------------------------------------------

" Compile the current top-level form
function! SlimvCompileDefun()
    let oldpos = getpos( '.' ) 
    if !SlimvSelectDefun()
        call setpos( '.', oldpos ) 
        return
    endif
    if g:slimv_swank
        if s:swank_connected
            let s:swank_form = SlimvGetSelection()
            call SlimvCommandUsePackage( 'python swank_compile_string("s:swank_form")' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        call SlimvFindPackage()
        let form = SlimvGetSelection()
        let form = substitute( form, '"', '\\\\"', 'g' )
        call SlimvEvalForm1( g:slimv_template_compile_string, form )
        call setpos( '.', oldpos ) 
    endif
endfunction

" Compile and load whole file
function! SlimvCompileLoadFile()
    let filename = fnamemodify( bufname(''), ':p' )
    let filename = substitute( filename, '\\', '/', 'g' )
    if &modified
        let answer = SlimvErrorAsk( '', "Save file before compiling [Y/n]?" )
        if answer[0] != 'n' && answer[0] != 'N'
            write
        endif
    endif
    if g:slimv_swank
        if s:swank_connected
            let s:compiled_file = ''
            call SlimvCommandUsePackage( 'python swank_compile_file("' . filename . '")' )
            let starttime = localtime()
            while s:compiled_file == '' && localtime()-starttime < g:slimv_timeout
                call SlimvSwankResponse()
            endwhile
            if s:compiled_file != ''
                call SlimvCommandUsePackage( 'python swank_load_file("' . s:compiled_file . '")' )
                let s:compiled_file = ''
            endif
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        call SlimvEvalForm2( g:slimv_template_compile_file, filename, 'T' )
    endif
endfunction

" Compile whole file
function! SlimvCompileFile()
    let filename = fnamemodify( bufname(''), ':p' )
    let filename = substitute( filename, '\\', '/', 'g' )
    if &modified
        let answer = SlimvErrorAsk( '', "Save file before compiling [Y/n]?" )
        if answer[0] != 'n' && answer[0] != 'N'
            write
        endif
    endif
    if g:slimv_swank
        if s:swank_connected
            call SlimvCommandUsePackage( 'python swank_compile_file("' . filename . '")' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        call SlimvEvalForm2( g:slimv_template_compile_file, filename, 'NIL' )
    endif
endfunction

function! SlimvCompileRegion() range
    let oldpos = getpos( '.' ) 
    let lines = SlimvGetRegion()
    let region = join( lines, "\n" )
    if g:slimv_swank
        if s:swank_connected
            let s:swank_form = region
            call SlimvCommandUsePackage( 'python swank_compile_string("s:swank_form")' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        call SlimvFindPackage()
        let region = substitute( region, '"', '\\\\"', 'g' )
        call SlimvEvalForm1( g:slimv_template_compile_string, region )
        call setpos( '.', oldpos ) 
    endif
endfunction

" ---------------------------------------------------------------------

" Describe the selected symbol
function! SlimvDescribeSymbol()
    if g:slimv_swank
        if s:swank_connected
            call SlimvCommandUsePackage( 'python swank_describe_symbol("' . SlimvSelectSymbol() . '")' )
        else
            call SlimvError( "Not connected to SWANK server." )
        endif
    else
        call SlimvEvalForm1( g:slimv_template_describe, SlimvSelectSymbol() )
    endif
endfunction

" Display symbol description in balloonexpr
function! SlimvDescribe(arg)
    let arg=a:arg
    if a:arg == ''
        let arg = expand('<cword>')
    endif
    if !s:swank_connected
        return ''
    endif
    let arglist = SlimvCommandGetResponse( ':operator-arglist', 'python swank_op_arglist("' . arg . '")' )
    if arglist == ''
        " Not able to fetch arglist, assuming function is not defined
        " Skip calling describe, otherwise SWANK goes into the debugger
        return ''
    endif
    let msg = SlimvCommandGetResponse( ':describe-function', 'python swank_describe_function("' . arg . '")' )
    if msg == ''
        " No describe info, display arglist
        if match( arglist, arg ) != 1
            " Function name is not received from REPL
            return "(" . arg . ' ' . arglist[1:]
        else
            return arglist
        endif
    else
        return msg
    endif
endfunction

" Setup balloonexp to display symbol description
if g:slimv_swank && g:slimv_balloon && has( 'balloon_eval' )
    "setlocal balloondelay=100
    setlocal ballooneval
    setlocal balloonexpr=SlimvDescribe(v:beval_text)
endif

" Apropos of the selected symbol
function! SlimvApropos()
    call SlimvEvalForm1( g:slimv_template_apropos, SlimvSelectSymbol() )
endfunction

" Generate tags file using ctags
function! SlimvGenerateTags()
    if exists( 'g:slimv_ctags' ) && g:slimv_ctags != ''
        execute 'silent !' . g:slimv_ctags
    else
        call SlimvError( "Copy ctags to the Vim path or define g:slimv_ctags." )
    endif
endfunction

" ---------------------------------------------------------------------

" Find word in the CLHS symbol database, with exact or partial match.
" Return either the first symbol found with the associated URL,
" or the list of all symbols found without the associated URL.
function! SlimvFindSymbol( word, exact, all, db, root, init )
    if a:word == ''
        return []
    endif
    if !a:all && a:init != []
        " Found something already at a previous db lookup, no need to search this db
        return a:init
    endif
    let lst = a:init
    let i = 0
    let w = tolower( a:word )
    if a:exact
        while i < len( a:db )
            " Try to find an exact match
            if a:db[i][0] == w
                " No reason to check a:all here
                return [a:db[i][0], a:root . a:db[i][1]]
            endif
            let i = i + 1
        endwhile
    else
        while i < len( a:db )
            " Try to find the symbol starting with the given word
            let w2 = escape( w, '~' )
            if match( a:db[i][0], w2 ) == 0
                if a:all
                    call add( lst, a:db[i][0] )
                else
                    return [a:db[i][0], a:root . a:db[i][1]]
                endif
            endif
            let i = i + 1
        endwhile
    endif

    " Return whatever found so far
    return lst
endfunction

" Lookup word in Common Lisp Hyperspec
function! SlimvLookup( word )
    " First try an exact match
    let w = a:word
    let symbol = []
    while symbol == []
        let symbol = b:SlimvHyperspecLookup( w, 1, 0 )
        if symbol == []
            " Symbol not found, try a match on beginning of symbol name
            let symbol = b:SlimvHyperspecLookup( w, 0, 0 )
            if symbol == []
                " We are out of luck, can't find anything
                let msg = 'Symbol ' . w . ' not found. Hyperspec lookup word: '
                let val = ''
            else
                let msg = 'Hyperspec lookup word: '
                let val = symbol[0]
            endif
            " Ask user if this is that he/she meant
            let w = input( msg, val )
            if w == ''
                " OK, user does not want to continue
                return
            endif
            let symbol = []
        endif
    endwhile
    if symbol != []
        " Symbol found, open HS page in browser
        if match( symbol[1], ':' ) < 0 && exists( g:slimv_hs_root )
            let page = g:slimv_hs_root . symbol[1]
        else
            " URL is already a fully qualified address
            let page = symbol[1]
        endif
        if exists( "g:slimv_browser_cmd" )
            " We have an given command to start the browser
            silent execute '! ' . g:slimv_browser_cmd . ' ' . page
        else
            if g:slimv_windows
                " Run the program associated with the .html extension
                silent execute '! start ' . page
            else
                " On Linux it's not easy to determine the default browser
                " Ask help from Python webbrowser package
                let pycmd = "import webbrowser; webbrowser.open('" . page . "')"
                silent execute '! ' . g:slimv_python . ' -c "' . pycmd . '"'
            endif
        endif
        " This is needed especially when using text browsers
        redraw!
    endif
endfunction

" Lookup current symbol in the Common Lisp Hyperspec
function! SlimvHyperspec()
    call SlimvLookup( SlimvSelectSymbol() )
endfunction

" Complete symbol name starting with 'base'
function! SlimvComplete( base )
    " Find all symbols starting with "a:base"
    if a:base == ''
        return []
    endif
    if g:slimv_swank && s:swank_connected
        if g:slimv_simple_compl
            let msg = SlimvCommandGetResponse( ':simple-completions', 'python swank_completions("' . a:base . '")' )
        else
            let msg = SlimvCommandGetResponse( ':fuzzy-completions', 'python swank_fuzzy_completions("' . a:base . '")' )
        endif
        if msg != ''
            " We have a completion list from SWANK
            let res = split( msg, '\n' )
            return res
        endif
    endif

    " No completion yet, try to fetch it from the Hyperspec database
    let res = []
    let symbol = b:SlimvHyperspecLookup( a:base, 0, 1 )
    call sort( symbol )
    for m in symbol
        if m =~ '^' . a:base
            call add( res, m )
        endif
    endfor
    return res
endfunction

" Complete function that uses the Hyperspec database
function! SlimvOmniComplete( findstart, base )
    if a:findstart
        " Locate the start of the symbol name
        call s:SetKeyword()
        let upto = strpart( getline( '.' ), 0, col( '.' ) - 1)
        let p = match(upto, '\k\+$')
        return p 
    else
        return SlimvComplete( a:base )
    endif
endfunction

" Define complete function only if none is defined yet
if &omnifunc == ''
    set omnifunc=SlimvOmniComplete
endif

" Complete function for user-defined commands
function! SlimvCommandComplete( arglead, cmdline, cursorpos )
    " Locate the start of the symbol name
    call s:SetKeyword()
    let upto = strpart( a:cmdline, 0, a:cursorpos )
    let base = matchstr(upto, '\k\+$')
    let ext  = matchstr(upto, '\S*\k\+$')
    let compl = SlimvComplete( base )
    if len(compl) > 0 && base != ext
        " Command completion replaces whole word between spaces, so we
        " need to add any prefix present in front of the keyword, like '('
        let prefix = strpart( ext, 0, len(ext) - len(base) )
        let i = 0
        while i < len(compl)
            let compl[i] = prefix . compl[i]
            let i = i + 1
        endwhile
    endif
    return compl
endfunction

" Set current package
function! SlimvSetPackage()
    if s:swank_connected
        let oldpos = getpos( '.' )
        call SlimvFindPackage()
        call setpos( '.', oldpos )
        let pkg = input( 'Package: ', s:swank_package )
        if pkg != ''
            let s:refresh_disabled = 1
            call SlimvCommand( 'python swank_set_package("' . pkg . '")' )
            let s:refresh_disabled = 0
            call SlimvRefreshReplBuffer()
        endif
    else
        call SlimvError( "Not connected to SWANK server." )
    endif
endfunction

" =====================================================================
"  Slimv keybindings
" =====================================================================

" <Leader> timeouts in 1000 msec by default, if this is too short,
" then increase 'timeoutlen'

" Map keyboard keyset dependant shortcut to command and also add it to menu
function! s:MenuMap( name, shortcut1, shortcut2, command )
    if g:slimv_keybindings == 1
        " Short (one-key) keybinding set
        let shortcut = a:shortcut1
    elseif g:slimv_keybindings == 2
        " Easy to remember (two-key) keybinding set
        let shortcut = a:shortcut2
    endif

    if shortcut != ''
        execute "noremap <silent> " . shortcut . " " . a:command
        if a:name != '' && g:slimv_menu == 1
            silent execute "amenu " . a:name . "<Tab>" . shortcut . " " . a:command
        endif
    elseif a:name != '' && g:slimv_menu == 1
        silent execute "amenu " . a:name . " " . a:command
    endif
endfunction

" Initialize buffer by adding buffer specific mappings
function! SlimvInitBuffer()
    if g:slimv_swank
        " Map space to display function argument list in status line
        inoremap <silent> <buffer> <Space>    <Space><C-R>=SlimvArglist()<CR>
        "noremap  <silent> <buffer> <C-C>      :call SlimvInterrupt()<CR>
        au InsertLeave * :let &showmode=s:save_showmode
    endif
    inoremap <silent> <buffer> <C-X>0     <C-O>:call SlimvCloseForm()<CR>
    inoremap <silent> <buffer> <Tab>      <C-R>=pumvisible() ? "\<lt>C-N>" : "\<lt>C-X>\<lt>C-O>"<CR>
endfunction

" Edit commands
call s:MenuMap( 'Slim&v.Edi&t.Close-&Form',                     g:slimv_leader.')',  g:slimv_leader.'tc',  ':<C-U>call SlimvCloseForm()<CR>' )
call s:MenuMap( 'Slim&v.Edi&t.&Complete-Symbol<Tab>Tab',        '',                  '',                   '<Ins><C-X><C-O>' )
call s:MenuMap( 'Slim&v.Edi&t.&Paredit-Toggle',                 g:slimv_leader.'(',  g:slimv_leader.'(t',  ':<C-U>call PareditToggle()<CR>' )

" Evaluation commands
call s:MenuMap( 'Slim&v.&Evaluation.Eval-&Defun',               g:slimv_leader.'d',  g:slimv_leader.'ed',  ':<C-U>call SlimvEvalDefun()<CR>' )
call s:MenuMap( 'Slim&v.&Evaluation.Eval-Current-&Exp',         g:slimv_leader.'e',  g:slimv_leader.'ee',  ':<C-U>call SlimvEvalExp()<CR>' )
if !g:slimv_swank
call s:MenuMap( 'Slim&v.&Evaluation.&Pprint-Eval-Exp',          g:slimv_leader.'E',  g:slimv_leader.'ep',  ':<C-U>call SlimvPprintEvalExp()<CR>' )
endif
call s:MenuMap( 'Slim&v.&Evaluation.Eval-&Region',              g:slimv_leader.'r',  g:slimv_leader.'er',  ':call SlimvEvalRegion()<CR>' )
call s:MenuMap( 'Slim&v.&Evaluation.Eval-&Buffer',              g:slimv_leader.'b',  g:slimv_leader.'eb',  ':<C-U>call SlimvEvalBuffer()<CR>' )
call s:MenuMap( 'Slim&v.&Evaluation.Interacti&ve-Eval\.\.\.',   g:slimv_leader.'v',  g:slimv_leader.'ei',  ':call SlimvInteractiveEval()<CR>' )
call s:MenuMap( 'Slim&v.&Evaluation.&Undefine-Function',        g:slimv_leader.'u',  g:slimv_leader.'eu',  ':call SlimvUndefineFunction()<CR>' )

" Debug commands
call s:MenuMap( 'Slim&v.De&bugging.Macroexpand-&1',             g:slimv_leader.'1',  g:slimv_leader.'m1',  ':<C-U>call SlimvMacroexpand()<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.&Macroexpand-All',           g:slimv_leader.'m',  g:slimv_leader.'ma',  ':<C-U>call SlimvMacroexpandAll()<CR>' )

if g:slimv_swank
call s:MenuMap( 'Slim&v.De&bugging.Toggle-&Trace\.\.\.',        g:slimv_leader.'t',  g:slimv_leader.'dt',  ':call SlimvTrace()<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.U&ntrace-All',               g:slimv_leader.'T',  g:slimv_leader.'du',  ':call SlimvUntrace()<CR>' )
else
call s:MenuMap( 'Slim&v.De&bugging.&Trace\.\.\.',               g:slimv_leader.'t',  g:slimv_leader.'dt',  ':call SlimvTrace()<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.U&ntrace\.\.\.',             g:slimv_leader.'T',  g:slimv_leader.'du',  ':call SlimvUntrace()<CR>' )
endif

call s:MenuMap( 'Slim&v.De&bugging.Disassemb&le\.\.\.',         g:slimv_leader.'l',  g:slimv_leader.'dd',  ':call SlimvDisassemble()<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.&Inspect\.\.\.',             g:slimv_leader.'i',  g:slimv_leader.'di',  ':call SlimvInspect()<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.&Abort',                     g:slimv_leader.'a',  g:slimv_leader.'da',  ':call SlimvDebugCommand("swank_invoke_abort")<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.&Quit-to-Toplevel',          g:slimv_leader.'q',  g:slimv_leader.'dq',  ':call SlimvDebugCommand("swank_throw_toplevel")<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.&Continue',                  g:slimv_leader.'n',  g:slimv_leader.'dc',  ':call SlimvDebugCommand("swank_invoke_continue")<CR>' )
if g:slimv_swank
call s:MenuMap( 'Slim&v.De&bugging.&List-Threads',              g:slimv_leader.'H',  g:slimv_leader.'dl',  ':call SlimvListThreads()<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.&Kill-Thread\.\.\.',         g:slimv_leader.'K',  g:slimv_leader.'dk',  ':call SlimvKillThread()<CR>' )
call s:MenuMap( 'Slim&v.De&bugging.&Debug-Thread\.\.\.',        g:slimv_leader.'G',  g:slimv_leader.'dg',  ':call SlimvDebugThread()<CR>' )
endif


" Compile commands
call s:MenuMap( 'Slim&v.&Compilation.Compile-&Defun',           g:slimv_leader.'D',  g:slimv_leader.'cd',  ':<C-U>call SlimvCompileDefun()<CR>' )
call s:MenuMap( 'Slim&v.&Compilation.Compile-&Load-File',       g:slimv_leader.'L',  g:slimv_leader.'cl',  ':<C-U>call SlimvCompileLoadFile()<CR>' )
call s:MenuMap( 'Slim&v.&Compilation.Compile-&File',            g:slimv_leader.'F',  g:slimv_leader.'cf',  ':<C-U>call SlimvCompileFile()<CR>' )
call s:MenuMap( 'Slim&v.&Compilation.Compile-&Region',          g:slimv_leader.'R',  g:slimv_leader.'cr',  ':call SlimvCompileRegion()<CR>' )

" Xref commands
call s:MenuMap( 'Slim&v.&Xref.Who-&Calls',                      g:slimv_leader.'xc', g:slimv_leader.'xc',  ':call SlimvXrefCalls()<CR>' )
call s:MenuMap( 'Slim&v.&Xref.Who-&References',                 g:slimv_leader.'xr', g:slimv_leader.'xr',  ':call SlimvXrefReferences()<CR>' )
call s:MenuMap( 'Slim&v.&Xref.Who-&Sets',                       g:slimv_leader.'xs', g:slimv_leader.'xs',  ':call SlimvXrefSets()<CR>' )
call s:MenuMap( 'Slim&v.&Xref.Who-&Binds',                      g:slimv_leader.'xb', g:slimv_leader.'xb',  ':call SlimvXrefBinds()<CR>' )
call s:MenuMap( 'Slim&v.&Xref.Who-&Macroexpands',               g:slimv_leader.'xm', g:slimv_leader.'xm',  ':call SlimvXrefMacroexpands()<CR>' )
call s:MenuMap( 'Slim&v.&Xref.Who-S&pecializes',                g:slimv_leader.'xp', g:slimv_leader.'xp',  ':call SlimvXrefSpecializes()<CR>' )
call s:MenuMap( 'Slim&v.&Xref.&List-Callers',                   g:slimv_leader.'xl', g:slimv_leader.'xl',  ':call SlimvXrefCallers()<CR>' )
call s:MenuMap( 'Slim&v.&Xref.List-Call&ees',                   g:slimv_leader.'xe', g:slimv_leader.'xe',  ':call SlimvXrefCallees()<CR>' )

" Profile commands
if g:slimv_swank
call s:MenuMap( 'Slim&v.&Profiling.Toggle-&Profile\.\.\.',      g:slimv_leader.'p',  g:slimv_leader.'pp',  ':<C-U>call SlimvProfile()<CR>' )
call s:MenuMap( 'Slim&v.&Profiling.Profile-&By-Substring\.\.\.',g:slimv_leader.'B',  g:slimv_leader.'pb',  ':<C-U>call SlimvProfileSubstring()<CR>' )
else
call s:MenuMap( 'Slim&v.&Profiling.&Load-Profiler',             g:slimv_leader.'O',  g:slimv_leader.'pl',  ':<C-U>call SlimvLoadProfiler()<CR>' )
call s:MenuMap( 'Slim&v.&Profiling.&Profile\.\.\.',             g:slimv_leader.'p',  g:slimv_leader.'pp',  ':<C-U>call SlimvProfile()<CR>' )
call s:MenuMap( 'Slim&v.&Profiling.&Unprofile\.\.\.',           g:slimv_leader.'P',  g:slimv_leader.'pu',  ':<C-U>call SlimvUnprofile()<CR>' )
endif
call s:MenuMap( 'Slim&v.&Profiling.Unprofile-&All',             g:slimv_leader.'U',  g:slimv_leader.'pa',  ':<C-U>call SlimvUnprofileAll()<CR>' )
call s:MenuMap( 'Slim&v.&Profiling.&Show-Profiled',             g:slimv_leader.'?',  g:slimv_leader.'ps',  ':<C-U>call SlimvShowProfiled()<CR>' )
call s:MenuMap( 'Slim&v.&Profiling.-ProfilingSep-',             '',                  '',                   ':' )
call s:MenuMap( 'Slim&v.&Profiling.Profile-Rep&ort',            g:slimv_leader.'o',  g:slimv_leader.'pr',  ':<C-U>call SlimvProfileReport()<CR>' )
call s:MenuMap( 'Slim&v.&Profiling.Profile-&Reset',             g:slimv_leader.'X',  g:slimv_leader.'px',  ':<C-U>call SlimvProfileReset()<CR>' )

" Documentation commands
call s:MenuMap( 'Slim&v.&Documentation.Describe-&Symbol',       g:slimv_leader.'s',  g:slimv_leader.'ds',  ':call SlimvDescribeSymbol()<CR>' )
call s:MenuMap( 'Slim&v.&Documentation.&Apropos',               g:slimv_leader.'A',  g:slimv_leader.'dp',  ':call SlimvApropos()<CR>' )
call s:MenuMap( 'Slim&v.&Documentation.&Hyperspec',             g:slimv_leader.'h',  g:slimv_leader.'dh',  ':call SlimvHyperspec()<CR>' )
call s:MenuMap( 'Slim&v.&Documentation.Generate-&Tags',         g:slimv_leader.']',  g:slimv_leader.'dg',  ':call SlimvGenerateTags()<CR>' )

" REPL commands
call s:MenuMap( 'Slim&v.&Repl.&Connect-Server',                 g:slimv_leader.'c',  g:slimv_leader.'rc',  ':call SlimvConnectServer()<CR>' )
if g:slimv_swank
call s:MenuMap( '',                                             g:slimv_leader.'g',  g:slimv_leader.'rp',  ':call SlimvSetPackage()<CR>' )
endif
call s:MenuMap( 'Slim&v.&Repl.Interrup&t-Lisp-Process',         g:slimv_leader.'y',  g:slimv_leader.'ri',  ':call SlimvInterrupt()<CR>' )


" =====================================================================
"  Slimv menu
" =====================================================================

if g:slimv_menu == 1
    " Works only if 'wildcharm' is <Tab>
    if &wildcharm == 0
        set wildcharm=<Tab>
    endif
    if &wildcharm != 0
        execute ':map ' . g:slimv_leader.', :emenu Slimv.' . nr2char( &wildcharm )
    endif
endif

" Add REPL menu. This menu exist only for the REPL buffer.
function! SlimvAddReplMenu()
    if &wildcharm != 0
        execute ':map ' . g:slimv_leader.'\ :emenu REPL.' . nr2char( &wildcharm )
    endif

    amenu &REPL.Send-&Input                            :call SlimvSendCommand(0)<CR>
    amenu &REPL.Cl&ose-Send-Input                      :call SlimvSendCommand(1)<CR>
    amenu &REPL.Set-Packa&ge                           :call SlimvSetPackage()<CR>
    amenu &REPL.Interrup&t-Lisp-Process                <Esc>:<C-U>call SlimvInterrupt()<CR>
    amenu &REPL.-REPLSep-                              :
    amenu &REPL.&Previous-Input                        :call SlimvPreviousCommand()<CR>
    amenu &REPL.&Next-Input                            :call SlimvNextCommand()<CR>
    amenu &REPL.&Refresh                               :call SlimvRefresh()<CR>
endfunction

" =====================================================================
"  Slimv commands
" =====================================================================

command! -complete=customlist,SlimvCommandComplete -nargs=* Lisp call SlimvEval([<q-args>])
command! -complete=customlist,SlimvCommandComplete -nargs=* Eval call SlimvEval([<q-args>])

" Switch on syntax highlighting
syntax on