summary refs log tree commit diff stats
path: root/lib/system/sysio.nim
Commit message (Collapse)AuthorAgeFilesLines
* float64 is now an alias to 'float'; fixes #545Araq2013-08-301-1/+1
|
* made some tests greenAraq2013-06-301-2/+2
|
* --os:standalone works againAraq2013-06-301-17/+22
|
* GC'ed wide strings for windowsAraq2013-05-201-8/+4
|
* Removes executable bit for text files.Grzegorz Adam Hankiewicz2013-03-161-0/+0
|
* made some tests greenAraq2013-03-041-0/+2
|
* Copyright 2012 -> 2013Araq2013-01-081-1/+1
|
* 'assert' hides EAssertionFailsure; stdlib makes use of 'tags'Araq2012-11-181-11/+13
|
* profiler improvementsAraq2012-09-171-1/+1
|
* term rewriting macros fully implemented; still buggyAraq2012-09-031-4/+0
|
* openarray/varargs split; breaks bootstrappingAraq2012-08-161-2/+2
|
* DLLs should work again; fixes #169Araq2012-07-241-0/+2
|
* changed integer promotion rules; breaks bootstrapping and lots of codeAraq2012-07-081-4/+4
|
* added devel/logging; weakrefs test; next steps for proper unsigned supportAraq2012-07-051-1/+1
|
* changed integer promotion rules; added math.fmodAraq2012-06-281-2/+2
|
* docgen2 improvementsAraq2012-06-231-3/+3
|
* win64 is a supported target; bugfix: nimrod c -r on windows; stdlib uses ↵Araq2012-03-041-4/+27
| | | | wide char versions of the WinAPI
* pragma on/off improvements; endb rewrittenAraq2012-01-281-1/+1
|
* year 2012 for most copyright headersAraq2012-01-021-1/+1
|
* sysio: got rid of now unnecessary length checkAraq2011-12-311-2/+0
|
* fixes for readAllSimon Hafner2011-12-301-17/+22
|
* implemented readAll()Simon Hafner2011-12-221-19/+45
|
* bugfix: tester compiles againAraq2011-11-261-1/+1
|
* deprecated endOfFile and readLineAraq2011-11-251-11/+8
|
* renamed optional to discardableAraq2011-09-241-5/+14
|
* beginning of a taint mode; type system enhancementsAraq2011-09-241-3/+3
|
* bugfixes; added events module, sequtils moduleAraq2011-07-261-5/+9
|
* code gen bugfixes; marshal.nim implementedAraq2011-06-261-6/+4
|
* readFile raises EIO instead of returning nil; added system.writeFileAraq2011-06-161-13/+19
|
* ugh cannot get rid of rawEcho yet because old compiler relies on itAraq2011-06-051-0/+3
|
* threads clean up their heapAraq2011-06-041-3/+0
|
* unary <; countup two type parameters; --recursivePath should work nowAraq2011-01-291-1/+9
|
* handling of compiler procs improved for DLL generationAndreas Rumpf2010-07-291-8/+0
|
* explicit types for generic routinesAndreas Rumpf2010-05-281-3/+8
|
* fixed pango/pangoutils new wrappersAndreas Rumpf2010-02-261-0/+0
|
* continued work on html/xmlparserrumpf_a@web.de2010-02-141-0/+0
|
* bugfixes for the high-level postgreSQL wrapperAndreas Rumpf2010-01-291-1/+4
|
* added tools and web dirsAndreas Rumpf2009-09-151-8/+6
|
* overload resolution for proc varsAndreas Rumpf2009-06-241-6/+14
|
* version0.7.10Andreas Rumpf2009-06-081-0/+178
#n665'>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
import std/deques
import std/options
import std/streams
import std/unicode

when defined(posix):
  import std/posix

import config/config
import display/term
import extern/stdio
import io/promise
import io/serialize
import js/javascript
import js/jstypes
import js/regex
import loader/connecterror
import loader/loader
import loader/request
import local/select
import server/buffer
import server/forkserver
import types/cell
import types/color
import types/cookie
import types/url
import utils/luwrap
import utils/mimeguess
import utils/strwidth
import utils/twtstr

import chagashi/charset

type
  CursorPosition* = object
    cursorx*: int
    cursory*: int
    xend*: int
    fromx*: int
    fromy*: int
    setx: int
    setxrefresh: bool

  ContainerEventType* = enum
    FAIL, SUCCESS, NEEDS_AUTH, REDIRECT, ANCHOR, NO_ANCHOR, UPDATE, READ_LINE,
    READ_AREA, OPEN, INVALID_COMMAND, STATUS, ALERT, LOADED, TITLE,
    CHECK_MAILCAP, QUIT

  ContainerEvent* = object
    case t*: ContainerEventType
    of READ_LINE:
      prompt*: string
      value*: string
      password*: bool
    of READ_AREA:
      tvalue*: string
    of OPEN, REDIRECT:
      request*: Request
    of ANCHOR, NO_ANCHOR:
      anchor*: string
    of ALERT:
      msg*: string
    of UPDATE:
      force*: bool
    else: discard

  HighlightType = enum
    HL_SEARCH, HL_SELECT

  SelectionType = enum
    SEL_NORMAL = "normal"
    SEL_BLOCK = "block"
    SEL_LINE = "line"

  Highlight = ref object
    case t: HighlightType
    of HL_SEARCH: discard
    of HL_SELECT:
      selectionType {.jsget.}: SelectionType
    x1, y1: int
    x2, y2: int

  PagePos = tuple
    x: int
    y: int

  BufferFilter* = ref object
    cmd*: string

  Container* = ref object
    # note: this is not the same as source.request.url (but should be synced
    # with buffer.url)
    url: URL
    #TODO this is inaccurate, because only the network charset is passed through
    charset*: Charset
    parent* {.jsget.}: Container
    children* {.jsget.}: seq[Container]
    config*: BufferConfig
    iface*: BufferInterface
    width* {.jsget.}: int
    height* {.jsget.}: int
    title*: string # used in status msg
    hovertext: array[HoverType, string]
    lastpeek: HoverType
    request*: Request # source request
    # if set, this *overrides* any content type received from the network. (this
    # is because it stores the content type from the -T flag.)
    contentType* {.jsget.}: Option[string]
    pos: CursorPosition
    bpos: seq[CursorPosition]
    highlights: seq[Highlight]
    process* {.jsget.}: Pid
    loaderPid* {.jsget.}: Pid
    loadinfo*: string
    lines: SimpleFlexibleGrid
    lineshift: int
    numLines*: int
    replace*: Container
    code*: int # note: this is not the status code, but the ConnectErrorCode.
    errorMessage*: string
    retry*: seq[URL]
    hlon*: bool # highlight on?
    sourcepair*: Container # pointer to buffer with a source view (may be nil)
    needslines*: bool
    canceled: bool
    events*: Deque[ContainerEvent]
    startpos: Option[CursorPosition]
    hasstart: bool
    redirectdepth*: int
    select*: Select
    canreinterpret*: bool
    cloned: bool
    currentSelection {.jsget.}: Highlight
    tmpJumpMark: PagePos
    jumpMark: PagePos
    marks: Table[string, PagePos]
    ishtml*: bool
    filter*: BufferFilter
    bgcolor*: CellColor

jsDestructor(Highlight)
jsDestructor(Container)

proc newBuffer*(forkserver: ForkServer, config: BufferConfig,
    request: Request, attrs: WindowAttributes, title = "",
    redirectdepth = 0, canreinterpret = true, fd = FileHandle(-1),
    contentType: Option[string]): Container =
  let (process, loaderPid) = forkserver.forkBuffer(request, config, attrs)
  if fd != -1:
    loaderPid.passFd(request.url.host, fd)
    if fd == 0:
      # We are passing stdin.
      closeStdin()
    else:
      discard close(fd)
  return Container(
    url: request.url,
    process: process,
    loaderPid: loaderPid,
    request: request,
    contentType: contentType,
    width: attrs.width,
    height: attrs.height - 1,
    title: title,
    config: config,
    redirectdepth: redirectdepth,
    pos: CursorPosition(
      setx: -1
    ),
    canreinterpret: canreinterpret
  )

proc newBufferFrom*(forkserver: ForkServer, attrs: WindowAttributes,
    container: Container, contentTypeOverride: string): Container =
  let request = newRequest(container.request.url, fromcache = true)
  let config = container.config
  let loaderPid = container.loaderPid
  let bufferPid = forkserver.forkBufferWithLoader(request, config, attrs,
    loaderPid)
  return Container(
    url: request.url,
    request: request,
    width: container.width,
    height: container.height,
    title: container.title,
    config: config,
    process: bufferPid,
    loaderPid: loaderPid,
    pos: CursorPosition(
      setx: -1
    ),
    canreinterpret: true,
    contentType: some(contentTypeOverride)
  )

func location*(container: Container): URL {.jsfget.} =
  return container.url

proc clone*(container: Container, newurl: URL): Promise[Container] =
  let url = if newurl != nil:
    newurl
  else:
    container.location
  return container.iface.clone(url).then(proc(pid: Pid): Container =
    if pid == -1:
      return nil
    return Container(
      url: url,
      config: container.config,
      iface: container.iface, # changed later in setStream
      width: container.width,
      height: container.height,
      title: container.title,
      hovertext: container.hovertext,
      lastpeek: container.lastpeek,
      request: container.request,
      pos: container.pos,
      bpos: container.bpos,
      highlights: container.highlights,
      process: pid,
      loaderPid: container.loaderPid,
      loadinfo: container.loadinfo,
      lines: container.lines,
      lineshift: container.lineshift,
      numLines: container.numLines,
      code: container.code,
      retry: container.retry,
      hlon: container.hlon,
      #needslines: container.needslines,
      canceled: container.canceled,
      events: container.events,
      startpos: container.startpos,
      hasstart: container.hasstart,
      redirectdepth: container.redirectdepth,
      select: container.select,
      canreinterpret: container.canreinterpret,
      ishtml: container.ishtml,
      cloned: true
    )
  )

func lineLoaded(container: Container, y: int): bool =
  return y - container.lineshift in 0..container.lines.high

func getLine(container: Container, y: int): SimpleFlexibleLine =
  if container.lineLoaded(y):
    return container.lines[y - container.lineshift]

iterator ilines*(container: Container, slice: Slice[int]): SimpleFlexibleLine {.inline.} =
  for y in slice:
    yield container.getLine(y)

func cursorx*(container: Container): int {.jsfget.} =
  container.pos.cursorx

func cursory*(container: Container): int {.jsfget.} =
  container.pos.cursory

func fromx*(container: Container): int {.jsfget.} =
  container.pos.fromx

func fromy*(container: Container): int {.jsfget.} =
  container.pos.fromy

func xend(container: Container): int {.inline.} = container.pos.xend
func lastVisibleLine(container: Container): int = min(container.fromy + container.height, container.numLines) - 1

func currentLine(container: Container): string =
  return container.getLine(container.cursory).str

func findColBytes(s: string, endx: int, startx = 0, starti = 0): int =
  var w = startx
  var i = starti
  while i < s.len and w < endx:
    var r: Rune
    fastRuneAt(s, i, r)
    w += r.twidth(w)
  return i

func cursorBytes(container: Container, y: int, cc = container.cursorx): int =
  return container.getLine(y).str.findColBytes(cc, 0, 0)

func currentCursorBytes(container: Container, cc = container.cursorx): int =
  return container.cursorBytes(container.cursory, cc)

# Returns the X position of the first cell occupied by the character the cursor
# currently points to.
func cursorFirstX(container: Container): int =
  if container.numLines == 0: return 0
  let line = container.currentLine
  var w = 0
  var i = 0
  var r: Rune
  let cc = container.cursorx
  while i < line.len:
    fastRuneAt(line, i, r)
    let tw = r.twidth(w)
    if w + tw > cc:
      return w
    w += tw

# Returns the X position of the last cell occupied by the character the cursor
# currently points to.
func cursorLastX(container: Container): int =
  if container.numLines == 0: return 0
  let line = container.currentLine
  var w = 0
  var i = 0
  var r: Rune
  let cc = container.cursorx
  while i < line.len and w <= cc:
    fastRuneAt(line, i, r)
    w += r.twidth(w)
  return max(w - 1, 0)

# Last cell for tab, first cell for everything else (e.g. double width.)
# This is needed because moving the cursor to the 2nd cell of a double
# width character clears it on some terminals.
func cursorDispX(container: Container): int =
  if container.numLines == 0: return 0
  let line = container.currentLine
  if line.len == 0: return 0
  var w = 0
  var pw = 0
  var i = 0
  var r: Rune
  let cc = container.cursorx
  while i < line.len and w <= cc:
    fastRuneAt(line, i, r)
    pw = w
    w += r.twidth(w)
  if r == Rune('\t'):
    return max(w - 1, 0)
  else:
    return pw

func acursorx*(container: Container): int =
  max(0, container.cursorDispX() - container.fromx)

func acursory*(container: Container): int =
  container.cursory - container.fromy

func maxScreenWidth(container: Container): int =
  for line in container.ilines(container.fromy..container.lastVisibleLine):
    result = max(line.str.width(), result)

func getTitle*(container: Container): string {.jsfunc.} =
  if container.title != "":
    return container.title
  return container.location.serialize(excludepassword = true)

func currentLineWidth(container: Container): int =
  if container.numLines == 0: return 0
  return container.currentLine.width()

func maxfromy(container: Container): int =
  return max(container.numLines - container.height, 0)

func maxfromx(container: Container): int =
  return max(container.maxScreenWidth() - container.width, 0)

func atPercentOf*(container: Container): int =
  if container.numLines == 0: return 100
  return (100 * (container.cursory + 1)) div container.numLines

func lineWindow(container: Container): Slice[int] =
  if container.numLines == 0: # not loaded
    return 0..container.height * 5
  let n = (container.height * 5) div 2
  var x = container.fromy - n + container.height div 2
  var y = container.fromy + n + container.height div 2
  if y >= container.numLines:
    x -= y - container.numLines
    y = container.numLines
  if x < 0:
    y += -x
    x = 0
  return x .. y

func startx(hl: Highlight): int =
  if hl.y1 < hl.y2:
    hl.x1
  elif hl.y2 < hl.y1:
    hl.x2
  else:
    min(hl.x1, hl.x2)
func starty(hl: Highlight): int = min(hl.y1, hl.y2)
func endx(hl: Highlight): int =
  if hl.y1 > hl.y2:
    hl.x1
  elif hl.y2 > hl.y1:
    hl.x2
  else:
    max(hl.x1, hl.x2)
func endy(hl: Highlight): int = max(hl.y1, hl.y2)

func colorNormal(container: Container, hl: Highlight, y: int,
    limitx: Slice[int]): Slice[int] =
  let starty = hl.starty
  let endy = hl.endy
  if y in starty + 1 .. endy - 1:
    let w = container.getLine(y).str.width()
    return min(limitx.a, w) .. min(limitx.b, w)
  if y == starty and y == endy:
    return max(hl.startx, limitx.a) .. min(hl.endx, limitx.b)
  if y == starty:
    let w = container.getLine(y).str.width()
    return max(hl.startx, limitx.a) .. min(limitx.b, w)
  if y == endy:
    let w = container.getLine(y).str.width()
    return min(limitx.a, w) .. min(hl.endx, limitx.b)

func colorArea(container: Container, hl: Highlight, y: int,
    limitx: Slice[int]): Slice[int] =
  case hl.t
  of HL_SELECT:
    case hl.selectionType
    of SEL_NORMAL:
      return container.colorNormal(hl, y, limitx)
    of SEL_BLOCK:
      if y in hl.starty .. hl.endy:
        let (x, endx) = if hl.x1 < hl.x2:
          (hl.x1, hl.x2)
        else:
          (hl.x2, hl.x1)
        return max(x, limitx.a) .. min(endx, limitx.b)
    of SEL_LINE:
      if y in hl.starty .. hl.endy:
        let w = container.getLine(y).str.width()
        return min(limitx.a, w) .. min(limitx.b, w)
  else:
    return container.colorNormal(hl, y, limitx)

func findHighlights*(container: Container, y: int): seq[Highlight] =
  for hl in container.highlights:
    if y in hl.starty .. hl.endy:
      result.add(hl)

func getHoverText*(container: Container): string =
  for t in HoverType:
    if container.hovertext[t] != "":
      return container.hovertext[t]

func isHoverURL*(container: Container, url: URL): bool =
  let hoverurl = parseURL(container.hovertext[HOVER_LINK])
  return hoverurl.isSome and url.host == hoverurl.get.host

proc triggerEvent(container: Container, event: ContainerEvent) =
  container.events.addLast(event)

proc triggerEvent(container: Container, t: ContainerEventType) =
  container.triggerEvent(ContainerEvent(t: t))

proc updateCursor(container: Container)

proc setNumLines(container: Container, lines: int, finish = false) =
  if container.numLines != lines:
    container.numLines = lines
    if container.startpos.isSome and finish:
      container.pos = container.startpos.get
      container.startpos = none(CursorPosition)
    container.updateCursor()

proc requestLines*(container: Container, w = container.lineWindow): EmptyPromise
    {.discardable.} =
  if container.iface == nil:
    let res = EmptyPromise()
    res.resolve()
    return res
  return container.iface.getLines(w).then(proc(res: GetLinesResult) =
    container.lines.setLen(w.len)
    container.lineshift = w.a
    for y in 0 ..< min(res.lines.len, w.len):
      container.lines[y] = res.lines[y]
      container.lines[y].str.mnormalize()
    container.updateCursor()
    var isBgNew = container.bgcolor != res.bgcolor
    if isBgNew:
      container.bgcolor = res.bgcolor
    if res.numLines != container.numLines:
      container.setNumLines(res.numLines, true)
      container.triggerEvent(STATUS)
    let cw = container.fromy ..< container.fromy + container.height
    if w.a in cw or w.b in cw or cw.a in w or cw.b in w or isBgNew:
      container.triggerEvent(UPDATE)
  )

proc redraw(container: Container) {.jsfunc.} =
  container.triggerEvent(ContainerEvent(t: UPDATE, force: true))

proc sendCursorPosition*(container: Container) =
  container.iface.updateHover(container.cursorx, container.cursory)
      .then(proc(res: UpdateHoverResult) =
    if res.link.isSome:
      container.hovertext[HOVER_LINK] = res.link.get
    if res.title.isSome:
      container.hovertext[HOVER_TITLE] = res.title.get
    if res.link.isSome or res.title.isSome:
      container.triggerEvent(STATUS)
    if res.repaint:
      container.needslines = true
  )

proc setFromY(container: Container, y: int) {.jsfunc.} =
  if container.pos.fromy != y:
    container.pos.fromy = max(min(y, container.maxfromy), 0)
    container.needslines = true
    container.triggerEvent(UPDATE)

proc setFromX(container: Container, x: int, refresh = true) {.jsfunc.} =
  if container.pos.fromx != x:
    container.pos.fromx = max(min(x, container.maxfromx), 0)
    if container.pos.fromx > container.cursorx:
      container.pos.cursorx = min(container.pos.fromx, container.currentLineWidth())
      if refresh:
        container.sendCursorPosition()
    container.triggerEvent(UPDATE)

proc setFromXY(container: Container, x, y: int) {.jsfunc.} =
  container.setFromY(y)
  container.setFromX(x)

# Set the cursor to the xth column. 0-based.
# * refresh = false inhibits reporting of the cursor position to the buffer.
# * save = false inhibits cursor movement if it is currently outside the
#   screen, and makes it so cursorx is not saved for restoration on cursory
#   movement.
proc setCursorX(container: Container, x: int, refresh = true, save = true)
    {.jsfunc.} =
  if not container.lineLoaded(container.cursory):
    container.pos.setx = x
    container.pos.setxrefresh = refresh
    return
  container.pos.setx = -1
  let cw = container.currentLineWidth()
  let x2 = x
  let x = max(min(x, cw - 1), 0)
  # we check for save here, because it is only set by restoreCursorX where
  # we do not want to move the cursor just because it is outside the window.
  if not save or container.fromx <= x and x < container.fromx + container.width:
    container.pos.cursorx = x
  elif save and container.fromx > x:
    if x2 < container.cursorx:
      container.setFromX(x, false)
    container.pos.cursorx = container.fromx
  elif x > container.cursorx:
    container.setFromX(max(x - container.width + 1, container.fromx), false)
    container.pos.cursorx = x
  elif x < container.cursorx:
    container.setFromX(x, false)
    container.pos.cursorx = x
  if container.cursorx == x and container.currentSelection != nil and
      container.currentSelection.x2 != x:
    container.currentSelection.x2 = x
    container.triggerEvent(UPDATE)
  if refresh:
    container.sendCursorPosition()
  if save:
    container.pos.xend = container.cursorx

proc restoreCursorX(container: Container) {.jsfunc.} =
  let x = clamp(container.currentLineWidth() - 1, 0, container.xend)
  container.setCursorX(x, false, false)

proc setCursorY(container: Container, y: int, refresh = true) {.jsfunc.} =
  let y = max(min(y, container.numLines - 1), 0)
  if container.cursory == y: return
  if y - container.fromy >= 0 and y - container.height < container.fromy:
    container.pos.cursory = y
  else:
    if y > container.cursory:
      container.setFromY(y - container.height + 1)
    else:
      container.setFromY(y)
    container.pos.cursory = y
  if container.currentSelection != nil and container.currentSelection.y2 != y:
    container.triggerEvent(UPDATE)
    container.currentSelection.y2 = y
  container.restoreCursorX()
  if refresh:
    container.sendCursorPosition()

proc setCursorXY(container: Container, x, y: int, refresh = true) {.jsfunc.} =
  container.setCursorY(y, refresh)
  container.setCursorX(x, refresh)

proc cursorLineTextStart(container: Container) {.jsfunc.} =
  if container.numLines == 0: return
  var x = 0
  for r in container.currentLine.runes:
    if not r.isWhitespace():
      break
    x += r.twidth(x)
  container.setCursorX(x)

# zb
proc lowerPage(container: Container, n = 0) {.jsfunc.} =
  if n != 0:
    container.setCursorY(n - 1)
  container.setFromY(container.cursory - container.height + 1)

# z-
proc lowerPageBegin(container: Container, n = 0) {.jsfunc.} =
  container.lowerPage(n)
  container.cursorLineTextStart()

# zz
proc centerLine(container: Container, n = 0) {.jsfunc.} =
  if n != 0:
    container.setCursorY(n - 1)
  container.setFromY(container.cursory - container.height div 2)

# z.
proc centerLineBegin(container: Container, n = 0) {.jsfunc.} =
  container.centerLine(n)
  container.cursorLineTextStart()

# zt
proc raisePage(container: Container, n = 0) {.jsfunc.} =
  if n != 0:
    container.setCursorY(n - 1)
  container.setFromY(container.cursory)

# z^M
proc raisePageBegin(container: Container, n = 0) {.jsfunc.} =
  container.raisePage(n)
  container.cursorLineTextStart()

# z+
proc nextPageBegin(container: Container, n = 0) {.jsfunc.} =
  if n == 0:
    container.setCursorY(container.fromy + container.height)
  else:
    container.setCursorY(n - 1)
  container.cursorLineTextStart()
  container.raisePage()

# z^
proc previousPageBegin(container: Container, n = 0) {.jsfunc.} =
  if n == 0:
    container.setCursorY(container.fromy - 1)
  else:
    container.setCursorY(n - container.height) # +- 1 cancels out
  container.cursorLineTextStart()
  container.lowerPage()

proc centerColumn(container: Container) {.jsfunc.} =
  container.setFromX(container.cursorx - container.width div 2)

proc setCursorYCenter(container: Container, y: int, refresh = true)
    {.jsfunc.} =
  let fy = container.fromy
  container.setCursorY(y, refresh)
  if fy != container.fromy:
    container.centerLine()

proc setCursorXYCenter(container: Container, x, y: int, refresh = true) {.jsfunc.} =
  let fy = container.fromy
  let fx = container.fromx
  container.setCursorXY(x, y, refresh)
  if fy != container.fromy:
    container.centerLine()
  if fx != container.fromx:
    container.centerColumn()

proc cursorDown(container: Container, n = 1) {.jsfunc.} =
  if container.select.open:
    container.select.cursorDown()
  else:
    container.setCursorY(container.cursory + n)

proc cursorUp(container: Container, n = 1) {.jsfunc.} =
  if container.select.open:
    container.select.cursorUp()
  else:
    container.setCursorY(container.cursory - n)

proc cursorLeft(container: Container, n = 1) {.jsfunc.} =
  if container.select.open:
    container.select.cursorLeft()
  else:
    container.setCursorX(container.cursorFirstX() - n)

proc cursorRight(container: Container, n = 1) {.jsfunc.} =
  if container.select.open:
    container.select.cursorRight()
  else:
    container.setCursorX(container.cursorLastX() + n)

proc cursorLineBegin(container: Container) {.jsfunc.} =
  container.setCursorX(0)

proc cursorLineEnd(container: Container) {.jsfunc.} =
  container.setCursorX(container.currentLineWidth() - 1)

type BreakFunc = proc(r: Rune): BreakCategory {.nimcall.}

proc cursorNextWord(container: Container, breakFunc: BreakFunc) =
  if container.numLines == 0: return
  var r: Rune
  var b = container.currentCursorBytes()
  var x = container.cursorx
  # meow
  let currentCat = if b < container.currentLine.len:
    container.currentLine.runeAt(b).breakFunc()
  else:
    BREAK_SPACE
  if currentCat != BREAK_SPACE:
    # not in space, skip chars that have the same category
    while b < container.currentLine.len:
      let pb = b
      fastRuneAt(container.currentLine, b, r)
      if r.breakFunc() != currentCat:
        b = pb
        break
      x += r.twidth(x)

  # skip space
  while b < container.currentLine.len:
    let pb = b
    fastRuneAt(container.currentLine, b, r)
    if r.breakFunc() != BREAK_SPACE:
      b = pb
      break
    x += r.twidth(x)

  if b < container.currentLine.len:
    container.setCursorX(x)
  else:
    if container.cursory < container.numLines - 1:
      container.cursorDown()
      container.cursorLineBegin()
    else:
      container.cursorLineEnd()

proc cursorNextWord(container: Container) {.jsfunc.} =
  container.cursorNextWord(breaksWordCat)

proc cursorNextViWord(container: Container) {.jsfunc.} =
  container.cursorNextWord(breaksViWordCat)

proc cursorNextBigWord(container: Container) {.jsfunc.} =
  container.cursorNextWord(breaksBigWordCat)

proc cursorPrevWord(container: Container, breakFunc: BreakFunc) =
  if container.numLines == 0: return
  var b = container.currentCursorBytes()
  var x = container.cursorx
  if container.currentLine.len > 0:
    b = min(b, container.currentLine.len - 1)
    let currentCat = if b >= 0:
      container.currentLine.runeAt(b).breakFunc()
    else:
      BREAK_SPACE
    if currentCat != BREAK_SPACE:
      # not in space, skip chars that have the same category
      while b >= 0:
        let (r, o) = lastRune(container.currentLine, b)
        if r.breakFunc() != currentCat:
          break
        b -= o
        x -= r.twidth(x)

    # skip space
    while b >= 0:
      let (r, o) = lastRune(container.currentLine, b)
      if r.breakFunc() != BREAK_SPACE:
        break
      b -= o
      x -= r.twidth(x)
  else:
    b = -1

  if b >= 0:
    container.setCursorX(x)
  else:
    if container.cursory > 0:
      container.cursorUp()
      container.cursorLineEnd()
    else:
      container.cursorLineBegin()

proc cursorPrevWord(container: Container) {.jsfunc.} =
  container.cursorPrevWord(breaksWordCat)

proc cursorPrevViWord(container: Container) {.jsfunc.} =
  container.cursorPrevWord(breaksViWordCat)

proc cursorPrevBigWord(container: Container) {.jsfunc.} =
  container.cursorPrevWord(breaksBigWordCat)

proc cursorWordEnd(container: Container, breakFunc: BreakFunc) =
  if container.numLines == 0: return
  var r: Rune
  var b = container.currentCursorBytes()
  var x = container.cursorx
  var px = x
  # if not in space, move to the right by one
  if b < container.currentLine.len:
    let pb = b
    fastRuneAt(container.currentLine, b, r)
    if r.breakFunc() == BREAK_SPACE:
      b = pb
    else:
      px = x
      x += r.twidth(x)

  # skip space
  while b < container.currentLine.len:
    let pb = b
    fastRuneAt(container.currentLine, b, r)
    if r.breakFunc() != BREAK_SPACE:
      b = pb
      break
    x += r.twidth(x)

  # move to the last char in the current category
  let ob = b
  if b < container.currentLine.len:
    let currentCat = container.currentLine.runeAt(b).breakFunc()
    while b < container.currentLine.len:
      let pb = b
      fastRuneAt(container.currentLine, b, r)
      if r.breakFunc() != currentCat:
        b = pb
        break
      px = x
      x += r.twidth(x)
    x = px

  if b < container.currentLine.len or ob != b:
    container.setCursorX(x)
  else:
    if container.cursory < container.numLines - 1:
      container.cursorDown()
      container.cursorLineBegin()
    else:
      container.cursorLineEnd()

proc cursorWordEnd(container: Container) {.jsfunc.} =
  container.cursorWordEnd(breaksWordCat)

proc cursorViWordEnd(container: Container) {.jsfunc.} =
  container.cursorWordEnd(breaksViWordCat)

proc cursorBigWordEnd(container: Container) {.jsfunc.} =
  container.cursorWordEnd(breaksBigWordCat)

proc cursorWordBegin(container: Container, breakFunc: BreakFunc) =
  if container.numLines == 0: return
  var b = container.currentCursorBytes()
  var x = container.cursorx
  var px = x
  var ob = b
  if container.currentLine.len > 0:
    b = min(b, container.currentLine.len - 1)
    if b >= 0:
      let (r, o) = lastRune(container.currentLine, b)
      # if not in space, move to the left by one
      if r.breakFunc() != BREAK_SPACE:
        b -= o
        px = x
        x -= r.twidth(x)

    # skip space
    while b >= 0:
      let (r, o) = lastRune(container.currentLine, b)
      if r.breakFunc() != BREAK_SPACE:
        break
      b -= o
      x -= r.twidth(x)

    # move to the first char in the current category
    ob = b
    if b >= 0:
      let (r, _) = lastRune(container.currentLine, b)
      let currentCat = r.breakFunc()
      while b >= 0:
        let (r, o) = lastRune(container.currentLine, b)
        if r.breakFunc() != currentCat:
          break
        b -= o
        px = x
        x -= r.twidth(x)
    x = px
  else:
    b = -1
    ob = -1

  if b >= 0 or ob != b:
    container.setCursorX(x)
  else:
    if container.cursory > 0:
      container.cursorUp()
      container.cursorLineEnd()
    else:
      container.cursorLineBegin()

proc cursorWordBegin(container: Container) {.jsfunc.} =
  container.cursorWordBegin(breaksWordCat)

proc cursorViWordBegin(container: Container) {.jsfunc.} =
  container.cursorWordBegin(breaksViWordCat)

proc cursorBigWordBegin(container: Container) {.jsfunc.} =
  container.cursorWordBegin(breaksBigWordCat)

proc pageDown(container: Container, n = 1) {.jsfunc.} =
  container.setFromY(container.fromy + container.height * n)
  container.setCursorY(container.cursory + container.height * n)
  container.restoreCursorX()

proc pageUp(container: Container, n = 1) {.jsfunc.} =
  container.setFromY(container.fromy - container.height * n)
  container.setCursorY(container.cursory - container.height * n)
  container.restoreCursorX()

proc pageLeft(container: Container, n = 1) {.jsfunc.} =
  container.setFromX(container.fromx - container.width * n)

proc pageRight(container: Container, n = 1) {.jsfunc.} =
  container.setFromX(container.fromx + container.width * n)

# I am not cloning the vi behavior here because it is counter-intuitive
# and annoying.
# Users who disagree are free to implement it themselves. (It is about
# 5 lines of JS.)
proc halfPageUp(container: Container, n = 1) {.jsfunc.} =
  container.setFromY(container.fromy - (container.height div 2 + 1) * n)
  container.setCursorY(container.cursory - (container.height div 2 + 1) * n)
  container.restoreCursorX()

proc halfPageDown(container: Container, n = 1) {.jsfunc.} =
  container.setFromY(container.fromy + (container.height div 2 - 1) * n)
  container.setCursorY(container.cursory + (container.height div 2 - 1) * n)
  container.restoreCursorX()

proc halfPageLeft(container: Container, n = 1) {.jsfunc.} =
  container.setFromX(container.fromx - (container.width div 2 + 1) * n)

proc halfPageRight(container: Container, n = 1) {.jsfunc.} =
  container.setFromX(container.fromx + (container.width div 2 - 1) * n)

proc markPos0*(container: Container) =
  container.tmpJumpMark = (container.cursorx, container.cursory)

proc markPos*(container: Container) =
  let pos = container.tmpJumpMark
  if container.cursorx != pos.x or container.cursory != pos.y:
    container.jumpMark = pos

proc cursorFirstLine(container: Container) {.jsfunc.} =
  if container.select.open:
    container.select.cursorFirstLine()
  else:
    container.markPos0()
    container.setCursorY(0)
    container.markPos()

proc cursorLastLine*(container: Container) {.jsfunc.} =
  if container.select.open:
    container.select.cursorLastLine()
  else:
    container.markPos0()
    container.setCursorY(container.numLines - 1)
    container.markPos()

proc cursorTop(container: Container, i = 1) {.jsfunc.} =
  container.markPos0()
  let i = clamp(i - 1, 0, container.height - 1)
  container.setCursorY(container.fromy + i)
  container.markPos()

proc cursorMiddle(container: Container) {.jsfunc.} =
  container.markPos0()
  container.setCursorY(container.fromy + (container.height - 2) div 2)
  container.markPos()

proc cursorBottom(container: Container, i = 1) {.jsfunc.} =
  container.markPos0()
  let i = clamp(i, 0, container.height)
  container.setCursorY(container.fromy + container.height - i)
  container.markPos()

proc cursorLeftEdge(container: Container) {.jsfunc.} =
  container.setCursorX(container.fromx)

proc cursorMiddleColumn(container: Container) {.jsfunc.} =
  container.setCursorX(container.fromx + (container.width - 2) div 2)

proc cursorRightEdge(container: Container) {.jsfunc.} =
  container.setCursorX(container.fromx + container.width - 1)

proc scrollDown(container: Container, n = 1) {.jsfunc.} =
  if container.fromy + container.height < container.numLines:
    container.setFromY(container.fromy + n)
    if container.fromy > container.cursory:
      container.cursorDown(container.fromy - container.cursory)
  else:
    container.cursorDown(n)

proc scrollUp(container: Container, n = 1) {.jsfunc.} =
  if container.fromy > 0:
    container.setFromY(container.fromy - n)
    if container.fromy + container.height <= container.cursory:
      container.cursorUp(container.cursory - container.fromy -
        container.height + 1)
  else:
    container.cursorUp(n)

proc scrollRight(container: Container, n = 1) {.jsfunc.} =
  if container.fromx + container.width + n <= container.maxScreenWidth():
    container.setFromX(container.fromx + n)

proc scrollLeft(container: Container, n = 1) {.jsfunc.} =
  if container.fromx - n >= 0:
    container.setFromX(container.fromx - n)

proc alert(container: Container, msg: string) =
  container.triggerEvent(ContainerEvent(t: ALERT, msg: msg))

proc lineInfo(container: Container) {.jsfunc.} =
  container.alert("line " & $(container.cursory + 1) & "/" &
    $container.numLines & " (" & $container.atPercentOf() & "%) col " &
    $(container.cursorx + 1) & "/" & $container.currentLineWidth &
    " (byte " & $container.currentCursorBytes & ")")

proc updateCursor(container: Container) =
  if container.pos.setx > -1:
    container.setCursorX(container.pos.setx, container.pos.setxrefresh)
  if container.fromy > container.maxfromy:
    container.setFromY(container.maxfromy)
  if container.cursory >= container.numLines:
    container.setCursorY(container.lastVisibleLine)
    container.alert("Last line is #" & $container.numLines)

proc gotoLine*[T: string|int](container: Container, s: T) =
  when s is string:
    if s == "":
      redraw(container)
    elif s[0] == '^':
      container.cursorFirstLine()
    elif s[0] == '$':
      container.cursorLastLine()
    else:
      let i = parseUInt32(s)
      if i.isSome and i.get > 0:
        container.markPos0()
        container.setCursorY(int(i.get - 1))
        container.markPos()
      else:
        container.alert("First line is #1") # :)
  else:
    container.markPos0()
    container.setCursorY(s - 1)
    container.markPos()

proc pushCursorPos*(container: Container) =
  if container.select.open:
    container.select.pushCursorPos()
  else:
    container.bpos.add(container.pos)

proc popCursorPos*(container: Container, nojump = false) =
  if container.select.open:
    container.select.popCursorPos(nojump)
  else:
    container.pos = container.bpos.pop()
    if not nojump:
      container.updateCursor()
      container.sendCursorPosition()
      container.needslines = true

proc copyCursorPos*(container, c2: Container) =
  container.startpos = some(c2.pos)
  container.hasstart = true

proc cursorNextLink*(container: Container, n = 1) {.jsfunc.} =
  container.markPos0()
  container.iface
    .findNextLink(container.cursorx, container.cursory, n)
    .then(proc(res: tuple[x, y: int]) =
      if res.x > -1 and res.y != -1:
        container.setCursorXYCenter(res.x, res.y)
        container.markPos()
    )

proc cursorPrevLink*(container: Container, n = 1) {.jsfunc.} =
  container.markPos0()
  container.iface
    .findPrevLink(container.cursorx, container.cursory, n)
    .then(proc(res: tuple[x, y: int]) =
      if res.x > -1 and res.y != -1:
        container.setCursorXYCenter(res.x, res.y)
        container.markPos()
    )

proc cursorNextParagraph*(container: Container, n = 1) {.jsfunc.} =
  container.markPos0()
  container.iface
    .findNextParagraph(container.cursory, n)
    .then(proc(res: int) =
      container.setCursorY(res)
      container.markPos()
    )

proc cursorPrevParagraph*(container: Container, n = 1) {.jsfunc.} =
  container.markPos0()
  container.iface
    .findPrevParagraph(container.cursory, n)
    .then(proc(res: int) =
      container.setCursorY(res)
      container.markPos()
    )

proc setMark*(container: Container, id: string, x = none(int),
    y = none(int)): bool {.jsfunc.} =
  let x = x.get(container.cursorx)
  let y = y.get(container.cursory)
  container.marks.withValue(id, p):
    p[] = (x, y)
    container.triggerEvent(UPDATE)
    return false
  do:
    container.marks[id] = (x, y)
    container.triggerEvent(UPDATE)
    return true

proc clearMark*(container: Container, id: string): bool {.jsfunc.} =
  result = id in container.marks
  container.marks.del(id)
  container.triggerEvent(UPDATE)

proc getMarkPos(container: Container, id: string): Opt[PagePos] {.jsfunc.} =
  if id == "`" or id == "'":
    return ok(container.jumpMark)
  container.marks.withValue(id, p):
    return ok(p[])
  return err()

proc gotoMark*(container: Container, id: string): bool {.jsfunc.} =
  container.markPos0()
  let mark = container.getMarkPos(id)
  if mark.isSome:
    let mark = mark.get
    container.setCursorXYCenter(mark.x, mark.y)
    container.markPos()
    return true
  return false

proc gotoMarkY*(container: Container, id: string): bool {.jsfunc.} =
  container.markPos0()
  let mark = container.getMarkPos(id)
  if mark.isSome:
    let mark = mark.get
    container.setCursorXYCenter(0, mark.y)
    container.markPos()
    return true
  return false

proc findNextMark*(container: Container, x = none(int), y = none(int)):
    Option[string] {.jsfunc.} =
  #TODO optimize (maybe store marks in an OrderedTable and sort on insert?)
  let x = x.get(container.cursorx)
  let y = y.get(container.cursory)
  var best: PagePos = (high(int), high(int))
  var bestid = none(string)
  for id, mark in container.marks:
    if mark.y < y or mark.y == y and mark.x <= x:
      continue
    if mark.y < best.y or mark.y == best.y and mark.x < best.x:
      best = mark
      bestid = some(id)
  return bestid

proc findPrevMark*(container: Container, x = none(int), y = none(int)):
    Option[string] {.jsfunc.} =
  #TODO optimize (maybe store marks in an OrderedTable and sort on insert?)
  let x = x.get(container.cursorx)
  let y = y.get(container.cursory)
  var best: PagePos = (-1, -1)
  var bestid = none(string)
  for id, mark in container.marks:
    if mark.y > y or mark.y == y and mark.x >= x:
      continue
    if mark.y > best.y or mark.y == best.y and mark.x > best.x:
      best = mark
      bestid = some(id)
  return bestid

proc cursorNthLink*(container: Container, n = 1) {.jsfunc.} =
  container.iface
    .findNthLink(n)
    .then(proc(res: tuple[x, y: int]) =
      if res.x > -1 and res.y != -1:
        container.setCursorXYCenter(res.x, res.y))

proc cursorRevNthLink*(container: Container, n = 1) {.jsfunc.} =
  container.iface
    .findRevNthLink(n)
    .then(proc(res: tuple[x, y: int]) =
      if res.x > -1 and res.y != -1:
        container.setCursorXYCenter(res.x, res.y))

proc clearSearchHighlights*(container: Container) =
  for i in countdown(container.highlights.high, 0):
    if container.highlights[i].t == HL_SEARCH:
      container.highlights.del(i)

proc onMatch(container: Container, res: BufferMatch, refresh: bool) =
  if res.success:
    container.setCursorXYCenter(res.x, res.y, refresh)
    if container.hlon:
      container.clearSearchHighlights()
      let ex = res.x + res.str.twidth(res.x) - 1
      let hl = Highlight(
        t: HL_SEARCH,
        x1: res.x,
        y1: res.y,
        x2: ex,
        y2: res.y
      )
      container.highlights.add(hl)
      container.triggerEvent(UPDATE)
      container.hlon = false
  elif container.hlon:
    container.clearSearchHighlights()
    container.triggerEvent(UPDATE)
    container.needslines = true
    container.hlon = false

proc cursorNextMatch*(container: Container, regex: Regex, wrap, refresh: bool,
    n: int): EmptyPromise {.discardable.} =
  if container.select.open:
    #TODO
    for _ in 0 ..< n:
      container.select.cursorNextMatch(regex, wrap)
    return newResolvedPromise()
  else:
    return container.iface
      .findNextMatch(regex, container.cursorx, container.cursory, wrap, n)
      .then(proc(res: BufferMatch) =
        container.onMatch(res, refresh))

proc cursorPrevMatch*(container: Container, regex: Regex, wrap, refresh: bool,
    n: int): EmptyPromise {.discardable.} =
  if container.select.open:
    #TODO
    for _ in 0 ..< n:
      container.select.cursorPrevMatch(regex, wrap)
    return newResolvedPromise()
  else:
    container.markPos0()
    return container.iface
      .findPrevMatch(regex, container.cursorx, container.cursory, wrap, n)
      .then(proc(res: BufferMatch) =
        container.onMatch(res, refresh)
        container.markPos()
      )

type
  SelectionOptions = object of JSDict
    selectionType: SelectionType

proc cursorToggleSelection(container: Container, n = 1,
    opts = SelectionOptions()): Highlight {.jsfunc.} =
  if container.currentSelection != nil:
    let i = container.highlights.find(container.currentSelection)
    if i != -1:
      container.highlights.delete(i)
    container.currentSelection = nil
  else:
    let cx = container.cursorFirstX()
    let n = n - 1
    container.cursorRight(n)
    let hl = Highlight(
      t: HL_SELECT,
      selectionType: opts.selectionType,
      x1: cx,
      y1: container.cursory,
      x2: container.cursorx,
      y2: container.cursory
    )
    container.highlights.add(hl)
    container.currentSelection = hl
  container.triggerEvent(UPDATE)
  return container.currentSelection

#TODO I don't like this API
# maybe make selection a subclass of highlight?
proc getSelectionText(container: Container, hl: Highlight = nil):
    Promise[string] {.jsfunc.} =
  let hl = if hl == nil: container.currentSelection else: hl
  if hl.t != HL_SELECT:
    let p = newPromise[string]()
    p.resolve("")
    return p
  let startx = hl.startx
  let starty = hl.starty
  let endx = hl.endx
  let endy = hl.endy
  let nw = starty .. endy
  return container.iface.getLines(nw).then(proc(res: GetLinesResult): string =
    var s = ""
    case hl.selectionType
    of SEL_NORMAL:
      if starty == endy:
        let si = res.lines[0].str.findColBytes(startx)
        let ei = res.lines[0].str.findColBytes(endx + 1, startx, si) - 1
        s = res.lines[0].str.substr(si, ei)
      else:
        let si = res.lines[0].str.findColBytes(startx)
        s &= res.lines[0].str.substr(si) & '\n'
        for i in 1 .. res.lines.high - 1:
          s &= res.lines[i].str & '\n'
        let ei = res.lines[^1].str.findColBytes(endx + 1) - 1
        s &= res.lines[^1].str.substr(0, ei)
    of SEL_BLOCK:
      for i, line in res.lines:
        let si = line.str.findColBytes(startx)
        let ei = line.str.findColBytes(endx + 1, startx, si) - 1
        if i > 0:
          s &= '\n'
        s &= line.str.substr(si, ei)
    of SEL_LINE:
      for i, line in res.lines:
        if i > 0:
          s &= '\n'
        s &= line.str
    return s
  )

proc setLoadInfo(container: Container, msg: string) =
  container.loadinfo = msg
  container.triggerEvent(STATUS)

#TODO TODO TODO this should be called with a timeout.
proc onload*(container: Container, res: LoadResult) =
  if container.canceled:
    container.setLoadInfo("")
    #TODO we wouldn't need the then part if we had incremental rendering of
    # HTML.
    container.iface.cancel().then(proc(lines: int) =
      if lines != container.numLines:
        container.setNumLines(lines)
        container.triggerEvent(STATUS)
      container.needslines = true
    )
  else:
    if res.bytes == -1 or res.atend:
      container.setLoadInfo("")
    elif not res.atend:
      container.setLoadInfo(convertSize(res.bytes) & " loaded")
    if res.lines != container.numLines or res.atend:
      container.setNumLines(res.lines, res.atend)
      if res.atend:
        container.triggerEvent(STATUS)
      container.needslines = true
    if not res.atend:
      discard container.iface.load().then(proc(res: LoadResult) =
        container.onload(res)
      )
    else:
      container.triggerEvent(LOADED)
      container.iface.getTitle().then(proc(title: string) =
        if title != "":
          container.title = title
          container.triggerEvent(TITLE)
      )
      if not container.hasstart and container.location.anchor != "":
        container.iface.gotoAnchor().then(proc(res: Opt[tuple[x, y: int]]) =
          if res.isSome:
            let res = res.get
            container.setCursorXYCenter(res.x, res.y)
        )

proc load(container: Container) =
  container.setLoadInfo("Connecting to " & container.location.host & "...")
  container.iface.connect().then(proc(res: ConnectResult) =
    let info = container.loadinfo
    if not res.invalid:
      container.code = res.code
      if res.code == 0:
        container.triggerEvent(SUCCESS)
        # accept cookies
        let cookiejar = container.config.loaderConfig.cookiejar
        if res.cookies.len > 0 and cookiejar != nil:
          cookiejar.add(res.cookies)
        # set referrer policy, if any
        if res.referrerPolicy.isSome and container.config.referer_from:
          container.config.referrerPolicy = res.referrerPolicy.get
        container.setLoadInfo("Connected to " & $container.location &
          ". Downloading...")
        if res.needsAuth:
          container.triggerEvent(NEEDS_AUTH)
        if res.redirect != nil:
          container.triggerEvent(ContainerEvent(t: REDIRECT, request: res.redirect))
        container.charset = res.charset
        if container.contentType.isNone:
          if res.contentType == "application/octet-stream":
            let contentType = guessContentType(container.location.pathname,
              "application/octet-stream", container.config.mimeTypes)
            if contentType != "application/octet-stream":
              container.contentType = some(contentType)
            else:
              container.contentType = some(res.contentType)
          else:
            container.contentType = some(res.contentType)
        container.ishtml = container.contentType.get == "text/html"
        container.triggerEvent(CHECK_MAILCAP)
      else:
        if res.errorMessage != "":
          container.errorMessage = res.errorMessage
        else:
          container.errorMessage = getLoaderErrorMessage(res.code)
        container.setLoadInfo("")
        container.triggerEvent(FAIL)
    else:
      container.setLoadInfo(info)
  )

proc startload*(container: Container) =
  container.iface.load()
    .then(proc(res: tuple[atend: bool, lines, bytes: int]) =
      container.onload(res))

proc connect2*(container: Container): EmptyPromise =
  return container.iface.connect2(container.ishtml)

proc redirectToFd*(container: Container, fdin: FileHandle, wait, cache: bool):
    EmptyPromise =
  return container.iface.redirectToFd(fdin, wait, cache)

proc readFromFd*(container: Container, fdout: FileHandle, id: string,
    ishtml: bool): EmptyPromise =
  container.ishtml = ishtml
  let url = newURL("stream:" & id).get
  container.loaderPid.passFd(url.host, fdout)
  return container.iface.readFromFd(url, ishtml)

proc quit*(container: Container) =
  container.triggerEvent(QUIT)

proc cancel*(container: Container) {.jsfunc.} =
  if container.select.open:
    container.select.cancel()
  else:
    container.canceled = true
    container.alert("Canceled loading")

proc findAnchor*(container: Container, anchor: string) =
  container.iface.findAnchor(anchor).then(proc(found: bool) =
    if found:
      container.triggerEvent(ContainerEvent(t: ANCHOR, anchor: anchor))
    else:
      container.triggerEvent(NO_ANCHOR))

proc readCanceled*(container: Container) =
  container.iface.readCanceled().then(proc(repaint: bool) =
    if repaint:
      container.needslines = true)

proc readSuccess*(container: Container, s: string) =
  container.iface.readSuccess(s).then(proc(res: ReadSuccessResult) =
    if res.repaint:
      container.needslines = true
    if res.open.isSome:
      container.triggerEvent(ContainerEvent(t: OPEN, request: res.open.get)))

proc reshape(container: Container): EmptyPromise {.jsfunc.} =
  return container.iface.render().then(proc(lines: int): auto =
    container.setNumLines(lines)
    container.triggerEvent(STATUS)
    return container.requestLines()
  )

proc onclick(container: Container, res: ClickResult)

proc displaySelect(container: Container, selectResult: SelectResult) =
  let submitSelect = proc(selected: seq[int]) =
    container.iface.select(selected).then(proc(res: ClickResult) =
      container.onclick(res))
  container.select.initSelect(selectResult, container.acursorx,
    container.acursory, container.height, submitSelect)
  container.triggerEvent(UPDATE)

proc onclick(container: Container, res: ClickResult) =
  if res.repaint:
    container.needslines = true
  if res.open.isSome:
    container.triggerEvent(ContainerEvent(t: OPEN, request: res.open.get))
  if res.select.isSome:
    container.displaySelect(res.select.get)
  if res.readline.isSome:
    let rl = res.readline.get
    let event = if rl.area:
      ContainerEvent(
        t: READ_AREA,
        tvalue: rl.value
      )
    else:
      ContainerEvent(
        t: READ_LINE,
        prompt: rl.prompt,
        value: rl.value,
        password: rl.hide
      )
    container.triggerEvent(event)

proc click(container: Container) {.jsfunc.} =
  if container.select.open:
    container.select.click()
  else:
    container.iface.click(container.cursorx, container.cursory)
      .then(proc(res: ClickResult) = container.onclick(res))

proc windowChange*(container: Container, attrs: WindowAttributes) =
  if attrs.width != container.width or attrs.height - 1 != container.height:
    container.width = attrs.width
    container.height = attrs.height - 1
    container.iface.windowChange(attrs).then(proc(): auto =
      container.needslines = true
      return container.iface.render()
    ).then(proc(lines: int) =
      if lines != container.numLines:
        container.setNumLines(lines, true)
      container.needslines = true)

proc peek(container: Container) {.jsfunc.} =
  container.alert($container.location)

proc clearHover*(container: Container) =
  container.lastpeek = low(HoverType)

proc peekCursor(container: Container) {.jsfunc.} =
  var p = container.lastpeek
  while true:
    if container.hovertext[p] != "":
      container.alert($p & ": " & container.hovertext[p])
      break
    if p < high(HoverType):
      inc p
    else:
      p = low(HoverType)
    if p == container.lastpeek: break
  if container.lastpeek < high(HoverType):
    inc container.lastpeek
  else:
    container.lastpeek = low(HoverType)

func hoverLink(container: Container): string {.jsfget.} =
  return container.hovertext[HOVER_LINK]

func hoverTitle(container: Container): string {.jsfget.} =
  return container.hovertext[HOVER_TITLE]

proc handleCommand(container: Container) =
  var packetid, len: int
  container.iface.stream.sread(len)
  container.iface.stream.sread(packetid)
  container.iface.resolve(packetid, len - slen(packetid))

proc setStream*(container: Container, stream: Stream) =
  if not container.cloned:
    container.iface = newBufferInterface(stream)
    container.load()
  else:
    container.iface = cloneInterface(stream)
    # Maybe we have to resume loading. Let's try.
    discard container.iface.load().then(proc(res: LoadResult) =
      container.onload(res))

proc onreadline(container: Container, w: Slice[int],
    handle: (proc(line: SimpleFlexibleLine)), res: GetLinesResult) =
  for line in res.lines:
    handle(line)
  if res.numLines > w.b + 1:
    var w = w
    w.a += 24
    w.b += 24
    container.iface.getLines(w).then(proc(res: GetLinesResult) =
      container.onreadline(w, handle, res))
  else:
    container.setNumLines(res.numLines, true)

# Synchronously read all lines in the buffer.
proc readLines*(container: Container, handle: proc(line: SimpleFlexibleLine)) =
  if container.code == 0:
    # load succeded
    let w = 0 .. 23
    container.iface.getLines(w).then(proc(res: GetLinesResult) =
      container.onreadline(w, handle, res))
    while container.iface.hasPromises:
      # fulfill all promises
      container.handleCommand()

proc drawLines*(container: Container, display: var FixedGrid,
    hlcolor: CellColor) =
  let bgcolor = container.bgcolor
  template set_fmt(cell, cf: typed) =
    if cf.pos != -1:
      cell.format = cf.format
    if bgcolor != defaultColor and cell.format.bgcolor == defaultColor:
      cell.format.bgcolor = bgcolor
  var r: Rune
  var by = 0
  let endy = min(container.fromy + display.height, container.numLines)
  for line in container.ilines(container.fromy ..< endy):
    var w = 0 # width of the row so far
    var i = 0 # byte in line.str
    # Skip cells till fromx.
    while w < container.fromx and i < line.str.len:
      fastRuneAt(line.str, i, r)
      w += r.twidth(w)
    let dls = by * display.width # starting position of row in display
    # Fill in the gap in case we skipped more cells than fromx mandates (i.e.
    # we encountered a double-width character.)
    var cf = line.findFormat(w)
    var nf = line.findNextFormat(w)
    var k = 0
    while k < w - container.fromx:
      display[dls + k].str &= ' '
      set_fmt display[dls + k], cf
      inc k
    let startw = w # save this for later
    # Now fill in the visible part of the row.
    while i < line.str.len:
      let pw = w
      fastRuneAt(line.str, i, r)
      let rw = r.twidth(w)
      w += rw
      if w > container.fromx + display.width:
        break # die on exceeding the width limit
      if nf.pos != -1 and nf.pos <= pw:
        cf = nf
        nf = line.findNextFormat(pw)
      if r == Rune('\t'):
        # Needs to be replaced with spaces, otherwise bgcolor isn't displayed.
        let tk = k + rw
        while k < tk:
          display[dls + k].str &= ' '
          set_fmt display[dls + k], cf
          inc k
      else:
        display[dls + k].str &= r
        set_fmt display[dls + k], cf
        k += rw
    if bgcolor != defaultColor:
      # Fill the screen if bgcolor is not default.
      while k < display.width:
        display[dls + k].str &= ' '
        display[dls + k].format.bgcolor = bgcolor
        inc k
    # Finally, override cell formatting for highlighted cells.
    let hls = container.findHighlights(container.fromy + by)
    let aw = container.width - (startw - container.fromx) # actual width
    for hl in hls:
      let area = container.colorArea(hl, container.fromy + by,
        startw .. startw + aw)
      for i in area:
        if i - startw >= container.width:
          break
        var hlformat = display[dls + i - startw].format
        hlformat.bgcolor = hlcolor
        display[dls + i - startw].format = hlformat
    inc by

proc highlightMarks*(container: Container, display: var FixedGrid,
    hlcolor: CellColor) =
  for mark in container.marks.values:
    if mark.x in container.fromx ..< container.fromx + display.width and
        mark.y in container.fromy ..< container.fromy + display.height:
      let x = mark.x - container.fromx
      let y = mark.y - container.fromy
      var hlformat = display[y * display.width + x].format
      hlformat.bgcolor = hlcolor
      display[y * display.width + x].format = hlformat

proc handleEvent*(container: Container) =
  container.handleCommand()
  if container.needslines:
    container.requestLines()
    container.needslines = false

proc addContainerModule*(ctx: JSContext) =
  ctx.registerType(Highlight)
  ctx.registerType(Container, name = "Buffer")