GNU 읽기 라인으로 멀티 라인 입력을 처리하는 좋은 방법이 있습니까?
-
03-07-2019 - |
문제
내 응용 프로그램에는 명령 줄 인터페이스가 있으며 GNU READLINE 라이브러리 역사, 편집 가능한 명령 줄 등을 제공합니다.
내 명령은 매우 길고 복잡 할 수 있으며 (SQL을 생각) 사용자가 여러 줄에 명령을 전파하여 역사상 더 읽을 수 있도록 할 수 있다는 것입니다.
readline에서 이것을 할 수 있습니까 (아마도 Newline과 명령 끝의 차이를 지정함으로써)?
아니면 내 명령 줄을 구현하는 것이 더 좋을까요 (그러나 아마도 GNU 역사 도서관)?
해결책
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);
}