Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 040869c754
Fetching contributors…

Cannot retrieve contributors at this time

file 2280 lines (1939 sloc) 82.208 kb
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
;;; scion.el --- Haskell Minor Mode for Interacting with the Scion Library
;;
;;;; License
;; Copyright (C) 2003 Eric Marsden, Luke Gorrie, Helmut Eller
;; Copyright (C) 2004,2005,2006 Luke Gorrie, Helmut Eller
;; Copyright (C) 2008 Thomas Schilling
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation; either version 2 of
;; the License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public
;; License along with this program; if not, write to the Free
;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
;; MA 02111-1307, USA.

;;;; Dependencies and setup

(eval-and-compile
  (require 'cl)
  (unless (fboundp 'define-minor-mode)
    (require 'easy-mmode)
    (defalias 'define-minor-mode 'easy-mmode-define-minor-mode)))
(require 'hideshow)
(eval-when (compile)
  (require 'apropos)
  (require 'outline)
  (require 'ido)
  ;; (require 'etags)
  )

;;;---------------------------------------------------------------------------
;;;; Customize groups
;;
;;;;; scion

(defgroup scion nil
  "Interaction with the Scion Server."
  :prefix "scion-"
  :group 'applications)

;;;;; scion-ui

(defgroup scion-ui nil
  "Interaction with the Scion Server."
  :prefix "scion-"
  :group 'scion)

(defcustom scion-kill-without-query-p nil
  "If non-nil, kill SCION processes without query when quitting Emacs.
This applies to the *inferior-lisp* buffer and the network connections."
  :type 'boolean
  :group 'scion-ui)

;;;;; scion-haskell

(defgroup scion-haskell nil
  "Haskell server configuration."
  :prefix "scion-"
  :group 'scion)

(defcustom scion-connected-hook nil
  "List of functions to call when SCION connects to Haskell."
  :type 'hook
  :group 'scion-haskell)

(defcustom scion-haskell-host "127.0.0.1"
  "The default hostname (or IP address) to connect to."
  :type 'string
  :group 'scion-haskell)

(defcustom scion-port 4005
  "Port to use as the default for `scion-connect'."
  :type 'integer
  :group 'scion-haskell)

(make-variable-buffer-local
 (defvar scion-modeline-string nil
   "The string that should be displayed in the modeline if
`scion-extended-modeline' is true, and which indicates the
current connection, package and state of a Lisp buffer.
The string is periodically updated by an idle timer."))

;;;---------------------------------------------------------------------------

;;;; Macros

(defmacro* when-let ((var value) &rest body)
  "Evaluate VALUE, and if the result is non-nil bind it to VAR and
evaluate BODY.

\(fn (VAR VALUE) &rest BODY)"
  `(let ((,var ,value))
     (when ,var ,@body)))

(defmacro destructure-case (value &rest patterns)
  "Dispatch VALUE to one of PATTERNS.
A cross between `case' and `destructuring-bind'.
The pattern syntax is:
((HEAD . ARGS) . BODY)
The list of patterns is searched for a HEAD `eq' to the car of
VALUE. If one is found, the BODY is executed with ARGS bound to the
corresponding values in the CDR of VALUE."
  (let ((operator (gensym "op-"))
(operands (gensym "rand-"))
(tmp (gensym "tmp-")))
    `(let* ((,tmp ,value)
(,operator (car ,tmp))
(,operands (cdr ,tmp)))
       (case ,operator
,@(mapcar (lambda (clause)
                     (if (eq (car clause) t)
                         `(t ,@(cdr clause))
                       (destructuring-bind ((op &rest rands) &rest body) clause
                         `(,op (destructuring-bind ,rands ,operands
                                 . ,body)))))
patterns)
,@(if (eq (caar (last patterns)) t)
'()
`((t (error "Elisp destructure-case failed: %S" ,tmp))))))))

(put 'destructure-case 'lisp-indent-function 1)

;;;; Temporary Popup Buffers

;; Interface
(defmacro* scion-with-popup-buffer ((name &optional package
                                          connection emacs-snapshot)
                                    &body body)
  "Similar to `with-output-to-temp-buffer'.
Bind standard-output and initialize some buffer-local variables.
Restore window configuration when closed.

NAME is the name of the buffer to be created.
PACKAGE is the value `scion-buffer-package'.
CONNECTION is the value for `scion-buffer-connection'.
If nil, no explicit connection is associated with
the buffer. If t, the current connection is taken.

If EMACS-SNAPSHOT is non-NIL, it's used to restore the previous
state of Emacs after closing the temporary buffer. Otherwise, the
current state will be saved and later restored."
  `(let* ((vars% (list ,(if (eq package t) '(scion-current-package) package)
                       ,(if (eq connection t) '(scion-connection) connection)
                       ;; Defer the decision for NILness until runtime.
                       (or ,emacs-snapshot (scion-current-emacs-snapshot))))
          (standard-output (scion-popup-buffer ,name vars%)))
     (with-current-buffer standard-output
       (prog1 (progn ,@body)
         (assert (eq (current-buffer) standard-output))
         (setq buffer-read-only t)
         (scion-init-popup-buffer vars%)))))

(put 'scion-with-popup-buffer 'lisp-indent-function 1)

(defmacro* with-struct ((conc-name &rest slots) struct &body body)
  "Like with-slots but works only for structs.
\(fn (CONC-NAME &rest SLOTS) STRUCT &body BODY)"
  (flet ((reader (slot) (intern (concat (symbol-name conc-name)
(symbol-name slot)))))
    (let ((struct-var (gensym "struct")))
      `(let ((,struct-var ,struct))
(symbol-macrolet
,(mapcar (lambda (slot)
(etypecase slot
(symbol `(,slot (,(reader slot) ,struct-var)))
(cons `(,(first slot) (,(reader (second slot))
,struct-var)))))
slots)
. ,body)))))

(put 'with-struct 'lisp-indent-function 2)

(defmacro scion-define-keys (keymap &rest key-command)
  "Define keys in KEYMAP. Each KEY-COMMAND is a list of (KEY COMMAND)."
  `(progn . ,(mapcar (lambda (k-c) `(define-key ,keymap . ,k-c))
key-command)))

(put 'slime-define-keys 'lisp-indent-function 1)


;;;---------------------------------------------------------------------------
;;;;;; Tree View Widget

(defstruct (scion-tree (:conc-name scion-tree.))
  item
  (print-fn #'scion-tree-default-printer :type function)
  (kids '() :type list)
  (collapsed-p t :type boolean)
  (prefix "" :type string)
  (start-mark nil)
  (end-mark nil)
  (plist '() :type list))

(defun scion-tree-leaf-p (tree)
  (not (scion-tree.kids tree)))

(defun scion-tree-default-printer (tree)
  (princ (scion-tree.item tree) (current-buffer)))

(defun scion-tree-decoration (tree)
  (cond ((scion-tree-leaf-p tree) "-- ")
((scion-tree.collapsed-p tree) "[+] ")
(t "-+ ")))

(defun scion-tree-insert-list (list prefix)
  "Insert a list of trees."
  (loop for (elt . rest) on list
do (cond (rest
(insert prefix " |")
(scion-tree-insert elt (concat prefix " |"))
                  (insert "\n"))
(t
(insert prefix " `")
(scion-tree-insert elt (concat prefix " "))))))

(defun scion-tree-insert-decoration (tree)
  (insert (scion-tree-decoration tree)))

(defun scion-tree-indent-item (start end prefix)
  "Insert PREFIX at the beginning of each but the first line.
This is used for labels spanning multiple lines."
  (save-excursion
    (goto-char end)
    (beginning-of-line)
    (while (< start (point))
      (insert-before-markers prefix)
      (forward-line -1))))

(defun scion-tree-insert (tree prefix)
  "Insert TREE prefixed with PREFIX at point."
  (with-struct (scion-tree. print-fn kids collapsed-p start-mark end-mark) tree
    (let ((line-start (line-beginning-position)))
      (setf start-mark (point-marker))
      (scion-tree-insert-decoration tree)
      (funcall print-fn tree)
      (scion-tree-indent-item start-mark (point) (concat prefix " "))
      (add-text-properties line-start (point) (list 'scion-tree tree))
      (set-marker-insertion-type start-mark t)
      (when (and kids (not collapsed-p))
        (terpri (current-buffer))
        (scion-tree-insert-list kids prefix))
      (setf (scion-tree.prefix tree) prefix)
      (setf end-mark (point-marker)))))

(defun scion-tree-at-point ()
  (cond ((get-text-property (point) 'scion-tree))
        (t (error "No tree at point"))))

(defun scion-tree-delete (tree)
  "Delete the region for TREE."
  (delete-region (scion-tree.start-mark tree)
                 (scion-tree.end-mark tree)))

(defun scion-tree-toggle (tree)
  "Toggle the visibility of TREE's children."
  (with-struct (scion-tree. collapsed-p start-mark end-mark prefix) tree
    (setf collapsed-p (not collapsed-p))
    (scion-tree-delete tree)
    (insert-before-markers " ") ; move parent's end-mark
    (backward-char 1)
    (scion-tree-insert tree prefix)
    (delete-char 1)
    (goto-char start-mark)))


;;;---------------------------------------------------------------------------

(defvar scion-program "scion_emacs"
  "Program name of the Scion server.")

(defvar scion-last-compilation-result nil
  "The result of the most recently issued compilation.")


(make-variable-buffer-local
 (defvar scion-mode-line " Scion"))

(define-minor-mode scion-mode
  "\\<scion-mode-map>\
Scion: Smart Haskell mode.
\\{scion-mode-map}"
  nil
  scion-mode-line
  ;; Fake binding to coax `define-minor-mode' to create the keymap
  '((" " 'self-insert-command))
  (when scion-last-compilation-result
    (scion-highlight-notes (scion-compiler-notes) (current-buffer))))

(define-key scion-mode-map " " 'self-insert-command)

;; dummy definitions for the compiler
(defvar scion-net-coding-system)
(defvar scion-net-processes)
(defvar scion-default-connection)

(defun scion (&optional command)
  "Start a Scion server and connect to it."
  (interactive)
  (let ((server-program (or command scion-program)))
    (scion-start :program server-program)))

(defun* scion-start (&key (program scion-program)
program-args
env
directory
name
(buffer "*scion-server*"))
  (let ((proc (scion-maybe-start-server program program-args env
directory buffer)))
    ))

(defun scion-maybe-start-server (program program-args env directory buffer)
  (cond
   ((not (comint-check-proc buffer))
    (scion-start-server program program-args env directory buffer))
   (t
    (message "Scion server is already running")
    nil)))

(defvar scion-connect-buffer nil
  "Buffer that is currently trying to connect to a Scion server.")

(defun scion-start-server (program program-args env directory buffer)
  (with-current-buffer (get-buffer-create buffer)
    (when directory
      (cd (expand-file-name directory)))
    (delete-region (point-min) (point-max))
    (comint-mode)
    (setq scion-connect-buffer (current-buffer))
    (message "Connecting... (Abort with `M-x scion-abort-connect`.)")
    (add-hook 'comint-output-filter-functions
              'scion-check-server-ready nil t)
    (let ((process-environment (append env process-environment)))
      (comint-exec (current-buffer) "scion-emacs" program nil program-args))
    (let ((proc (get-buffer-process (current-buffer))))
      ; (scion-set-query-on-exit-flag proc)
      proc)))

(defun scion-check-server-ready (server-output)
  "Watches the server's output for the port number to connect to."
  (let* ((regexp "^=== Listening on port: \\([0-9]+\\)$")
         (port (save-excursion
                 (goto-char (point-min))
                 (when (re-search-forward regexp nil t)
                   (read (match-string 1)) ))))
    (when port
      (remove-hook 'comint-output-filter-functions
                   'scion-check-server-ready t)
      (setq scion-connect-buffer nil)
      (sleep-for 0.1) ;; give the server some time to get connected
      (scion-connect "127.0.0.1" port))))

(defun scion-abort-connect ()
  "Abort the current connection attempt."
  (interactive)
  (cond (scion-connect-buffer
         (kill-buffer scion-connect-buffer)
         (message "Connection attempt aborted."))
        (t
         (error "Not connecting."))))

(defun scion-connect (host port &optional coding-system)
  "Connect to a running Swank server."
  (interactive (list (read-from-minibuffer "Host: " scion-haskell-host)
                     (read-from-minibuffer "Port: " (format "%d" scion-port)
                                           nil t)))
  (when (and (interactive-p) scion-net-processes
             (y-or-n-p "Close old connections first? "))
    (scion-disconnect))
  (message "Connecting to Scion Server on port %S.." port)
  (let ((coding-system (or coding-system scion-net-coding-system)))
    (scion-check-coding-system coding-system)
    (message "Connecting to Scion Server on port %S.." port)
    (let* ((process (scion-net-connect host port coding-system))
           (scion-dispatching-connection process))
      (scion-setup-connection process))))

;;;---------------------------------------------------------------------------
;;;; Networking
;;;---------------------------------------------------------------------------
;;;
;;; This section covers the low-level networking: establishing
;;; connections and encoding/decoding protocol messages.
;;;
;;; Each SCION protocol message begins with a 3-byte length header
;;; followed by an S-expression as text. [XXX: The sexp must be readable
;;; both by Emacs and by Common Haskell, so if it contains any embedded
;;; code fragments they should be sent as strings.]
;;;
;;; The set of meaningful protocol messages are not specified
;;; here. They are defined elsewhere by the event-dispatching
;;; functions in this file and in Scion/Server/Emacs.hs.

(defvar scion-net-processes nil
  "List of processes (sockets) connected to Haskell.")

(defvar scion-net-process-close-hooks '()
  "List of functions called when a scion network connection closes.
The functions are called with the process as their argument.")

(defun scion-secret ()
  "Finds the magic secret from the user's home directory.
Returns nil if the file doesn't exist or is empty; otherwise the first
line of the file."
  nil) ; disable for now

;;;---------------------------------------------------------------------------
;;; Interface

(defun scion-net-connect (host port coding-system)
  "Establish a connection with a Scion Server.

<hostname> <port> <coding-system> -> <network-stream-process>"
  (let* ((inhibit-quit nil)
         (proc (open-network-stream "Scion Server" nil host port))
         (buffer (scion-make-net-buffer " *scion-connection*")))
    (push proc scion-net-processes)
    (set-process-buffer proc buffer)
    (set-process-filter proc 'scion-net-filter)
    (set-process-sentinel proc 'scion-net-sentinel)
    (scion-set-query-on-exit-flag proc)
    (when (fboundp 'set-process-coding-system)
      (scion-check-coding-system coding-system)
      (set-process-coding-system proc coding-system coding-system))
    (when-let (secret (scion-secret))
      (scion-net-send secret proc))
    proc))

(defun scion-make-net-buffer (name)
  "Make a buffer suitable for a network process."
  (let ((buffer (generate-new-buffer name)))
    (with-current-buffer buffer
      (buffer-disable-undo))
    buffer))

(defun scion-set-query-on-exit-flag (process)
  "Set PROCESS's query-on-exit-flag to `scion-kill-without-query-p'."
  (when scion-kill-without-query-p
    ;; avoid byte-compiler warnings
    (let ((fun (if (fboundp 'set-process-query-on-exit-flag)
                   'set-process-query-on-exit-flag
                 'process-kill-without-query)))
      (funcall fun process nil))))


;;;---------------------------------------------------------------------------
;;;;; Coding system madness

(defvar scion-net-valid-coding-systems
  '((iso-latin-1-unix nil "iso-latin-1-unix")
    (iso-8859-1-unix nil "iso-latin-1-unix")
    (binary nil "iso-latin-1-unix")
    ;; (utf-8-unix t "utf-8-unix")
;; (emacs-mule-unix t "emacs-mule-unix")
;; (euc-jp-unix t "euc-jp-unix")
    )
  "A list of valid coding systems.
Each element is of the form: (NAME MULTIBYTEP CL-NAME)")

(defun scion-find-coding-system (name)
  "Return the coding system for the symbol NAME.
The result is either an element in `scion-net-valid-coding-systems'
or NIL."
  (let* ((probe (assq name scion-net-valid-coding-systems)))
    (if (and probe (if (fboundp 'check-coding-system)
                       (ignore-errors (check-coding-system (car probe)))
                     (eq (car probe) 'binary)))
        probe)))

(defvar scion-net-coding-system
  (find-if 'scion-find-coding-system
           '(iso-latin-1-unix iso-8859-1-unix binary))
  "*Coding system used for network connections.
See also `scion-net-valid-coding-systems'.")
  
(defun scion-check-coding-system (coding-system)
  "Signal an error if CODING-SYSTEM isn't a valid coding system."
  (interactive)
  (let ((props (scion-find-coding-system coding-system)))
    (unless props
      (error "Invalid scion-net-coding-system: %s. %s"
             coding-system (mapcar #'car scion-net-valid-coding-systems)))
    (when (and (second props) (boundp 'default-enable-multibyte-characters))
      (assert default-enable-multibyte-characters))
    t))

(defcustom scion-repl-history-file-coding-system
  (cond ((scion-find-coding-system 'utf-8-unix) 'utf-8-unix)
        (t scion-net-coding-system))
  "*The coding system for the history file."
  :type 'symbol
  :group 'scion-repl)

(defun scion-coding-system-mulibyte-p (coding-system)
  (second (scion-find-coding-system coding-system)))

(defun scion-coding-system-cl-name (coding-system)
  (third (scion-find-coding-system coding-system)))

;;;---------------------------------------------------------------------------
;;; Interface

(defun scion-net-send (sexp proc)
  "Send a SEXP to Lisp over the socket PROC.
This is the lowest level of communication. The sexp will be READ and
EVAL'd by Lisp."
  (let* ((msg (concat (scion-prin1-to-string sexp) "\n"))
         (string (concat (scion-net-encode-length (length msg)) msg))
         (coding-system (cdr (process-coding-system proc))))
    (scion-log-event sexp)
    (cond ((scion-safe-encoding-p coding-system string)
           (process-send-string proc string))
          (t (error "Coding system %s not suitable for %S"
                    coding-system string)))))

(defun scion-safe-encoding-p (coding-system string)
  "Return true iff CODING-SYSTEM can safely encode STRING."
  (if (featurep 'xemacs)
      ;; FIXME: XEmacs encodes non-encodeable chars as ?~ automatically
      t
    (or (let ((candidates (find-coding-systems-string string))
              (base (coding-system-base coding-system)))
          (or (equal candidates '(undecided))
              (memq base candidates)))
        (and (not (multibyte-string-p string))
             (not (scion-coding-system-mulibyte-p coding-system))))))

(defun scion-net-close (process &optional debug)
  (setq scion-net-processes (remove process scion-net-processes))
  (when (eq process scion-default-connection)
    (setq scion-default-connection nil))
  (cond (debug
         (set-process-sentinel process 'ignore)
         (set-process-filter process 'ignore)
         (delete-process process))
        (t
         (run-hook-with-args 'scion-net-process-close-hooks process)
         ;; killing the buffer also closes the socket
         (kill-buffer (process-buffer process)))))

(defun scion-net-sentinel (process message)
  (message "Connection to Scion server closed unexpectedly: %s" message)
  (scion-net-close process))

;;; Socket input is handled by `scion-net-filter', which decodes any
;;; complete messages and hands them off to the event dispatcher.

(defun scion-net-filter (process string)
  "Accept output from the socket and process all complete messages."
  (with-current-buffer (process-buffer process)
    (goto-char (point-max))
    (insert string))
  (scion-process-available-input process))

(defun scion-process-available-input (process)
  "Process all complete messages that have arrived from Lisp."
  (with-current-buffer (process-buffer process)
    (while (scion-net-have-input-p)
      (let ((event (scion-net-read-or-lose process))
            (ok nil))
        (scion-log-event event)
        (unwind-protect
            (save-current-buffer
              (scion-dispatch-event event process)
              (setq ok t))
          (unless ok
            (scion-run-when-idle 'scion-process-available-input process)))))))

(defun scion-net-have-input-p ()
  "Return true if a complete message is available."
  (goto-char (point-min))
  (and (>= (buffer-size) 6)
       (>= (- (buffer-size) 6) (scion-net-decode-length))))

(defun scion-run-when-idle (function &rest args)
  "Call FUNCTION as soon as Emacs is idle."
  (apply #'run-at-time
         (if (featurep 'xemacs) itimer-short-interval 0)
         nil function args))

(defun scion-net-read-or-lose (process)
  (condition-case error
      (scion-net-read)
    (error
     (debug)
     (scion-net-close process t)
     (error "net-read error: %S" error))))

(defun scion-net-read ()
  "Read a message from the network buffer."
  (goto-char (point-min))
  (let* ((length (scion-net-decode-length))
         (start (+ 6 (point)))
         (end (+ start length)))
    (assert (plusp length))
    (prog1 (save-restriction
             (narrow-to-region start end)
             (read (current-buffer)))
      (delete-region (point-min) end))))

(defun scion-net-decode-length ()
  "Read a 24-bit hex-encoded integer from buffer."
  (string-to-number (buffer-substring-no-properties (point) (+ (point) 6)) 16))

(defun scion-net-encode-length (n)
  "Encode an integer into a 24-bit hex string."
  (format "%06x" n))

(defun scion-prin1-to-string (sexp)
  "Like `prin1-to-string' but don't octal-escape non-ascii characters.
This is more compatible with the CL reader."
  (with-temp-buffer
    (let (print-escape-nonascii
          print-escape-newlines
          print-length
          print-level)
      (prin1 sexp (current-buffer))
      (buffer-string))))

;;;---------------------------------------------------------------------------


;;;; Connections
;;;
;;; "Connections" are the high-level Emacs<->Lisp networking concept.
;;;
;;; Emacs has a connection to each Lisp process that it's interacting
;;; with. Typically there would only be one, but a user can choose to
;;; connect to many Lisps simultaneously.
;;;
;;; A connection consists of a control socket, optionally an extra
;;; socket dedicated to receiving Lisp output (an optimization), and a
;;; set of connection-local state variables.
;;;
;;; The state variables are stored as buffer-local variables in the
;;; control socket's process-buffer and are used via accessor
;;; functions. These variables include things like the *FEATURES* list
;;; and Unix Pid of the Lisp process.
;;;
;;; One connection is "current" at any given time. This is:
;;; `scion-dispatching-connection' if dynamically bound, or
;;; `scion-buffer-connection' if this is set buffer-local, or
;;; `scion-default-connection' otherwise.
;;;
;;; When you're invoking commands in your source files you'll be using
;;; `scion-default-connection'. This connection can be interactively
;;; reassigned via the connection-list buffer.
;;;
;;; When a command creates a new buffer it will set
;;; `scion-buffer-connection' so that commands in the new buffer will
;;; use the connection that the buffer originated from. For example,
;;; the apropos command creates the *Apropos* buffer and any command
;;; in that buffer (e.g. `M-.') will go to the same Lisp that did the
;;; apropos search. REPL buffers are similarly tied to their
;;; respective connections.
;;;
;;; When Emacs is dispatching some network message that arrived from a
;;; connection it will dynamically bind `scion-dispatching-connection'
;;; so that the event will be processed in the context of that
;;; connection.
;;;
;;; This is mostly transparent. The user should be aware that he can
;;; set the default connection to pick which Lisp handles commands in
;;; Lisp-mode source buffers, and scion hackers should be aware that
;;; they can tie a buffer to a specific connection. The rest takes
;;; care of itself.

(defvar scion-dispatching-connection nil
  "Network process currently executing.
This is dynamically bound while handling messages from Lisp; it
overrides `scion-buffer-connection' and `scion-default-connection'.")

(make-variable-buffer-local
 (defvar scion-buffer-connection nil
   "Network connection to use in the current buffer.
This overrides `scion-default-connection'."))

(defvar scion-default-connection nil
  "Network connection to use by default.
Used for all Lisp communication, except when overridden by
`scion-dispatching-connection' or `scion-buffer-connection'.")

(defun scion-current-connection ()
  "Return the connection to use for Lisp interaction.
Return nil if there's no connection."
  (or scion-dispatching-connection
      scion-buffer-connection
      scion-default-connection))

(defun scion-connection ()
  "Return the connection to use for Lisp interaction.
Signal an error if there's no connection."
  (let ((conn (scion-current-connection)))
    (cond ((and (not conn) scion-net-processes)
           (or (scion-auto-select-connection)
               (error "No default connection selected.")))
          ((not conn)
           (or (scion-auto-connect)
               (error "Not connected.")))
          ((not (eq (process-status conn) 'open))
           (error "Connection closed."))
          (t conn))))

(defvar scion-auto-connect 'always)

(defun scion-auto-connect ()
  (cond ((or (eq scion-auto-connect 'always)
             (and (eq scion-auto-connect 'ask)
                  (y-or-n-p "No connection. Start Scion? ")))
         (save-window-excursion
           (scion) ; XXX
           (while (not (scion-current-connection))
             (sleep-for 1))
           (scion-connection)))
        (t nil)))

(defvar scion-auto-select-connection 'ask)

(defun scion-auto-select-connection ()
  (let* ((c0 (car scion-net-processes))
         (c (cond ((eq scion-auto-select-connection 'always) c0)
                  ((and (eq scion-auto-select-connection 'ask)
                        (y-or-n-p
                         (format "No default connection selected. %s %s? "
                                 "Switch to" (scion-connection-name c0))))
                   c0))))
    (when c
      (scion-select-connection c)
      (message "Switching to connection: %s" (scion-connection-name c))
      c)))

(defun scion-select-connection (process)
  "Make PROCESS the default connection."
  (setq scion-default-connection process))

(defun scion-cycle-connections ()
  "Change current scion connection, and make it buffer local."
  (interactive)
  (let* ((tail (or (cdr (member (scion-current-connection)
                                scion-net-processes))
                   scion-net-processes))
         (p (car tail)))
    (scion-select-connection p)
    (unless (eq major-mode 'scion-repl-mode)
      (setq scion-buffer-connection p))
    (message "Lisp: %s %s" (scion-connection-name p) (process-contact p))))

(defmacro* scion-with-connection-buffer ((&optional process) &rest body)
  "Execute BODY in the process-buffer of PROCESS.
If PROCESS is not specified, `scion-connection' is used.

\(fn (&optional PROCESS) &body BODY))"
  `(with-current-buffer
       (process-buffer (or ,process (scion-connection)
                           (error "No connection")))
     ,@body))

(put 'scion-with-connection-buffer 'lisp-indent-function 1)

(defun scion-connected-p ()
  "Return true if the Swank connection is open."
  (not (null scion-net-processes)))

(defun scion-compute-connection-state (conn)
  (cond ((null conn) :disconnected)
        ;((scion-stale-connection-p conn) :stale)
        ;((scion-debugged-connection-p conn) :debugged)
        ((and (scion-use-sigint-for-interrupt conn)
              (scion-busy-p conn)) :busy)
        ((eq scion-buffer-connection conn) :local)
        (t :connected)))

(defun scion-connection-state-as-string (state)
  (case state
    (:connected "")
    (:disconnected "not connected")
    (:busy "busy..")
    (:debugged "debugged..")
    (:stale "stale")
    (:local "local")
    ))

;;; Connection-local variables:

(defmacro scion-def-connection-var (varname &rest initial-value-and-doc)
  "Define a connection-local variable.
The value of the variable can be read by calling the function of the
same name (it must not be accessed directly). The accessor function is
setf-able.

The actual variable bindings are stored buffer-local in the
process-buffers of connections. The accessor function refers to
the binding for `scion-connection'."
  (let ((real-var (intern (format "%s:connlocal" varname))))
    `(progn
       ;; Variable
       (make-variable-buffer-local
        (defvar ,real-var ,@initial-value-and-doc))
       ;; Accessor
       (defun ,varname (&optional process)
         (scion-with-connection-buffer (process) ,real-var))
       ;; Setf
       (defsetf ,varname (&optional process) (store)
         `(scion-with-connection-buffer (,process)
            (setq (\, (quote (\, real-var))) (\, store))
            (\, store)))
       '(\, varname))))

(put 'scion-def-connection-var 'lisp-indent-function 2)

;; Let's indulge in some pretty colours.
(unless (featurep 'xemacs)
  (font-lock-add-keywords
   'emacs-lisp-mode
   '(("(\\(scion-def-connection-var\\)\\s +\\(\\(\\w\\|\\s_\\)+\\)"
      (1 font-lock-keyword-face)
      (2 font-lock-variable-name-face)))))

(scion-def-connection-var scion-connection-number nil
  "Serial number of a connection.
Bound in the connection's process-buffer.")

(scion-def-connection-var scion-pid nil
  "The process id of the Haskell process.")

(scion-def-connection-var scion-connection-name nil
  "The short name for connection.")

;;;;; Connection setup

(defvar scion-connection-counter 0
  "The number of SCION connections made. For generating serial numbers.")

;;; Interface
(defun scion-setup-connection (process)
  "Make a connection out of PROCESS."
  (let ((scion-dispatching-connection process))
    (scion-init-connection-state process)
    (scion-select-connection process)
    process))

(defun scion-init-connection-state (proc)
  "Initialize connection state in the process-buffer of PROC."
  ;; To make life simpler for the user: if this is the only open
  ;; connection then reset the connection counter.
  (when (equal scion-net-processes (list proc))
    (setq scion-connection-counter 0))
  (scion-with-connection-buffer ()
    (setq scion-buffer-connection proc))
  (setf (scion-connection-number proc) (incf scion-connection-counter))
  ;; We do the rest of our initialization asynchronously. The current
  ;; function may be called from a timer, and if we setup the REPL
  ;; from a timer then it mysteriously uses the wrong keymap for the
  ;; first command.
  (scion-eval-async '(connection-info)
                    (scion-curry #'scion-set-connection-info proc)))

(defun scion-set-connection-info (connection info)
  "Initialize CONNECTION with INFO received from Lisp."
  (let ((scion-dispatching-connection connection))
    (destructuring-bind (&key pid version
                              &allow-other-keys) info
      (scion-check-version version connection)
      (setf (scion-pid) pid
(scion-connection-name) (format "%d" pid)))
    (let ((args nil))
      (run-hooks 'scion-connected-hook))
    (message "Connected.")))

(defvar scion-protocol-version 1)

(defun scion-check-version (version conn)
  (or (equal version scion-protocol-version)
      (equal scion-protocol-version 'ignore)
      (y-or-n-p
       (format "Versions differ: %s (scion client) vs. %s (scion server). Continue? "
               scion-protocol-version version))
      (scion-net-close conn)
      (top-level)))

(defun scion-generate-connection-name (lisp-name)
  (loop for i from 1
        for name = lisp-name then (format "%s<%d>" lisp-name i)
        while (find name scion-net-processes
                    :key #'scion-connection-name :test #'equal)
        finally (return name)))

(defun scion-connection-close-hook (process)
  (when (eq process scion-default-connection)
    (when scion-net-processes
      (scion-select-connection (car scion-net-processes))
      (message "Default connection closed; switched to #%S (%S)"
               (scion-connection-number)
               (scion-connection-name)))))

(add-hook 'scion-net-process-close-hooks 'scion-connection-close-hook)

;;;;; Commands on connections

(defun scion-disconnect ()
  "Disconnect all connections."
  (interactive)
  (mapc #'scion-net-close scion-net-processes))

(defun scion-connection-port (connection)
  "Return the remote port number of CONNECTION."
  (if (featurep 'xemacs)
      (car (process-id connection))
    (cadr (process-contact connection))))

(defun scion-process (&optional connection)
  "Return the Lisp process for CONNECTION (default `scion-connection').
Can return nil if there's no process object for the connection."
  nil
  ;; (let ((proc (scion-inferior-process connection)))
;; (if (and proc
;; (memq (process-status proc) '(run stop)))
;; proc))
  )

;; Non-macro version to keep the file byte-compilable.
;; (defun scion-set-inferior-process (connection process)
;; (setf (scion-inferior-process connection) process))

(defvar scion-inhibit-pipelining t
  "*If true, don't send background requests if Lisp is already busy.")

(defun scion-background-activities-enabled-p ()
  nil)


;;;; Communication protocol

;;;;; Emacs Lisp programming interface
;;;
;;; The programming interface for writing Emacs commands is based on
;;; remote procedure calls (RPCs). The basic operation is to ask Lisp
;;; to apply a named Lisp function to some arguments, then to do
;;; something with the result.
;;;
;;; Requests can be either synchronous (blocking) or asynchronous
;;; (with the result passed to a callback/continuation function). If
;;; an error occurs during the request then the debugger is entered
;;; before the result arrives -- for synchronous evaluations this
;;; requires a recursive edit.
;;;
;;; You should use asynchronous evaluations (`scion-eval-async') for
;;; most things. Reserve synchronous evaluations (`scion-eval') for
;;; the cases where blocking Emacs is really appropriate (like
;;; completion) and that shouldn't trigger errors (e.g. not evaluate
;;; user-entered code).
;;;
;;; We have the concept of the "current Lisp package". RPC requests
;;; always say what package the user is making them from and the Lisp
;;; side binds that package to *BUFFER-PACKAGE* to use as it sees
;;; fit. The current package is defined as the buffer-local value of
;;; `scion-buffer-package' if set, and otherwise the package named by
;;; the nearest IN-PACKAGE as found by text search (first backwards,
;;; then forwards).
;;;
;;; Similarly we have the concept of the current thread, i.e. which
;;; thread in the Lisp process should handle the request. The current
;;; thread is determined solely by the buffer-local value of
;;; `scion-current-thread'. This is usually bound to t meaning "no
;;; particular thread", but can also be used to nominate a specific
;;; thread. The REPL and the debugger both use this feature to deal
;;; with specific threads.

(make-variable-buffer-local
 (defvar scion-current-thread t
   "The id of the current thread on the Lisp side.
t means the \"current\" thread;
:repl-thread the thread that executes REPL requests;
fixnum a specific thread."))

(make-variable-buffer-local
 (defvar scion-buffer-package nil
   "The Lisp package associated with the current buffer.
This is set only in buffers bound to specific packages."))


(defun scion-current-package ()
  nil)

(defvar scion-accept-process-output-supports-floats
  (ignore-errors (accept-process-output nil 0.0) t))

(defun scion-accept-process-output (&optional process timeout)
  "Like `accept-process-output' but the TIMEOUT argument can be a float."
  (cond (scion-accept-process-output-supports-floats
         (accept-process-output process timeout))
        (t
         (accept-process-output process
                                (if timeout (truncate timeout))
                                ;; Emacs 21 uses microsecs; Emacs 22 millisecs
                                (if timeout (truncate (* timeout 1000000)))))))

;;; Synchronous requests are implemented in terms of asynchronous
;;; ones. We make an asynchronous request with a continuation function
;;; that `throw's its result up to a `catch' and then enter a loop of
;;; handling I/O until that happens.

(defvar scion-stack-eval-tags nil
  "List of stack-tags of continuations waiting on the stack.")

;;; `scion-rex' is the RPC primitive which is used to implement both
;;; `scion-eval' and `scion-eval-async'. You can use it directly if
;;; you need to, but the others are usually more convenient.

(defmacro* scion-rex ((&rest saved-vars)
                      (sexp &optional
                            (package '(scion-current-package))
                            (thread 'scion-current-thread))
                      &rest continuations)
  "(scion-rex (VAR ...) (SEXP &optional PACKAGE THREAD) CLAUSES ...)

Remote EXecute SEXP.

VARs are a list of saved variables visible in the other forms. Each
VAR is either a symbol or a list (VAR INIT-VALUE).

SEXP is evaluated and the princed version is sent to Lisp.

PACKAGE is evaluated and Lisp binds *BUFFER-PACKAGE* to this package.
The default value is (scion-current-package).

CLAUSES is a list of patterns with same syntax as
`destructure-case'. The result of the evaluation of SEXP is
dispatched on CLAUSES. The result is either a sexp of the
form (:ok VALUE) or (:abort). CLAUSES is executed
asynchronously.

Note: don't use backquote syntax for SEXP, because Emacs20 cannot
deal with that."
  (let ((result (gensym)))
    `(lexical-let ,(loop for var in saved-vars
                         collect (etypecase var
                                   (symbol (list var var))
                                   (cons var)))
       (scion-dispatch-event
        (list :emacs-rex ,sexp ,package ,thread
              (lambda (,result)
                (destructure-case ,result
                  ,@continuations)))))))



(defun scion-eval (sexp &optional package)
  "Evaluate EXPR on the superior Lisp and return the result."
  (when (null package) (setq package (scion-current-package)))
  (let* ((tag (gensym (format "scion-result-%d-"
                              (1+ (scion-continuation-counter)))))
(scion-stack-eval-tags (cons tag scion-stack-eval-tags)))
    (apply
     #'funcall
     (catch tag
       (scion-rex (tag sexp)
           (sexp package)
         ((:ok value)
          (unless (member tag scion-stack-eval-tags)
            (error "Reply to canceled synchronous eval request tag=%S sexp=%S"
                   tag sexp))
          (throw tag (list #'identity value)))
         ((:abort)
          (throw tag (list #'error "Synchronous Remote Evaluation aborted"))))
       (let ((debug-on-quit t)
             (inhibit-quit nil)
             (conn (scion-connection)))
         (while t
           (unless (eq (process-status conn) 'open)
             (error "Server connection closed unexpectedly"))
           (scion-accept-process-output nil 0.01)))))))

(defun scion-eval-async (sexp &optional cont package)
  "Evaluate EXPR on the server and call CONT with the result."
  (scion-rex (cont (buffer (current-buffer)))
(sexp (or package (scion-current-package)))
    ((:ok result)
     (when cont
       (set-buffer buffer)
       (funcall cont result)))
    ((:abort)
     (message "Evaluation aborted."))))



;;;;; Protocol event handler (the guts)
;;;
;;; This is the protocol in all its glory. The input to this function
;;; is a protocol event that either originates within Emacs or arrived
;;; over the network from Lisp.
;;;
;;; Each event is a list beginning with a keyword and followed by
;;; arguments. The keyword identifies the type of event. Events
;;; originating from Emacs have names starting with :emacs- and events
;;; from Lisp don't.

(scion-def-connection-var scion-rex-continuations '()
  "List of (ID . FUNCTION) continuations waiting for RPC results.")

(scion-def-connection-var scion-continuation-counter 0
  "Continuation serial number counter.")

(defvar scion-event-hooks)

(defun scion-dispatch-event (event &optional process)
  (let ((scion-dispatching-connection (or process (scion-connection))))
    (or (run-hook-with-args-until-success 'scion-event-hooks event)
        (destructure-case event
;; ((:write-string output &optional target)
;; (scion-write-string output target))
          ((:emacs-rex form package thread continuation)
           (when (and (scion-use-sigint-for-interrupt) (scion-busy-p))
             (scion-display-oneliner "; pipelined request... %S" form))
           (let ((id (incf (scion-continuation-counter))))
             (push (cons id continuation) (scion-rex-continuations))
             (scion-send `(:emacs-rex ,form
;,package ,thread
,id))))
          ((:return value id)
           (let ((rec (assq id (scion-rex-continuations))))
             (cond (rec (setf (scion-rex-continuations)
                              (remove rec (scion-rex-continuations)))
                        (funcall (cdr rec) value))
                   (t
                    (error "Unexpected reply: %S %S" id value)))))
          ((:emacs-interrupt thread)
           (scion-send `(:emacs-interrupt ,thread)))
;; ((:read-string thread tag)
;; (assert thread)
;; (scion-repl-read-string thread tag))
          ((:emacs-return-string thread tag string)
           (scion-send `(:emacs-return-string ,thread ,tag ,string)))
          ((:eval-no-wait fun args)
           (apply (intern fun) args))
;; ((:eval thread tag form-string)
;; (scion-check-eval-in-emacs-enabled)
;; (scion-eval-for-lisp thread tag form-string))
          ((:emacs-return thread tag value)
           (scion-send `(:emacs-return ,thread ,tag ,value)))
          ((:ping thread tag)
           (scion-send `(:emacs-pong ,thread ,tag)))
          ((:reader-error packet condition)
           (scion-with-popup-buffer ("*Scion Error*")
             (princ (format "Invalid protocol message:\n%s\n\n%S"
                            condition packet))
             (goto-char (point-min)))
           (error "Invalid protocol message"))))))

(defun scion-send (sexp)
  "Send SEXP directly over the wire on the current connection."
  (scion-net-send sexp (scion-connection)))

(defun scion-stop-server ()
  "Stop the server we are currently connected to."
  (interactive)
  (scion-send '(:quit)))


(defun scion-use-sigint-for-interrupt (&optional connection)
  nil)

(defun scion-busy-p (&optional conn)
  "True if Haskell has outstanding requests.
Debugged requests are ignored."
  nil)

(defun scion-display-oneliner (format-string &rest format-args)
  (let* ((msg (apply #'format format-string format-args)))
    (unless (minibuffer-window-active-p (minibuffer-window))
      (message "%s" (scion-oneliner msg)))))

(defun scion-oneliner (string)
  "Return STRING truncated to fit in a single echo-area line."
  (substring string 0 (min (length string)
                           (or (position ?\n string) most-positive-fixnum)
                           (1- (frame-width)))))

(defun scion-curry (fun &rest args)
  `(lambda (&rest more) (apply ',fun (append ',args more))))

(defun scion-rcurry (fun &rest args)
  `(lambda (&rest more) (apply ',fun (append more ',args))))

(defsubst scion-makehash (&optional test)
  (if (fboundp 'make-hash-table)
      (if test (make-hash-table :test test) (make-hash-table))
    (with-no-warnings
      (makehash test))))

;;;;; Snapshots of current Emacs state

;;; Window configurations do not save (and hence not restore)
;;; any narrowing that could be applied to a buffer.
;;;
;;; For this purpose, we introduce a superset of a window
;;; configuration that does include the necessary information to
;;; properly restore narrowing.
;;;
;;; We call this superset an Emacs Snapshot.

(defstruct (scion-narrowing-configuration
             (:conc-name scion-narrowing-configuration.))
  narrowedp beg end)

(defstruct (scion-emacs-snapshot (:conc-name scion-emacs-snapshot.))
  ;; We explicitly store the value of point even though it's implicitly
  ;; stored in the window-configuration because Emacs provides no
  ;; way to access the things stored in a window configuration.
  window-configuration narrowing-configuration point-marker)

(defun scion-current-narrowing-configuration (&optional buffer)
  (with-current-buffer (or buffer (current-buffer))
    (make-scion-narrowing-configuration :narrowedp (scion-buffer-narrowed-p)
                                        :beg (point-min-marker)
                                        :end (point-max-marker))))

(defun scion-set-narrowing-configuration (narrowing-cfg)
  (when (scion-narrowing-configuration.narrowedp narrowing-cfg)
    (narrow-to-region (scion-narrowing-configuration.beg narrowing-cfg)
                      (scion-narrowing-configuration.end narrowing-cfg))))

(defun scion-current-emacs-snapshot (&optional frame)
  "Returns a snapshot of the current state of FRAME, or the
currently active frame if FRAME is not given respectively."
  (with-current-buffer
      (if frame
          (window-buffer (frame-selected-window (selected-frame)))
          (current-buffer))
    (make-scion-emacs-snapshot
     :window-configuration (current-window-configuration frame)
     :narrowing-configuration (scion-current-narrowing-configuration)
     :point-marker (point-marker))))

(defun scion-set-emacs-snapshot (snapshot)
  "Restores the state of Emacs according to the information saved
in SNAPSHOT."
  (let ((window-cfg (scion-emacs-snapshot.window-configuration snapshot))
        (narrowing-cfg (scion-emacs-snapshot.narrowing-configuration snapshot))
        (marker (scion-emacs-snapshot.point-marker snapshot)))
    (set-window-configuration window-cfg) ; restores previously current buffer.
    (scion-set-narrowing-configuration narrowing-cfg)
    (goto-char (marker-position marker))))

(defun scion-current-emacs-snapshot-fingerprint (&optional frame)
  "Return a fingerprint of the current emacs snapshot.
Fingerprints are `equalp' if and only if they represent window
configurations that are very similar (same windows and buffers.)

Unlike real window-configuration objects, fingerprints are not
sensitive to the point moving and they can't be restored."
  (mapcar (lambda (window) (list window (window-buffer window)))
          (scion-frame-windows frame)))

(defun scion-frame-windows (&optional frame)
  "Return the list of windows in FRAME."
  (loop with last-window = (previous-window (frame-first-window frame))
        for window = (frame-first-window frame) then (next-window window)
        collect window
        until (eq window last-window)))

;;;;; Temporary popup buffers

(make-variable-buffer-local
 (defvar scion-popup-buffer-saved-emacs-snapshot nil
   "The snapshot of the current state in Emacs before the popup-buffer
was displayed, so that this state can be restored later on.
Buffer local in popup-buffers."))

(make-variable-buffer-local
 (defvar scion-popup-buffer-saved-fingerprint nil
   "The emacs snapshot \"fingerprint\" after displaying the buffer."))



(defun scion-popup-buffer (name buffer-vars)
  "Return a temporary buffer called NAME.
The buffer also uses the minor-mode `scion-popup-buffer-mode'.
Pressing `q' in the buffer will restore the window configuration
to the way it is when the buffer was created, i.e. when this
function was called."
  (when (and (get-buffer name) (kill-buffer (get-buffer name))))
  (with-current-buffer (get-buffer-create name)
    (set-syntax-table lisp-mode-syntax-table)
    (prog1 (pop-to-buffer (current-buffer))
      (scion-init-popup-buffer buffer-vars))))

(defun scion-init-popup-buffer (buffer-vars)
  (scion-popup-buffer-mode 1)
  (setq scion-popup-buffer-saved-fingerprint
        (scion-current-emacs-snapshot-fingerprint))
  (multiple-value-setq (scion-buffer-package
                        scion-buffer-connection
                        scion-popup-buffer-saved-emacs-snapshot)
    buffer-vars))

(define-minor-mode scion-popup-buffer-mode
  "Mode for displaying read only stuff"
  nil
  (" Scion-Tmp" scion-modeline-string)
  '(("q" . scion-popup-buffer-quit-function)
    ;("\C-c\C-z" . scion-switch-to-output-buffer)
    ;; ("\M-." . scion-edit-definition)
    ))

(make-variable-buffer-local
 (defvar scion-popup-buffer-quit-function 'scion-popup-buffer-quit
   "The function that is used to quit a temporary popup buffer."))

(defun scion-popup-buffer-quit-function (&optional kill-buffer-p)
  "Wrapper to invoke the value of `scion-popup-buffer-quit-function'."
  (interactive)
  (funcall scion-popup-buffer-quit-function kill-buffer-p))

;; Interface
(defun scion-popup-buffer-quit (&optional kill-buffer-p)
  "Get rid of the current (temp) buffer without asking.
Restore the window configuration unless it was changed since we
last activated the buffer."
  (interactive)
  (let ((buffer (current-buffer)))
    (when (scion-popup-buffer-snapshot-unchanged-p)
      (scion-popup-buffer-restore-snapshot))
    (with-current-buffer buffer
      (setq scion-popup-buffer-saved-emacs-snapshot nil) ; buffer-local var!
      (cond (kill-buffer-p (kill-buffer nil))
            (t (bury-buffer))))))

(defun scion-popup-buffer-snapshot-unchanged-p ()
  (equalp (scion-current-emacs-snapshot-fingerprint)
          scion-popup-buffer-saved-fingerprint))

(defun scion-popup-buffer-restore-snapshot ()
  (let ((snapshot scion-popup-buffer-saved-emacs-snapshot))
    (assert snapshot)
    (scion-set-emacs-snapshot snapshot)))


;;;;; Event logging to *scion-events*
;;;
;;; The *scion-events* buffer logs all protocol messages for debugging
;;; purposes. Optionally you can enable outline-mode in that buffer,
;;; which is convenient but slows things down significantly.

(defvar scion-log-events t
  "*Log protocol events to the *scion-events* buffer.")

(defvar scion-outline-mode-in-events-buffer nil
  "*Non-nil means use outline-mode in *scion-events*.")

(defvar scion-event-buffer-name "*scion-events*"
  "The name of the scion event buffer.")

(defun scion-log-event (event)
  "Record the fact that EVENT occurred."
  (when scion-log-events
    (with-current-buffer (scion-events-buffer)
      ;; trim?
      (when (> (buffer-size) 100000)
        (goto-char (/ (buffer-size) 2))
        (re-search-forward "^(" nil t)
        (delete-region (point-min) (point)))
      (goto-char (point-max))
      (save-excursion
        (scion-pprint-event event (current-buffer)))
      (when (and (boundp 'outline-minor-mode)
                 outline-minor-mode)
        (hide-entry))
      (goto-char (point-max)))))

(defun scion-pprint-event (event buffer)
  "Pretty print EVENT in BUFFER with limited depth and width."
  (let ((print-length 20)
(print-level 6)
(pp-escape-newlines t))
    (pp event buffer)))

(defun scion-events-buffer ()
  (or (get-buffer scion-event-buffer-name)
      (let ((buffer (get-buffer-create scion-event-buffer-name)))
        (with-current-buffer buffer
          (buffer-disable-undo)
          (set (make-local-variable 'outline-regexp) "^(")
          (set (make-local-variable 'comment-start) ";")
          (set (make-local-variable 'comment-end) "")
          (when scion-outline-mode-in-events-buffer
            (outline-minor-mode)))
        buffer)))

;;;;; Buffer related

(defun scion-buffer-narrowed-p (&optional buffer)
  "Returns T if BUFFER (or the current buffer respectively) is narrowed."
  (with-current-buffer (or buffer (current-buffer))
    (let ((beg (point-min))
          (end (point-max))
          (total (buffer-size)))
      (or (/= beg 1) (/= end (1+ total))))))

(defun scion-column-max ()
  (save-excursion
    (goto-char (point-min))
    (loop for column = (prog2 (end-of-line) (current-column) (forward-line))
          until (= (point) (point-max))
          maximizing column)))

;;;---------------------------------------------------------------------------

;;;;; scion-mode-faces

(defgroup scion-mode-faces nil
  "Faces in scion-mode source code buffers."
  :prefix "scion-"
  :group 'scion-mode)

(defun scion-underline-color (color)
  "Return a legal value for the :underline face attribute based on COLOR."
  ;; In XEmacs the :underline attribute can only be a boolean.
  ;; In GNU it can be the name of a colour.
  (if (featurep 'xemacs)
      (if color t nil)
    color))

(defface scion-error-face
  `((((class color) (background light))
     (:underline ,(scion-underline-color "red")))
    (((class color) (background dark))
     (:underline ,(scion-underline-color "red")))
    (t (:underline t)))
  "Face for errors from the compiler."
  :group 'scion-mode-faces)

(defface scion-warning-face
  `((((class color) (background light))
     (:underline ,(scion-underline-color "orange")))
    (((class color) (background dark))
     (:underline ,(scion-underline-color "coral")))
    (t (:underline t)))
  "Face for warnings from the compiler."
  :group 'scion-mode-faces)

(defun scion-face-inheritance-possible-p ()
  "Return true if the :inherit face attribute is supported."
  (assq :inherit custom-face-attributes))

(defface scion-highlight-face
  (if (scion-face-inheritance-possible-p)
      '((t (:inherit highlight :underline nil)))
    '((((class color) (background light))
       (:background "darkseagreen2"))
      (((class color) (background dark))
       (:background "darkolivegreen"))
      (t (:inverse-video t))))
  "Face for compiler notes while selected."
  :group 'scion-mode-faces)

;;;---------------------------------------------------------------------------
;;;; Overlays for compiler messages and other things

(defstruct (scion-compilation-result
             (:type list)
             (:conc-name scion-compilation-result.)
             (:constructor nil)
             (:copier nil))
  tag successp notes duration)


(defvar scion-project-root-dir nil
  "The root directory of the current project.

This is used, for example, to translate relative path names from
error messages into absolute path names.")

(defun scion-compiler-notes ()
  "Return all compiler notes, warnings, and errors."
  (scion-compilation-result.notes scion-last-compilation-result))

;;; TODO: notes should be sorted by filename (using a hashtable)

(defun scion-highlight-notes (notes &optional buffer)
  "Highlight compiler notes, warnings, and errors in the buffer."
  (interactive (list (scion-compiler-notes)))
  (with-temp-message (if (not buffer) "Highlighting notes..." nil)
    (save-excursion
      (save-restriction
        (widen) ; highlight notes on the whole buffer
        (scion-remove-old-overlays buffer)
(let ((buffers (if buffer
(list buffer)
(scion-filter-buffers (lambda () scion-mode)))))
(loop for b in buffers do
(with-current-buffer b
(save-excursion
(save-restriction
(widen)
(loop for note in (scion-notes-for-buffer notes b) do
(scion-overlay-note note b))))))))))
  nil)

(defun scion-notes-for-buffer (notes buffer)
  "Return only the notes that relate to BUFFER."
  (let ((fname (buffer-file-name buffer)))
    (if fname
(gethash fname notes nil)
      nil)))

(defun scion-remove-old-overlays (&optional buffer)
  "Delete the existing Scion overlays in the current buffer."
  (dolist (buffer (if buffer
(list buffer)
(scion-filter-buffers (lambda () scion-mode))))
    (with-current-buffer buffer
      (save-excursion
        (save-restriction
          (widen) ; remove overlays within the whole buffer.
          (goto-char (point-min))
          (while (not (eobp))
            (dolist (o (overlays-at (point)))
              (when (overlay-get o 'scion)
                (delete-overlay o)))
            (goto-char (next-overlay-change (point)))))))))

(defun scion-filter-buffers (predicate)
  "Return a list of buffers where PREDICATE returns true.
PREDICATE is executed in the buffer to test."
  (remove-if-not (lambda (%buffer)
                   (with-current-buffer %buffer
                     (funcall predicate)))
                 (buffer-list)))

(defun scion-flash-region (start end &optional timeout)
  (let ((overlay (make-overlay start end)))
    (overlay-put overlay 'face 'secondary-selection)
    (run-with-timer (or timeout 0.2) nil 'delete-overlay overlay)))

;;; the node representation
;;;
;;; (:warning <loc> message-string more-info-string)
;;; (:error <loc> message-string more-info-string)
;;;
;;; <loc> ::= (:loc filename start-line start-col end-line end-col)
;;; | (:no-loc text)

(defun scion-note.message (note)
  (destructure-case note
     ((:warning loc msg info)
      msg)
     ((:error loc msg info)
      msg)))

(defun scion-note.filename (note)
  (destructure-case (cadr note)
    ((:loc fn sl sc el ec) fn)
    ((:no-loc _) nil)))

(defun scion-note.line (note)
  (destructure-case (cadr note)
    ((:loc fn sl sc el ec) sl)
    ((:no-loc r) nil)))

(defun scion-note.region (note buffer)
  (destructuring-bind (tag loc msg more) note
    (destructure-case loc
      ((:loc filename sl sc el ec)
       (if (equal (buffer-file-name buffer) filename)
(scion-location-to-region sl sc el ec buffer)
nil))
      ((:no-loc _)
       nil))))

(defun scion-note.severity (note)
  (car note))

(defun scion-note.location (note)
  (destructure-case note
    ((:warning loc msg info)
     loc)
    ((:error loc msg info)
     loc)))

(defun scion-location-to-region (start-line start-col end-line end-col
&optional buffer)
  "Translate a Haskell (line,col) region into an Emacs region.

TODO: Fix up locations if buffer has been modified in between."
  (with-current-buffer (or buffer (current-buffer))
    (save-excursion
      (save-restriction
(widen) ; look in whole buffer
(goto-char 1)
(forward-line (1- start-line))
(move-to-column start-col)
(let ((start (point)))
(forward-line (- end-line start-line))
(move-to-column end-col)
(let ((end (point)))
(cond
((< end start)
(list end start))
((= start end) ; span would be invisible
(list start (progn ; a bit of a hack, but well
(goto-char start)
(forward-word)
(point))))
(t
(list start end)))))))))

(defun scion-canonicalise-note-location (note)
  "Translate the note's location into absolute path names.
Modifies input note."
  (destructure-case (cadr note)
    ((:loc fname _ _ _ _)
     (setf (cadadr note)
(expand-file-name fname scion-project-root-dir))))
  note)

;;;;; Adding a single compiler note

(defun scion-overlay-note (note buffer)
  "Add a compiler note to the buffer as an overlay."
  (multiple-value-bind (start end) (scion-note.region note buffer)
    (when start
      (goto-char start)
      (let ((severity (scion-note.severity note))
            (message (scion-note.message note)))
        (scion-create-note-overlay note start end severity message)))))

(defun scion-create-note-overlay (note start end severity message)
  "Create an overlay representing a compiler note.
The overlay has several properties:
FACE - to underline the relevant text.
SEVERITY - for future reference, :NOTE, :STYLE-WARNING, :WARNING, or :ERROR.
MOUSE-FACE - highlight the note when the mouse passes over.
HELP-ECHO - a string describing the note, both for future reference
and for display as a tooltip (due to the special
property name)."
  (let ((overlay (make-overlay start end)))
    (flet ((putp (name value) (overlay-put overlay name value)))
      (putp 'scion note)
      (putp 'face (scion-severity-face severity))
      ;(putp 'severity severity)
      (unless (scion-emacs-20-p)
(putp 'mouse-face 'highlight))
      (putp 'help-echo message)
      overlay)))

(defun scion-severity-face (severity)
  "Return the name of the font-lock face representing SEVERITY."
  (ecase severity
    (:error 'scion-error-face)
    (:warning 'scion-warning-face)))

(defun scion-make-notes (warnings errors &optional keep-existing-notes)
  (let ((notes (if keep-existing-notes
(scion-compiler-notes)
(scion-makehash #'equal))))
    (loop for note in (nconc errors warnings)
do (progn
(scion-canonicalise-note-location note)
(let* ((fname (scion-note.filename note))
(old-notes (gethash fname notes)))
(puthash fname (cons note old-notes) notes))))
    notes))

(defun scion-next-note-in-buffer ()
  "Goto next note in current buffer."
  (interactive)
  (scion-next-note-in-buffer-aux nil))

(defun scion-previous-note-in-buffer ()
  "Goto previous note in current buffer if any."
  (interactive)
  (scion-next-note-in-buffer-aux t))

(defun scion-next-note-in-buffer-aux (&optional backwards)
  (flet ((my-next-overlay-change (p) (if backwards
(previous-overlay-change p)
(next-overlay-change p)))
(my-eobp () (if backwards (bobp) (eobp))))
    (let ((note0 (scion-note-at-point)))
      (let ((next-note
(save-excursion
(block found-sth
(while (not (my-eobp))
(dolist (o (overlays-at (point)))
(let ((note (overlay-get o 'scion)))
(when (and note (not (equal note note0)))
(return-from found-sth (cons (point) note)))))
(goto-char (my-next-overlay-change (point))))))))
(if next-note
(progn
(goto-char (car next-note))
(message "%s" (scion-note.message (cdr next-note))))
(message "No more notes in this buffer."))))))

(defun scion-note-at-point (&optional pt)
  (block nil
    (let ((pt (or pt (point))))
      (dolist (o (overlays-at pt))
(let ((note (overlay-get o 'scion)))
(when note
(return note)))))))

;;;---------------------------------------------------------------------------
;;; The buffer that shows the compiler notes

(defvar scion-compiler-notes-mode-map)

(define-derived-mode scion-compiler-notes-mode fundamental-mode
  "Compiler-Notes"
  "\\<scion-compiler-notes-mode-map>\
\\{scion-compiler-notes-mode-map}
\\{scion-popup-buffer-mode-map}
"
  ;(scion-set-truncate-lines)
  )

(scion-define-keys scion-compiler-notes-mode-map
  ((kbd "RET") 'scion-compiler-notes-default-action-or-show-details)
  ([return] 'scion-compiler-notes-default-action-or-show-details)
  ([mouse-2] 'scion-compiler-notes-default-action-or-show-details/mouse))

(defun scion-compiler-notes-default-action-or-show-details/mouse (event)
  "Invoke the action pointed at by the mouse, or show details."
  (interactive "e")
  (destructuring-bind (mouse-2 (w pos &rest _) &rest __) event
    (save-excursion
      (goto-char pos)
      (let ((fn (get-text-property (point)
                                   'scion-compiler-notes-default-action)))
(if fn (funcall fn) (scion-compiler-notes-show-details))))))

(defun scion-compiler-notes-default-action-or-show-details ()
  "Invoke the action at point, or show details."
  (interactive)
  (let ((fn (get-text-property (point) 'scion-compiler-notes-default-action)))
    (if fn (funcall fn) (scion-compiler-notes-show-details))))

(defun scion-compiler-notes-show-details ()
  (interactive)
  (let* ((tree (scion-tree-at-point))
         (note (plist-get (scion-tree.plist tree) 'note))
         (inhibit-read-only t))
    (cond ((not (scion-tree-leaf-p tree))
           (scion-tree-toggle tree))
          (t
           (scion-show-source-location note t)))))

(defun scion-show-source-location (note &optional no-highlight-p)
  (save-selected-window ; show the location, but don't hijack focus.
    (scion-goto-source-location note)
    ;(unless no-highlight-p (sldb-highlight-sexp))
    ;(scion-show-buffer-position (point))
    ))

(defun scion-goto-source-location (loc)
  (let ((file (scion-note.filename loc)))
    (when file
      (find-file file)
      (goto-line (scion-note.line loc)))))

(defun scion-list-compiler-notes (notes)
  "Show the compiler notes NOTES in tree view."
  (interactive (list (scion-compiler-notes)))
  (with-temp-message "Preparing compiler note tree..."
    (scion-with-popup-buffer ("*SCION Compiler-Notes*")
      (erase-buffer)
      (scion-compiler-notes-mode)
      (when (null notes)
        (insert "[no notes]"))
      (let ((collapsed-p))
        (dolist (tree (scion-compiler-notes-to-tree notes))
          (when (scion-tree.collapsed-p tree) (setf collapsed-p t))
          (scion-tree-insert tree "")
          (insert "\n"))
        (goto-char (point-min))))))

(defvar scion-tree-printer 'scion-tree-default-printer)

(defun scion-compiler-notes-to-tree (notes)
  (let ((warns nil)
(errs nil))
    (maphash (lambda (file notes)
(loop for note in notes
do (case (scion-note.severity note)
(:warning (setq warns (cons note warns)))
(:error (setq errs (cons note warns))))))
notes)
    (let ((alist (list (cons :error errs)
(cons :warning warns))))
      (loop for (severity . notes) in alist
collect (scion-tree-for-severity severity notes nil)))))

(defun scion-tree-for-severity (severity notes collapsed-p)
  (make-scion-tree :item (format "%s (%d)"
(case severity
(:warning "Warnings")
(:error "Errors")
(t (print severity)))
(length notes))
:kids (mapcar #'scion-tree-for-note notes)
:collapsed-p collapsed-p))

(defun scion-tree-for-note (note)
  (make-scion-tree :item (format "%s:\n%s"
(scion-note.filename note)
(scion-note.message note))
:plist (list 'note note)
:print-fn scion-tree-printer))


;;;---------------------------------------------------------------------------

(defmacro* scion-handling-failure ((res-var) &body body)
  (let ((x (gensym))
(val (gensym)))
  `(lambda (,x)
     (destructure-case ,x
       ((:ok ,val)
(let ((,res-var ,val))
,@body))
       ((:error ,val)
(message "Remote command failed: %s" ,val)
nil)))))

(put 'scion-handling-failure 'lisp-indent-function 1)

(defun scion-cabal-root-dir (&optional start-directory)
  "Look for a <name>.cabal file from START-DIRECTORY upwards."
  (let ((dir (or start-directory
default-directory
(error "No start directory given"))))
    (if (car (directory-files dir t ".cabal$"))
dir
      (let ((next-dir (file-name-directory (directory-file-name
                                            (file-truename dir)))))
(unless (or (equal dir next-dir) (null next-dir))
          (scion-cabal-root-dir next-dir))))))

(defun scion-cabal-file (dir)
  "Return the only Cabal file in the given directory.
Returns NIL if the directory does not contain such file, and
signals an error if multiple files are present."
  (let ((cabal-files (directory-files dir t ".cabal$")))
    (if (car cabal-files)
(if (cadr cabal-files)
(error "Multiple .cabal files in directory: %s" dir)
(car cabal-files))
      nil)))

(defun scion-open-cabal-project (root-dir rel-dist-dir extra-args)
  "Load project metadata from a Cabal description.

This does not load the project but merely loads the metadata.

ROOT-DIR is the project root directory \(the directory
which contains the .cabal file\).

REL-DIST-DIR is the directory name relative to the project root.
By default Scion uses \".scion-dist\" to avoid interfering with
command line tools.

EXTRA-ARGS is a string of command line flags."
  (interactive (scion-interactive-configure-args))
  (lexical-let ((root-dir root-dir))
    (scion-eval-async `(open-cabal-project ,(expand-file-name root-dir)
,rel-dist-dir
,extra-args)
(scion-handling-failure (x)
(setq scion-project-root-dir root-dir)
(message (format "Cabal project loaded: %s" x)))))
  (message "Loading Cabal project."))

(defun scion-interactive-configure-args ()
  (let ((root (scion-cabal-root-dir)))
     (list (funcall (if (fboundp 'read-directory-name)
                        'read-directory-name
                      'read-file-name)
"Directory: " root root)
(read-from-minibuffer "Dist directory: " ".dist-scion")
(read-from-minibuffer "Configure Flags: " ""))))

(defun scion-configure-cabal-project (root-dir rel-dist-dir extra-args)
  "Configure/Reconfigure a Cabal project.

This does not load the project but merely loads the metadata and
pre-processes files.

ROOT-DIR is the project root directory \(the directory
which contains the .cabal file\).

REL-DIST-DIR is the directory name relative to the project root.
By default Scion uses \".scion-dist\" to avoid interfering with
command line tools.

EXTRA-ARGS is a string of command line flags."
  (interactive (scion-interactive-configure-args))
  (lexical-let ((root-dir root-dir))
    (scion-eval-async `(configure-cabal-project ,(expand-file-name root-dir)
,rel-dist-dir
,extra-args)
(scion-handling-failure (x)
(setq scion-project-root-dir root-dir)
(message (format "Cabal project loaded: %s" x))))))

(defun scion-load-library ()
  "Load the library of the current cabal project.

Sets the GHC flags for the library from the current Cabal project and loads it."
  (interactive)
  (message "Loading library...")
  (scion-eval-async `(load-component library)
    (scion-handling-failure (result)
      (scion-report-compilation-result result))))

(defun scion-report-compilation-result (result &optional buf)
  (destructuring-bind (tag successp warns errs duration) result
    (assert (eq tag 'compilation-result))
    (let ((nerrors (length errs))
(nwarnings (length warns))
(notes (scion-make-notes errs warns)))
      (setq scion-last-compilation-result
(list tag successp notes duration))
      (scion-highlight-notes notes buf)
      (when (not buf)
(scion-show-note-counts successp nwarnings nerrors duration)
(when (< 0 (+ nwarnings nerrors))
(scion-list-compiler-notes notes)))
      (scion-report-status (format ":%d/%d" nerrors nwarnings))
      nil)))
    
;; ((:ok warns)
;; (setq scion-last-compilation-result
;; (list 42 (mapc #'scion-canonicalise-note-location
;; warns) t nil))
;; (scion-highlight-notes warns)
;; (scion-show-note-counts t warns nil))
;; ((:error errs warns)
;; (let ((notes (mapc #'scion-canonicalise-note-location
;; (append errs warns))))
;; (setq scion-last-compilation-result
;; (list 42 notes nil nil))
;; (scion-highlight-notes notes))
;; (scion-show-note-counts nil warns errs))))

(defun scion-show-note-counts (successp nwarnings nerrors secs)
  (message "Compilation %s: %s%s%s"
(if successp "finished" "FAILED")
(scion-note-count-string "error" nerrors)
(scion-note-count-string "warning" nwarnings)
(if secs (format "[%.2f secs]" secs) "")))

(defun scion-note-count-string (category count &optional suppress-if-zero)
  (cond ((and (zerop count) suppress-if-zero)
         "")
        (t (format "%2d %s%s " count category (if (= count 1) "" "s")))))

(defun scion-supported-languages ()
  ;; TODO: cache result
  (scion-eval '(list-supported-languages)))

(defun haskell-insert-language (lang)
  "Insert a LANGUAGE pragma at the top of the file."
  ;; TODO: automatically jump to or insert LANGUAGE pragma
  (interactive
   (let ((langs (scion-supported-languages)))
     (list (ido-completing-read "Language: " langs))))
  (save-excursion
    (goto-char (point-min))
    (insert "{-# LANGUAGE " lang " #-}\n"))
  (message "Added language %s" lang))

(defun scion-supported-pragmas ()
  ;; TODO: cache result
  (scion-eval '(list-supported-pragmas)))

(defun haskell-insert-pragma (pragma)
  "Insert a pragma at the current point."
  (interactive (let ((choices (scion-supported-pragmas)))
;; standard completing-read cannot even deal properly
;; with upper-case words.
(list (ido-completing-read "Pragma: " choices))))
  (insert "{-# " (upcase pragma) " #-}")
  (backward-char 4))

(defun scion-supported-flags ()
  ;; TODO: cache result
  (scion-eval '(list-supported-flags)))

(defun haskell-insert-flag (flag)
  "Insert a command line flag at the curretn point."
  ;; TODO: automatically insert/add OPTIONS pragma
  (interactive
   (let ((flags (scion-supported-flags)))
     (list (ido-completing-read "Flag: " flags))))
  (insert flag))

(defun scion-set-command-line-flag (flag)
  (interactive "sCommand Line Flag: ")
  (scion-eval `(add-command-line-flag ,flag)))

(defun scion-exposed-modules ()
  (scion-eval '(list-exposed-modules)))

(defun haskell-insert-module-name (mod)
  "Insert a module name at the current point.

When called interactively tries to complete to modules of all
installed packages (However, not of the current project.)"
  (interactive
   (let ((mods (scion-exposed-modules)))
     (list (ido-completing-read "Module: " mods))))
  (insert mod))

(define-key scion-mode-map "\C-cil" 'haskell-insert-language)
(define-key scion-mode-map "\C-cip" 'haskell-insert-pragma)
(define-key scion-mode-map "\C-cif" 'haskell-insert-flag)
(define-key scion-mode-map "\C-cim" 'haskell-insert-module-name)

(define-key scion-mode-map "\C-c\C-o" 'scion-open-cabal-project)
(define-key scion-mode-map "\C-c\C-L" 'scion-load)
(define-key scion-mode-map "\M-n" 'scion-next-note-in-buffer)
(define-key scion-mode-map "\M-p" 'scion-previous-note-in-buffer)
(define-key scion-mode-map "\C-c\C-n" 'scion-list-compiler-notes)

(defun haskell-insert-module-header (module-name &optional
author
email)
  (interactive (list (read-from-minibuffer "Module name: ")
(read-from-minibuffer "Author name: " user-full-name)
(read-from-minibuffer "Author email: " user-mail-address)))
  (insert "-- |"
          "\n-- Module : " module-name
"\n-- Copyright : (c) " author " " (substring (current-time-string) -4)
"\n-- License : BSD-style\n--" ;; TODO: extract from .cabal file
"\n-- Maintainer : " email
"\n-- Stability : experimental"
"\n-- Portability : portable\n--\n"))

(defun scion-set-ghc-verbosity (n)
  (interactive "nLevel [0-5]: ")
  (scion-eval `(set-ghc-verbosity ,n)))

;;;---------------------------------------------------------------------------

(defun scion-emacs-20-p ()
  (and (not (featurep 'xemacs))
       (= emacs-major-version 20)))

;;;---------------------------------------------------------------------------

(defalias 'scion-float-time
  (if (fboundp 'float-time)
      'float-time
    (if (featurep 'xemacs)
(lambda ()
(multiple-value-bind (s0 s1 s2) (current-time)
(+ (* (float (ash 1 16)) s0) (float s1) (* 0.0000001 s2)))))))

;;;---------------------------------------------------------------------------
;;;; Flycheck (background type checking)

(make-variable-buffer-local
 (defvar scion-flycheck-timer nil
   "The timer for starting background compilation"))

(make-variable-buffer-local
;; TODO: hm, maybe this should be global (due to single-threadedness)
(defvar scion-flycheck-is-running nil
  "If t, the (single-threaded) background typechecker is running."))

(make-variable-buffer-local
 (defvar scion-flycheck-last-change-time nil
   "Time of last buffer change."))

(defcustom scion-flycheck-no-changes-timeout 2.0
  "Time to wait after last change before starting compilation."
  :group 'scion
  :type 'number)

(defun scion-turn-on-flycheck ()
  "Turn on flycheck in current buffer"
  (interactive)
  (if (not scion-mode)
      (message "Background typechecking only supported inside scion-mode.")
    (add-hook 'after-change-functions 'scion-flycheck-after-change-function nil t)
    (add-hook 'kill-buffer-hook 'scion-kill-buffer-hook nil t)

    (scion-flycheck-on-save 1)

    ;; TODO: update modeline

    (setq scion-flycheck-timer
(run-at-time nil 1 'scion-flycheck-on-timer-event (current-buffer)))))

(defun scion-turn-off-flycheck ()
  (interactive)

  (remove-hook 'after-change-functions 'scion-flycheck-after-change-function t)
  (remove-hook 'kill-buffer-hook 'scion-kill-buffer-hook t)

  (scion-flycheck-on-save -1)
  ;; TODO: delete overlays?
  (when scion-flycheck-timer
    (cancel-timer scion-flycheck-timer)
    (setq scion-flycheck-timer nil))
  (setq scion-flycheck-is-running nil))

(make-variable-buffer-local
 (defvar scion-flycheck-on-save-state nil
   "Non-nil iff type checking should be performed when the file is saved."))

(defun scion-flycheck-on-save (&optional arg)
  "Toggle type checking the current file when it is saved.

A positive argument forces type checking to be on, a negative
forces it to be off. NIL toggles the current state."
  (interactive "P")
  (if (not scion-mode)
      (message "Background typechecking only supported inside scion-mode.")
    (let ((new-state
(cond
((null arg) (not scion-flycheck-on-save-state))
((consp arg) nil)
((numberp arg) (>= arg 0)))))
      (when (not (eq (not new-state)
(not scion-flycheck-on-save-state)))
(if new-state
(add-hook 'after-save-hook 'scion-after-save-hook nil t)
(remove-hook 'after-save-hook 'scion-after-save-hook t))
      
(setq scion-flycheck-on-save-state new-state)
(message (format "Typecheck-on-save has been turned %s"
(if new-state "ON" "OFF")))))))

(defun scion-flycheck-after-change-function (start stop len)
  ;; TODO: be more smarter about which parts need updating.
  ;;
  ;; flymake (optionally) supports syntax/typechecking if a newline was inserted
  (setq scion-flycheck-last-change-time (scion-float-time)))

(defun scion-after-save-hook ()
  (when (and scion-mode
(not scion-flycheck-is-running))
    (setq scion-flycheck-last-change-time nil)
    (scion-flycheck-start-check)))
 
(defun scion-kill-buffer-hook ()
  (when scion-flycheck-timer
    (cancel-timer scion-flycheck-timer)
    (setq scion-flycheck-timer nil)))

(defun scion-flycheck-on-timer-event (buffer)
  "Start a syntax check for buffer BUFFER if necessary."
  (when (buffer-live-p buffer)
    (with-current-buffer buffer
      (when (and (not scion-flycheck-is-running)
scion-flycheck-last-change-time
(> (- (scion-float-time) scion-flycheck-last-change-time)
                    scion-flycheck-no-changes-timeout))
(setq scion-flycheck-last-change-time nil)
;; HACK: prevent scion-after-save-hook from running a typecheck
(setq scion-flycheck-is-running t)
(save-buffer buffer)
(scion-flycheck-start-check)))))

(defun scion-flycheck-start-check ()
  (interactive)
  (when (scion-connected-p)
    (let ((filename (buffer-file-name)))
      (setq scion-flycheck-is-running t)
      (scion-report-status ":-/-")
      (scion-eval-async `(background-typecheck-file ,filename)
(lambda (res)
(setq scion-flycheck-is-running nil)
(funcall (scion-handling-failure (result)
(destructuring-bind (ok comp-rslt) result
(if ok
(scion-report-compilation-result comp-rslt
(current-buffer))
(scion-report-status "[?]"))))
res)
nil)))))

(make-variable-buffer-local
 (defvar scion-mode-line-notes nil))

(defun scion-report-status (status)
  (let ((stats-str (concat " Scion" status)))
    (setq scion-mode-line stats-str)
    (force-mode-line-update)))

;;;---------------------------------------------------------------------------
;;;; To be sorted

(defun scion-thing-at-point ()
  (interactive)
  (let ((filename (buffer-file-name))
(line (line-number-at-pos))
(col (current-column)))
    (message
     (let ((rslt (scion-eval `(thing-at-point ,filename ,line ,col))))
       (funcall (scion-handling-failure (r) r) rslt)))))

(defun scion-dump-sources ()
  (interactive)
  (scion-eval '(dump-sources)))

(define-key scion-mode-map "\C-c\C-t" 'scion-thing-at-point)

(provide 'scion)

(defun scion-load (comp)
  "Load current file or Cabal project.

If the file is within a Cabal project, prompts the user which
component to load, or whether only the current file should be
loaded."
  (interactive (list (scion-select-component)))
  (message "Loading %s..." (scion-format-component comp))
  (scion-eval-async `(load ,comp)
     (scion-handling-failure (result)
       (scion-report-compilation-result result))))

(defun scion-select-component ()
  (let* ((cabal-dir (scion-cabal-root-dir))
(cabal-file (ignore-errors (scion-cabal-file cabal-dir)))
(cabal-components (ignore-errors
(when cabal-file
(scion-cabal-components cabal-file))))
(options (nconc cabal-components
`((file ,(buffer-file-name))))))
    (if (null (cdr options))
(car options)
      ;; TODO: abstract this kludge into `scion-completing-read`
      (let* ((disp->comp (scion-makehash #'equal))
(opts (loop for c in options
do (puthash (scion-format-component c) c disp->comp)
collect (scion-format-component c))))
(gethash (ido-completing-read "Load Component: "
opts
nil
t)
disp->comp)))))

(defun scion-format-component (comp)
  (cond
   ((eq comp 'library)
    "Library")
   ((eq (car comp) 'executable)
    (format "Executable %s" (cadr comp)))
   ((eq (car comp) 'file)
    (format "File %s" (cadr comp)))
   (t
    (format "%s" comp))))


(defun scion-cabal-components (cabal-file)
  "Return list of components in CABAL-FILE.
The result is a list where each element is either the symbol
LIBRARY or (EXECUTABLE <name>)."
  (let ((comps (scion-eval `(list-cabal-components ,cabal-file))))
    (destructure-case comps
      ((:ok cs)
       cs)
      ((:error _)
       (error "Could not process .cabal file")))))


;; Local Variables:
;; outline-regexp: ";;;;+"
;; End:
;; indent-tabs-mode: nil
Something went wrong with that request. Please try again.