开发者

How to make an interactive promp with arrow key functionality?

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 implemen开发者_开发百科t 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜