有没有一种使用GNU readline处理多行输入的好方法? [英] Is there a nice way of handling multi-line input with GNU readline?

查看:65
本文介绍了有没有一种使用GNU readline处理多行输入的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

困难在于我的命令可能很长很复杂(请考虑使用SQL),我想允许用户将命令分布在多行上,以使它们在历史记录中更具可读性。

The hitch is that my commands can be quite long and complex (think SQL) and I'd like to allow users to spread commands over multiple lines to make them more readable in the history.

是否可以在readline中执行此操作(也许通过指定一个

Is it possible to do this in readline (maybe by specifying a difference between a newline and an end of command)?

或者我会更好地实现自己的命令行(但也许使用 GNU历史库)?

Or would I be better off implementing my own command line (but maybe using the GNU History library)?

推荐答案

您当然可以。

您可以使用$

rl_bind_key('\r', return_func);

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

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

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

如果要在UNIX终端中执行此操作,则要移动光标,需要了解ANSI终端代码。维基百科上有一个开始引用

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.

下面是一些使用readline读取多行代码的示例代码,当您输入分号时,它将停止编辑(我将其设置为EOQ或end-or-query)。 Readline功能非常强大,有很多东西需要学习。

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

这篇关于有没有一种使用GNU readline处理多行输入的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆