Hristo Hristov
Hristo Hristov

Reputation: 4151

How to write interactive shell with readline support in scala?

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:

Upvotes: 5

Views: 2352

Answers (1)

paradigmatic
paradigmatic

Reputation: 40461

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.

Upvotes: 7

Related Questions