readline 注册key function

http://stackoverflow.com/questions/161495/is-there-a-nice-way-of-handling-multi-line-input-with-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.

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.

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

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

share | edit
   

2 Answers

up vote 7 down vote accepted

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 here on wikipedia

[http://en.wikipedia.org/wiki/ANSI_escape_code#Codes][1]

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

Just want to leave a note about a non-GPL library that have similare functionality as GNU readline

Project tecla

share | edit
 
1  
On that note, libedit (thrysoee.dk/editline) is a BSD-licensed library with similar functionality and APIs as libreadline. –  DGentry  Oct 2 '08 at 14:14
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值