blob: 2ffd1a2a2b7ea08fd43d5fb59b896ec05c7c298b [file] [log] [blame]
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07001/*
2 * Minimal command line editing
3 * Copyright (c) 2010, Jouni Malinen <j@w1.fi>
4 *
Dmitry Shmidtc5ec7f52012-03-06 16:33:24 -08005 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -07007 */
8
9#include "includes.h"
10
11#include "common.h"
12#include "eloop.h"
13#include "edit.h"
14
15
Dmitry Shmidtdf5a7e42014-04-02 12:59:59 -070016#define CMD_BUF_LEN 4096
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070017static char cmdbuf[CMD_BUF_LEN];
18static int cmdbuf_pos = 0;
Dmitry Shmidt61d9df32012-08-29 16:22:06 -070019static const char *ps2 = NULL;
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070020
21static void *edit_cb_ctx;
22static void (*edit_cmd_cb)(void *ctx, char *cmd);
23static void (*edit_eof_cb)(void *ctx);
24
25
26static void edit_read_char(int sock, void *eloop_ctx, void *sock_ctx)
27{
28 int c;
29 unsigned char buf[1];
30 int res;
31
32 res = read(sock, buf, 1);
33 if (res < 0)
34 perror("read");
35 if (res <= 0) {
36 edit_eof_cb(edit_cb_ctx);
37 return;
38 }
39 c = buf[0];
40
41 if (c == '\r' || c == '\n') {
42 cmdbuf[cmdbuf_pos] = '\0';
43 cmdbuf_pos = 0;
44 edit_cmd_cb(edit_cb_ctx, cmdbuf);
Dmitry Shmidt61d9df32012-08-29 16:22:06 -070045 printf("%s> ", ps2 ? ps2 : "");
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070046 fflush(stdout);
47 return;
48 }
49
Dmitry Shmidt849734c2016-05-27 09:59:01 -070050 if (c == '\b') {
51 if (cmdbuf_pos > 0)
52 cmdbuf_pos--;
53 return;
54 }
55
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070056 if (c >= 32 && c <= 255) {
57 if (cmdbuf_pos < (int) sizeof(cmdbuf) - 1) {
58 cmdbuf[cmdbuf_pos++] = c;
59 }
60 }
61}
62
63
64int edit_init(void (*cmd_cb)(void *ctx, char *cmd),
65 void (*eof_cb)(void *ctx),
66 char ** (*completion_cb)(void *ctx, const char *cmd, int pos),
Dmitry Shmidt61d9df32012-08-29 16:22:06 -070067 void *ctx, const char *history_file, const char *ps)
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070068{
69 edit_cb_ctx = ctx;
70 edit_cmd_cb = cmd_cb;
71 edit_eof_cb = eof_cb;
72 eloop_register_read_sock(STDIN_FILENO, edit_read_char, NULL, NULL);
Dmitry Shmidt61d9df32012-08-29 16:22:06 -070073 ps2 = ps;
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070074
Dmitry Shmidt61d9df32012-08-29 16:22:06 -070075 printf("%s> ", ps2 ? ps2 : "");
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070076 fflush(stdout);
77
78 return 0;
79}
80
81
82void edit_deinit(const char *history_file,
83 int (*filter_cb)(void *ctx, const char *cmd))
84{
85 eloop_unregister_read_sock(STDIN_FILENO);
86}
87
88
89void edit_clear_line(void)
90{
91}
92
93
94void edit_redraw(void)
95{
96 cmdbuf[cmdbuf_pos] = '\0';
97 printf("\r> %s", cmdbuf);
98}