Skip to content

Commit 17b1613

Browse files
committed
Merge pull request adafruit#21 from pfalcon/readline-improve
Support Readline history and make it optional
2 parents 209d1b1 + fa02767 commit 17b1613

2 files changed

Lines changed: 31 additions & 3 deletions

File tree

unix/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ PYSRC=../py
22
BUILD=build
33

44
CC = gcc
5-
CFLAGS = -I. -I$(PYSRC) -Wall -Werror -ansi -std=gnu99 -Os #-DNDEBUG
5+
CFLAGS = -I. -I$(PYSRC) -Wall -Werror -ansi -std=gnu99 -Os -DUSE_READLINE #-DNDEBUG
66
LDFLAGS = -lm
77

88
SRC_C = \

unix/main.c

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515
#include "runtime.h"
1616
#include "repl.h"
1717

18+
#ifdef USE_READLINE
1819
#include <readline/readline.h>
20+
#include <readline/history.h>
21+
#endif
1922

2023
static char *str_join(const char *s1, int sep_char, const char *s2) {
2124
int l1 = strlen(s1);
@@ -31,16 +34,41 @@ static char *str_join(const char *s1, int sep_char, const char *s2) {
3134
return s;
3235
}
3336

37+
static char *prompt(char *p) {
38+
#ifdef USE_READLINE
39+
char *line = readline(p);
40+
if (line) {
41+
add_history(line);
42+
}
43+
#else
44+
static char buf[256];
45+
fputs(p, stdout);
46+
char *s = fgets(buf, sizeof(buf), stdin);
47+
if (!s) {
48+
return NULL;
49+
}
50+
int l = strlen(buf);
51+
if (buf[l - 1] == '\n') {
52+
buf[l - 1] = 0;
53+
} else {
54+
l++;
55+
}
56+
char *line = m_new(char, l);
57+
memcpy(line, buf, l);
58+
#endif
59+
return line;
60+
}
61+
3462
static void do_repl(void) {
3563
for (;;) {
36-
char *line = readline(">>> ");
64+
char *line = prompt(">>> ");
3765
if (line == NULL) {
3866
// EOF
3967
return;
4068
}
4169
if (mp_repl_is_compound_stmt(line)) {
4270
for (;;) {
43-
char *line2 = readline("... ");
71+
char *line2 = prompt("... ");
4472
if (line2 == NULL || strlen(line2) == 0) {
4573
break;
4674
}

0 commit comments

Comments
 (0)