The following problem arised while building a REPL console application for a programming language. Essentially, the language relies on you being able to write multiple lines of text. However, the ENTER
key should also be usable to evaluate an expression.
> 1 + 1<enter>
int int1 = 2
> <cursor>
To allow multi-line input, I am using an algorithm that counts the number of parentheses, braces, brackets and quotes, so if either of them are unbalanced, it inserts a newline:
> if (int1 < 3) {<enter>
| println "ok"<enter>
| }<enter>
ok
> <cursor>
The main problem with this approach is that as soon as I press enter on a line, that line cannot be edited anymore. Repeatedly pressing BACKSPACE
at the }
symbol will first delete it and then stay at that position without removing the newline and allowing me to delete the println
line. This makes programs very error-prone and editing very tedious.
Another problem is the fact that I can't even use the cursor in some consoles (like the Mac Terminal). The console will just show ANSI control codes in that event.
Is there a way to solve both problems, perhaps by introducing custom cursor handling to my REPL frontend? How much access does the JVM give me to the enclosing console? Can I force consoles to redirect all key presses to the program? And, do I have to use different techniques for different IDE consoles / terminals / Operating Systems?