I want to write interactive shell in scala, with support for readline (Ctrl-l, arrow keys, line editing, history, etc.).
I know how to do it in python:
# enable support for Ctrl-l, arrow keys, line editing, history, etc.
import readline
finished = False
while not finished:
try:
line = raw_input('> ')
if line:
if line == 'q':
finished = True
else:
print line
except KeyboardInterrupt:
print 'Ctrl-c'; finished = True
except EOFError:
print 'Ctrl-d'; finished = True
I want to write a simple scala program, with exactly the same behaviour. My closest solution until now is the following scala:
// used to support Ctrl-l, arrow keys, line editing, history, etc.
import scala.tools.jline
val consoleReader = new jline.console.ConsoleReader()
var finished = false
while (!finished) {
val line = consoleReader.readLine("> ")
if (line == null) {
println("Ctrl-d")
finished = true
} else if (line.size > 0) {
if (line == "q") {
finished = true
} else {
println(line)
}
}
}
The open questions are:
You could write a hierarchy of jline
events, for example:
sealed trait JLineEvent
case class Line(value: String) extends JLineEvent
case object EmptyLine extends JLineEvent
case object EOF extends JLineEvent
Then you can encapsulate the while
loop in a function which takes as parameter a function of JLineEvent
:
def console( handler: JLineEvent => Boolean ) {
val consoleReader = new jline.console.ConsoleReader()
var finished = false
while (!finished) {
val line = consoleReader.readLine("> ")
if (line == null) {
finished = handler( EOF )
} else if (line.size == 0) {
finished = handler( EmptyLine )
} else if (line.size > 0) {
finished = handler( Line( line ) )
}
}
Finally you can call it with the appropriate function:
console {
case EOF =>
println("Ctrl-d")
true
case Line(s) if s == "q" =>
true
case Line(s) =>
println(line)
false
case _ =>
false
}
For catching ctrl+C
perhaps shutdown hooks can be a solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With