【问题标题】:Is there a nice way of handling multi-line input with GNU readline?有没有用 GNU readline 处理多行输入的好方法?
【发布时间】:2010-09-14 18:13:52
【问题描述】:

我的应用程序有一个命令行界面,我正在考虑使用GNU Readline library 来提供历史记录、可编辑的命令行等。

问题是我的命令可能相当长且复杂(想想 SQL),我希望允许用户将命令分散到多行以使它们在历史记录中更具可读性。

是否可以在 readline 中执行此操作(可能通过指定换行符和命令结尾之间的差异)?

或者我最好实现自己的命令行(但也许使用GNU History library)?

【问题讨论】:

    标签: c command-line gnu readline


    【解决方案1】:

    你当然可以。

    您可以使用 '\r' 和 '\n' 值定义选项

    rl_bind_key('\r', return_func);
    

    您的 return_func 现在可以决定如何处理这些键。

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

    如果您在 UNIX 终端中执行此操作,则需要了解 ANSI 终端代码才能移动光标。维基百科上有一个starting reference

    这里有一些示例代码,它使用 readline 读取多行,并在您输入分号时停止编辑(我已将其设置为 EOQ 或 end-or-query)。 Readline 非常强大,有很多东西要学。

    #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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 2014-06-04
      • 2021-07-02
      • 1970-01-01
      • 2010-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多