Search code examples
inputdefaultpromptraku

perl6 Is there a way to do editable prompt input?


In bash shell, if you hit up or down arrows, the shell will show you your previous or next command that you entered, and you can edit those commands to be new shell commands.

In perl6, if you do

my $name = prompt("Enter name: ");

it will print "Enter name: " and then ask for input; is there a way to have perl6 give you a default value and then you just edit the default to be the new value. E.g.:

my $name = prompt("Your name:", "John Doe");

and it prints

Your name: John Doe

where the John Doe part is editable, and when you hit enter, the edited string is the value of $name.

https://docs.raku.org/routine/prompt does not show how to do it.

This is useful if you have to enter many long strings each of which is just a few chars different from others.

Thanks.


Solution

  • To get the editing part going, you could use the Linenoise module:

    zef install Linenoise
    

    (https://github.com/hoelzro/p6-linenoise)

    Then, in your code, do:

    use Linenoise;
    sub prompt($p) {
        my $l = linenoise $p;
        linenoiseHistoryAdd($l);
        $l
    }
    

    Then you can do your loop with prompt. Remember, basically all Perl 6 builtin functions can be overridden lexically. Now, how to fill in the original string, that I haven't figure out just yet. Perhaps the libreadline docs can help you with that.