Fossil SCM

fossil-scm / extsrc / linenoise.c
Blame History Raw 2813 lines
1
#line 1 "utf8.h"
2
#ifndef UTF8_UTIL_H
3
#define UTF8_UTIL_H
4
5
#ifdef __cplusplus
6
extern "C" {
7
#endif
8
9
/**
10
* UTF-8 utility functions
11
*
12
* (c) 2010-2019 Steve Bennett <[email protected]>
13
*
14
* See utf8.c for licence details.
15
*/
16
17
#ifndef USE_UTF8
18
#include <ctype.h>
19
20
#define MAX_UTF8_LEN 1
21
22
/* No utf-8 support. 1 byte = 1 char */
23
#define utf8_strlen(S, B) ((B) < 0 ? (int)strlen(S) : (B))
24
#define utf8_strwidth(S, B) utf8_strlen((S), (B))
25
#define utf8_tounicode(S, CP) (*(CP) = (unsigned char)*(S), 1)
26
#define utf8_index(C, I) (I)
27
#define utf8_charlen(C) 1
28
#define utf8_width(C) 1
29
30
#else
31
32
#define MAX_UTF8_LEN 4
33
34
/**
35
* Converts the given unicode codepoint (0 - 0x1fffff) to utf-8
36
* and stores the result at 'p'.
37
*
38
* Returns the number of utf-8 characters
39
*/
40
int utf8_fromunicode(char *p, unsigned uc);
41
42
/**
43
* Returns the length of the utf-8 sequence starting with 'c'.
44
*
45
* Returns 1-4, or -1 if this is not a valid start byte.
46
*
47
* Note that charlen=4 is not supported by the rest of the API.
48
*/
49
int utf8_charlen(int c);
50
51
/**
52
* Returns the number of characters in the utf-8
53
* string of the given byte length.
54
*
55
* Any bytes which are not part of an valid utf-8
56
* sequence are treated as individual characters.
57
*
58
* The string *must* be null terminated.
59
*
60
* Does not support unicode code points > \u1fffff
61
*/
62
int utf8_strlen(const char *str, int bytelen);
63
64
/**
65
* Calculates the display width of the first 'charlen' characters in 'str'.
66
* See utf8_width()
67
*/
68
int utf8_strwidth(const char *str, int charlen);
69
70
/**
71
* Returns the byte index of the given character in the utf-8 string.
72
*
73
* The string *must* be null terminated.
74
*
75
* This will return the byte length of a utf-8 string
76
* if given the char length.
77
*/
78
int utf8_index(const char *str, int charindex);
79
80
/**
81
* Returns the unicode codepoint corresponding to the
82
* utf-8 sequence 'str'.
83
*
84
* Stores the result in *uc and returns the number of bytes
85
* consumed.
86
*
87
* If 'str' is null terminated, then an invalid utf-8 sequence
88
* at the end of the string will be returned as individual bytes.
89
*
90
* If it is not null terminated, the length *must* be checked first.
91
*
92
* Does not support unicode code points > \u1fffff
93
*/
94
int utf8_tounicode(const char *str, int *uc);
95
96
/**
97
* Returns the width (in characters) of the given unicode codepoint.
98
* This is 1 for normal letters and 0 for combining characters and 2 for wide characters.
99
*/
100
int utf8_width(int ch);
101
102
#endif
103
104
#ifdef __cplusplus
105
}
106
#endif
107
108
#endif
109
#line 1 "utf8.c"
110
/**
111
* UTF-8 utility functions
112
*
113
* (c) 2010-2019 Steve Bennett <[email protected]>
114
*
115
* All rights reserved.
116
*
117
* Redistribution and use in source and binary forms, with or without
118
* modification, are permitted provided that the following conditions are met:
119
*
120
* * Redistributions of source code must retain the above copyright notice,
121
* this list of conditions and the following disclaimer.
122
*
123
* * Redistributions in binary form must reproduce the above copyright notice,
124
* this list of conditions and the following disclaimer in the documentation
125
* and/or other materials provided with the distribution.
126
*
127
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
128
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
129
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
130
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
131
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
132
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
133
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
134
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
135
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
136
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
137
*/
138
139
#include <ctype.h>
140
#include <stdlib.h>
141
#include <string.h>
142
#include <stdio.h>
143
#ifndef UTF8_UTIL_H
144
#include "utf8.h"
145
#endif
146
147
#ifdef USE_UTF8
148
int utf8_fromunicode(char *p, unsigned uc)
149
{
150
if (uc <= 0x7f) {
151
*p = uc;
152
return 1;
153
}
154
else if (uc <= 0x7ff) {
155
*p++ = 0xc0 | ((uc & 0x7c0) >> 6);
156
*p = 0x80 | (uc & 0x3f);
157
return 2;
158
}
159
else if (uc <= 0xffff) {
160
*p++ = 0xe0 | ((uc & 0xf000) >> 12);
161
*p++ = 0x80 | ((uc & 0xfc0) >> 6);
162
*p = 0x80 | (uc & 0x3f);
163
return 3;
164
}
165
/* Note: We silently truncate to 21 bits here: 0x1fffff */
166
else {
167
*p++ = 0xf0 | ((uc & 0x1c0000) >> 18);
168
*p++ = 0x80 | ((uc & 0x3f000) >> 12);
169
*p++ = 0x80 | ((uc & 0xfc0) >> 6);
170
*p = 0x80 | (uc & 0x3f);
171
return 4;
172
}
173
}
174
175
int utf8_charlen(int c)
176
{
177
if ((c & 0x80) == 0) {
178
return 1;
179
}
180
if ((c & 0xe0) == 0xc0) {
181
return 2;
182
}
183
if ((c & 0xf0) == 0xe0) {
184
return 3;
185
}
186
if ((c & 0xf8) == 0xf0) {
187
return 4;
188
}
189
/* Invalid sequence */
190
return -1;
191
}
192
193
int utf8_strlen(const char *str, int bytelen)
194
{
195
int charlen = 0;
196
if (bytelen < 0) {
197
bytelen = strlen(str);
198
}
199
while (bytelen > 0) {
200
int c;
201
int l = utf8_tounicode(str, &c);
202
charlen++;
203
str += l;
204
bytelen -= l;
205
}
206
return charlen;
207
}
208
209
int utf8_strwidth(const char *str, int charlen)
210
{
211
int width = 0;
212
while (charlen) {
213
int c;
214
int l = utf8_tounicode(str, &c);
215
width += utf8_width(c);
216
str += l;
217
charlen--;
218
}
219
return width;
220
}
221
222
int utf8_index(const char *str, int index)
223
{
224
const char *s = str;
225
while (index--) {
226
int c;
227
s += utf8_tounicode(s, &c);
228
}
229
return s - str;
230
}
231
232
int utf8_tounicode(const char *str, int *uc)
233
{
234
unsigned const char *s = (unsigned const char *)str;
235
236
if (s[0] < 0xc0) {
237
*uc = s[0];
238
return 1;
239
}
240
if (s[0] < 0xe0) {
241
if ((s[1] & 0xc0) == 0x80) {
242
*uc = ((s[0] & ~0xc0) << 6) | (s[1] & ~0x80);
243
if (*uc >= 0x80) {
244
return 2;
245
}
246
/* Otherwise this is an invalid sequence */
247
}
248
}
249
else if (s[0] < 0xf0) {
250
if (((str[1] & 0xc0) == 0x80) && ((str[2] & 0xc0) == 0x80)) {
251
*uc = ((s[0] & ~0xe0) << 12) | ((s[1] & ~0x80) << 6) | (s[2] & ~0x80);
252
if (*uc >= 0x800) {
253
return 3;
254
}
255
/* Otherwise this is an invalid sequence */
256
}
257
}
258
else if (s[0] < 0xf8) {
259
if (((str[1] & 0xc0) == 0x80) && ((str[2] & 0xc0) == 0x80) && ((str[3] & 0xc0) == 0x80)) {
260
*uc = ((s[0] & ~0xf0) << 18) | ((s[1] & ~0x80) << 12) | ((s[2] & ~0x80) << 6) | (s[3] & ~0x80);
261
if (*uc >= 0x10000) {
262
return 4;
263
}
264
/* Otherwise this is an invalid sequence */
265
}
266
}
267
268
/* Invalid sequence, so just return the byte */
269
*uc = *s;
270
return 1;
271
}
272
273
struct utf8range {
274
int lower; /* lower inclusive */
275
int upper; /* upper exclusive */
276
};
277
278
/* From http://unicode.org/Public/UNIDATA/UnicodeData.txt */
279
static const struct utf8range unicode_range_combining[] = {
280
{ 0x0300, 0x0370 }, { 0x0483, 0x048a }, { 0x0591, 0x05d0 }, { 0x0610, 0x061b },
281
{ 0x064b, 0x0660 }, { 0x0670, 0x0671 }, { 0x06d6, 0x06dd }, { 0x06df, 0x06e5 },
282
{ 0x06e7, 0x06ee }, { 0x0711, 0x0712 }, { 0x0730, 0x074d }, { 0x07a6, 0x07b1 },
283
{ 0x07eb, 0x07f4 }, { 0x0816, 0x0830 }, { 0x0859, 0x085e }, { 0x08d4, 0x0904 },
284
{ 0x093a, 0x0958 }, { 0x0962, 0x0964 }, { 0x0981, 0x0985 }, { 0x09bc, 0x09ce },
285
{ 0x09d7, 0x09dc }, { 0x09e2, 0x09e6 }, { 0x0a01, 0x0a05 }, { 0x0a3c, 0x0a59 },
286
{ 0x0a70, 0x0a72 }, { 0x0a75, 0x0a85 }, { 0x0abc, 0x0ad0 }, { 0x0ae2, 0x0ae6 },
287
{ 0x0afa, 0x0b05 }, { 0x0b3c, 0x0b5c }, { 0x0b62, 0x0b66 }, { 0x0b82, 0x0b83 },
288
{ 0x0bbe, 0x0bd0 }, { 0x0bd7, 0x0be6 }, { 0x0c00, 0x0c05 }, { 0x0c3e, 0x0c58 },
289
{ 0x0c62, 0x0c66 }, { 0x0c81, 0x0c85 }, { 0x0cbc, 0x0cde }, { 0x0ce2, 0x0ce6 },
290
{ 0x0d00, 0x0d05 }, { 0x0d3b, 0x0d4e }, { 0x0d57, 0x0d58 }, { 0x0d62, 0x0d66 },
291
{ 0x0d82, 0x0d85 }, { 0x0dca, 0x0de6 }, { 0x0df2, 0x0df4 }, { 0x0e31, 0x0e32 },
292
{ 0x0e34, 0x0e3f }, { 0x0e47, 0x0e4f }, { 0x0eb1, 0x0eb2 }, { 0x0eb4, 0x0ebd },
293
{ 0x0ec8, 0x0ed0 }, { 0x0f18, 0x0f1a }, { 0x0f35, 0x0f3a }, { 0x0f3e, 0x0f40 },
294
{ 0x0f71, 0x0f88 }, { 0x0f8d, 0x0fbe }, { 0x0fc6, 0x0fc7 }, { 0x102b, 0x103f },
295
{ 0x1056, 0x105a }, { 0x105e, 0x1065 }, { 0x1067, 0x106e }, { 0x1071, 0x1075 },
296
{ 0x1082, 0x1090 }, { 0x109a, 0x109e }, { 0x135d, 0x1360 }, { 0x1712, 0x1720 },
297
{ 0x1732, 0x1735 }, { 0x1752, 0x1760 }, { 0x1772, 0x1780 }, { 0x17b4, 0x17d4 },
298
{ 0x17dd, 0x17e0 }, { 0x180b, 0x180e }, { 0x1885, 0x1887 }, { 0x18a9, 0x18aa },
299
{ 0x1920, 0x1940 }, { 0x1a17, 0x1a1e }, { 0x1a55, 0x1a80 }, { 0x1ab0, 0x1b05 },
300
{ 0x1b34, 0x1b45 }, { 0x1b6b, 0x1b74 }, { 0x1b80, 0x1b83 }, { 0x1ba1, 0x1bae },
301
{ 0x1be6, 0x1bfc }, { 0x1c24, 0x1c3b }, { 0x1cd0, 0x1ce9 }, { 0x1ced, 0x1cee },
302
{ 0x1cf2, 0x1cf5 }, { 0x1cf7, 0x1d00 }, { 0x1dc0, 0x1e00 }, { 0x20d0, 0x2100 },
303
{ 0x2cef, 0x2cf2 }, { 0x2d7f, 0x2d80 }, { 0x2de0, 0x2e00 }, { 0x302a, 0x3030 },
304
{ 0x3099, 0x309b }, { 0xa66f, 0xa67e }, { 0xa69e, 0xa6a0 }, { 0xa6f0, 0xa6f2 },
305
{ 0xa802, 0xa803 }, { 0xa806, 0xa807 }, { 0xa80b, 0xa80c }, { 0xa823, 0xa828 },
306
{ 0xa880, 0xa882 }, { 0xa8b4, 0xa8ce }, { 0xa8e0, 0xa8f2 }, { 0xa926, 0xa92e },
307
{ 0xa947, 0xa95f }, { 0xa980, 0xa984 }, { 0xa9b3, 0xa9c1 }, { 0xa9e5, 0xa9e6 },
308
{ 0xaa29, 0xaa40 }, { 0xaa43, 0xaa44 }, { 0xaa4c, 0xaa50 }, { 0xaa7b, 0xaa7e },
309
{ 0xaab0, 0xaab5 }, { 0xaab7, 0xaab9 }, { 0xaabe, 0xaac2 }, { 0xaaeb, 0xaaf0 },
310
{ 0xaaf5, 0xab01 }, { 0xabe3, 0xabf0 }, { 0xfb1e, 0xfb1f }, { 0xfe00, 0xfe10 },
311
{ 0xfe20, 0xfe30 },
312
};
313
314
/* From http://unicode.org/Public/UNIDATA/EastAsianWidth.txt */
315
static const struct utf8range unicode_range_wide[] = {
316
{ 0x1100, 0x115f }, { 0x231a, 0x231b }, { 0x2329, 0x232a }, { 0x23e9, 0x23ec },
317
{ 0x23f0, 0x23f0 }, { 0x23f3, 0x23f3 }, { 0x25fd, 0x25fe }, { 0x2614, 0x2615 },
318
{ 0x2648, 0x2653 }, { 0x267f, 0x267f }, { 0x2693, 0x2693 }, { 0x26a1, 0x26a1 },
319
{ 0x26aa, 0x26ab }, { 0x26bd, 0x26be }, { 0x26c4, 0x26c5 }, { 0x26ce, 0x26ce },
320
{ 0x26d4, 0x26d4 }, { 0x26ea, 0x26ea }, { 0x26f2, 0x26f3 }, { 0x26f5, 0x26f5 },
321
{ 0x26fa, 0x26fa }, { 0x26fd, 0x26fd }, { 0x2705, 0x2705 }, { 0x270a, 0x270b },
322
{ 0x2728, 0x2728 }, { 0x274c, 0x274c }, { 0x274e, 0x274e }, { 0x2753, 0x2755 },
323
{ 0x2757, 0x2757 }, { 0x2795, 0x2797 }, { 0x27b0, 0x27b0 }, { 0x27bf, 0x27bf },
324
{ 0x2b1b, 0x2b1c }, { 0x2b50, 0x2b50 }, { 0x2b55, 0x2b55 }, { 0x2e80, 0x2e99 },
325
{ 0x2e9b, 0x2ef3 }, { 0x2f00, 0x2fd5 }, { 0x2ff0, 0x2ffb }, { 0x3001, 0x303e },
326
{ 0x3041, 0x3096 }, { 0x3099, 0x30ff }, { 0x3105, 0x312e }, { 0x3131, 0x318e },
327
{ 0x3190, 0x31ba }, { 0x31c0, 0x31e3 }, { 0x31f0, 0x321e }, { 0x3220, 0x3247 },
328
{ 0x3250, 0x32fe }, { 0x3300, 0x4dbf }, { 0x4e00, 0xa48c }, { 0xa490, 0xa4c6 },
329
{ 0xa960, 0xa97c }, { 0xac00, 0xd7a3 }, { 0xf900, 0xfaff }, { 0xfe10, 0xfe19 },
330
{ 0xfe30, 0xfe52 }, { 0xfe54, 0xfe66 }, { 0xfe68, 0xfe6b }, { 0x16fe0, 0x16fe1 },
331
{ 0x17000, 0x187ec }, { 0x18800, 0x18af2 }, { 0x1b000, 0x1b11e }, { 0x1b170, 0x1b2fb },
332
{ 0x1f004, 0x1f004 }, { 0x1f0cf, 0x1f0cf }, { 0x1f18e, 0x1f18e }, { 0x1f191, 0x1f19a },
333
{ 0x1f200, 0x1f202 }, { 0x1f210, 0x1f23b }, { 0x1f240, 0x1f248 }, { 0x1f250, 0x1f251 },
334
{ 0x1f260, 0x1f265 }, { 0x1f300, 0x1f320 }, { 0x1f32d, 0x1f335 }, { 0x1f337, 0x1f37c },
335
{ 0x1f37e, 0x1f393 }, { 0x1f3a0, 0x1f3ca }, { 0x1f3cf, 0x1f3d3 }, { 0x1f3e0, 0x1f3f0 },
336
{ 0x1f3f4, 0x1f3f4 }, { 0x1f3f8, 0x1f43e }, { 0x1f440, 0x1f440 }, { 0x1f442, 0x1f4fc },
337
{ 0x1f4ff, 0x1f53d }, { 0x1f54b, 0x1f54e }, { 0x1f550, 0x1f567 }, { 0x1f57a, 0x1f57a },
338
{ 0x1f595, 0x1f596 }, { 0x1f5a4, 0x1f5a4 }, { 0x1f5fb, 0x1f64f }, { 0x1f680, 0x1f6c5 },
339
{ 0x1f6cc, 0x1f6cc }, { 0x1f6d0, 0x1f6d2 }, { 0x1f6eb, 0x1f6ec }, { 0x1f6f4, 0x1f6f8 },
340
{ 0x1f910, 0x1f93e }, { 0x1f940, 0x1f94c }, { 0x1f950, 0x1f96b }, { 0x1f980, 0x1f997 },
341
{ 0x1f9c0, 0x1f9c0 }, { 0x1f9d0, 0x1f9e6 }, { 0x20000, 0x2fffd }, { 0x30000, 0x3fffd },
342
};
343
344
#define ARRAYSIZE(A) sizeof(A) / sizeof(*(A))
345
346
static int cmp_range(const void *key, const void *cm)
347
{
348
const struct utf8range *range = (const struct utf8range *)cm;
349
int ch = *(int *)key;
350
if (ch < range->lower) {
351
return -1;
352
}
353
if (ch >= range->upper) {
354
return 1;
355
}
356
return 0;
357
}
358
359
static int utf8_in_range(const struct utf8range *range, int num, int ch)
360
{
361
const struct utf8range *r =
362
bsearch(&ch, range, num, sizeof(*range), cmp_range);
363
364
if (r) {
365
return 1;
366
}
367
return 0;
368
}
369
370
int utf8_width(int ch)
371
{
372
/* short circuit for common case */
373
if (isascii(ch)) {
374
return 1;
375
}
376
if (utf8_in_range(unicode_range_combining, ARRAYSIZE(unicode_range_combining), ch)) {
377
return 0;
378
}
379
if (utf8_in_range(unicode_range_wide, ARRAYSIZE(unicode_range_wide), ch)) {
380
return 2;
381
}
382
return 1;
383
}
384
#endif
385
#line 1 "stringbuf.h"
386
#ifndef STRINGBUF_H
387
#define STRINGBUF_H
388
/**
389
* resizable string buffer
390
*
391
* (c) 2017-2020 Steve Bennett <[email protected]>
392
*
393
* See utf8.c for licence details.
394
*/
395
#ifdef __cplusplus
396
extern "C" {
397
#endif
398
399
/** @file
400
* A stringbuf is a resizing, null terminated string buffer.
401
*
402
* The buffer is reallocated as necessary.
403
*
404
* In general it is *not* OK to call these functions with a NULL pointer
405
* unless stated otherwise.
406
*
407
* If USE_UTF8 is defined, supports utf8.
408
*/
409
410
/**
411
* The stringbuf structure should not be accessed directly.
412
* Use the functions below.
413
*/
414
typedef struct {
415
int remaining; /**< Allocated, but unused space */
416
int last; /**< Index of the null terminator (and thus the length of the string) */
417
#ifdef USE_UTF8
418
int chars; /**< Count of characters */
419
#endif
420
char *data; /**< Allocated memory containing the string or NULL for empty */
421
} stringbuf;
422
423
/**
424
* Allocates and returns a new stringbuf with no elements.
425
*/
426
stringbuf *sb_alloc(void);
427
428
/**
429
* Frees a stringbuf.
430
* It is OK to call this with NULL.
431
*/
432
void sb_free(stringbuf *sb);
433
434
/**
435
* Returns an allocated copy of the stringbuf
436
*/
437
stringbuf *sb_copy(stringbuf *sb);
438
439
/**
440
* Returns the byte length of the buffer.
441
*
442
* Returns 0 for both a NULL buffer and an empty buffer.
443
*/
444
static inline int sb_len(stringbuf *sb) {
445
return sb->last;
446
}
447
448
/**
449
* Returns the utf8 character length of the buffer.
450
*
451
* Returns 0 for both a NULL buffer and an empty buffer.
452
*/
453
static inline int sb_chars(stringbuf *sb) {
454
#ifdef USE_UTF8
455
return sb->chars;
456
#else
457
return sb->last;
458
#endif
459
}
460
461
/**
462
* Appends a null terminated string to the stringbuf
463
*/
464
void sb_append(stringbuf *sb, const char *str);
465
466
/**
467
* Like sb_append() except does not require a null terminated string.
468
* The length of 'str' is given as 'len'
469
*
470
* Note that in utf8 mode, characters will *not* be counted correctly
471
* if a partial utf8 sequence is added with sb_append_len()
472
*/
473
void sb_append_len(stringbuf *sb, const char *str, int len);
474
475
/**
476
* Returns a pointer to the null terminated string in the buffer.
477
*
478
* Note this pointer only remains valid until the next modification to the
479
* string buffer.
480
*
481
* The returned pointer can be used to update the buffer in-place
482
* as long as care is taken to not overwrite the end of the buffer.
483
*/
484
static inline char *sb_str(const stringbuf *sb)
485
{
486
return sb->data;
487
}
488
489
/**
490
* Inserts the given string *before* (zero-based) byte 'index' in the stringbuf.
491
* If index is past the end of the buffer, the string is appended,
492
* just like sb_append()
493
*/
494
void sb_insert(stringbuf *sb, int index, const char *str);
495
496
/**
497
* Delete 'len' bytes in the string at the given index.
498
*
499
* Any bytes past the end of the buffer are ignored.
500
* The buffer remains null terminated.
501
*
502
* If len is -1, deletes to the end of the buffer.
503
*/
504
void sb_delete(stringbuf *sb, int index, int len);
505
506
/**
507
* Clear to an empty buffer.
508
*/
509
void sb_clear(stringbuf *sb);
510
511
/**
512
* Return an allocated copy of buffer and frees 'sb'.
513
*
514
* If 'sb' is empty, returns an allocated copy of "".
515
*/
516
char *sb_to_string(stringbuf *sb);
517
518
#ifdef __cplusplus
519
}
520
#endif
521
522
#endif
523
#line 1 "stringbuf.c"
524
/**
525
* resizable string buffer
526
*
527
* (c) 2017-2020 Steve Bennett <[email protected]>
528
*
529
* See utf8.c for licence details.
530
*/
531
#include <stdlib.h>
532
#include <string.h>
533
#include <stdio.h>
534
#include <ctype.h>
535
#include <assert.h>
536
537
#ifndef STRINGBUF_H
538
#include "stringbuf.h"
539
#endif
540
#ifdef USE_UTF8
541
#ifndef UTF8_UTIL_H
542
#include "utf8.h"
543
#endif
544
#endif
545
546
#define SB_INCREMENT 200
547
548
stringbuf *sb_alloc(void)
549
{
550
stringbuf *sb = (stringbuf *)malloc(sizeof(*sb));
551
sb->remaining = 0;
552
sb->last = 0;
553
#ifdef USE_UTF8
554
sb->chars = 0;
555
#endif
556
sb->data = NULL;
557
558
return(sb);
559
}
560
561
void sb_free(stringbuf *sb)
562
{
563
if (sb) {
564
free(sb->data);
565
}
566
free(sb);
567
}
568
569
static void sb_realloc(stringbuf *sb, int newlen)
570
{
571
sb->data = (char *)realloc(sb->data, newlen);
572
sb->remaining = newlen - sb->last;
573
}
574
575
void sb_append(stringbuf *sb, const char *str)
576
{
577
sb_append_len(sb, str, strlen(str));
578
}
579
580
void sb_append_len(stringbuf *sb, const char *str, int len)
581
{
582
if (sb->remaining < len + 1) {
583
sb_realloc(sb, sb->last + len + 1 + SB_INCREMENT);
584
}
585
memcpy(sb->data + sb->last, str, len);
586
sb->data[sb->last + len] = 0;
587
588
sb->last += len;
589
sb->remaining -= len;
590
#ifdef USE_UTF8
591
sb->chars += utf8_strlen(str, len);
592
#endif
593
}
594
595
char *sb_to_string(stringbuf *sb)
596
{
597
if (sb->data == NULL) {
598
/* Return an allocated empty string, not null */
599
return strdup("");
600
}
601
else {
602
/* Just return the data and free the stringbuf structure */
603
char *pt = sb->data;
604
free(sb);
605
return pt;
606
}
607
}
608
609
/* Insert and delete operations */
610
611
/* Moves up all the data at position 'pos' and beyond by 'len' bytes
612
* to make room for new data
613
*
614
* Note: Does *not* update sb->chars
615
*/
616
static void sb_insert_space(stringbuf *sb, int pos, int len)
617
{
618
assert(pos <= sb->last);
619
620
/* Make sure there is enough space */
621
if (sb->remaining < len) {
622
sb_realloc(sb, sb->last + len + SB_INCREMENT);
623
}
624
/* Now move it up */
625
memmove(sb->data + pos + len, sb->data + pos, sb->last - pos);
626
sb->last += len;
627
sb->remaining -= len;
628
/* And null terminate */
629
sb->data[sb->last] = 0;
630
}
631
632
/**
633
* Move down all the data from pos + len, effectively
634
* deleting the data at position 'pos' of length 'len'
635
*/
636
static void sb_delete_space(stringbuf *sb, int pos, int len)
637
{
638
assert(pos < sb->last);
639
assert(pos + len <= sb->last);
640
641
#ifdef USE_UTF8
642
sb->chars -= utf8_strlen(sb->data + pos, len);
643
#endif
644
645
/* Now move it up */
646
memmove(sb->data + pos, sb->data + pos + len, sb->last - pos - len);
647
sb->last -= len;
648
sb->remaining += len;
649
/* And null terminate */
650
sb->data[sb->last] = 0;
651
}
652
653
void sb_insert(stringbuf *sb, int index, const char *str)
654
{
655
if (index >= sb->last) {
656
/* Inserting after the end of the list appends. */
657
sb_append(sb, str);
658
}
659
else {
660
int len = strlen(str);
661
662
sb_insert_space(sb, index, len);
663
memcpy(sb->data + index, str, len);
664
#ifdef USE_UTF8
665
sb->chars += utf8_strlen(str, len);
666
#endif
667
}
668
}
669
670
/**
671
* Delete the bytes at index 'index' for length 'len'
672
* Has no effect if the index is past the end of the list.
673
*/
674
void sb_delete(stringbuf *sb, int index, int len)
675
{
676
if (index < sb->last) {
677
char *pos = sb->data + index;
678
if (len < 0) {
679
len = sb->last;
680
}
681
682
sb_delete_space(sb, pos - sb->data, len);
683
}
684
}
685
686
void sb_clear(stringbuf *sb)
687
{
688
if (sb->data) {
689
/* Null terminate */
690
sb->data[0] = 0;
691
sb->last = 0;
692
#ifdef USE_UTF8
693
sb->chars = 0;
694
#endif
695
}
696
}
697
#line 1 "linenoise.c"
698
/* linenoise.c -- guerrilla line editing library against the idea that a
699
* line editing lib needs to be 20,000 lines of C code.
700
*
701
* You can find the latest source code at:
702
*
703
* http://github.com/msteveb/linenoise
704
* (forked from http://github.com/antirez/linenoise)
705
*
706
* Does a number of crazy assumptions that happen to be true in 99.9999% of
707
* the 2010 UNIX computers around.
708
*
709
* ------------------------------------------------------------------------
710
*
711
* Copyright (c) 2010, Salvatore Sanfilippo <antirez at gmail dot com>
712
* Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis at gmail dot com>
713
* Copyright (c) 2011, Steve Bennett <steveb at workware dot net dot au>
714
*
715
* All rights reserved.
716
*
717
* Redistribution and use in source and binary forms, with or without
718
* modification, are permitted provided that the following conditions are
719
* met:
720
*
721
* * Redistributions of source code must retain the above copyright
722
* notice, this list of conditions and the following disclaimer.
723
*
724
* * Redistributions in binary form must reproduce the above copyright
725
* notice, this list of conditions and the following disclaimer in the
726
* documentation and/or other materials provided with the distribution.
727
*
728
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
729
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
730
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
731
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
732
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
733
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
734
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
735
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
736
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
737
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
738
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
739
*
740
* ------------------------------------------------------------------------
741
*
742
* References:
743
* - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
744
* - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html
745
*
746
* Bloat:
747
* - Completion?
748
*
749
* Unix/termios
750
* ------------
751
* List of escape sequences used by this program, we do everything just
752
* a few sequences. In order to be so cheap we may have some
753
* flickering effect with some slow terminal, but the lesser sequences
754
* the more compatible.
755
*
756
* EL (Erase Line)
757
* Sequence: ESC [ 0 K
758
* Effect: clear from cursor to end of line
759
*
760
* CUF (CUrsor Forward)
761
* Sequence: ESC [ n C
762
* Effect: moves cursor forward n chars
763
*
764
* CR (Carriage Return)
765
* Sequence: \r
766
* Effect: moves cursor to column 1
767
*
768
* The following are used to clear the screen: ESC [ H ESC [ 2 J
769
* This is actually composed of two sequences:
770
*
771
* cursorhome
772
* Sequence: ESC [ H
773
* Effect: moves the cursor to upper left corner
774
*
775
* ED2 (Clear entire screen)
776
* Sequence: ESC [ 2 J
777
* Effect: clear the whole screen
778
*
779
* == For highlighting control characters, we also use the following two ==
780
* SO (enter StandOut)
781
* Sequence: ESC [ 7 m
782
* Effect: Uses some standout mode such as reverse video
783
*
784
* SE (Standout End)
785
* Sequence: ESC [ 0 m
786
* Effect: Exit standout mode
787
*
788
* == Only used if TIOCGWINSZ fails ==
789
* DSR/CPR (Report cursor position)
790
* Sequence: ESC [ 6 n
791
* Effect: reports current cursor position as ESC [ NNN ; MMM R
792
*
793
* == Only used in multiline mode ==
794
* CUU (Cursor Up)
795
* Sequence: ESC [ n A
796
* Effect: moves cursor up n chars.
797
*
798
* CUD (Cursor Down)
799
* Sequence: ESC [ n B
800
* Effect: moves cursor down n chars.
801
*
802
* win32/console
803
* -------------
804
* If __MINGW32__ is defined, the win32 console API is used.
805
* This could probably be made to work for the msvc compiler too.
806
* This support based in part on work by Jon Griffiths.
807
*/
808
809
#ifdef _WIN32 /* Windows platform, either MinGW or Visual Studio (MSVC) */
810
#include <windows.h>
811
#include <fcntl.h>
812
#define USE_WINCONSOLE
813
#ifdef __MINGW32__
814
#define HAVE_UNISTD_H
815
#endif
816
#else
817
#include <termios.h>
818
#include <sys/ioctl.h>
819
#include <poll.h>
820
#define USE_TERMIOS
821
#define HAVE_UNISTD_H
822
#endif
823
824
#ifdef HAVE_UNISTD_H
825
#include <unistd.h>
826
#endif
827
#include <stdlib.h>
828
#include <stdarg.h>
829
#include <stdio.h>
830
#include <assert.h>
831
#include <errno.h>
832
#include <string.h>
833
#include <signal.h>
834
#include <stdlib.h>
835
#include <sys/types.h>
836
837
#if defined(_WIN32) && !defined(__MINGW32__)
838
/* Microsoft headers don't like old POSIX names */
839
#define strdup _strdup
840
#define snprintf _snprintf
841
#endif
842
843
#include "linenoise.h"
844
#ifndef STRINGBUF_H
845
#include "stringbuf.h"
846
#endif
847
#ifndef UTF8_UTIL_H
848
#include "utf8.h"
849
#endif
850
851
#define LINENOISE_DEFAULT_HISTORY_MAX_LEN 100
852
853
/* ctrl('A') -> 0x01 */
854
#define ctrl(C) ((C) - '@')
855
/* meta('a') -> 0xe1 */
856
#define meta(C) ((C) | 0x80)
857
858
/* Use -ve numbers here to co-exist with normal unicode chars */
859
enum {
860
SPECIAL_NONE,
861
/* don't use -1 here since that indicates error */
862
SPECIAL_UP = -20,
863
SPECIAL_DOWN = -21,
864
SPECIAL_LEFT = -22,
865
SPECIAL_RIGHT = -23,
866
SPECIAL_DELETE = -24,
867
SPECIAL_HOME = -25,
868
SPECIAL_END = -26,
869
SPECIAL_INSERT = -27,
870
SPECIAL_PAGE_UP = -28,
871
SPECIAL_PAGE_DOWN = -29,
872
873
/* Some handy names for other special keycodes */
874
CHAR_ESCAPE = 27,
875
CHAR_DELETE = 127,
876
};
877
878
static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN;
879
static int history_len = 0;
880
static int history_index = 0;
881
static char **history = NULL;
882
883
/* Structure to contain the status of the current (being edited) line */
884
struct current {
885
stringbuf *buf; /* Current buffer. Always null terminated */
886
int pos; /* Cursor position, measured in chars */
887
int cols; /* Size of the window, in chars */
888
int nrows; /* How many rows are being used in multiline mode (>= 1) */
889
int rpos; /* The current row containing the cursor - multiline mode only */
890
int colsright; /* refreshLine() cached cols for insert_char() optimisation */
891
int colsleft; /* refreshLine() cached cols for remove_char() optimisation */
892
const char *prompt;
893
stringbuf *capture; /* capture buffer, or NULL for none. Always null terminated */
894
stringbuf *output; /* used only during refreshLine() - output accumulator */
895
#if defined(USE_TERMIOS)
896
int fd; /* Terminal fd */
897
int pending; /* pending char fd_read_char() */
898
#elif defined(USE_WINCONSOLE)
899
HANDLE outh; /* Console output handle */
900
HANDLE inh; /* Console input handle */
901
int rows; /* Screen rows */
902
int x; /* Current column during output */
903
int y; /* Current row */
904
#ifdef USE_UTF8
905
#define UBUF_MAX_CHARS 132
906
WORD ubuf[UBUF_MAX_CHARS + 1]; /* Accumulates utf16 output - one extra for final surrogate pairs */
907
int ubuflen; /* length used in ubuf */
908
int ubufcols; /* how many columns are represented by the chars in ubuf? */
909
#endif
910
#endif
911
};
912
913
static int fd_read(struct current *current);
914
static int getWindowSize(struct current *current);
915
static void cursorDown(struct current *current, int n);
916
static void cursorUp(struct current *current, int n);
917
static void eraseEol(struct current *current);
918
static void refreshLine(struct current *current);
919
static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos);
920
static void setCursorPos(struct current *current, int x);
921
static void setOutputHighlight(struct current *current, const int *props, int nprops);
922
static void set_current(struct current *current, const char *str);
923
924
static int fd_isatty(struct current *current)
925
{
926
#ifdef USE_TERMIOS
927
return isatty(current->fd);
928
#else
929
(void)current;
930
return 0;
931
#endif
932
}
933
934
void linenoiseHistoryFree(void) {
935
if (history) {
936
int j;
937
938
for (j = 0; j < history_len; j++)
939
free(history[j]);
940
free(history);
941
history = NULL;
942
history_len = 0;
943
}
944
}
945
946
typedef enum {
947
EP_START, /* looking for ESC */
948
EP_ESC, /* looking for [ */
949
EP_DIGITS, /* parsing digits */
950
EP_PROPS, /* parsing digits or semicolons */
951
EP_END, /* ok */
952
EP_ERROR, /* error */
953
} ep_state_t;
954
955
struct esc_parser {
956
ep_state_t state;
957
int props[5]; /* properties are stored here */
958
int maxprops; /* size of the props[] array */
959
int numprops; /* number of properties found */
960
int termchar; /* terminator char, or 0 for any alpha */
961
int current; /* current (partial) property value */
962
};
963
964
/**
965
* Initialise the escape sequence parser at *parser.
966
*
967
* If termchar is 0 any alpha char terminates ok. Otherwise only the given
968
* char terminates successfully.
969
* Run the parser state machine with calls to parseEscapeSequence() for each char.
970
*/
971
static void initParseEscapeSeq(struct esc_parser *parser, int termchar)
972
{
973
parser->state = EP_START;
974
parser->maxprops = sizeof(parser->props) / sizeof(*parser->props);
975
parser->numprops = 0;
976
parser->current = 0;
977
parser->termchar = termchar;
978
}
979
980
/**
981
* Pass character 'ch' into the state machine to parse:
982
* 'ESC' '[' <digits> (';' <digits>)* <termchar>
983
*
984
* The first character must be ESC.
985
* Returns the current state. The state machine is done when it returns either EP_END
986
* or EP_ERROR.
987
*
988
* On EP_END, the "property/attribute" values can be read from parser->props[]
989
* of length parser->numprops.
990
*/
991
static int parseEscapeSequence(struct esc_parser *parser, int ch)
992
{
993
switch (parser->state) {
994
case EP_START:
995
parser->state = (ch == '\x1b') ? EP_ESC : EP_ERROR;
996
break;
997
case EP_ESC:
998
parser->state = (ch == '[') ? EP_DIGITS : EP_ERROR;
999
break;
1000
case EP_PROPS:
1001
if (ch == ';') {
1002
parser->state = EP_DIGITS;
1003
donedigits:
1004
if (parser->numprops + 1 < parser->maxprops) {
1005
parser->props[parser->numprops++] = parser->current;
1006
parser->current = 0;
1007
}
1008
break;
1009
}
1010
/* fall through */
1011
case EP_DIGITS:
1012
if (ch >= '0' && ch <= '9') {
1013
parser->current = parser->current * 10 + (ch - '0');
1014
parser->state = EP_PROPS;
1015
break;
1016
}
1017
/* must be terminator */
1018
if (parser->termchar != ch) {
1019
if (parser->termchar != 0 || !((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
1020
parser->state = EP_ERROR;
1021
break;
1022
}
1023
}
1024
parser->state = EP_END;
1025
goto donedigits;
1026
case EP_END:
1027
parser->state = EP_ERROR;
1028
break;
1029
case EP_ERROR:
1030
break;
1031
}
1032
return parser->state;
1033
}
1034
1035
/*#define DEBUG_REFRESHLINE*/
1036
1037
#ifdef DEBUG_REFRESHLINE
1038
#define DRL(ARGS...) fprintf(dfh, ARGS)
1039
static FILE *dfh;
1040
1041
static void DRL_CHAR(int ch)
1042
{
1043
if (ch < ' ') {
1044
DRL("^%c", ch + '@');
1045
}
1046
else if (ch > 127) {
1047
DRL("\\u%04x", ch);
1048
}
1049
else {
1050
DRL("%c", ch);
1051
}
1052
}
1053
static void DRL_STR(const char *str)
1054
{
1055
while (*str) {
1056
int ch;
1057
int n = utf8_tounicode(str, &ch);
1058
str += n;
1059
DRL_CHAR(ch);
1060
}
1061
}
1062
#else
1063
#define DRL(...)
1064
#define DRL_CHAR(ch)
1065
#define DRL_STR(str)
1066
#endif
1067
1068
#if defined(USE_WINCONSOLE)
1069
#include "linenoise-win32.c"
1070
#endif
1071
1072
#if defined(USE_TERMIOS)
1073
static void linenoiseAtExit(void);
1074
static struct termios orig_termios; /* in order to restore at exit */
1075
static int rawmode = 0; /* for atexit() function to check if restore is needed*/
1076
static int atexit_registered = 0; /* register atexit just 1 time */
1077
1078
static const char *unsupported_term[] = {"dumb","cons25","emacs",NULL};
1079
1080
static int isUnsupportedTerm(void) {
1081
char *term = getenv("TERM");
1082
1083
if (term) {
1084
int j;
1085
for (j = 0; unsupported_term[j]; j++) {
1086
if (strcmp(term, unsupported_term[j]) == 0) {
1087
return 1;
1088
}
1089
}
1090
}
1091
return 0;
1092
}
1093
1094
static int enableRawMode(struct current *current) {
1095
struct termios raw;
1096
1097
current->fd = STDIN_FILENO;
1098
current->cols = 0;
1099
1100
if (!isatty(current->fd) || isUnsupportedTerm() ||
1101
tcgetattr(current->fd, &orig_termios) == -1) {
1102
fatal:
1103
errno = ENOTTY;
1104
return -1;
1105
}
1106
1107
if (!atexit_registered) {
1108
atexit(linenoiseAtExit);
1109
atexit_registered = 1;
1110
}
1111
1112
raw = orig_termios; /* modify the original mode */
1113
/* input modes: no break, no CR to NL, no parity check, no strip char,
1114
* no start/stop output control. */
1115
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
1116
/* output modes - actually, no need to disable post processing */
1117
/*raw.c_oflag &= ~(OPOST);*/
1118
/* control modes - set 8 bit chars */
1119
raw.c_cflag |= (CS8);
1120
/* local modes - choing off, canonical off, no extended functions,
1121
* no signal chars (^Z,^C) */
1122
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
1123
/* control chars - set return condition: min number of bytes and timer.
1124
* We want read to return every single byte, without timeout. */
1125
raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
1126
1127
/* put terminal in raw mode. Because we aren't changing any output
1128
* settings we don't need to use TCSADRAIN and I have seen that hang on
1129
* OpenBSD when running under a pty
1130
*/
1131
if (tcsetattr(current->fd,TCSANOW,&raw) < 0) {
1132
goto fatal;
1133
}
1134
rawmode = 1;
1135
return 0;
1136
}
1137
1138
static void disableRawMode(struct current *current) {
1139
/* Don't even check the return value as it's too late. */
1140
if (rawmode && tcsetattr(current->fd,TCSANOW,&orig_termios) != -1)
1141
rawmode = 0;
1142
}
1143
1144
/* At exit we'll try to fix the terminal to the initial conditions. */
1145
static void linenoiseAtExit(void) {
1146
if (rawmode) {
1147
tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
1148
}
1149
linenoiseHistoryFree();
1150
}
1151
1152
/* gcc/glibc insists that we care about the return code of write!
1153
* Clarification: This means that a void-cast like "(void) (EXPR)"
1154
* does not work.
1155
*/
1156
#define IGNORE_RC(EXPR) if (EXPR) {}
1157
1158
/**
1159
* Output bytes directly, or accumulate output (if current->output is set)
1160
*/
1161
static void outputChars(struct current *current, const char *buf, int len)
1162
{
1163
if (len < 0) {
1164
len = strlen(buf);
1165
}
1166
if (current->output) {
1167
sb_append_len(current->output, buf, len);
1168
}
1169
else {
1170
IGNORE_RC(write(current->fd, buf, len));
1171
}
1172
}
1173
1174
/* Like outputChars, but using printf-style formatting
1175
*/
1176
static void outputFormatted(struct current *current, const char *format, ...)
1177
{
1178
va_list args;
1179
char buf[64];
1180
int n;
1181
1182
va_start(args, format);
1183
n = vsnprintf(buf, sizeof(buf), format, args);
1184
/* This will never happen because we are sure to use outputFormatted() only for short sequences */
1185
assert(n < (int)sizeof(buf));
1186
va_end(args);
1187
outputChars(current, buf, n);
1188
}
1189
1190
static void cursorToLeft(struct current *current)
1191
{
1192
outputChars(current, "\r", -1);
1193
}
1194
1195
static void setOutputHighlight(struct current *current, const int *props, int nprops)
1196
{
1197
outputChars(current, "\x1b[", -1);
1198
while (nprops--) {
1199
outputFormatted(current, "%d%c", *props, (nprops == 0) ? 'm' : ';');
1200
props++;
1201
}
1202
}
1203
1204
static void eraseEol(struct current *current)
1205
{
1206
outputChars(current, "\x1b[0K", -1);
1207
}
1208
1209
static void setCursorPos(struct current *current, int x)
1210
{
1211
if (x == 0) {
1212
cursorToLeft(current);
1213
}
1214
else {
1215
outputFormatted(current, "\r\x1b[%dC", x);
1216
}
1217
}
1218
1219
static void cursorUp(struct current *current, int n)
1220
{
1221
if (n) {
1222
outputFormatted(current, "\x1b[%dA", n);
1223
}
1224
}
1225
1226
static void cursorDown(struct current *current, int n)
1227
{
1228
if (n) {
1229
outputFormatted(current, "\x1b[%dB", n);
1230
}
1231
}
1232
1233
void linenoiseClearScreen(void)
1234
{
1235
IGNORE_RC(write(STDOUT_FILENO, "\x1b[H\x1b[2J", 7));
1236
}
1237
1238
/**
1239
* Reads a char from 'current->fd', waiting at most 'timeout' milliseconds.
1240
*
1241
* A timeout of -1 means to wait forever.
1242
*
1243
* Returns -1 if no char is received within the time or an error occurs.
1244
*/
1245
static int fd_read_char(struct current *current, int timeout)
1246
{
1247
struct pollfd p;
1248
unsigned char c;
1249
1250
if (current->pending) {
1251
c = current->pending;
1252
current->pending = 0;
1253
return c;
1254
}
1255
1256
p.fd = current->fd;
1257
p.events = POLLIN;
1258
1259
if (poll(&p, 1, timeout) == 0) {
1260
/* timeout */
1261
return -1;
1262
}
1263
if (read(current->fd, &c, 1) != 1) {
1264
return -1;
1265
}
1266
return c;
1267
}
1268
1269
/**
1270
* Reads a complete utf-8 character
1271
* and returns the unicode value, or -1 on error.
1272
*/
1273
static int fd_read(struct current *current)
1274
{
1275
#ifdef USE_UTF8
1276
char buf[MAX_UTF8_LEN];
1277
int n;
1278
int i;
1279
int c;
1280
1281
if (current->pending) {
1282
buf[0] = current->pending;
1283
current->pending = 0;
1284
}
1285
else if (read(current->fd, &buf[0], 1) != 1) {
1286
return -1;
1287
}
1288
n = utf8_charlen(buf[0]);
1289
if (n < 1) {
1290
return -1;
1291
}
1292
for (i = 1; i < n; i++) {
1293
if (read(current->fd, &buf[i], 1) != 1) {
1294
return -1;
1295
}
1296
}
1297
/* decode and return the character */
1298
utf8_tounicode(buf, &c);
1299
return c;
1300
#else
1301
return fd_read_char(current, -1);
1302
#endif
1303
}
1304
1305
1306
/**
1307
* Stores the current cursor column in '*cols'.
1308
* Returns 1 if OK, or 0 if failed to determine cursor pos.
1309
*/
1310
static int queryCursor(struct current *current, int* cols)
1311
{
1312
struct esc_parser parser;
1313
int ch;
1314
/* Unfortunately we don't have any persistent state, so assume
1315
* a process will only ever interact with one terminal at a time.
1316
*/
1317
static int query_cursor_failed;
1318
1319
if (query_cursor_failed) {
1320
/* If it ever fails, don't try again */
1321
return 0;
1322
}
1323
1324
/* Should not be buffering this output, it needs to go immediately */
1325
assert(current->output == NULL);
1326
1327
/* control sequence - report cursor location */
1328
outputChars(current, "\x1b[6n", -1);
1329
1330
/* Parse the response: ESC [ rows ; cols R */
1331
initParseEscapeSeq(&parser, 'R');
1332
while ((ch = fd_read_char(current, 100)) > 0) {
1333
switch (parseEscapeSequence(&parser, ch)) {
1334
default:
1335
continue;
1336
case EP_END:
1337
if (parser.numprops == 2 && parser.props[1] < 1000) {
1338
*cols = parser.props[1];
1339
return 1;
1340
}
1341
break;
1342
case EP_ERROR:
1343
/* Push back the character that caused the error */
1344
current->pending = ch;
1345
break;
1346
}
1347
/* failed */
1348
break;
1349
}
1350
query_cursor_failed = 1;
1351
return 0;
1352
}
1353
1354
/**
1355
* Updates current->cols with the current window size (width)
1356
*/
1357
static int getWindowSize(struct current *current)
1358
{
1359
struct winsize ws;
1360
1361
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col != 0) {
1362
current->cols = ws.ws_col;
1363
return 0;
1364
}
1365
1366
/* Failed to query the window size. Perhaps we are on a serial terminal.
1367
* Try to query the width by sending the cursor as far to the right
1368
* and reading back the cursor position.
1369
* Note that this is only done once per call to linenoise rather than
1370
* every time the line is refreshed for efficiency reasons.
1371
*
1372
* In more detail, we:
1373
* (a) request current cursor position,
1374
* (b) move cursor far right,
1375
* (c) request cursor position again,
1376
* (d) at last move back to the old position.
1377
* This gives us the width without messing with the externally
1378
* visible cursor position.
1379
*/
1380
1381
if (current->cols == 0) {
1382
int here;
1383
1384
/* If anything fails => default 80 */
1385
current->cols = 80;
1386
1387
/* (a) */
1388
if (queryCursor (current, &here)) {
1389
/* (b) */
1390
setCursorPos(current, 999);
1391
1392
/* (c). Note: If (a) succeeded, then (c) should as well.
1393
* For paranoia we still check and have a fallback action
1394
* for (d) in case of failure..
1395
*/
1396
if (queryCursor (current, &current->cols)) {
1397
/* (d) Reset the cursor back to the original location. */
1398
if (current->cols > here) {
1399
setCursorPos(current, here);
1400
}
1401
}
1402
}
1403
}
1404
1405
return 0;
1406
}
1407
1408
/**
1409
* If CHAR_ESCAPE was received, reads subsequent
1410
* chars to determine if this is a known special key.
1411
*
1412
* Returns SPECIAL_NONE if unrecognised, or -1 if EOF.
1413
*
1414
* If no additional char is received within a short time,
1415
* CHAR_ESCAPE is returned.
1416
*/
1417
static int check_special(struct current *current)
1418
{
1419
int c = fd_read_char(current, 50);
1420
int c2;
1421
1422
if (c < 0) {
1423
return CHAR_ESCAPE;
1424
}
1425
else if (c >= 'a' && c <= 'z') {
1426
/* esc-a => meta-a */
1427
return meta(c);
1428
}
1429
1430
c2 = fd_read_char(current, 50);
1431
if (c2 < 0) {
1432
return c2;
1433
}
1434
if (c == '[' || c == 'O') {
1435
/* Potential arrow key */
1436
switch (c2) {
1437
case 'A':
1438
return SPECIAL_UP;
1439
case 'B':
1440
return SPECIAL_DOWN;
1441
case 'C':
1442
return SPECIAL_RIGHT;
1443
case 'D':
1444
return SPECIAL_LEFT;
1445
case 'F':
1446
return SPECIAL_END;
1447
case 'H':
1448
return SPECIAL_HOME;
1449
}
1450
}
1451
if (c == '[' && c2 >= '1' && c2 <= '8') {
1452
/* extended escape */
1453
c = fd_read_char(current, 50);
1454
if (c == '~') {
1455
switch (c2) {
1456
case '2':
1457
return SPECIAL_INSERT;
1458
case '3':
1459
return SPECIAL_DELETE;
1460
case '5':
1461
return SPECIAL_PAGE_UP;
1462
case '6':
1463
return SPECIAL_PAGE_DOWN;
1464
case '7':
1465
return SPECIAL_HOME;
1466
case '8':
1467
return SPECIAL_END;
1468
}
1469
}
1470
while (c != -1 && c != '~') {
1471
/* .e.g \e[12~ or '\e[11;2~ discard the complete sequence */
1472
c = fd_read_char(current, 50);
1473
}
1474
}
1475
1476
return SPECIAL_NONE;
1477
}
1478
#endif
1479
1480
static void clearOutputHighlight(struct current *current)
1481
{
1482
int nohighlight = 0;
1483
setOutputHighlight(current, &nohighlight, 1);
1484
}
1485
1486
static void outputControlChar(struct current *current, char ch)
1487
{
1488
int reverse = 7;
1489
setOutputHighlight(current, &reverse, 1);
1490
outputChars(current, "^", 1);
1491
outputChars(current, &ch, 1);
1492
clearOutputHighlight(current);
1493
}
1494
1495
#ifndef utf8_getchars
1496
static int utf8_getchars(char *buf, int c)
1497
{
1498
#ifdef USE_UTF8
1499
return utf8_fromunicode(buf, c);
1500
#else
1501
*buf = c;
1502
return 1;
1503
#endif
1504
}
1505
#endif
1506
1507
/**
1508
* Returns the unicode character at the given offset,
1509
* or -1 if none.
1510
*/
1511
static int get_char(struct current *current, int pos)
1512
{
1513
if (pos >= 0 && pos < sb_chars(current->buf)) {
1514
int c;
1515
int i = utf8_index(sb_str(current->buf), pos);
1516
(void)utf8_tounicode(sb_str(current->buf) + i, &c);
1517
return c;
1518
}
1519
return -1;
1520
}
1521
1522
static int char_display_width(int ch)
1523
{
1524
if (ch < ' ') {
1525
/* control chars take two positions */
1526
return 2;
1527
}
1528
else {
1529
return utf8_width(ch);
1530
}
1531
}
1532
1533
#ifndef NO_COMPLETION
1534
static linenoiseCompletionCallback *completionCallback = NULL;
1535
static void *completionUserdata = NULL;
1536
static int showhints = 1;
1537
static linenoiseHintsCallback *hintsCallback = NULL;
1538
static linenoiseFreeHintsCallback *freeHintsCallback = NULL;
1539
static void *hintsUserdata = NULL;
1540
1541
static void beep(void) {
1542
#ifdef USE_TERMIOS
1543
fprintf(stderr, "\x7");
1544
fflush(stderr);
1545
#endif
1546
}
1547
1548
static void freeCompletions(linenoiseCompletions *lc) {
1549
size_t i;
1550
for (i = 0; i < lc->len; i++)
1551
free(lc->cvec[i]);
1552
free(lc->cvec);
1553
}
1554
1555
static int completeLine(struct current *current) {
1556
linenoiseCompletions lc = { 0, NULL };
1557
int c = 0;
1558
1559
completionCallback(sb_str(current->buf),&lc,completionUserdata);
1560
if (lc.len == 0) {
1561
beep();
1562
} else {
1563
size_t stop = 0, i = 0;
1564
1565
while(!stop) {
1566
/* Show completion or original buffer */
1567
if (i < lc.len) {
1568
int chars = utf8_strlen(lc.cvec[i], -1);
1569
refreshLineAlt(current, current->prompt, lc.cvec[i], chars);
1570
} else {
1571
refreshLine(current);
1572
}
1573
1574
c = fd_read(current);
1575
if (c == -1) {
1576
break;
1577
}
1578
1579
switch(c) {
1580
case '\t': /* tab */
1581
i = (i+1) % (lc.len+1);
1582
if (i == lc.len) beep();
1583
break;
1584
case CHAR_ESCAPE: /* escape */
1585
/* Re-show original buffer */
1586
if (i < lc.len) {
1587
refreshLine(current);
1588
}
1589
stop = 1;
1590
break;
1591
default:
1592
/* Update buffer and return */
1593
if (i < lc.len) {
1594
set_current(current,lc.cvec[i]);
1595
}
1596
stop = 1;
1597
break;
1598
}
1599
}
1600
}
1601
1602
freeCompletions(&lc);
1603
return c; /* Return last read character */
1604
}
1605
1606
/* Register a callback function to be called for tab-completion.
1607
Returns the prior callback so that the caller may (if needed)
1608
restore it when done. */
1609
linenoiseCompletionCallback * linenoiseSetCompletionCallback(linenoiseCompletionCallback *fn, void *userdata) {
1610
linenoiseCompletionCallback * old = completionCallback;
1611
completionCallback = fn;
1612
completionUserdata = userdata;
1613
return old;
1614
}
1615
1616
void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) {
1617
lc->cvec = (char **)realloc(lc->cvec,sizeof(char*)*(lc->len+1));
1618
lc->cvec[lc->len++] = strdup(str);
1619
}
1620
1621
void linenoiseSetHintsCallback(linenoiseHintsCallback *callback, void *userdata)
1622
{
1623
hintsCallback = callback;
1624
hintsUserdata = userdata;
1625
}
1626
1627
void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *callback)
1628
{
1629
freeHintsCallback = callback;
1630
}
1631
1632
#endif
1633
1634
1635
static const char *reduceSingleBuf(const char *buf, int availcols, int *cursor_pos)
1636
{
1637
/* We have availcols columns available.
1638
* If necessary, strip chars off the front of buf until *cursor_pos
1639
* fits within availcols
1640
*/
1641
int needcols = 0;
1642
int pos = 0;
1643
int new_cursor_pos = *cursor_pos;
1644
const char *pt = buf;
1645
1646
DRL("reduceSingleBuf: availcols=%d, cursor_pos=%d\n", availcols, *cursor_pos);
1647
1648
while (*pt) {
1649
int ch;
1650
int n = utf8_tounicode(pt, &ch);
1651
pt += n;
1652
1653
needcols += char_display_width(ch);
1654
1655
/* If we need too many cols, strip
1656
* chars off the front of buf to make it fit.
1657
* We keep 3 extra cols to the right of the cursor.
1658
* 2 for possible wide chars, 1 for the last column that
1659
* can't be used.
1660
*/
1661
while (needcols >= availcols - 3) {
1662
n = utf8_tounicode(buf, &ch);
1663
buf += n;
1664
needcols -= char_display_width(ch);
1665
DRL_CHAR(ch);
1666
1667
/* and adjust the apparent cursor position */
1668
new_cursor_pos--;
1669
1670
if (buf == pt) {
1671
/* can't remove more than this */
1672
break;
1673
}
1674
}
1675
1676
if (pos++ == *cursor_pos) {
1677
break;
1678
}
1679
1680
}
1681
DRL("<snip>");
1682
DRL_STR(buf);
1683
DRL("\nafter reduce, needcols=%d, new_cursor_pos=%d\n", needcols, new_cursor_pos);
1684
1685
/* Done, now new_cursor_pos contains the adjusted cursor position
1686
* and buf points to he adjusted start
1687
*/
1688
*cursor_pos = new_cursor_pos;
1689
return buf;
1690
}
1691
1692
static int mlmode = 0;
1693
1694
void linenoiseSetMultiLine(int enableml)
1695
{
1696
mlmode = enableml;
1697
}
1698
1699
/* Helper of refreshSingleLine() and refreshMultiLine() to show hints
1700
* to the right of the prompt.
1701
* Returns 1 if a hint was shown, or 0 if not
1702
* If 'display' is 0, does no output. Just returns the appropriate return code.
1703
*/
1704
static int refreshShowHints(struct current *current, const char *buf, int availcols, int display)
1705
{
1706
int rc = 0;
1707
if (showhints && hintsCallback && availcols > 0) {
1708
int bold = 0;
1709
int color = -1;
1710
char *hint = hintsCallback(buf, &color, &bold, hintsUserdata);
1711
if (hint) {
1712
rc = 1;
1713
if (display) {
1714
const char *pt;
1715
if (bold == 1 && color == -1) color = 37;
1716
if (bold || color > 0) {
1717
int props[3] = { bold, color, 49 }; /* bold, color, fgnormal */
1718
setOutputHighlight(current, props, 3);
1719
}
1720
DRL("<hint bold=%d,color=%d>", bold, color);
1721
pt = hint;
1722
while (*pt) {
1723
int ch;
1724
int n = utf8_tounicode(pt, &ch);
1725
int width = char_display_width(ch);
1726
1727
if (width >= availcols) {
1728
DRL("<hinteol>");
1729
break;
1730
}
1731
DRL_CHAR(ch);
1732
1733
availcols -= width;
1734
outputChars(current, pt, n);
1735
pt += n;
1736
}
1737
if (bold || color > 0) {
1738
clearOutputHighlight(current);
1739
}
1740
/* Call the function to free the hint returned. */
1741
if (freeHintsCallback) freeHintsCallback(hint, hintsUserdata);
1742
}
1743
}
1744
}
1745
return rc;
1746
}
1747
1748
#ifdef USE_TERMIOS
1749
static void refreshStart(struct current *current)
1750
{
1751
/* We accumulate all output here */
1752
assert(current->output == NULL);
1753
current->output = sb_alloc();
1754
}
1755
1756
static void refreshEnd(struct current *current)
1757
{
1758
/* Output everything at once */
1759
IGNORE_RC(write(current->fd, sb_str(current->output), sb_len(current->output)));
1760
sb_free(current->output);
1761
current->output = NULL;
1762
}
1763
1764
static void refreshStartChars(struct current *current)
1765
{
1766
(void)current;
1767
}
1768
1769
static void refreshNewline(struct current *current)
1770
{
1771
DRL("<nl>");
1772
outputChars(current, "\n", 1);
1773
}
1774
1775
static void refreshEndChars(struct current *current)
1776
{
1777
(void)current;
1778
}
1779
#endif
1780
1781
static void refreshLineAlt(struct current *current, const char *prompt, const char *buf, int cursor_pos)
1782
{
1783
int i;
1784
const char *pt;
1785
int displaycol;
1786
int displayrow;
1787
int visible;
1788
int currentpos;
1789
int notecursor;
1790
int cursorcol = 0;
1791
int cursorrow = 0;
1792
int hint;
1793
struct esc_parser parser;
1794
1795
#ifdef DEBUG_REFRESHLINE
1796
dfh = fopen("linenoise.debuglog", "a");
1797
#endif
1798
1799
/* Should intercept SIGWINCH. For now, just get the size every time */
1800
getWindowSize(current);
1801
1802
refreshStart(current);
1803
1804
DRL("wincols=%d, cursor_pos=%d, nrows=%d, rpos=%d\n", current->cols, cursor_pos, current->nrows, current->rpos);
1805
1806
/* Here is the plan:
1807
* (a) move the the bottom row, going down the appropriate number of lines
1808
* (b) move to beginning of line and erase the current line
1809
* (c) go up one line and do the same, until we have erased up to the first row
1810
* (d) output the prompt, counting cols and rows, taking into account escape sequences
1811
* (e) output the buffer, counting cols and rows
1812
* (e') when we hit the current pos, save the cursor position
1813
* (f) move the cursor to the saved cursor position
1814
* (g) save the current cursor row and number of rows
1815
*/
1816
1817
/* (a) - The cursor is currently at row rpos */
1818
cursorDown(current, current->nrows - current->rpos - 1);
1819
DRL("<cud=%d>", current->nrows - current->rpos - 1);
1820
1821
/* (b), (c) - Erase lines upwards until we get to the first row */
1822
for (i = 0; i < current->nrows; i++) {
1823
if (i) {
1824
DRL("<cup>");
1825
cursorUp(current, 1);
1826
}
1827
DRL("<clearline>");
1828
cursorToLeft(current);
1829
eraseEol(current);
1830
}
1831
DRL("\n");
1832
1833
/* (d) First output the prompt. control sequences don't take up display space */
1834
pt = prompt;
1835
displaycol = 0; /* current display column */
1836
displayrow = 0; /* current display row */
1837
visible = 1;
1838
1839
refreshStartChars(current);
1840
1841
while (*pt) {
1842
int width;
1843
int ch;
1844
int n = utf8_tounicode(pt, &ch);
1845
1846
if (visible && ch == CHAR_ESCAPE) {
1847
/* The start of an escape sequence, so not visible */
1848
visible = 0;
1849
initParseEscapeSeq(&parser, 'm');
1850
DRL("<esc-seq-start>");
1851
}
1852
1853
if (ch == '\n' || ch == '\r') {
1854
/* treat both CR and NL the same and force wrap */
1855
refreshNewline(current);
1856
displaycol = 0;
1857
displayrow++;
1858
}
1859
else {
1860
width = visible * utf8_width(ch);
1861
1862
displaycol += width;
1863
if (displaycol >= current->cols) {
1864
/* need to wrap to the next line because of newline or if it doesn't fit
1865
* XXX this is a problem in single line mode
1866
*/
1867
refreshNewline(current);
1868
displaycol = width;
1869
displayrow++;
1870
}
1871
1872
DRL_CHAR(ch);
1873
#ifdef USE_WINCONSOLE
1874
if (visible) {
1875
outputChars(current, pt, n);
1876
}
1877
#else
1878
outputChars(current, pt, n);
1879
#endif
1880
}
1881
pt += n;
1882
1883
if (!visible) {
1884
switch (parseEscapeSequence(&parser, ch)) {
1885
case EP_END:
1886
visible = 1;
1887
setOutputHighlight(current, parser.props, parser.numprops);
1888
DRL("<esc-seq-end,numprops=%d>", parser.numprops);
1889
break;
1890
case EP_ERROR:
1891
DRL("<esc-seq-err>");
1892
visible = 1;
1893
break;
1894
}
1895
}
1896
}
1897
1898
/* Now we are at the first line with all lines erased */
1899
DRL("\nafter prompt: displaycol=%d, displayrow=%d\n", displaycol, displayrow);
1900
1901
1902
/* (e) output the buffer, counting cols and rows */
1903
if (mlmode == 0) {
1904
/* In this mode we may need to trim chars from the start of the buffer until the
1905
* cursor fits in the window.
1906
*/
1907
pt = reduceSingleBuf(buf, current->cols - displaycol, &cursor_pos);
1908
}
1909
else {
1910
pt = buf;
1911
}
1912
1913
currentpos = 0;
1914
notecursor = -1;
1915
1916
while (*pt) {
1917
int ch;
1918
int n = utf8_tounicode(pt, &ch);
1919
int width = char_display_width(ch);
1920
1921
if (currentpos == cursor_pos) {
1922
/* (e') wherever we output this character is where we want the cursor */
1923
notecursor = 1;
1924
}
1925
1926
if (displaycol + width >= current->cols) {
1927
if (mlmode == 0) {
1928
/* In single line mode stop once we print as much as we can on one line */
1929
DRL("<slmode>");
1930
break;
1931
}
1932
/* need to wrap to the next line since it doesn't fit */
1933
refreshNewline(current);
1934
displaycol = 0;
1935
displayrow++;
1936
}
1937
1938
if (notecursor == 1) {
1939
/* (e') Save this position as the current cursor position */
1940
cursorcol = displaycol;
1941
cursorrow = displayrow;
1942
notecursor = 0;
1943
DRL("<cursor>");
1944
}
1945
1946
displaycol += width;
1947
1948
if (ch < ' ') {
1949
outputControlChar(current, ch + '@');
1950
}
1951
else {
1952
outputChars(current, pt, n);
1953
}
1954
DRL_CHAR(ch);
1955
if (width != 1) {
1956
DRL("<w=%d>", width);
1957
}
1958
1959
pt += n;
1960
currentpos++;
1961
}
1962
1963
/* If we didn't see the cursor, it is at the current location */
1964
if (notecursor) {
1965
DRL("<cursor>");
1966
cursorcol = displaycol;
1967
cursorrow = displayrow;
1968
}
1969
1970
DRL("\nafter buf: displaycol=%d, displayrow=%d, cursorcol=%d, cursorrow=%d\n", displaycol, displayrow, cursorcol, cursorrow);
1971
1972
/* (f) show hints */
1973
hint = refreshShowHints(current, buf, current->cols - displaycol, 1);
1974
1975
/* Remember how many many cols are available for insert optimisation */
1976
if (prompt == current->prompt && hint == 0) {
1977
current->colsright = current->cols - displaycol;
1978
current->colsleft = displaycol;
1979
}
1980
else {
1981
/* Can't optimise */
1982
current->colsright = 0;
1983
current->colsleft = 0;
1984
}
1985
DRL("\nafter hints: colsleft=%d, colsright=%d\n\n", current->colsleft, current->colsright);
1986
1987
refreshEndChars(current);
1988
1989
/* (g) move the cursor to the correct place */
1990
cursorUp(current, displayrow - cursorrow);
1991
setCursorPos(current, cursorcol);
1992
1993
/* (h) Update the number of rows if larger, but never reduce this */
1994
if (displayrow >= current->nrows) {
1995
current->nrows = displayrow + 1;
1996
}
1997
/* And remember the row that the cursor is on */
1998
current->rpos = cursorrow;
1999
2000
refreshEnd(current);
2001
2002
#ifdef DEBUG_REFRESHLINE
2003
fclose(dfh);
2004
#endif
2005
}
2006
2007
static void refreshLine(struct current *current)
2008
{
2009
refreshLineAlt(current, current->prompt, sb_str(current->buf), current->pos);
2010
}
2011
2012
static void set_current(struct current *current, const char *str)
2013
{
2014
sb_clear(current->buf);
2015
sb_append(current->buf, str);
2016
current->pos = sb_chars(current->buf);
2017
}
2018
2019
/**
2020
* Removes the char at 'pos'.
2021
*
2022
* Returns 1 if the line needs to be refreshed, 2 if not
2023
* and 0 if nothing was removed
2024
*/
2025
static int remove_char(struct current *current, int pos)
2026
{
2027
if (pos >= 0 && pos < sb_chars(current->buf)) {
2028
int offset = utf8_index(sb_str(current->buf), pos);
2029
int nbytes = utf8_index(sb_str(current->buf) + offset, 1);
2030
int rc = 1;
2031
2032
/* Now we try to optimise in the simple but very common case that:
2033
* - outputChars() can be used directly (not win32)
2034
* - we are removing the char at EOL
2035
* - the buffer is not empty
2036
* - there are columns available to the left
2037
* - the char being deleted is not a wide or utf-8 character
2038
* - no hints are being shown
2039
*/
2040
if (current->output && current->pos == pos + 1 && current->pos == sb_chars(current->buf) && pos > 0) {
2041
#ifdef USE_UTF8
2042
/* Could implement utf8_prev_len() but simplest just to not optimise this case */
2043
char last = sb_str(current->buf)[offset];
2044
#else
2045
char last = 0;
2046
#endif
2047
if (current->colsleft > 0 && (last & 0x80) == 0) {
2048
/* Have cols on the left and not a UTF-8 char or continuation */
2049
/* Yes, can optimise */
2050
current->colsleft--;
2051
current->colsright++;
2052
rc = 2;
2053
}
2054
}
2055
2056
sb_delete(current->buf, offset, nbytes);
2057
2058
if (current->pos > pos) {
2059
current->pos--;
2060
}
2061
if (rc == 2) {
2062
if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
2063
/* A hint needs to be shown, so can't optimise after all */
2064
rc = 1;
2065
}
2066
else {
2067
/* optimised output */
2068
outputChars(current, "\b \b", 3);
2069
}
2070
}
2071
return rc;
2072
return 1;
2073
}
2074
return 0;
2075
}
2076
2077
/**
2078
* Insert 'ch' at position 'pos'
2079
*
2080
* Returns 1 if the line needs to be refreshed, 2 if not
2081
* and 0 if nothing was inserted (no room)
2082
*/
2083
static int insert_char(struct current *current, int pos, int ch)
2084
{
2085
if (pos >= 0 && pos <= sb_chars(current->buf)) {
2086
char buf[MAX_UTF8_LEN + 1];
2087
int offset = utf8_index(sb_str(current->buf), pos);
2088
int n = utf8_getchars(buf, ch);
2089
int rc = 1;
2090
2091
/* null terminate since sb_insert() requires it */
2092
buf[n] = 0;
2093
2094
/* Now we try to optimise in the simple but very common case that:
2095
* - outputChars() can be used directly (not win32)
2096
* - we are inserting at EOL
2097
* - there are enough columns available
2098
* - no hints are being shown
2099
*/
2100
if (current->output && pos == current->pos && pos == sb_chars(current->buf)) {
2101
int width = char_display_width(ch);
2102
if (current->colsright > width) {
2103
/* Yes, can optimise */
2104
current->colsright -= width;
2105
current->colsleft -= width;
2106
rc = 2;
2107
}
2108
}
2109
sb_insert(current->buf, offset, buf);
2110
if (current->pos >= pos) {
2111
current->pos++;
2112
}
2113
if (rc == 2) {
2114
if (refreshShowHints(current, sb_str(current->buf), current->colsright, 0)) {
2115
/* A hint needs to be shown, so can't optimise after all */
2116
rc = 1;
2117
}
2118
else {
2119
/* optimised output */
2120
outputChars(current, buf, n);
2121
}
2122
}
2123
return rc;
2124
}
2125
return 0;
2126
}
2127
2128
/**
2129
* Captures up to 'n' characters starting at 'pos' for the cut buffer.
2130
*
2131
* This replaces any existing characters in the cut buffer.
2132
*/
2133
static void capture_chars(struct current *current, int pos, int nchars)
2134
{
2135
if (pos >= 0 && (pos + nchars - 1) < sb_chars(current->buf)) {
2136
int offset = utf8_index(sb_str(current->buf), pos);
2137
int nbytes = utf8_index(sb_str(current->buf) + offset, nchars);
2138
2139
if (nbytes > 0) {
2140
if (current->capture) {
2141
sb_clear(current->capture);
2142
}
2143
else {
2144
current->capture = sb_alloc();
2145
}
2146
sb_append_len(current->capture, sb_str(current->buf) + offset, nbytes);
2147
}
2148
}
2149
}
2150
2151
/**
2152
* Removes up to 'n' characters at cursor position 'pos'.
2153
*
2154
* Returns 0 if no chars were removed or non-zero otherwise.
2155
*/
2156
static int remove_chars(struct current *current, int pos, int n)
2157
{
2158
int removed = 0;
2159
2160
/* First save any chars which will be removed */
2161
capture_chars(current, pos, n);
2162
2163
while (n-- && remove_char(current, pos)) {
2164
removed++;
2165
}
2166
return removed;
2167
}
2168
/**
2169
* Inserts the characters (string) 'chars' at the cursor position 'pos'.
2170
*
2171
* Returns 0 if no chars were inserted or non-zero otherwise.
2172
*/
2173
static int insert_chars(struct current *current, int pos, const char *chars)
2174
{
2175
int inserted = 0;
2176
2177
while (*chars) {
2178
int ch;
2179
int n = utf8_tounicode(chars, &ch);
2180
if (insert_char(current, pos, ch) == 0) {
2181
break;
2182
}
2183
inserted++;
2184
pos++;
2185
chars += n;
2186
}
2187
return inserted;
2188
}
2189
2190
static int skip_space_nonspace(struct current *current, int dir, int check_is_space)
2191
{
2192
int moved = 0;
2193
int checkoffset = (dir < 0) ? -1 : 0;
2194
int limit = (dir < 0) ? 0 : sb_chars(current->buf);
2195
while (current->pos != limit && (get_char(current, current->pos + checkoffset) == ' ') == check_is_space) {
2196
current->pos += dir;
2197
moved++;
2198
}
2199
return moved;
2200
}
2201
2202
static int skip_space(struct current *current, int dir)
2203
{
2204
return skip_space_nonspace(current, dir, 1);
2205
}
2206
2207
static int skip_nonspace(struct current *current, int dir)
2208
{
2209
return skip_space_nonspace(current, dir, 0);
2210
}
2211
2212
static void set_history_index(struct current *current, int new_index)
2213
{
2214
if (history_len > 1) {
2215
/* Update the current history entry before to
2216
* overwrite it with the next one. */
2217
free(history[history_len - 1 - history_index]);
2218
history[history_len - 1 - history_index] = strdup(sb_str(current->buf));
2219
/* Show the new entry */
2220
history_index = new_index;
2221
if (history_index < 0) {
2222
history_index = 0;
2223
} else if (history_index >= history_len) {
2224
history_index = history_len - 1;
2225
} else {
2226
set_current(current, history[history_len - 1 - history_index]);
2227
refreshLine(current);
2228
}
2229
}
2230
}
2231
2232
/**
2233
* Returns the keycode to process, or 0 if none.
2234
*/
2235
static int reverseIncrementalSearch(struct current *current)
2236
{
2237
/* Display the reverse-i-search prompt and process chars */
2238
char rbuf[50];
2239
char rprompt[80];
2240
int rchars = 0;
2241
int rlen = 0;
2242
int searchpos = history_len - 1;
2243
int c;
2244
2245
rbuf[0] = 0;
2246
while (1) {
2247
int n = 0;
2248
const char *p = NULL;
2249
int skipsame = 0;
2250
int searchdir = -1;
2251
2252
snprintf(rprompt, sizeof(rprompt), "(reverse-i-search)'%s': ", rbuf);
2253
refreshLineAlt(current, rprompt, sb_str(current->buf), current->pos);
2254
c = fd_read(current);
2255
if (c == ctrl('H') || c == CHAR_DELETE) {
2256
if (rchars) {
2257
int p_ind = utf8_index(rbuf, --rchars);
2258
rbuf[p_ind] = 0;
2259
rlen = strlen(rbuf);
2260
}
2261
continue;
2262
}
2263
#ifdef USE_TERMIOS
2264
if (c == CHAR_ESCAPE) {
2265
c = check_special(current);
2266
}
2267
#endif
2268
if (c == ctrl('R')) {
2269
/* Search for the previous (earlier) match */
2270
if (searchpos > 0) {
2271
searchpos--;
2272
}
2273
skipsame = 1;
2274
}
2275
else if (c == ctrl('S')) {
2276
/* Search for the next (later) match */
2277
if (searchpos < history_len) {
2278
searchpos++;
2279
}
2280
searchdir = 1;
2281
skipsame = 1;
2282
}
2283
else if (c == ctrl('P') || c == SPECIAL_UP) {
2284
/* Exit Ctrl-R mode and go to the previous history line from the current search pos */
2285
set_history_index(current, history_len - searchpos);
2286
c = 0;
2287
break;
2288
}
2289
else if (c == ctrl('N') || c == SPECIAL_DOWN) {
2290
/* Exit Ctrl-R mode and go to the next history line from the current search pos */
2291
set_history_index(current, history_len - searchpos - 2);
2292
c = 0;
2293
break;
2294
}
2295
else if (c >= ' ' && c <= '~') {
2296
/* >= here to allow for null terminator */
2297
if (rlen >= (int)sizeof(rbuf) - MAX_UTF8_LEN) {
2298
continue;
2299
}
2300
2301
n = utf8_getchars(rbuf + rlen, c);
2302
rlen += n;
2303
rchars++;
2304
rbuf[rlen] = 0;
2305
2306
/* Adding a new char resets the search location */
2307
searchpos = history_len - 1;
2308
}
2309
else {
2310
/* Exit from incremental search mode */
2311
break;
2312
}
2313
2314
/* Now search through the history for a match */
2315
for (; searchpos >= 0 && searchpos < history_len; searchpos += searchdir) {
2316
p = strstr(history[searchpos], rbuf);
2317
if (p) {
2318
/* Found a match */
2319
if (skipsame && strcmp(history[searchpos], sb_str(current->buf)) == 0) {
2320
/* But it is identical, so skip it */
2321
continue;
2322
}
2323
/* Copy the matching line and set the cursor position */
2324
history_index = history_len - 1 - searchpos;
2325
set_current(current,history[searchpos]);
2326
current->pos = utf8_strlen(history[searchpos], p - history[searchpos]);
2327
break;
2328
}
2329
}
2330
if (!p && n) {
2331
/* No match, so don't add it */
2332
rchars--;
2333
rlen -= n;
2334
rbuf[rlen] = 0;
2335
}
2336
}
2337
if (c == ctrl('G') || c == ctrl('C')) {
2338
/* ctrl-g terminates the search with no effect */
2339
set_current(current, "");
2340
history_index = 0;
2341
c = 0;
2342
}
2343
else if (c == ctrl('J')) {
2344
/* ctrl-j terminates the search leaving the buffer in place */
2345
history_index = 0;
2346
c = 0;
2347
}
2348
/* Go process the char normally */
2349
refreshLine(current);
2350
return c;
2351
}
2352
2353
static int linenoiseEdit(struct current *current) {
2354
history_index = 0;
2355
2356
refreshLine(current);
2357
2358
while(1) {
2359
int c = fd_read(current);
2360
2361
#ifndef NO_COMPLETION
2362
/* Only autocomplete when the callback is set. It returns < 0 when
2363
* there was an error reading from fd. Otherwise it will return the
2364
* character that should be handled next. */
2365
if (c == '\t' && current->pos == sb_chars(current->buf) && completionCallback != NULL) {
2366
c = completeLine(current);
2367
}
2368
#endif
2369
if (c == ctrl('R')) {
2370
/* reverse incremental search will provide an alternative keycode or 0 for none */
2371
c = reverseIncrementalSearch(current);
2372
/* go on to process the returned char normally */
2373
}
2374
2375
#ifdef USE_TERMIOS
2376
if (c == CHAR_ESCAPE) { /* escape sequence */
2377
c = check_special(current);
2378
}
2379
#endif
2380
if (c == -1) {
2381
/* Return on errors */
2382
return sb_len(current->buf);
2383
}
2384
2385
switch(c) {
2386
case SPECIAL_NONE:
2387
break;
2388
case '\r': /* enter/CR */
2389
case '\n': /* LF */
2390
history_len--;
2391
free(history[history_len]);
2392
current->pos = sb_chars(current->buf);
2393
if (mlmode || hintsCallback) {
2394
showhints = 0;
2395
refreshLine(current);
2396
showhints = 1;
2397
}
2398
return sb_len(current->buf);
2399
case ctrl('C'): /* ctrl-c */
2400
errno = EAGAIN;
2401
return -1;
2402
case ctrl('Z'): /* ctrl-z */
2403
#ifdef SIGTSTP
2404
/* send ourselves SIGSUSP */
2405
disableRawMode(current);
2406
raise(SIGTSTP);
2407
/* and resume */
2408
enableRawMode(current);
2409
refreshLine(current);
2410
#endif
2411
continue;
2412
case CHAR_DELETE: /* backspace */
2413
case ctrl('H'):
2414
if (remove_char(current, current->pos - 1) == 1) {
2415
refreshLine(current);
2416
}
2417
break;
2418
case ctrl('D'): /* ctrl-d */
2419
if (sb_len(current->buf) == 0) {
2420
/* Empty line, so EOF */
2421
history_len--;
2422
free(history[history_len]);
2423
return -1;
2424
}
2425
/* Otherwise fall through to delete char to right of cursor */
2426
/* fall-thru */
2427
case SPECIAL_DELETE:
2428
if (remove_char(current, current->pos) == 1) {
2429
refreshLine(current);
2430
}
2431
break;
2432
case SPECIAL_INSERT:
2433
/* Ignore. Expansion Hook.
2434
* Future possibility: Toggle Insert/Overwrite Modes
2435
*/
2436
break;
2437
case meta('b'): /* meta-b, move word left */
2438
if (skip_nonspace(current, -1)) {
2439
refreshLine(current);
2440
}
2441
else if (skip_space(current, -1)) {
2442
skip_nonspace(current, -1);
2443
refreshLine(current);
2444
}
2445
break;
2446
case meta('f'): /* meta-f, move word right */
2447
if (skip_space(current, 1)) {
2448
refreshLine(current);
2449
}
2450
else if (skip_nonspace(current, 1)) {
2451
skip_space(current, 1);
2452
refreshLine(current);
2453
}
2454
break;
2455
case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */
2456
/* eat any spaces on the left */
2457
{
2458
int pos = current->pos;
2459
while (pos > 0 && get_char(current, pos - 1) == ' ') {
2460
pos--;
2461
}
2462
2463
/* now eat any non-spaces on the left */
2464
while (pos > 0 && get_char(current, pos - 1) != ' ') {
2465
pos--;
2466
}
2467
2468
if (remove_chars(current, pos, current->pos - pos)) {
2469
refreshLine(current);
2470
}
2471
}
2472
break;
2473
case ctrl('T'): /* ctrl-t */
2474
if (current->pos > 0 && current->pos <= sb_chars(current->buf)) {
2475
/* If cursor is at end, transpose the previous two chars */
2476
int fixer = (current->pos == sb_chars(current->buf));
2477
c = get_char(current, current->pos - fixer);
2478
remove_char(current, current->pos - fixer);
2479
insert_char(current, current->pos - 1, c);
2480
refreshLine(current);
2481
}
2482
break;
2483
case ctrl('V'): /* ctrl-v */
2484
/* Insert the ^V first */
2485
if (insert_char(current, current->pos, c)) {
2486
refreshLine(current);
2487
/* Now wait for the next char. Can insert anything except \0 */
2488
c = fd_read(current);
2489
2490
/* Remove the ^V first */
2491
remove_char(current, current->pos - 1);
2492
if (c > 0) {
2493
/* Insert the actual char, can't be error or null */
2494
insert_char(current, current->pos, c);
2495
}
2496
refreshLine(current);
2497
}
2498
break;
2499
case ctrl('B'):
2500
case SPECIAL_LEFT:
2501
if (current->pos > 0) {
2502
current->pos--;
2503
refreshLine(current);
2504
}
2505
break;
2506
case ctrl('F'):
2507
case SPECIAL_RIGHT:
2508
if (current->pos < sb_chars(current->buf)) {
2509
current->pos++;
2510
refreshLine(current);
2511
}
2512
break;
2513
case SPECIAL_PAGE_UP: /* move to start of history */
2514
set_history_index(current, history_len - 1);
2515
break;
2516
case SPECIAL_PAGE_DOWN: /* move to 0 == end of history, i.e. current */
2517
set_history_index(current, 0);
2518
break;
2519
case ctrl('P'):
2520
case SPECIAL_UP:
2521
set_history_index(current, history_index + 1);
2522
break;
2523
case ctrl('N'):
2524
case SPECIAL_DOWN:
2525
set_history_index(current, history_index - 1);
2526
break;
2527
case ctrl('A'): /* Ctrl+a, go to the start of the line */
2528
case SPECIAL_HOME:
2529
current->pos = 0;
2530
refreshLine(current);
2531
break;
2532
case ctrl('E'): /* ctrl+e, go to the end of the line */
2533
case SPECIAL_END:
2534
current->pos = sb_chars(current->buf);
2535
refreshLine(current);
2536
break;
2537
case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */
2538
if (remove_chars(current, 0, current->pos)) {
2539
refreshLine(current);
2540
}
2541
break;
2542
case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */
2543
if (remove_chars(current, current->pos, sb_chars(current->buf) - current->pos)) {
2544
refreshLine(current);
2545
}
2546
break;
2547
case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */
2548
if (current->capture && insert_chars(current, current->pos, sb_str(current->capture))) {
2549
refreshLine(current);
2550
}
2551
break;
2552
case ctrl('L'): /* Ctrl+L, clear screen */
2553
linenoiseClearScreen();
2554
/* Force recalc of window size for serial terminals */
2555
current->cols = 0;
2556
current->rpos = 0;
2557
refreshLine(current);
2558
break;
2559
default:
2560
if (c >= meta('a') && c <= meta('z')) {
2561
/* Don't insert meta chars that are not bound */
2562
break;
2563
}
2564
/* Only tab is allowed without ^V */
2565
if (c == '\t' || c >= ' ') {
2566
if (insert_char(current, current->pos, c) == 1) {
2567
refreshLine(current);
2568
}
2569
}
2570
break;
2571
}
2572
}
2573
return sb_len(current->buf);
2574
}
2575
2576
int linenoiseColumns(void)
2577
{
2578
struct current current;
2579
current.output = NULL;
2580
enableRawMode (&current);
2581
getWindowSize (&current);
2582
disableRawMode (&current);
2583
return current.cols;
2584
}
2585
2586
/**
2587
* Reads a line from the file handle (without the trailing NL or CRNL)
2588
* and returns it in a stringbuf.
2589
* Returns NULL if no characters are read before EOF or error.
2590
*
2591
* Note that the character count will *not* be correct for lines containing
2592
* utf8 sequences. Do not rely on the character count.
2593
*/
2594
static stringbuf *sb_getline(FILE *fh)
2595
{
2596
stringbuf *sb = sb_alloc();
2597
int c;
2598
int n = 0;
2599
2600
while ((c = getc(fh)) != EOF) {
2601
char ch;
2602
n++;
2603
if (c == '\r') {
2604
/* CRLF -> LF */
2605
continue;
2606
}
2607
if (c == '\n' || c == '\r') {
2608
break;
2609
}
2610
ch = c;
2611
/* ignore the effect of character count for partial utf8 sequences */
2612
sb_append_len(sb, &ch, 1);
2613
}
2614
if (n == 0 || sb->data == NULL) {
2615
sb_free(sb);
2616
return NULL;
2617
}
2618
return sb;
2619
}
2620
2621
char *linenoiseWithInitial(const char *prompt, const char *initial)
2622
{
2623
int count;
2624
struct current current;
2625
stringbuf *sb;
2626
2627
memset(&current, 0, sizeof(current));
2628
2629
if (enableRawMode(&current) == -1) {
2630
printf("%s", prompt);
2631
fflush(stdout);
2632
sb = sb_getline(stdin);
2633
if (sb && !fd_isatty(&current)) {
2634
printf("%s\n", sb_str(sb));
2635
fflush(stdout);
2636
}
2637
}
2638
else {
2639
current.buf = sb_alloc();
2640
current.pos = 0;
2641
current.nrows = 1;
2642
current.prompt = prompt;
2643
2644
/* The latest history entry is always our current buffer */
2645
linenoiseHistoryAdd(initial);
2646
set_current(&current, initial);
2647
2648
count = linenoiseEdit(&current);
2649
2650
disableRawMode(&current);
2651
printf("\n");
2652
2653
sb_free(current.capture);
2654
if (count == -1) {
2655
sb_free(current.buf);
2656
return NULL;
2657
}
2658
sb = current.buf;
2659
}
2660
return sb ? sb_to_string(sb) : NULL;
2661
}
2662
2663
char *linenoise(const char *prompt)
2664
{
2665
return linenoiseWithInitial(prompt, "");
2666
}
2667
2668
/* Using a circular buffer is smarter, but a bit more complex to handle. */
2669
static int linenoiseHistoryAddAllocated(char *line) {
2670
2671
if (history_max_len == 0) {
2672
notinserted:
2673
free(line);
2674
return 0;
2675
}
2676
if (history == NULL) {
2677
history = (char **)calloc(sizeof(char*), history_max_len);
2678
}
2679
2680
/* do not insert duplicate lines into history */
2681
if (history_len > 0 && strcmp(line, history[history_len - 1]) == 0) {
2682
goto notinserted;
2683
}
2684
2685
if (history_len == history_max_len) {
2686
free(history[0]);
2687
memmove(history,history+1,sizeof(char*)*(history_max_len-1));
2688
history_len--;
2689
}
2690
history[history_len] = line;
2691
history_len++;
2692
return 1;
2693
}
2694
2695
int linenoiseHistoryAdd(const char *line) {
2696
return linenoiseHistoryAddAllocated(strdup(line));
2697
}
2698
2699
int linenoiseHistoryGetMaxLen(void) {
2700
return history_max_len;
2701
}
2702
2703
int linenoiseHistorySetMaxLen(int len) {
2704
char **newHistory;
2705
2706
if (len < 1) return 0;
2707
if (history) {
2708
int tocopy = history_len;
2709
2710
newHistory = (char **)calloc(sizeof(char*), len);
2711
2712
/* If we can't copy everything, free the elements we'll not use. */
2713
if (len < tocopy) {
2714
int j;
2715
2716
for (j = 0; j < tocopy-len; j++) free(history[j]);
2717
tocopy = len;
2718
}
2719
memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy);
2720
free(history);
2721
history = newHistory;
2722
}
2723
history_max_len = len;
2724
if (history_len > history_max_len)
2725
history_len = history_max_len;
2726
return 1;
2727
}
2728
2729
/* Save the history in the specified file. On success 0 is returned
2730
* otherwise -1 is returned. */
2731
int linenoiseHistorySave(const char *filename) {
2732
FILE *fp = fopen(filename,"w");
2733
int j;
2734
2735
if (fp == NULL) return -1;
2736
for (j = 0; j < history_len; j++) {
2737
const char *str = history[j];
2738
/* Need to encode backslash, nl and cr */
2739
while (*str) {
2740
if (*str == '\\') {
2741
fputs("\\\\", fp);
2742
}
2743
else if (*str == '\n') {
2744
fputs("\\n", fp);
2745
}
2746
else if (*str == '\r') {
2747
fputs("\\r", fp);
2748
}
2749
else {
2750
fputc(*str, fp);
2751
}
2752
str++;
2753
}
2754
fputc('\n', fp);
2755
}
2756
2757
fclose(fp);
2758
return 0;
2759
}
2760
2761
/* Load the history from the specified file.
2762
*
2763
* If the file does not exist or can't be opened, no operation is performed
2764
* and -1 is returned.
2765
* Otherwise 0 is returned.
2766
*/
2767
int linenoiseHistoryLoad(const char *filename) {
2768
FILE *fp = fopen(filename,"r");
2769
stringbuf *sb;
2770
2771
if (fp == NULL) return -1;
2772
2773
while ((sb = sb_getline(fp)) != NULL) {
2774
/* Take the stringbuf and decode backslash escaped values */
2775
char *buf = sb_to_string(sb);
2776
char *dest = buf;
2777
const char *src;
2778
2779
for (src = buf; *src; src++) {
2780
char ch = *src;
2781
2782
if (ch == '\\') {
2783
src++;
2784
if (*src == 'n') {
2785
ch = '\n';
2786
}
2787
else if (*src == 'r') {
2788
ch = '\r';
2789
} else {
2790
ch = *src;
2791
}
2792
}
2793
*dest++ = ch;
2794
}
2795
*dest = 0;
2796
2797
linenoiseHistoryAddAllocated(buf);
2798
}
2799
fclose(fp);
2800
return 0;
2801
}
2802
2803
/* Provide access to the history buffer.
2804
*
2805
* If 'len' is not NULL, the length is stored in *len.
2806
*/
2807
char **linenoiseHistory(int *len) {
2808
if (len) {
2809
*len = history_len;
2810
}
2811
return history;
2812
}
2813

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button