Is there a nice way of handling multi-line input with GNU readline?

后端 未结 1 1125
独厮守ぢ
独厮守ぢ 2021-02-02 13:49

My application has a command line interface, and I\'m thinking about using the GNU Readline library to provide history, an editable command line, etc.

The hitch is that

相关标签:
1条回答
  • 2021-02-02 14:22

    You sure can.

    You can define options for the '\r' and '\n' values with

    rl_bind_key('\r', return_func);
    

    Your return_func can now decide what to do with those keys.

    int return_func(int cnt, int key) { ... }
    

    If you're doing this inside a UNIX terminal, you will need to learn about ANSI terminal codes if you want to move your cursor around. There's a starting reference on wikipedia.

    Here's some sample code that uses readline to read multi-line and will stop editing when you enter in a semi-colon (I've set that as the EOQ or end-or-query). Readline is extremely powerful, there's plenty of stuff to learn.

    #include <stdio.h>
    #include <unistd.h>
    #include <readline/readline.h>
    #include <readline/history.h>
    
    int my_startup(void);
    int my_bind_cr(int, int);
    int my_bind_eoq(int, int);
    char *my_readline(void);
    
    int my_eoq; 
    
    int
    main(int argc, char *argv[])
    {
    
      if (isatty(STDIN_FILENO)) {
        rl_readline_name = "my";
        rl_startup_hook = my_startup;
        my_readline();
      }
    }
    
    int
    my_startup(void) 
    {
      my_eoq = 0;
      rl_bind_key('\n', my_bind_cr);
      rl_bind_key('\r', my_bind_cr);
      rl_bind_key(';', my_bind_eoq);
    }
    
    int
    my_bind_cr(int count, int key) {
      if (my_eoq == 1) {
        rl_done = 1;
      }
      printf("\n");
    }
    
    int
    my_bind_eoq(int count, int key) {
      my_eoq = 1;
    
      printf(";");
    }
    
    char * 
    my_readline(void)
    {
      char *line;
    
      if ((line = readline("")) == NULL) {
        return NULL;
      }
    
      printf("LINE : %s\n", line);
    }
    
    0 讨论(0)
提交回复
热议问题