#include <getopt.h>
#include <gettext.h>
-#include <readline.h>
#include <localcharset.h>
#include <mbswidth.h>
#include "copysym.h"
#include "options.h"
+#if HAVE_READLINE_READLINE_H
+# include <readline/readline.h>
+#endif
+
static const char *progname = "cdecl99";
static bool interactive = true;
return !line[strspn(line, " \t")];
}
-static int repl(void)
-{
- char *line;
-
- for (; (line = readline("> ")); free(line)) {
- if (!is_blank_line(line))
- add_history(line);
-
- if (run_command(line, true) > 0)
- break;
- }
-
- free(line);
- return 0;
-}
-
static int repl_cmdline(unsigned count, char **commands)
{
int ret = 0;
return ret;
}
-static int repl_noninteractive(void)
+static int do_getline(char **linebuf, size_t *n)
{
- int rc, ret = 0, saved_errno;
- char *line = NULL;
- size_t n;
+ ssize_t rc;
- while (getline(&line, &n, stdin) >= 0) {
- char *c = strchr(line, '\n');
- if (c)
- *c = '\0';
+ if ((rc = getline(linebuf, n, stdin)) < 0) {
+ if (ferror(stdin))
+ print_error("%s", strerror(errno));
+ return 0;
+ }
- rc = run_command(line, false);
- if (rc < 0)
- ret = -1;
- else if (rc > 0)
- break;
+ if (rc-- && (*linebuf)[rc] == '\n')
+ (*linebuf)[rc] = '\0';
+ return 1;
+}
+
+static int do_readline(char **linebuf, size_t *n, int interactive)
+{
+#if !HAVE_READLINE
+ if (interactive) {
+ fputs("> ", stdout);
+ fflush(stdout);
}
- saved_errno = errno;
- free(line);
+ return do_getline(linebuf, n);
+#else
+ if (!interactive)
+ return do_getline(linebuf, n);
+
+ free(*linebuf);
+ if (!(*linebuf = readline("> ")))
+ return 0;
+
+ if (!is_blank_line(*linebuf))
+ add_history(*linebuf);
+ return 1;
+#endif
+}
+
+static int repl(int interactive)
+{
+ char *line = NULL;
+ int ret = 0;
+ size_t n;
- if (ferror(stdin)) {
- print_error("%s", strerror(saved_errno));
- return -1;
+ while (do_readline(&line, &n, interactive)) {
+ int rc = run_command(line, interactive);
+ if (rc > 0)
+ break;
+ else if (rc < 0)
+ ret = -!interactive;
}
+ free(line);
return ret;
}
case INIT_EXIT_FAILURE: return EXIT_FAILURE;
}
- if (interactive)
- rc = repl();
- else if (execute)
+ if (execute)
rc = repl_cmdline(execute, argv);
else
- rc = repl_noninteractive();
+ rc = repl(interactive);
if (rc != 0)
return EXIT_FAILURE;