Prefill a line with jline
Asked Answered
M

4

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).

Mallorca answered 4/9, 2012 at 17:24 Comment(0)
C
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.

Colubrine answered 26/3, 2015 at 22:43 Comment(0)
N
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()
Namara answered 24/11, 2015 at 13:38 Comment(0)
A
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.

Arly answered 7/8, 2020 at 10:35 Comment(0)
H
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).

Haworth answered 17/5, 2013 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.