readline.pony

  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
use "collections"
use "files"
use "promises"
use strings = "strings"

class Readline is ANSINotify
  """
  Line editing, history, and tab completion.
  """
  let _notify: ReadlineNotify
  let _out: OutStream
  let _path: (FilePath | None)
  embed _history: Array[String]
  embed _queue: Array[String] = Array[String]
  let _maxlen: USize

  var _edit: String iso = recover String end
  var _cur_prompt: String = ""
  var _cur_line: USize = 0
  var _cur_pos: ISize = 0
  var _blocked: Bool = true

  new iso create(
    notify: ReadlineNotify iso,
    out: OutStream,
    path: (FilePath | None) = None,
    maxlen: USize = 0)
  =>
    """
    Create a readline handler to be passed to stdin. It begins blocked. Set an
    initial prompt on the ANSITerm to begin processing.
    """
    _notify = consume notify
    _out = out
    _path = path
    _history = Array[String](maxlen)
    _maxlen = maxlen

    _load_history()

  fun ref apply(term: ANSITerm ref, input: U8) =>
    """
    Receives input.
    """
    match \exhaustive\ input
    | 0x01 => home() // ctrl-a
    | 0x02 => left() // ctrl-b
    | 0x04 =>
      // ctrl-d
      if _edit.size() == 0 then
        _out.write("\n")
        term.dispose()
      else
        delete()
      end
    | 0x05 => end_key() // ctrl-e
    | 0x06 => right() // ctrl-f
    | 0x08 => _backspace() // ctrl-h
    | 0x09 => _tab()
    | 0x0A => _dispatch(term) // LF
    | 0x0B =>
      // ctrl-k, delete to the end of the line.
      _edit.truncate(_cur_pos.usize())
      _refresh_line()
    | 0x0C => _clear() // ctrl-l
    | 0x0D => _dispatch(term) // CR
    | 0x0E => down() // ctrl-n
    | 0x10 => up() // ctrl-p
    | 0x14 => _swap() // ctrl-t
    | 0x15 =>
      // ctrl-u, delete the whole line.
      _edit.clear()
      home()
    | 0x17 => _delete_prev_word() // ctrl-w
    | 0x7F => _backspace() // backspace
    | if input < 0x20 => None // unknown control character
    else
      // Insert.
      _edit.insert_byte(_cur_pos, input)
      _cur_pos = _cur_pos + 1
      _refresh_line()
    end

  fun ref prompt(term: ANSITerm ref, value: String) =>
    """
    Set a new prompt, unblock, and handle the pending queue.
    """
    _cur_prompt = value
    _blocked = false

    try
      let line = _queue.shift()?
      _add_history(line)
      _out.print(_cur_prompt + line)
      _handle_line(term, line)
    else
      _refresh_line()
    end

  fun ref closed() =>
    """
    No more input is available.
    """
    _save_history()

  fun ref up(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
    """
    Previous line.
    """
    try
      if _cur_line > 0 then
        _cur_line = _cur_line - 1
        _edit = _history(_cur_line)?.clone()
        end_key()
      end
    end

  fun ref down(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
    """
    Next line.
    """
    // With no history there is no next line, and _history.size() - 1 would
    // underflow. Do nothing, as up does when there is no previous line.
    if _history.size() == 0 then
      return
    end

    try
      if _cur_line < (_history.size() - 1) then
        _cur_line = _cur_line + 1
        _edit = _history(_cur_line)?.clone()
      else
        _cur_line = _history.size()
        _edit.clear()
      end

      end_key()
    end

  fun ref left(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
    """
    Move left.
    """
    if _cur_pos == 0 then
      return
    end

    try
      repeat
        _cur_pos = _cur_pos - 1
      until
        (_cur_pos == 0) or
        ((_edit.at_offset(_cur_pos)? and 0xC0) != 0x80)
      end

      _refresh_line()
    end

  fun ref right(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
    """
    Move right.
    """
    try
      if _cur_pos < _edit.size().isize() then
        _cur_pos = _cur_pos + 1
      end

      while
        (_cur_pos < _edit.size().isize()) and
        ((_edit.at_offset(_cur_pos)? and 0xC0) == 0x80)
      do
        _cur_pos = _cur_pos + 1
      end

      _refresh_line()
    end

  fun ref home(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
    """
    Beginning of the line.
    """
    _cur_pos = 0
    _refresh_line()

  fun ref end_key(
    ctrl: Bool = false,
    alt: Bool = false,
    shift: Bool = false)
  =>
    """
    End of the line.
    """
    _cur_pos = _edit.size().isize()
    _refresh_line()

  fun ref _backspace() =>
    """
    Backward delete.
    """
    if _cur_pos == 0 then
      return
    end

    try
      var c = U8(0)

      repeat
        _cur_pos = _cur_pos - 1
        c = _edit.at_offset(_cur_pos)?
        _edit.delete(_cur_pos, 1)
      until
        (_cur_pos == 0) or ((c and 0xC0) != 0x80)
      end

      _refresh_line()
    end

  fun ref delete(ctrl: Bool = false, alt: Bool = false, shift: Bool = false) =>
    """
    Forward delete.
    """
    try
      if _cur_pos < _edit.size().isize() then
        _edit.delete(_cur_pos, 1)
      end

      while
        (_cur_pos < _edit.size().isize()) and
        ((_edit.at_offset(_cur_pos)? and 0xC0) == 0x80)
      do
        _edit.delete(_cur_pos, 1)
      end

      _refresh_line()
    end

  fun ref _clear() =>
    """
    Clear the screen.
    """
    _out.write(ANSI.clear())
    _refresh_line()

  fun ref _swap() =>
    """
    Swap the previous character with the current one.
    """
    try
      if (_cur_pos > 0) and (_cur_pos < _edit.size().isize()) then
        _edit(_cur_pos.usize())? =
          _edit((_cur_pos - 1).usize())? =
            _edit(_cur_pos.usize())?
      end

      _refresh_line()
    end

  fun ref _delete_prev_word() =>
    """
    Delete the previous word.
    """
    try
      let old = _cur_pos

      while (_cur_pos > 0) and (_edit((_cur_pos - 1).usize())? == ' ') do
        _cur_pos = _cur_pos - 1
      end

      while (_cur_pos > 0) and (_edit((_cur_pos - 1).usize())? != ' ') do
        _cur_pos = _cur_pos - 1
      end

      _edit.delete(_cur_pos, (old - _cur_pos).usize())
      _refresh_line()
    end

  fun ref _tab() =>
    """
    Tab completion.

    TODO: Improve this.
    """
    let r = _notify.tab(_edit.clone())

    match r.size()
    | 0 => None
    | 1 =>
      try
        _edit = r(0)?.clone()
        end_key()
      end
    else
      _out.write("\n")

      for completion in r.values() do
        _out.print(completion)
      end

      _edit = strings.CommonPrefix(r)
      end_key()
    end

  fun ref _dispatch(term: ANSITerm) =>
    """
    Send a finished line to the notifier.
    """
    if _edit.size() > 0 then
      let line: String = _edit = recover String end

      if _blocked then
        _queue.push(line)
      else
        _add_history(line)
        _out.write("\n")
        _handle_line(term, line)
      end
    end

  fun ref _handle_line(term: ANSITerm, line: String) =>
    """
    Dispatch a single line.
    """
    let promise = Promise[String]

    promise.next[Any tag](
      recover term~prompt() end,
      recover term~dispose() end)

    _notify(line, promise)
    _cur_pos = 0
    _blocked = true

  fun ref _refresh_line() =>
    """
    Refresh the line on screen.
    """
    if not _blocked then
      let len = 40 + _cur_prompt.size() + _edit.size()
      let out = recover String(len) end

      // Move to the left edge.
      out.append("\r")

      // Print the prompt.
      out.append(_cur_prompt)

      // Print the current line.
      out.append(_edit.clone())

      // Erase to the right edge.
      out.append(ANSI.erase())

      // Set the cursor position.
      var pos = _cur_prompt.codepoints()

      if _cur_pos > 0 then
        pos = pos + _edit.codepoints(0, _cur_pos)
      end

      out.append("\r")

      // Only move right when the cursor is off the left edge. ANSI.right(0)
      // emits a one-column move, so appending it here would nudge the cursor
      // right on an empty line with an empty prompt.
      if pos > 0 then
        out.append(ANSI.right(pos.u32()))
      end

      _out.write(consume out)
    end

  fun ref _add_history(line: String) =>
    """
    Add a line to the history, trimming an earlier line if necessary.
    """
    try
      if (_history.size() > 0) and (_history(_history.size() - 1)? == line) then
        _cur_line = _history.size()
        return
      end
    end

    if (_maxlen > 0) and (_history.size() >= _maxlen) then
      try
        _history.shift()?
      end
    end

    _history.push(line)
    _cur_line = _history.size()

  fun ref _load_history() =>
    """
    Load the history from a file.
    """
    _history.clear()

    try
      with file = File.open(_path as FilePath) do
        for line in file.lines() do
          _add_history(consume line)
        end
      end
    end

  fun _save_history() =>
    """
    Write the history back to a file.
    """
    try
      with file = File(_path as FilePath) do
        for line in _history.values() do
          file.print(line)
        end
      end
    end