-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.c
More file actions
98 lines (86 loc) · 2.59 KB
/
command.c
File metadata and controls
98 lines (86 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
struct {
char chars[1024];
int len; // without NUL-termination
int cursor;
} g_current_command;
static struct {
char history[100][256];
int count;
int cursor;
} command_history;
static void string_insert_at(char *text, const int idx, const char c) {
for (int i = strlen(text) + 1; i > idx; --i) {
text[i] = text[i - 1];
}
text[idx] = c;
}
static void string_remove_at(char *text, const int idx) {
for (int i = idx;; i++) {
text[i] = text[i + 1];
if (text[i] == '\0') {
return;
}
}
}
void command_mode_enter(void) {
g_current_command.cursor = 0;
g_current_command.chars[0] = '\0';
g_current_command.len = 0;
command_history.cursor = command_history.count;
}
void command_history_prev(void) {
if (command_history.cursor == 0) {
return;
}
command_history.cursor--;
strlcpy(g_current_command.chars, command_history.history[command_history.cursor], sizeof(g_current_command.chars));
int len = strlen(g_current_command.chars);
g_current_command.len = len;
g_current_command.cursor = len;
}
void command_history_next(void) {
if (command_history.cursor >= command_history.count) {
return;
}
command_history.cursor++;
strlcpy(g_current_command.chars, command_history.history[command_history.cursor], sizeof(g_current_command.chars));
const int len = strlen(g_current_command.chars);
g_current_command.len = len;
g_current_command.cursor = len;
}
void command_history_add(void) {
strlcpy(command_history.history[command_history.count], g_current_command.chars,
sizeof(command_history.history[command_history.count]));
command_history.count++;
}
void command_input_add(const uint32_t ch) {
g_current_command.len++;
if (g_current_command.cursor < g_current_command.len) {
// middle of command
string_insert_at(g_current_command.chars, g_current_command.cursor, ch);
} else {
// end of command
g_current_command.chars[g_current_command.cursor] = ch;
g_current_command.chars[g_current_command.len] = '\0';
}
g_current_command.cursor++;
}
bool command_input_backspace(void) {
if (g_current_command.len > 0 && g_current_command.cursor > 0) {
g_current_command.len--;
g_current_command.cursor--;
if (g_current_command.cursor < g_current_command.len) {
// middle of command
string_remove_at(g_current_command.chars, g_current_command.cursor);
} else {
// end of command
g_current_command.chars[g_current_command.len] = '\0';
}
return false; // stay in command mode
}
return true; // enter normal mode
}