gnureadlinelibreadline

GNU Readline: how to set the initial content of the input string


Colleagues, tell me how to set the initial value of the input line in readline()?

Let's assume that I can guess with a high degree of probability what value the user will enter. Although, the likelihood of a different value remains.

Therefore, I would like the input from the beginning to look like

Enter username: John

not

Enter username:

Is it possible to enter an initial value into the string buffer of the readline() function so that it will be output when it runs? And then, the user will either change it, or simply press enter, if he agrees with it.

Thanks in advance for your reply.


Solution

  • Thanks to the kind help of Chet Ramey, GNU Readline mainteiner's, I already know the answer to my question.

    To do this, you need to use the hook mechanism, create and declare a startup hook function.

    static char *deftext;
    
    static int
    set_deftext ()
    {
        if (deftext) {
            rl_insert_text (deftext);
            deftext = (char *) NULL;
            rl_startup_hook = (rl_hook_func_t *) NULL;
        }
    
        return 0;
    }
    

    Next, in the main code:

    deftext = "Initial Text";
    rl_startup_hook = set_deftext;
    line = readline ("My Prompt> ");
    

    An example is given in the distribution, in the file examples/rl.c