如何制作具有箭头键功能的交互式提示?

发布于 2024-12-02 08:33:29 字数 243 浏览 6 评论 0原文

我正在制作一种解释性语言。我使用交互式提示,在其中输入要计算的表达式(REPL)。我想知道,如何实现标准提示行为?就像按向上和向下箭头键导航命令历史记录,按左右箭头键移动文本光标,而不是打印 ^[[D^[[C^[[A^[[B 代码。我只是不知道如何捕获它们,或者一般的任何控制字符。

我在Linux上。我需要使用 ncurses 或某些外部库,还是可以使用内置函数来完成?这与我的语言无关,但在没有导航的情况下使用这样的提示让我发疯。它使测试变得更加困难。

I am making an interpreted language. I use an interactive prompt where I enter expressions to be evaluated (a REPL). I was wondering, how do I implement standard prompt behavior? Like pressing the up and down arrow keys to navigate command history, and pressing the left and right arrow keys to move the text cursor, instead of printing the ^[[D^[[C^[[A^[[B codes. I just don't know how to catch them, or any control characters in general.

I'm on Linux. Will I need to use ncurses or some external library, or can it be done with built-in functions? This is unrelated to my language, but it drives me mad to use the prompt like this, with no navigation. It makes testing more difficult.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

诗笺 2024-12-09 08:33:29

下面是一个示例 C 程序,可让您使用 readline 来完成此操作(必须使用-lncurses -lreadline):

#include <stdio.h>
#include <curses.h>
#include <readline/readline.h>
#include <readline/history.h>

int main (void) {
    char *input = readline("$ ");
    printf("You typed `%s'!\n", input);
    return 0;
}

基本上,它模仿元键(如 home/end 和方向箭头键)的命令行行为。但这一切都取决于您的 inputrc 是否正确配置。

Here is an example C program that lets you do just that using readline (must be compiled with -lncurses -lreadline):

#include <stdio.h>
#include <curses.h>
#include <readline/readline.h>
#include <readline/history.h>

int main (void) {
    char *input = readline("$ ");
    printf("You typed `%s'!\n", input);
    return 0;
}

Basically, it mimics the command line behavior for meta keys like home/end and the directional arrow keys. But that all depends on whether you have your inputrc correctly configured.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文