Readline with default value

I can limit user input to 5 characters using the GNU readline :

#include <readline/readline.h>
#include <stdio.h>
#include <stdlib.h>

static int limit_rl(FILE *f)
{
    if (rl_end > 5) {
        return '\b';
    }
    return rl_getc(f);
}

int main(void)
{
    char *str;

    rl_getc_function = limit_rl;
    str = readline("> ");
    printf("%s\n", str);
    free(str);
    return 0;
}

But how to read input with a default value (and not with a hint), for example:

> ummy
  ^ cursor here

if user types dand Enterreturn "dummy"

if the user types DELand Enterreturns "mmy"

+4
source share
1 answer

The home page readlinementions possible uses:

rl.c is an example program that uses Readline to read user input lines and echoes standard output suitable for use by shell scripts.

, ( ). , , readline, , hook:

: rl_hook_func_t * rl_startup_hook

, , readline .
(https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#IDX223)

hook , , :

: int rl_insert_text (const char * )

. .
(https://cnswww.cns.cwru.edu/php/chet/readline/readline.html#IDX295)

hook ( readline readline_internal_setup), , -, , .

rl.c, :

/* a global char * to hold a default initial text */
static char *deftext;

/* the callback function. The argument is supposed to be 'void' per
   its declaration:
       typedef int rl_hook_func_t (void);
   so you cannot provide the default text here */
static int set_deftext ()
{
  if (deftext)
    {
      /* Apparently the "current cursor position" in which text is inserted
         is 0, when initially called */
      rl_insert_text (deftext);
      deftext = (char *)NULL;

      /* disable the global 'rl_startup_hook' function by setting it to NULL */
      rl_startup_hook = (rl_hook_func_t *)NULL;
    }
  return 0;
}

// ...
if (deftext && *deftext)
   rl_startup_hook = set_deftext;

temp = readline (prompt);
+2

Source: https://habr.com/ru/post/1613180/


All Articles