beryx / text-io

A library for creating interactive console applications in Java
http://text-io.beryx.org/
Apache License 2.0
342 stars 45 forks source link

how to save a history of previous input ? #20

Closed mokun closed 5 years ago

mokun commented 5 years ago

Thanks to https://github.com/beryx/text-io/issues/17 that I now have the autocomplete setup for my program.

There are times that I would like to reenter the same input that I made in the past.

Is there an elegant way to program the Left and Right arrow keys to scroll backward and forward the input ?

I come up with this in SwingHandler but fall short of what to do next ?

    private static final String KEY_STROKE_LEFT = "pressed LEFT";
    private static final String KEY_STROKE_RIGHT = "pressed RIGHT";
    private String historyInput = "";
    private int historyIndex = -1;
    private String[] history = {};

  public SwingHandler(SwingTextTerminal terminal) {
        this.terminal = terminal;
        terminal.registerHandler(KEY_STROKE_LEFT, t -> {
            if (historyIndex >= 0) {
                historyIndex--;
                String text = (historyIndex < 0) ? historyInput : choices[historyIndex ];
                t.replaceInput(text, false);
            }
            return new ReadHandlerData(ReadInterruptionStrategy.Action.CONTINUE);
        });
siordache commented 5 years ago

You need a way to store and retrieve previously entered values. In the demo app I implemented the history store using a properties file. You may want to replace this solution with a more robust persistence mechanism.

I used Ctrl-Shift-Left and Ctrl-Shift-Right instead of just Left and Right, because I didn't want to disable the standard way to move the caret.

mokun commented 5 years ago

That's very awesome ! Using properties file to save the history will do the job well in my case.