7

Using either JLine (or JLine2), is it possible to issue a call to readline on a ConsoleReader and have, in addition to the standard prompt, the buffer be pre-filled with a string of my choosing?

I have tried to do, e.g.:

reader.getCursorBuffer().write("Default");
reader.readLine("Prompt> ");

This seems to indeed write into the buffer, but the line only displays the prompt. If I press enter, readLine returns "Default" as I would expect. If I clear the screen, the buffer is redrawn and shown correctly.

My understanding is that I should somehow call reader.redrawLine() right after the call to readLine. This last one however is blocking, which makes it hard (not impossible, but it certainly feels wrong to use a second thread for that).

Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
Philippe
  • 9,582
  • 4
  • 39
  • 59

4 Answers4

1

I ran into exactly this use case today.

It's a bit of a hack, but I was able to preload text into the JLine buffer and then let the user edit it by doing this:

String preloadReadLine(ConsoleReader reader, String prompt, String preload)
    throws IOException
{
    reader.resetPromptLine(prompt, preload, 0);
    reader.print("\r");
    return reader.readLine(prompt);
}

Yeah, the printing of \r is a hack, but it seems to make the thing work.

I'm using JLine-2.13.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
1

I managed to do that using a thread (yes, it does feel wrong, but I found no other way).

I took inspiration from code found in JLine itself that also uses a thread for similar purposes.

In Scala:

      val thr = new Thread() {
        override def run() = {
          reader.putString("Default")
          reader.flush()
          // Another way is:
          // reader.getCursorBuffer.write("Default") // writes into the buffer without displaying
          // out.print("D*f*ult") // here you can choose to display something different
          // reader.flush()
        }
      }
      thr.setPriority(Thread.MAX_PRIORITY)
      thr.setDaemon(true)
      thr.start()
Lionel Parreaux
  • 1,115
  • 1
  • 9
  • 22
1

Update for JLine3:

This can be accomplished with one of the existing overloads of readLine:

readLine(String prompt, Character mask, String buffer)

For example, reader.readLine("> ", null, "abc") will yield > abc where abc is part of the buffer being edited.

mzc
  • 3,265
  • 1
  • 20
  • 25
0

I think you want either resetPromptLine or putStream if you already have the prompt set.

Not to hijack your question but I can't figure out how to simply print a line replacing the prompt (ostensibly or visually pushing the prompt down with a message above it).

Adam Gent
  • 47,843
  • 23
  • 153
  • 203