aboutsummaryrefslogtreecommitdiff
path: root/coffee/node_readline.coffee
blob: 31e5ca0feecabcc3322ea728c6cea18b8366d4b3 (plain)
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
# IMPORTANT: choose one
RL_LIB = "libreadline"  # NOTE: libreadline is GPL
#RL_LIB = "libedit"

HISTORY_FILE = require('path').join(process.env.HOME, '.mal-history')

rlwrap = {} # namespace for this module in web context

ffi = require('ffi')
fs = require('fs')

rllib = ffi.Library(RL_LIB, {
    'readline': ['string', ['string']],
    'add_history': ['int', ['string']]})

rl_history_loaded = false

exports.readline = rlwrap.readline = (prompt = 'user> ') ->
  if !rl_history_loaded
    rl_history_loaded = true
    lines = []
    if fs.existsSync(HISTORY_FILE)
        lines = fs.readFileSync(HISTORY_FILE).toString().split("\n");

    # Max of 2000 lines
    lines = lines[Math.max(lines.length - 2000, 0)..]
    rllib.add_history(line) for line in lines when line != ""

  line = rllib.readline prompt
  if line
    rllib.add_history line
    fs.appendFileSync HISTORY_FILE, line + "\n"

  line

# vim: ts=2:sw=2