/**
    Demonstration of the 'linenoiseish' plugin.

    Linenoise home: https://github.com/msteveb/linenoise
*/
const ln = [api.loadModule 'linenoiseish'].linenoise
$print 'ln =' ln

scope {
    assert 0 < ln.size() // get history limit
    ln.size(20) // set history limit
    assert 20 == ln.size()

    const hFile = "history.ln"
    if(!catch{ln.load(hFile)}){
        // Found/loaded history file
        assert ln.historyFile === hFile
    }else{
        // Could not load (probably doesn't exist)
        ln.historyFile = hFile // will auto-save this at destruction
    }

    print("Just FYI... console width =",ln.consoleWidth())

}

//ln.add("added from script "+__SRC)

/**
    To install custom completion handlers, add a method
    named customCompletions(). It takes 1 argument (the string
    entered up to the point where TAB was pressed). It may
    return nothing (no completions), a single string (a unique
    completion) or an array of strings (multiple completions
    through which linenoise will alternate on subsequent
    presses of the TAB key).

    Throwing an exception from the callback will propagate it
    up to the call point but, due to linenoise internals it
    does not get triggered until the user has pressed
    ENTER or the local EOF sequence (Unix: Ctrl-D).

    In the context of the callback, 'this' will be the
    linenoise module object.
*/
ln.myComps = ln.propertyKeys() // test/dummy completions
ln.customCompletions = proc(s){
    // throw "Just testing"
    return this.myComps // this === ln
}

// Define default prompt used by ln.read():
ln.prompt = "prompt > "

// api.x = 3 // this caused an assertion when run from user input inside our loop
1 && scope {
    var line;
    while(undefined !== (line = ln.read())){
        /* A prompt string may be passed to read() or
           set as ln.prompt. */
        if(ln.canCompile(line)){
            const v = catch {toss eval line}
            if(v inherits api.Exception){print("EXCEPTION:",v.code,':',v)}
            else{(undefined === v) || print(typename v, v)}
            //else { print(typename v, v) }
        }else{
            print("Got non-script:",line);
        }
    }
    print("Done looping")
}

0 && scope {
    ln.size(2) // C API rejects value 0 :-?
    $print ln.getHistoryList()
}

//ln.save() // not necessary: saves automatically at destruction
ln
