forked from jbonjean/re-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
re-search.c
378 lines (309 loc) · 7.82 KB
/
re-search.c
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/*
* Copyright (C) 2014 Julien Bonjean <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <string.h>
#include <signal.h>
#include <fcntl.h>
#include "config.h"
#define NORMAL "\x1B[0m"
#define RED "\x1B[31m"
#define GREEN "\x1B[32m"
#define XSTR(A) STR(A)
#define STR(A) #A
#define MAX_INPUT_LEN 100
#define MAX_LINE_LEN 512
#define MAX_HISTORY_SIZE 8192
#ifdef DEBUG
#define debug(fmt, ...) \
fprintf(stderr, "DEBUG %s:%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
#else
#define debug(fmt, ...) \
do { } while (0)
#endif /* DEBUG */
#define error(fmt, ...) \
fprintf(stderr, fmt "\n", ##__VA_ARGS__)
#ifndef PROMPT
#define PROMPT(buffer, direction, index, result) \
do { \
/* print the first part of the prompt */ \
fprintf(stderr, "<%s search> %s", direction, buffer); \
if (index > 0) { \
/* if there is a result, append it */ \
i = fprintf(stderr, " (%d)[%s]", index, result); \
/* move back the cursor after the user input */ \
fprintf(stderr, "\033[%dD", i); \
}} while (0)
#endif /* PROMPT */
typedef enum {
SEARCH_BACKWARD, SEARCH_FORWARD
} action_t;
/* will be used as exit code to differenciate cases */
typedef enum {
RESULT_EXECUTE = 0, SEARCH_CANCEL = 1, RESULT_EDIT = 10
} exit_t;
struct termios saved_attributes;
char *history[MAX_HISTORY_SIZE];
char buffer[MAX_INPUT_LEN];
int history_size;
int search_result_index;
void reset_input_mode() {
debug("restore terminal settings");
tcsetattr(STDIN_FILENO, TCSANOW, &saved_attributes);
}
int set_input_mode() {
debug("setup terminal");
struct termios tattr;
// make sure stdin is a terminal
if (!isatty(STDIN_FILENO)) {
error("not a terminal");
return 1;
}
// save the terminal attributes so we can restore them later
tcgetattr(STDIN_FILENO, &saved_attributes);
atexit(reset_input_mode);
// set the funny terminal modes
tcgetattr(STDIN_FILENO, &tattr);
tattr.c_lflag &= ~(ICANON | ECHO);
tattr.c_cc[VMIN] = 1;
tattr.c_cc[VTIME] = 0;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tattr);
return 0;
}
int parse_fish_history() {
debug("parse fish history");
FILE* fp;
int res;
char path[1024];
char cmdline[MAX_LINE_LEN + 1];
snprintf(path, sizeof(path), "%s/.config/fish/fish_history",
getenv("HOME"));
fp = fopen(path, "r");
if (!fp) {
error("cannot open history file");
return 1;
}
// parse the fish history file and search for line with pattern "- cmd: *"
while ((res = fscanf(fp, "- cmd: %" XSTR(MAX_LINE_LEN) "[^\n]\n", cmdline))
!= EOF) {
if (res == 1) {
// append to history array, we don't check for duplicates as it
// should be handled by the shell
history[history_size] = malloc(strlen(cmdline) + 1);
if (!history[history_size]) {
error("cannot allocate memory");
fclose(fp);
return 1;
}
strncpy(history[history_size], cmdline, strlen(cmdline) + 1);
history_size++;
if (history_size >= MAX_HISTORY_SIZE) {
error("too many history entries");
fclose(fp);
return 1;
}
}
// we need to consume at least one character for fscan to continue
// scanning (why?), should we use fseek?
fgetc(fp);
}
fclose(fp);
debug("%d entries loaded", history_size);
return 0;
}
void restore_terminal() {
// reset color
fprintf(stderr, "%s", NORMAL);
// clear last printed results
fprintf(stderr, "\33[2K");
// restore cursor position
fprintf(stderr, "\033[u");
fflush(stderr);
}
int nb_getchar() {
int c;
// mark stdin nonblocking
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
c = getchar();
// restore stdin
fcntl(STDIN_FILENO, F_SETFL, flags);
return c;
}
void free_history() {
int i = 0;
for (i = 0; i < history_size; i++)
free(history[i]);
// just to be ensure we won't free again
history_size = 0;
}
void cleanup() {
debug("cleanup resources");
restore_terminal();
free_history();
}
void accept(int status) {
// print result/buffer to stdout
fprintf(stdout, "%s",
search_result_index < history_size ?
history[search_result_index] : buffer);
cleanup();
exit(status);
}
void cancel() {
cleanup();
exit(SEARCH_CANCEL);
}
int main() {
// ensure everything is initialized
buffer[0] = '\0';
history_size = 0;
// handle sigint for clean exit
signal(SIGINT, cancel);
// prepare terminal
if (set_input_mode())
exit(EXIT_FAILURE);
// load fish history
if (parse_fish_history()) {
free_history();
exit(EXIT_FAILURE);
}
char c;
int search_index = 0;
int buffer_pos = 0;
int i = 0;
action_t action = SEARCH_BACKWARD;
search_result_index = history_size;
// if the buffer environment variable is set, populate the input buffer
char* env_buffer = getenv("SEARCH_BUFFER");
if (env_buffer && strlen(env_buffer) > 0) {
strncpy(buffer, env_buffer, strlen(env_buffer) + 1);
buffer_pos = strlen(env_buffer);
// remove trailing '\n'
if (buffer[buffer_pos - 1] == '\n')
buffer[--buffer_pos] = '\0';
}
// save cursor position
fprintf(stderr, "\033[s");
while (1) {
if (buffer_pos > 0) {
// search in the history array
// TODO: factorize?
if (action == SEARCH_BACKWARD) {
for (i = search_result_index - 1; i >= 0; i--) {
if (strstr(history[i], buffer)) {
search_index++;
search_result_index = i;
break;
}
}
} else {
for (i = search_result_index + 1; i < history_size; i++) {
if (strstr(history[i], buffer)) {
search_index--;
search_result_index = i;
break;
}
}
}
}
// erase line
fprintf(stderr, "\033[2K\r");
// print the color
fprintf(stderr, "%s", search_index > 0 ? GREEN : RED);
// print the prompt
PROMPT(buffer, (action == SEARCH_BACKWARD ? "backward" : "forward"),
search_index,
search_index > 0 ? history[search_result_index] : "");
fflush(stderr);
c = getchar();
switch (c) {
case 27:
c = nb_getchar();
if (c == -1) { // esc
cancel();
break;
} else if (c != 91 && c != 79) {
ungetc(c, stdin);
break;
}
// multi-characters sequence
switch (getchar()) {
case 53: // pg-up
getchar();
/* no break */
case 65: // up
action = SEARCH_BACKWARD;
break;
case 54: // pg-down
getchar();
/* no break */
case 66: // down
action = SEARCH_FORWARD;
break;
case 70: // end
case 67: // right
accept(RESULT_EDIT);
break;
case 72: // home
case 68: // left
cancel();
break;
}
break;
case '\004': // C-d
cancel();
break;
case '\n': // enter
accept(RESULT_EXECUTE);
break;
case 18: //C-r
action = SEARCH_BACKWARD;
break;
case 19: //C-s
action = SEARCH_FORWARD;
break;
case 127: // backspace
case 8: // backspace
if (buffer_pos <= 0)
continue;
buffer[--buffer_pos] = '\0';
// reset search
action = SEARCH_BACKWARD;
search_result_index = history_size;
search_index = 0;
break;
default:
// exclude the first 32 non-printing characters
if (c < 32)
break;
// prevent buffer overflow
if (buffer_pos >= MAX_INPUT_LEN - 1)
continue;
buffer[buffer_pos] = c;
buffer[++buffer_pos] = '\0';
// reset search
action = SEARCH_BACKWARD;
search_result_index = history_size;
search_index = 0;
}
}
error("should not happen");
cancel();
}