DISABLE FDs (REMOVE ME).
[jackhill/mal.git] / coffee / node_readline.coffee
1 # IMPORTANT: choose one
2 RL_LIB = "libreadline" # NOTE: libreadline is GPL
3 #RL_LIB = "libedit"
4
5 HISTORY_FILE = require('path').join(process.env.HOME, '.mal-history')
6
7 rlwrap = {} # namespace for this module in web context
8
9 ffi = require('ffi-napi')
10 fs = require('fs')
11
12 rllib = ffi.Library(RL_LIB, {
13 'readline': ['string', ['string']],
14 'add_history': ['int', ['string']]})
15
16 rl_history_loaded = false
17
18 exports.readline = rlwrap.readline = (prompt = 'user> ') ->
19 if !rl_history_loaded
20 rl_history_loaded = true
21 lines = []
22 if fs.existsSync(HISTORY_FILE)
23 lines = fs.readFileSync(HISTORY_FILE).toString().split("\n");
24
25 # Max of 2000 lines
26 lines = lines[Math.max(lines.length - 2000, 0)..]
27 rllib.add_history(line) for line in lines when line != ""
28
29 line = rllib.readline prompt
30 if line
31 rllib.add_history line
32 try
33 fs.appendFileSync HISTORY_FILE, line + "\n"
34 catch exc
35 true
36
37 line
38
39 # vim: ts=2:sw=2