blob: 13173cb19361a0c8b8e555f2aef3c6e22c71e3a0 [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
50 if (c >= 32 && c <= 255) {
51 if (cmdbuf_pos < (int) sizeof(cmdbuf) - 1) {
52 cmdbuf[cmdbuf_pos++] = c;
53 }
54 }
55}
56
57
58int edit_init(void (*cmd_cb)(void *ctx, char *cmd),
59 void (*eof_cb)(void *ctx),
60 char ** (*completion_cb)(void *ctx, const char *cmd, int pos),
Dmitry Shmidt61d9df32012-08-29 16:22:06 -070061 void *ctx, const char *history_file, const char *ps)
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070062{
63 edit_cb_ctx = ctx;
64 edit_cmd_cb = cmd_cb;
65 edit_eof_cb = eof_cb;
66 eloop_register_read_sock(STDIN_FILENO, edit_read_char, NULL, NULL);
Dmitry Shmidt61d9df32012-08-29 16:22:06 -070067 ps2 = ps;
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070068
Dmitry Shmidt61d9df32012-08-29 16:22:06 -070069 printf("%s> ", ps2 ? ps2 : "");
Dmitry Shmidt8d520ff2011-05-09 14:06:53 -070070 fflush(stdout);
71
72 return 0;
73}
74
75
76void edit_deinit(const char *history_file,
77 int (*filter_cb)(void *ctx, const char *cmd))
78{
79 eloop_unregister_read_sock(STDIN_FILENO);
80}
81
82
83void edit_clear_line(void)
84{
85}
86
87
88void edit_redraw(void)
89{
90 cmdbuf[cmdbuf_pos] = '\0';
91 printf("\r> %s", cmdbuf);
92}