about summary refs log tree commit diff stats
path: root/src/display/pager.nim
blob: d4a2dc99c976d23bd8d51524637c0ac69f2ab0fd (plain) (blame)
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
import options
import os
import selectors
import streams
import tables
import terminal
import unicode

import buffer/buffer
import buffer/cell
import buffer/container
import config/config
import io/lineedit
import io/request
import io/term
import js/javascript
import js/regex
import types/url
import utils/twtstr

type
  LineMode* = enum
    NO_LINEMODE, LOCATION, USERNAME, PASSWORD, COMMAND, BUFFER, SEARCH_F,
    SEARCH_B, ISEARCH_F, ISEARCH_B

  Pager* = ref object
    attrs: TermAttributes
    commandMode*: bool
    container*: Container
    lineedit*: Option[LineEdit]
    linemode*: LineMode
    username: string
    scommand*: string
    config: Config
    regex: Option[Regex]
    iregex: Option[Regex]
    reverseSearch: bool
    status*: seq[string]
    statusmsg*: FixedGrid
    tty: File
    selector*: Selector[Container]
    fdmap*: Table[FileHandle, Container]
    icpos: CursorPosition
    display: FixedGrid
    bheight*: int
    bwidth*: int
    redraw*: bool

iterator containers*(pager: Pager): Container =
  if pager.container != nil:
    var c = pager.container
    while c.parent != nil: c = c.parent
    var stack: seq[Container]
    stack.add(c)
    while stack.len > 0:
      yield stack.pop()
      for i in countdown(c.children.high, 0):
        stack.add(c.children[i])

proc setContainer*(pager: Pager, c: Container) =
  pager.container = c
  pager.redraw = true

proc cursorDown(pager: Pager) {.jsfunc.} = pager.container.cursorDown()
proc cursorUp(pager: Pager) {.jsfunc.} = pager.container.cursorUp()
proc cursorLeft(pager: Pager) {.jsfunc.} = pager.container.cursorLeft()
proc cursorRight(pager: Pager) {.jsfunc.} = pager.container.cursorRight()
proc cursorLineBegin(pager: Pager) {.jsfunc.} = pager.container.cursorLineBegin()
proc cursorLineEnd(pager: Pager) {.jsfunc.} = pager.container.cursorLineEnd()
proc cursorNextWord(pager: Pager) {.jsfunc.} = pager.container.cursorNextWord()
proc cursorPrevWord(pager: Pager) {.jsfunc.} = pager.container.cursorPrevWord()
proc cursorNextLink(pager: Pager) {.jsfunc.} = pager.container.cursorNextLink()
proc cursorPrevLink(pager: Pager) {.jsfunc.} = pager.container.cursorPrevLink()
proc pageUp(pager: Pager) {.jsfunc.} = pager.container.pageUp()
proc pageDown(pager: Pager) {.jsfunc.} = pager.container.pageDown()
proc pageRight(pager: Pager) {.jsfunc.} = pager.container.pageRight()
proc pageLeft(pager: Pager) {.jsfunc.} = pager.container.pageLeft()
proc halfPageDown(pager: Pager) {.jsfunc.} = pager.container.halfPageDown()
proc halfPageUp(pager: Pager) {.jsfunc.} = pager.container.halfPageUp()
proc cursorFirstLine(pager: Pager) {.jsfunc.} = pager.container.cursorFirstLine()
proc cursorLastLine(pager: Pager) {.jsfunc.} = pager.container.cursorLastLine()
proc cursorTop(pager: Pager) {.jsfunc.} = pager.container.cursorTop()
proc cursorMiddle(pager: Pager) {.jsfunc.} = pager.container.cursorMiddle()
proc cursorBottom(pager: Pager) {.jsfunc.} = pager.container.cursorBottom()
proc cursorLeftEdge(pager: Pager) {.jsfunc.} = pager.container.cursorLeftEdge()
proc cursorVertMiddle(pager: Pager) {.jsfunc.} = pager.container.cursorVertMiddle()
proc cursorRightEdge(pager: Pager) {.jsfunc.} = pager.container.cursorRightEdge()
proc centerLine(pager: Pager) {.jsfunc.} = pager.container.centerLine()
proc scrollDown(pager: Pager) {.jsfunc.} = pager.container.scrollDown()
proc scrollUp(pager: Pager) {.jsfunc.} = pager.container.scrollUp()
proc scrollLeft(pager: Pager) {.jsfunc.} = pager.container.scrollLeft()
proc scrollRight(pager: Pager) {.jsfunc.} = pager.container.scrollRight()
proc reshape(pager: Pager) {.jsfunc.} = pager.container.render()

proc searchNext(pager: Pager) {.jsfunc.} =
  if pager.regex.issome:
    if not pager.reverseSearch:
      pager.container.cursorNextMatch(pager.regex.get, true)
    else:
      pager.container.cursorPrevMatch(pager.regex.get, true)

proc searchPrev(pager: Pager) {.jsfunc.} =
  if pager.regex.issome:
    if not pager.reverseSearch:
      pager.container.cursorPrevMatch(pager.regex.get, true)
    else:
      pager.container.cursorNextMatch(pager.regex.get, true)

proc statusMode(pager: Pager) =
  print(HVP(pager.attrs.height + 1, 1))
  print(SGR())
  print(EL())

proc setLineEdit*(pager: Pager, edit: LineEdit, mode: LineMode) =
  pager.statusMode()
  edit.writeStart()
  stdout.flushFile()
  pager.lineedit = some(edit)
  pager.linemode = mode

proc clearLineEdit(pager: Pager) =
  pager.lineedit = none(LineEdit)

proc searchForward(pager: Pager) {.jsfunc.} =
  pager.setLineEdit(readLine("/", pager.attrs.width, config = pager.config, tty = pager.tty), SEARCH_F)

proc searchBackward(pager: Pager) {.jsfunc.} =
  pager.setLineEdit(readLine("?", pager.attrs.width, config = pager.config, tty = pager.tty), SEARCH_B)

proc isearchForward(pager: Pager) {.jsfunc.} =
  pager.container.pushCursorPos()
  pager.setLineEdit(readLine("/", pager.attrs.width, config = pager.config, tty = pager.tty), ISEARCH_F)

proc isearchBackward(pager: Pager) {.jsfunc.} =
  pager.container.pushCursorPos()
  pager.setLineEdit(readLine("?", pager.attrs.width, config = pager.config, tty = pager.tty), ISEARCH_B)

proc newPager*(config: Config, attrs: TermAttributes, tty: File): Pager =
  new(result)
  result.config = config
  result.attrs = attrs
  result.tty = tty
  result.selector = newSelector[Container]()
  result.bwidth = attrs.width - 1 # writing to the last column is a bad idea it seems
  result.bheight = attrs.height - 1
  result.display = newFixedGrid(result.bwidth, result.bheight)

proc clearDisplay(pager: Pager) =
  pager.display = newFixedGrid(pager.bwidth, pager.bheight)

proc refreshDisplay*(pager: Pager, container = pager.container) =
  var r: Rune
  var by = 0
  pager.clearDisplay()
  var hlformat = newFormat()
  hlformat.bgcolor = pager.config.hlcolor
  for line in container.ilines(container.fromy ..< min(container.fromy + pager.bheight, container.numLines)):
    var w = 0 # width of the row so far
    var i = 0 # byte in line.str
    # Skip cells till buffer.fromx.
    while w < container.fromx and i < line.str.len:
      fastRuneAt(line.str, i, r)
      w += r.width()
    let dls = by * container.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 k = 0
    if w > container.fromx:
      while k < w - container.fromx:
        pager.display[dls + k].str &= ' '
        inc k
    var cf = line.findFormat(w)
    var nf = line.findNextFormat(w)
    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)
      w += r.width()
      if w > container.fromx + pager.bwidth:
        break # die on exceeding the width limit
      if nf.pos != -1 and nf.pos <= pw:
        cf = nf
        nf = line.findNextFormat(pw)
      pager.display[dls + k].str &= r
      if cf.pos != -1:
        pager.display[dls + k].format = cf.format
      let tk = k + r.width()
      while k < tk and k < pager.bwidth - 1:
        inc k
    # Finally, override cell formatting for highlighted cells.
    let hls = container.findHighlights(by)
    let aw = container.width - (startw - container.fromx) # actual width
    for hl in hls:
      let area = hl.colorArea(by, startw .. startw + aw)
      for i in area:
        pager.display[dls + i - startw].format = hlformat
    inc by

func generateStatusMessage*(pager: Pager): string =
  var format = newFormat()
  var w = 0
  for cell in pager.statusmsg:
    result &= format.processFormat(cell.format)
    result &= cell.str
    w += cell.width()
  if w < pager.bwidth:
    result &= EL()

proc clearStatusMessage(pager: Pager) =
  pager.statusmsg = newFixedGrid(pager.bwidth)

proc writeStatusMessage(pager: Pager, str: string, format: Format = Format()) =
  pager.clearStatusMessage()
  var i = 0
  for r in str.runes:
    i += r.width()
    if i >= pager.statusmsg.len:
      pager.statusmsg[^1].str = "$"
      break
    pager.statusmsg[i].str &= r
    pager.statusmsg[i].format = format

proc refreshStatusMsg*(pager: Pager) =
  let container = pager.container
  if container != nil:
    var msg = $(container.cursory + 1) & "/" & $container.numLines & " (" &
              $container.atPercentOf() & "%) " & "<" & container.getTitle() & ">"
    if container.hovertext.len > 0:
      msg &= " " & container.hovertext
    var format: Format
    format.reverse = true
    pager.writeStatusMessage(msg, format)

func generateStatusOutput(pager: Pager): string =
  if pager.status.len > 0:
    result = pager.status[0] & EL()
    pager.status = pager.status[1..^1]
  else:
    return pager.generateStatusMessage()

func generateFullOutput(pager: Pager): string =
  var x = 0
  var w = 0
  var format = newFormat()
  result &= HVP(1, 1)
  for cell in pager.display:
    if x >= pager.bwidth:
      result &= EL()
      result &= "\r\n"
      x = 0
      w = 0
    result &= format.processFormat(cell.format)
    result &= cell.str
    w += cell.width()
    inc x
  result &= EL()
  result &= "\r\n"

proc displayCursor*(pager: Pager) =
  if pager.container == nil: return
  print(HVP(pager.container.acursory + 1, pager.container.acursorx + 1))
  stdout.flushFile()

proc displayStatus*(pager: Pager) =
  if pager.lineedit.isNone:
    pager.statusMode()
    print(pager.generateStatusOutput())
    stdout.flushFile()

proc displayPage*(pager: Pager) =
  stdout.hideCursor()
  print(SGR())
  print(pager.generateFullOutput())
  pager.displayStatus()
  pager.displayCursor()
  stdout.showCursor()
  if pager.lineedit.isSome:
    pager.statusMode()
    pager.lineedit.get.writePrompt()
    pager.lineedit.get.fullRedraw()
  stdout.flushFile()

proc redraw(pager: Pager) {.jsfunc.} =
  pager.redraw = true

proc draw*(pager: Pager) =
  pager.refreshDisplay()
  pager.refreshStatusMsg()
  pager.displayPage()

proc registerContainer*(pager: Pager, container: Container) =
  pager.fdmap[container.ifd] = container
  pager.selector.registerHandle(int(container.ifd), {Read}, pager.container)

proc addContainer*(pager: Pager, container: Container) =
  container.parent = pager.container
  if pager.container != nil:
    pager.container.children.add(container)
  pager.setContainer(container)
  assert int(container.ifd) != 0
  pager.registerContainer(container)

proc dupeContainer(pager: Pager, container: Container, location: Option[URL]): Container =
  return container.dupeBuffer(pager.config, location)

proc dupeBuffer*(pager: Pager, location = none(URL)) {.jsfunc.} =
  pager.addContainer(pager.dupeContainer(pager.container, location))

# The prevBuffer and nextBuffer procedures emulate w3m's PREV and NEXT
# commands by traversing the container tree in a depth-first order.
proc prevBuffer*(pager: Pager): bool {.jsfunc.} =
  if pager.container == nil:
    return false
  if pager.container.parent == nil:
    return false
  let n = pager.container.parent.children.find(pager.container)
  assert n != -1, "Container not a child of its parent"
  if n > 0:
    pager.setContainer(pager.container.parent.children[n - 1])
  else:
    pager.setContainer(pager.container.parent)
  return true

proc nextBuffer*(pager: Pager): bool {.jsfunc.} =
  if pager.container == nil:
    return false
  if pager.container.children.len > 0:
    pager.setContainer(pager.container.children[0])
    return true
  if pager.container.parent == nil:
    return false
  let n = pager.container.parent.children.find(pager.container)
  assert n != -1, "Container not a child of its parent"
  if n < pager.container.parent.children.high:
    pager.setContainer(pager.container.parent.children[n + 1])
    return true
  return false

proc setStatusMessage*(pager: Pager, msg: string) =
  pager.status.add(msg)
  pager.refreshStatusMsg()

proc lineInfo(pager: Pager) {.jsfunc.} =
  pager.setStatusMessage(pager.container.lineInfo())

proc deleteContainer(pager: Pager, container: Container) =
  if container.parent == nil and container.children.len == 0 and container != pager.container:
    return
  if container.parent != nil:
    let parent = container.parent
    let n = parent.children.find(container)
    assert n != -1, "Container not a child of its parent"
    for i in countdown(container.children.high, 0):
      let child = container.children[i]
      child.parent = container.parent
      parent.children.insert(child, n + 1)
    parent.children.delete(n)
    if container == pager.container:
      pager.setContainer(parent)
  elif container.children.len > 0:
    let parent = container.children[0]
    parent.parent = nil
    for i in 1..container.children.high:
      container.children[i].parent = parent
      parent.children.add(container.children[i])
    if container == pager.container:
      pager.setContainer(parent)
  else:
    for child in container.children:
      child.parent = nil
    if container == pager.container:
      pager.setContainer(nil)
  container.parent = nil
  container.children.setLen(0)
  pager.fdmap.del(container.ifd)
  pager.selector.unregister(int(container.ifd))
  container.istream.close()
  container.ostream.close()

proc discardBuffer*(pager: Pager) {.jsfunc.} =
  if pager.container == nil or pager.container.parent == nil and
      pager.container.children.len == 0:
    pager.setStatusMessage("Cannot discard last buffer!")
  else:
    pager.deleteContainer(pager.container)

proc toggleSource*(pager: Pager) {.jsfunc.} =
  if pager.container.sourcepair != nil:
    pager.setContainer(pager.container.sourcepair)
  else:
    let contenttype = if pager.container.contenttype.get("") == "text/html":
      some("text/plain")
    else:
      some("text/html")
    let container = pager.container.dupeBuffer(pager.config, contenttype = contenttype)
    container.sourcepair = pager.container
    pager.container.sourcepair = container
    pager.container.children.add(container)

# Load request in a new buffer.
proc gotoURL*(pager: Pager, request: Request, prevurl = none(URL), ctype = none(string), replace: Container = nil) =
  if prevurl.isnone or not prevurl.get.equals(request.url, true) or
      request.url.hash == "" or request.httpmethod != HTTP_GET:
    # Basically, we want to reload the page *only* when
    # a) we force a reload (by setting prevurl to none)
    # b) or the new URL isn't just the old URL + an anchor
    # I think this makes navigation pretty natural, or at least very close to
    # what other browsers do. Still, it would be nice if we got some visual
    # feedback on what is actually going to happen when typing a URL; TODO.
    let source = BufferSource(
      t: LOAD_REQUEST,
      request: request,
      contenttype: ctype,
      location: request.url
    )
    let container = newBuffer(pager.config, source, pager.tty.getFileHandle())
    container.replace = replace
    pager.addContainer(container)
    container.load()
  else:
    pager.container.redirect = some(request.url)
    pager.container.gotoAnchor(request.url.anchor)

# When the user has passed a partial URL as an argument, they might've meant
# either:
# * file://$PWD/<file>
# * https://<url>
# So we attempt to load both, and see what works.
# (TODO: make this optional)
proc loadURL*(pager: Pager, url: string, ctype = none(string)) =
  let firstparse = parseURL(url)
  if firstparse.issome:
    let prev = if pager.container != nil:
      some(pager.container.source.location)
    else:
      none(URL)
    pager.gotoURL(newRequest(firstparse.get), prev, ctype)
    return
  var urls: seq[URL]
  let pageurl = parseURL("https://" & url)
  if pageurl.isSome: # attempt to load remote page
    urls.add(pageurl.get)
  let cdir = parseURL("file://" & getCurrentDir() & DirSep)
  let purl = percentEncode(url, LocalPathPercentEncodeSet)
  if purl != url:
    let newurl = parseURL(purl, cdir)
    if newurl.isSome:
      urls.add(newurl.get)
  let localurl = parseURL(url, cdir)
  if localurl.isSome: # attempt to load local file
    urls.add(localurl.get)
  if urls.len == 0:
    pager.setStatusMessage("Invalid URL " & url)
  else:
    let prevc = pager.container
    pager.gotoURL(newRequest(urls.pop()), ctype = ctype)
    if pager.container != prevc:
      pager.container.retry = urls

proc readPipe0*(pager: Pager, ctype: Option[string], fd: FileHandle, location: Option[URL]): Container =
  let source = BufferSource(
    t: LOAD_PIPE,
    fd: fd,
    contenttype: some(ctype.get("text/plain")),
    location: location.get(newURL("file://-"))
  )
  let container = newBuffer(pager.config, source, pager.tty.getFileHandle(), ispipe = true)
  container.load()
  return container

proc readPipe*(pager: Pager, ctype: Option[string], fd: FileHandle) =
  let container = pager.readPipe0(ctype, fd, none(URL))
  pager.addContainer(container)

proc command(pager: Pager) {.jsfunc.} =
  pager.setLineEdit(readLine("COMMAND: ", pager.attrs.width, config = pager.config, tty = pager.tty), COMMAND)

proc commandMode(pager: Pager) {.jsfunc.} =
  pager.commandMode = true
  pager.command()

proc updateReadLineISearch(pager: Pager, linemode: LineMode) =
  let lineedit = pager.lineedit.get
  case lineedit.state
  of CANCEL:
    pager.iregex = none(Regex)
    pager.container.popCursorPos()
    pager.container.clearSearchHighlights()
  of EDIT:
    let x = $lineedit.news
    if x != "": pager.iregex = compileSearchRegex(x)
    pager.container.clearSearchHighlights()
    pager.container.popCursorPos()
    if pager.iregex.isSome:
      if linemode == ISEARCH_F:
        pager.container.cursorNextMatch(pager.iregex.get, true)
      else:
        pager.container.cursorPrevMatch(pager.iregex.get, true)
      pager.container.hlon = true
    pager.container.pushCursorPos()
    pager.displayPage()
    pager.statusMode()
    pager.lineedit.get.fullRedraw()
  of FINISH:
    if pager.iregex.isSome:
      pager.regex = pager.iregex
    pager.reverseSearch = linemode == ISEARCH_B
    pager.container.clearSearchHighlights()
    pager.redraw = true

proc updateReadLine*(pager: Pager) =
  let lineedit = pager.lineedit.get
  template s: string = $lineedit.news
  if pager.linemode in {ISEARCH_F, ISEARCH_B}:
    pager.updateReadLineISearch(pager.linemode)
  else:
    case lineedit.state
    of EDIT: return
    of FINISH:
      case pager.linemode
      of LOCATION: pager.loadURL(s)
      of USERNAME:
        pager.username = s
        pager.setLineEdit(readLine("Password: ", pager.attrs.width, hide = true, config = pager.config, tty = pager.tty), PASSWORD)
      of PASSWORD:
        let url = newURL(pager.container.source.location)
        url.username = pager.username
        url.password = s
        pager.username = ""
        pager.gotoURL(newRequest(url), some(pager.container.source.location), replace = pager.container)
      of COMMAND:
        pager.scommand = s
        if pager.commandmode:
          pager.command()
      of BUFFER: pager.container.readSuccess(s)
      of SEARCH_F:
        let x = s
        if x != "": pager.regex = compileSearchRegex(x)
        pager.reverseSearch = false
        pager.searchNext()
      of SEARCH_B:
        let x = s
        if x != "": pager.regex = compileSearchRegex(x)
        pager.reverseSearch = true
        pager.searchPrev()
      else: discard
    of CANCEL:
      case pager.linemode
      of USERNAME: pager.discardBuffer()
      of PASSWORD:
        pager.username = ""
        pager.discardBuffer()
      of BUFFER: pager.container.readCanceled()
      of COMMAND: pager.commandmode = false
      else: discard
  if lineedit.state in {CANCEL, FINISH}:
    if pager.lineedit.get == lineedit:
      pager.clearLineEdit()

# Open a URL prompt and visit the specified URL.
proc changeLocation(pager: Pager) {.jsfunc.} =
  var url = pager.container.source.location.serialize()
  pager.setLineEdit(readLine("URL: ", pager.attrs.width, current = url, config = pager.config, tty = pager.tty), LOCATION)

# Reload the page in a new buffer, then kill the previous buffer.
proc reload(pager: Pager) {.jsfunc.} =
  pager.gotoURL(newRequest(pager.container.source.location), none(URL), pager.container.contenttype, pager.container)

proc click(pager: Pager) {.jsfunc.} =
  pager.container.click()

proc authorize*(pager: Pager) =
  pager.setLineEdit(readLine("Username: ", pager.attrs.width, config = pager.config, tty = pager.tty), USERNAME)

proc handleEvent*(pager: Pager, container: Container): bool =
  let event = container.handleEvent()
  case event.t
  of FAIL:
    pager.deleteContainer(container)
    if container.retry.len > 0:
      pager.gotoURL(newRequest(container.retry.pop()), ctype = container.contenttype)
    else:
      pager.setStatusMessage("Couldn't load " & $container.source.location & " (error code " & $container.code & ")")
      pager.displayStatus()
      pager.displayCursor()
    if pager.container == nil:
      return false
  of SUCCESS:
    container.render()
    if container.replace != nil:
      container.children.add(container.replace.children)
      for child in container.children:
        child.parent = container
      container.replace.children.setLen(0)
      if container.replace.parent != nil:
        container.parent = container.replace.parent
        let n = container.replace.parent.children.find(container.replace)
        assert n != -1, "Container not a child of its parent"
        container.parent.children[n] = container
      if pager.container == container.replace:
        pager.setContainer(container)
  of NEEDS_AUTH:
    if pager.container == container:
      pager.authorize()
  of REDIRECT:
    let redirect = container.redirect.get
    pager.setStatusMessage("Redirecting to " & $redirect)
    pager.displayStatus()
    pager.displayCursor()
    pager.gotoURL(newRequest(redirect), some(pager.container.source.location), replace = pager.container)
  of ANCHOR:
    pager.addContainer(pager.dupeContainer(container, container.redirect))
  of NO_ANCHOR:
    pager.setStatusMessage("Couldn't find anchor " & container.redirect.get.anchor)
    pager.displayStatus()
    pager.displayCursor()
  of UPDATE:
    if container == pager.container:
      pager.redraw = true
  of JUMP:
    if container == pager.container:
      pager.refreshStatusMsg()
      pager.displayStatus()
      pager.displayCursor()
  of STATUS:
    if container == pager.container:
      pager.refreshStatusMsg()
      pager.displayStatus()
      pager.displayCursor()
  of READ_LINE:
    if container == pager.container:
      pager.setLineEdit(readLine(event.prompt, pager.bwidth, current = event.value, hide = event.password, config = pager.config, tty = pager.tty), BUFFER)
  of OPEN:
    pager.gotoURL(event.request, some(container.source.location))
  of NO_EVENT: discard
  return true

proc addPagerModule*(ctx: JSContext) =
  ctx.registerType(Pager)