我构建了一个shell,试图让tab(\t
)键使用rl_bind_key()
做一些自定义的东西,但它在macOS Sierra中不起作用,但是它适用于Ubuntu,Fedora和CentOS的。这是mcve:
#include <stdlib.h>
#include <stdio.h>
#include <readline/readline.h>
static int cmd_complete(int count, int key)
{
printf("\nCustom tab action goes here...\n");
rl_forced_update_display();
return 0;
}
char *interactive_input()
{
char *buffer = readline(" > ");
return buffer;
}
int main(int argc, char **argv)
{
rl_bind_key('\t', cmd_complete); // this doesn't seem to work in macOS
char *buffer = 0;
while (!buffer || strncmp(buffer, "exit", 4)) {
if (buffer) { free(buffer); buffer=0; }
// get command
buffer = interactive_input();
printf("awesome command: %s\n", buffer);
}
free(buffer);
return 0;
}
我像这样使用Clang进行编译:
$ cc -lreadline cli.c -o cli
此行为的原因是什么?如何解决?
答案 0 :(得分:1)
我正在使用旗帜-lreadline
,但我不知道,Clang似乎秘密使用了libedit(我也看过它也称为editline)。在libedit中,出于某种原因(值得提出另一个问题),rl_bind_key
似乎不适用于rl_insert
以外的所有内容。
所以我找到的一个解决方案是使用Homebrew来安装GNU Readline(brew install readline
),然后为了确保我使用该版本,我编译:
$ cc -lreadline cli.c -o cli -L/usr/local/opt/readline/lib -I/usr/local/opt/readline/include
事实上,当您安装readline时,它会在安装结束时告诉您,或者您执行brew info readline
:
gns-mac1:~ gns$ brew info readline
readline: stable 7.0.3 (bottled) [keg-only]
Library for command-line editing
https://tiswww.case.edu/php/chet/readline/rltop.html
/usr/local/Cellar/readline/7.0.3_1 (46 files, 1.5MB)
Poured from bottle on 2017-10-24 at 12:21:35
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/readline.rb
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local,
because macOS provides the BSD libedit library, which shadows libreadline.
In order to prevent conflicts when programs look for libreadline we are
defaulting this GNU Readline installation to keg-only..
For compilers to find this software you may need to set:
LDFLAGS: -L/usr/local/opt/readline/lib
CPPFLAGS: -I/usr/local/opt/readline/include
所以这就是它在libedit中不起作用的原因。我下载了源代码,这就是rl_bind_key
函数的定义方式:
/*
* bind key c to readline-type function func
*/
int
rl_bind_key(int c, rl_command_func_t *func)
{
int retval = -1;
if (h == NULL || e == NULL)
rl_initialize();
if (func == rl_insert) {
/* XXX notice there is no range checking of ``c'' */
e->el_map.key[c] = ED_INSERT;
retval = 0;
}
return retval;
}
所以它似乎不适用于除rl_insert
之外的任何内容。这似乎是一个错误,而不是一个功能。我希望我知道如何成为libedit的贡献者。