forked from antirez/linenoise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
libline.c
1405 lines (1308 loc) · 37.5 KB
/
libline.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**@file libline.c
* @brief A guerrilla line editing library against the idea that a
* line editing lib needs to be 20,000 lines of C code.
* @author Salvatore Sanfilippo
* @author Pieter Noordhuis
* @author Richard James Howe
* @license BSD (included as comment)
*
* * TODO:
* - Full Windows Port, allow this to be ported to embedded platforms as well
* - Assertions
* - Put system dependent functionality into a series of callbacks, including
* the allocator, making this suitable to porting to an embedded environment
* - There are a few vi commands that should be added (rR)
* - The vi section and the rest should be separated.
*
* You can find the original/latest source code at:
*
* http://github.com/antirez/linenoise
*
* Does a number of crazy assumptions that happen to be true in 99.9999% of
* the 2010 UNIX computers around.
*
* DEVIATIONS FROM ORIGINAL:
*
* This merges and updates changes from user 'bobrippling' on Github.com
* <https://github.com/bobrippling/linenoise/blob/master/linenoise.c>
* <https://github.com/antirez/linenoise/pull/11>
*
* The API has also been changed so better suite my style and a few minor
* typos fixed.
*
* ------------------------------------------------------------------------
*
* ADDITIONAL COPYRIGHT
*
* Copyright (c) 2015, Richard James Howe <howe.r.j.89@gmail.com>
*
* ORIGINAL COPYRIGHT HEADER
*
* ------------------------------------------------------------------------
*
* Copyright (c) 2010-2013, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis at gmail dot com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ------------------------------------------------------------------------
*
* References:
* - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
*
* List of escape sequences used by this program, we do everything just
* with three sequences. In order to be so cheap we may have some
* flickering effect with some slow terminal, but the lesser sequences
* the more compatible.
*
* CHA (Cursor Horizontal Absolute)
* Sequence: ESC [ n G
* Effect: moves cursor to column n
*
* EL (Erase Line)
* Sequence: ESC [ n K
* Effect: if n is 0 or missing, clear from cursor to end of line
* Effect: if n is 1, clear from beginning of line to cursor
* Effect: if n is 2, clear entire line
*
* CUF (CUrsor Forward)
* Sequence: ESC [ n C
* Effect: moves cursor forward of n chars
*
* When multi line mode is enabled, we also use an additional escape
* sequence. However multi line editing is disabled by default.
*
* CUU (Cursor Up)
* Sequence: ESC [ n A
* Effect: moves cursor up of n chars.
*
* CUD (Cursor Down)
* Sequence: ESC [ n B
* Effect: moves cursor down of n chars.
*
* The following are used to clear the screen: ESC [ H ESC [ 2 J
* This is actually composed of two sequences:
*
* cursorhome
* Sequence: ESC [ H
* Effect: moves the cursor to upper left corner
*
* ED2 (Clear entire screen)
* Sequence: ESC [ 2 J
* Effect: clear the whole screen
*
* Useful links for porting to Windows:
* <https://stackoverflow.com/questions/24708700/c-detect-when-user-presses-arrow-key>
* <https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462%28v=vs.85%29.aspx>
* <https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033%28v=vs.85%29.aspx>
* <https://msdn.microsoft.com/en-us/library/windows/desktop/ms683231%28v=vs.85%29.aspx> */
#include "libline.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef __unix__
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#else
#error "Unsupported system"
#endif
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN (128)
#define LINENOISE_MAX_LINE (512)
#define LINENOISE_HISTORY_NEXT (0)
#define LINENOISE_HISTORY_PREV (1)
#define SEQ_BUF_LEN (64)
static char *unsupported_term[] = { "dumb", "cons25", "emacs", NULL };
typedef long long le_ssize_t;
struct line_completions {
size_t len;
char **cvec;
};
/* The line_state structure represents the state during line editing.
* We pass this state to functions implementing specific editing
* functionalities. */
struct line_state {
char *buf; /* Edited line buffer. */
size_t buflen; /* Edited line buffer size. */
const char *prompt; /* Prompt to display. */
size_t plen; /* Prompt length. */
size_t pos; /* Current cursor position. */
size_t oldpos; /* Previous refresh cursor position. */
size_t len; /* Current edited line length. */
size_t cols; /* Number of columns in terminal. */
size_t maxrows; /* Maximum num of rows used so far (multiline mode) */
int history_index; /* The history index we are currently editing. */
};
enum KEY_ACTION {
KEY_NULL = 0, /* NULL */
CTRL_A = 1, /* Ctrl+a */
CTRL_B = 2, /* Ctrl-b */
CTRL_C = 3, /* Ctrl-c */
CTRL_D = 4, /* Ctrl-d */
CTRL_E = 5, /* Ctrl-e */
CTRL_F = 6, /* Ctrl-f */
CTRL_H = 8, /* Ctrl-h */
TAB = 9, /* Tab */
CTRL_K = 11, /* Ctrl+k */
CTRL_L = 12, /* Ctrl+l */
ENTER = 13, /* Enter */
CTRL_N = 14, /* Ctrl-n */
CTRL_P = 16, /* Ctrl-p */
CTRL_T = 20, /* Ctrl-t */
CTRL_U = 21, /* Ctrl+u */
CTRL_W = 23, /* Ctrl+w */
ESC = 27, /* Escape */
BACKSPACE = 127, /* Backspace */
};
/* We define a very simple "append buffer" structure, that is an heap
* allocated string where we can append to. This is useful in order to
* write all the escape sequences in a buffer and flush them to the standard
* output in a single call, to avoid flickering effects. */
struct abuf {
size_t len;
char *b;
};
/**TODO Reorder code to avoid forward declarations */
static int line_edit_delete_char(libline_t *ll, struct line_state *l);
static int refresh_line(libline_t *ll, struct line_state *l);
static void *le_realloc(libline_t *ll, void *p, size_t sz) {
assert(ll);
return realloc(p, sz);
}
static void le_free(libline_t *ll, void *p) {
assert(ll);
free(p);
}
static void *le_malloc(libline_t *ll, size_t sz) {
assert(ll);
return malloc(sz);
}
static le_ssize_t le_write(libline_t *ll, void const * buf, size_t count) {
assert(ll);
return write(ll->out, buf, count);
}
static char *le_strdup(libline_t *ll, const char *s) {
assert(ll);
assert(s);
char *str = le_malloc(ll, strlen(s) + 1);
if (!str) {
fputs("Out of memory", stderr);
exit(1); /*not the best thing to do in a library*/
}
strcpy(str, s);
return str;
}
static int le_isatty(libline_t *ll, int fd) {
assert(ll);
return isatty(fd);
}
static int disable_raw_mode(libline_t *ll, struct termios *original) {
assert(ll);
if (ll->rawmode && tcsetattr(ll->in, TCSANOW, original) != -1)
ll->rawmode = 0;
return 0;
}
static int enable_raw_mode(libline_t *ll, struct termios *original) {
assert(ll);
struct termios raw;
if (!le_isatty(ll, ll->in))
goto error;
if (tcgetattr(ll->in, original) == -1)
goto error;
raw = *original; /* modify the original mode */
/* input modes: no break, no CR to NL, no parity check, no strip char,
no start/stop output control. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
/* output modes - disable post processing */
raw.c_oflag &= ~(OPOST);
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8);
/* local modes - echoing off, canonical off, no extended functions,
no signal chars (^Z,^C) */
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
/* control chars - set return condition: min number of bytes and timer.
We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1;
raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
/* put terminal in raw mode now */
if (tcsetattr(ll->in, TCSANOW, &raw) < 0)
goto error;
ll->rawmode = 1;
return 0;
error:
/* errno = ENOTTY; */
return -1;
}
static le_ssize_t le_read(libline_t *ll, void *buf, size_t count) {
assert(ll);
struct termios original;
const int tty = le_isatty(ll, ll->in);
if (tty)
enable_raw_mode(ll, &original);
const le_ssize_t r = read(ll->in, buf, count);
if (tty)
disable_raw_mode(ll, &original);
return r;
}
static int le_strcasecmp(const char *a, const char *b) {
assert(a);
assert(b);
int ca = 0, cb = 0;
for (ca = 0, cb = 0; (ca = *a++) && (cb = *b++);) {
ca = tolower(ca);
cb = tolower(cb);
if (ca != cb)
break;
}
return ca - cb;
}
/** @brief Return true if the terminal name is in the list of terminals
* we know are not able to understand basic escape sequences. **/
static int le_is_unsupported_term(void) {
char *term = getenv("TERM");
if (!term)
return 0;
for (int j = 0; unsupported_term[j]; j++)
if (!le_strcasecmp(term, unsupported_term[j]))
return 1;
return 0;
}
static char *le_fgets(libline_t *ll) {
assert(ll);
char *line = NULL;
size_t len = 0, maxlen = 0;
while(1) {
if (len == maxlen) {
if (maxlen == 0) maxlen = 16;
maxlen *= 2;
char *oldval = line;
line = le_realloc(ll, line, maxlen);
if (!line) {
if (oldval)
le_free(ll, oldval);
return NULL;
}
}
const int c = fgetc(stdin);
if (c == EOF || c == '\n') {
if (c == EOF && len == 0) {
le_free(ll, line);
return NULL;
} else {
line[len] = '\0';
return line;
}
} else {
line[len] = c;
len++;
}
}
}
/************************* Low level terminal handling ***********************/
/**@brief Use the ESC [6n escape sequence to query the horizontal
cursor position and return it. On error -1 is returned,
on success the position of the cursor. **/
static int get_cursor_position(libline_t *ll) {
/* Report cursor location */
if (le_write(ll, "\x1b[6n", 4) != 4)
return -1;
/* Read the response: ESC [ rows ; cols R */
size_t i = 0;
char buf[32] = { 0 };
while (i < sizeof(buf) - 1) {
if (le_read(ll, buf + i, 1) != 1)
break;
if (buf[i] == 'R')
break;
i++;
}
buf[i] = '\0';
/* Parse it. */
if (buf[0] != ESC || buf[1] != '[')
return -1;
int cols = 0, rows = 0;
if (sscanf(buf + 2, "%d;%d", &rows, &cols) != 2)
return -1;
return cols;
}
/** @brief Try to get the number of columns in the current terminal, or
* assume 80 if it fails. **/
static int get_columns(libline_t *ll) {
assert(ll);
struct winsize ws;
if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
return (int)ws.ws_col;
/* ioctl() failed. Try to query the terminal itself. */
/* Get the initial position so we can restore it later. */
const int start = get_cursor_position(ll);
if (start == -1)
goto failed;
/* Go to right margin and get position. */
if (le_write(ll, "\x1b[999C", 6) != 6)
goto failed;
const int cols = get_cursor_position(ll);
if (cols == -1)
goto failed;
/* Restore position. */
if (cols > start) {
char seq[32] = { 0 };
snprintf(seq, sizeof seq, "\x1b[%dD", cols - start);
if (le_write(ll, seq, strlen(seq)) == -1) {
goto failed; /* Can't recover... */
}
}
return cols;
failed:
return 80;
}
/**@brief Clear the screen. Used to handle ctrl+l **/
int line_clearscreen(libline_t *ll) {
assert(ll);
if (le_write(ll, "\x1b[H\x1b[2J", 7) <= 0)
return -1;
return 0;
}
/**@brief Beep, used for completion when there is nothing to complete
* or when all the choices were already shown. **/
static int line_beep(libline_t *ll) {
assert(ll);
return le_write(ll, "\x7", 1);
}
/******************************** Completion *********************************/
/**@brief Free a list of completion options populated by
line_add_completion(). **/
static void free_completions(libline_t *ll, line_completions * lc) {
assert(ll);
assert(lc);
for (size_t i = 0; i < lc->len; i++)
le_free(ll, lc->cvec[i]);
if (lc->cvec)
le_free(ll, lc->cvec);
}
/**@brief This is an helper function for line_edit() and is called when the
user types the <tab> key in order to complete the string currently
in the input. The state of the editing is encapsulated into the pointed
line_state structure as described in the structure definition. **/
static int complete_line(libline_t *ll, struct line_state *ls) {
assert(ll);
assert(ls);
assert(ll->completion_callback);
line_completions lc = { 0, NULL };
size_t stop = 0, i = 0;
int c = 0;
ll->completion_callback(ls->buf, ls->pos, &lc);
if (lc.len == 0) {
line_beep(ll);
goto end;
}
while (!stop) {
/* Show completion or original buffer */
if (i < lc.len) {
struct line_state saved = *ls;
ls->len = ls->pos = strlen(lc.cvec[i]);
ls->buf = lc.cvec[i];
if (refresh_line(ll, ls) < 0) {
c = -1;
goto end;
}
ls->len = saved.len;
ls->pos = saved.pos;
ls->buf = saved.buf;
} else {
if (refresh_line(ll, ls) < 0) {
c = -1;
goto end;
}
}
char cb[1] = { 0 };
const le_ssize_t nread = le_read(ll, &cb, 1);
c = cb[0];
if (nread <= 0) {
c = -1;
goto end;
}
switch (c) {
case TAB: /* tab */
i = (i + 1) % (lc.len + 1);
if (i == lc.len)
line_beep(ll);
break;
case ESC: /* escape */
/* Re-show original buffer */
if (i < lc.len)
refresh_line(ll, ls); // !!
stop = 1;
break;
default:
/* Update buffer and return */
if (i < lc.len) {
const int nwritten = snprintf(ls->buf, ls->buflen, "%s", lc.cvec[i]);
ls->len = ls->pos = (size_t)nwritten;
}
stop = 1;
break;
}
}
end:
free_completions(ll, &lc);
return c; /* Return last read character, or error */
}
/** @brief Register a callback function to be called for tab-completion. **/
void line_set_completion_callback(libline_t *ll, line_completion_callback * fn) {
assert(ll);
ll->completion_callback = fn;
}
/** @brief This function is used by the callback function registered by the user
* in order to add completion options given the input string when the
* user typed <tab>. See the example.c source code for a very easy to
* understand example. **/
void line_add_completion(libline_t *ll, line_completions * lc, const char *str) {
assert(ll);
assert(lc);
assert(str);
const size_t len = strlen(str);
char *copy = le_malloc(ll, len + 1);
if (!copy)
return;
memcpy(copy, str, len + 1);
char **cvec = le_realloc(ll, lc->cvec, sizeof(char *) * (lc->len + 1));
if (!cvec) {
le_free(ll, copy);
return;
}
lc->cvec = cvec;
lc->cvec[lc->len++] = copy;
}
/***************************** Line editing **********************************/
/** @brief Initialize a abuf structure to zero **/
static void ab_init(struct abuf *ab) {
assert(ab);
ab->b = NULL;
ab->len = 0;
}
/**@brief Append a string to an abuf struct **/
static int ab_append(libline_t *ll, struct abuf *ab, const char *s, size_t len) {
assert(ab);
assert(s);
char *new = le_realloc(ll, ab->b, ab->len + len);
if (!new)
return -1;
memcpy(new + ab->len, s, len);
ab->b = new;
ab->len += len;
return 0;
}
/**@brief Handle abuf memory freeing **/
static void ab_free(libline_t *ll, struct abuf *ab) {
assert(ab);
le_free(ll, ab->b);
ab->b = NULL;
}
/**@brief Single line low level line refresh.
*
* Rewrite the currently edited line accordingly to the buffer content,
* cursor position, and number of columns of the terminal. **/
static int refresh_line(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
char seq[SEQ_BUF_LEN] = { 0 };
size_t plen = strlen(l->prompt);
char *buf = l->buf;
size_t len = l->len;
size_t pos = l->pos;
struct abuf ab;
if ((plen + pos) >= l->cols) {
const size_t take = (plen + pos) - l->cols;
len -= take;
pos -= take;
buf += take;
}
if (plen + len > l->cols)
len = l->cols - plen;
ab_init(&ab);
/* Cursor to left edge */
if (snprintf(seq, SEQ_BUF_LEN, "\x1b[0G") < 0)
goto fail;
if (ab_append(ll, &ab, seq, strlen(seq)) < 0)
goto fail;
/* Write the prompt and the current buffer content */
if (ab_append(ll, &ab, l->prompt, strlen(l->prompt)) < 0)
goto fail;
if (ab_append(ll, &ab, buf, len) < 0)
goto fail;
/* Erase to right */
snprintf(seq, SEQ_BUF_LEN, "\x1b[0K");
if (ab_append(ll, &ab, seq, strlen(seq)) < 0)
goto fail;
/* Move cursor to original position. */
if (snprintf(seq, SEQ_BUF_LEN, "\x1b[0G\x1b[%dC", (int)(pos + plen)) < 0)
goto fail;
if (ab_append(ll, &ab, seq, strlen(seq)) < 0)
goto fail;
if (le_write(ll, ab.b, ab.len) == -1) /* Can't recover from write error. */
goto fail;
ab_free(ll, &ab);
return 0;
fail:
ab_free(ll, &ab);
return -1;
}
/**@brief Insert the character 'c' at cursor current position.
*
* On error writing to the terminal -1 is returned, otherwise 0. **/
static int line_edit_insert(libline_t *ll, struct line_state *l, char c) {
assert(l);
if (l->len < l->buflen) {
if (l->len == l->pos) {
l->buf[l->pos] = c;
l->pos++;
l->len++;
l->buf[l->len] = '\0';
if ((l->plen + l->len) < l->cols) {
/* Avoid a full update of the line in the trivial case. */
if (le_write(ll, &c, 1) == -1)
return -1;
} else {
if (refresh_line(ll, l) < 0)
return -1;
}
} else {
memmove(l->buf + l->pos + 1, l->buf + l->pos, l->len - l->pos);
l->buf[l->pos] = c;
l->len++;
l->pos++;
l->buf[l->len] = '\0';
if (refresh_line(ll, l) < 0)
return -1;
}
}
return 0;
}
/** @brief Move cursor on the left. **/
static int line_edit_move_left(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
if (l->pos > 0) {
l->pos--;
if (refresh_line(ll, l) < 0)
return -1;
}
return 0;
}
/** @brief Move cursor on the right. **/
static int line_edit_move_right(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
if (l->pos != l->len) {
l->pos++;
if (refresh_line(ll, l) < 0)
return -1;
}
return 0;
}
/** @brief Move cursor to the start of the line. **/
static int line_edit_move_home(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
if (l->pos != 0) {
l->pos = 0;
if (refresh_line(ll, l) < 0)
return -1;
}
return 0;
}
/** @brief Move cursor to the end of the line. **/
static int line_edit_move_end(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
if (l->pos != l->len) {
l->pos = l->len;
if (refresh_line(ll, l) < 0)
return -1;
}
return 0;
}
/** * @brief Substitute the currently edited line with the next or
* previous history entry as specified by 'dir'. **/
static int line_edit_history_next(libline_t *ll, struct line_state *l, int dir) {
assert(ll);
assert(l);
if (ll->history_len > 1) {
/* Update the current history entry before to
* overwrite it with the next one. */
le_free(ll, ll->history[ll->history_len - 1 - l->history_index]);
ll->history[ll->history_len - 1 - l->history_index] = le_strdup(ll, l->buf);
/* Show the new entry */
l->history_index += (dir == LINENOISE_HISTORY_PREV) ? 1 : -1;
if (l->history_index < 0) {
l->history_index = 0;
return 0;
} else if (l->history_index >= ll->history_len) {
l->history_index = ll->history_len - 1;
return 0;
}
strncpy(l->buf, ll->history[ll->history_len - 1 - l->history_index], l->buflen);
l->buf[l->buflen - 1] = '\0';
l->len = l->pos = strlen(l->buf);
if (refresh_line(ll, l) < 0)
return -1;
}
return 0;
}
/** @brief Delete the character at the right of the cursor without altering the
cursor position. Basically this is what happens with the "Delete"
keyboard key. **/
static int line_edit_delete(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
if (l->len > 0 && l->pos < l->len) {
memmove(l->buf + l->pos, l->buf + l->pos + 1, l->len - l->pos - 1);
l->len--;
l->buf[l->len] = '\0';
if (refresh_line(ll, l) < 0)
return -1;
}
return 0;
}
/** @brief Backspace implementation. **/
static int line_edit_backspace(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
if (l->pos > 0 && l->len > 0) {
memmove(l->buf + l->pos - 1, l->buf + l->pos, l->len - l->pos);
l->pos--;
l->len--;
l->buf[l->len] = '\0';
if (refresh_line(ll, l) < 0)
return -1;
}
return 0;
}
/**@brief Move the cursor to the next word **/
static void line_edit_next_word(struct line_state *l) {
assert(l);
while ((l->pos < l->len) && (' ' == l->buf[l->pos + 1]))
l->pos++;
while ((l->pos < l->len) && (' ' != l->buf[l->pos + 1]))
l->pos++;
if (l->pos < l->len)
l->pos++;
}
/**@brief Delete the next word, maintaining the cursor at the start
* of the current word. **/
static int line_edit_delete_next_word(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
const size_t old_pos = l->pos;
line_edit_next_word(l);
const size_t diff = l->pos - old_pos;
memmove(l->buf + old_pos, l->buf + l->pos, l->len - old_pos + 1);
l->len -= diff;
l->pos = old_pos;
return refresh_line(ll, l);
}
/**@brief Move the cursor to the previous word. **/
static void line_edit_prev_word(struct line_state *l) {
assert(l);
while ((l->pos > 0) && (l->buf[l->pos - 1] == ' '))
l->pos--;
while ((l->pos > 0) && (l->buf[l->pos - 1] != ' '))
l->pos--;
}
/**@brief Delete the previous word, maintaining the cursor at the start
of the current word. **/
static int line_edit_delete_prev_word(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
size_t old_pos = l->pos;
line_edit_prev_word(l);
const size_t diff = old_pos - l->pos;
memmove(l->buf + l->pos, l->buf + old_pos, l->len - old_pos + 1);
l->len -= diff;
return refresh_line(ll, l);
}
/**@brief This function processes vi-key commands.
* @param l The state of the line editor
* @param c Current keyboard character we are processing
* @param buf Input buffer
* @return int -1 on error **/
static int line_edit_process_vi(libline_t *ll, struct line_state *l, char c, char *buf) {
assert(ll);
assert(l);
assert(buf);
switch (c) {
case 'x': /*delete char*/
if (l->pos && (l->pos == l->len))
l->pos--;
return line_edit_delete_char(ll, l);
case 'w': /* move forward a word */
line_edit_next_word(l);
return refresh_line(ll, l);
case 'b': /* move back a word */
line_edit_prev_word(l);
return refresh_line(ll, l);
case 'C': /*Change*/
ll->vi_escape = 0;
/*fall through*/
case 'D': /*Delete from cursor to the end of the line*/
buf[l->pos] = '\0';
l->len = l->pos;
return refresh_line(ll, l);
case '0': /*Go to the beginning of the line*/
return line_edit_move_home(ll, l);
case '$': /*move to the end of the line*/
return line_edit_move_end(ll, l);
case 'l': /*move right*/
return line_edit_move_right(ll, l);
case 'h': /*move left*/
return line_edit_move_left(ll, l);
case 'A':/*append at end of line*/
l->pos = l->len;
if (refresh_line(ll, l) < 0)
return -1;
/*fall through*/
case 'a':/*append after the cursor*/
if (l->pos != l->len) {
l->pos++;
if (refresh_line(ll, l) < 0)
return -1;
}
/*fall through*/
case 'i':/*insert text before the cursor*/
ll->vi_escape = 0;
break;
case 'I':/*Insert text before the first non-blank in the line*/
ll->vi_escape = 0;
l->pos = 0;
return refresh_line(ll, l);
case 'k': /*move up*/
return line_edit_history_next(ll, l, LINENOISE_HISTORY_PREV);
case 'r': { /*replace a character*/
int replace = 0;
if (le_read(ll, &replace, 1) == -1)
return -1;
buf[l->pos] = replace;
return refresh_line(ll, l);
}
case 'j': /*move down*/
return line_edit_history_next(ll, l, LINENOISE_HISTORY_NEXT);
case 'f': /*fall through*/
case 'F': /*fall through*/
case 't': /*fall through*/
case 'T': /*fall through*/
{
le_ssize_t dir = 0, lim = 0, cpos = 0;
int find = 0;
if (le_read(ll, &find, 1) == -1)
return -1;
if (islower(c)) {
/* forwards */
lim = l->len;
dir = 1;
} else {
lim = dir = -1;
}
for (cpos = l->pos + dir; (cpos < lim) && (cpos > 0); cpos += dir) {
if (buf[cpos] == find) {
l->pos = cpos;
if (tolower(c) == 't')
l->pos -= dir;
if (refresh_line(ll, l) < 0)
return -1;
break;
}
}
if (cpos == lim)
line_beep(ll);
}
break;
case 'c':
ll->vi_escape = 0;
case 'd': /*delete*/
{
char rc[1] = { 0 };
if (le_read(ll, rc, 1) == -1)
return -1;
switch (rc[0]) {
case 'w':
return line_edit_delete_next_word(ll, l);
case 'b':
return line_edit_delete_prev_word(ll, l);
case '0': /** @todo d0 **/
break;
case '$':
buf[l->pos] = '\0';
l->len = l->pos;
return refresh_line(ll, l);
case 'c':
case 'd':
buf[0] = '\0';
l->pos = l->len = 0;
return refresh_line(ll, l);
default:
ll->vi_escape = 1;
return line_beep(ll);
}
}
break;
default:
return line_beep(ll);
}
return 0;
}
/**@brief Remove a character from the current line
* @param l linenoise state
* @return int negative on error **/
static int line_edit_delete_char(libline_t *ll, struct line_state *l) {
assert(ll);
assert(l);
if (l->len > 0) {
line_edit_delete(ll, l);
return 0;
}
if (ll->history_len > 0) {
ll->history_len--;
le_free(ll, ll->history[ll->history_len]);
ll->history[ll->history_len] = NULL;
}
return -1;
}
/**@brief The core line editing function, most of the work is done here.
*
* This function is the core of the line editing capability of linenoise.
* It expects 'fd' to be already in "raw mode" so that every key pressed
* will be returned ASAP to read().
*
* The resulting string is put into 'buf' when the user type enter, or
* when ctrl+d is typed.
*
* The function returns the length of the current buffer. */
static int line_edit(libline_t *ll, char *buf, size_t buflen, const char *prompt) {
assert(ll);
assert(buf);
assert(prompt);
struct line_state l = { 0 };
if (buflen < 80)
return -1;
/* Populate the linenoise state that we pass to functions implementing
* specific editing functionalities. */
l.buf = buf;
l.buflen = buflen;
l.prompt = prompt;
l.plen = strlen(prompt);
l.oldpos = 0;
l.pos = 0;
l.len = 0;
l.cols = get_columns(ll);
l.maxrows = 0;
l.history_index = 0;
/* Buffer starts empty. */
l.buf[0] = '\0';
l.buflen--; /* Make sure there is always space for the NUL terminator */
/* The latest history entry is always our current buffer, that