forked from lurk101/pshell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vi.c
3854 lines (3551 loc) · 121 KB
/
vi.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
/* vi: set sw=4 ts=4: */
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* tiny vi.c: A small 'vi' clone
* Copyright (C) 2000, 2001 Sterling Huxley <[email protected]>
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
/* Adapted for Raspberry Pi, 2021 lurk101 */
#include <ctype.h>
#include <errno.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pico/stdlib.h"
#include "fs.h"
extern char* full_path(const char* name);
#define ARRAY_SIZE(x) ((uint32_t)(sizeof(x) / sizeof((x)[0])))
#define BB_VER ("Pico Vi 0.9 - " __DATE__)
static int argc, optind;
static jmp_buf die_jmp;
static inline void puts_no_eol(const char* s) {
while (*s)
putchar_raw(*s++);
}
static int index_in_strings(const char* strings, const char* key) {
int j, idx = 0;
while (*strings) {
/* Do we see "key\0" at current position in strings? */
for (j = 0; *strings == key[j]; ++j) {
if (*strings++ == '\0') {
// bb_error_msg("found:'%s' i:%u", key, idx);
return idx; /* yes */
}
}
/* No. Move to the start of the next string. */
while (*strings++ != '\0')
continue;
idx++;
}
return -1;
}
/* "Keycodes" that report an escape sequence.
* We use something which fits into signed char,
* yet doesn't represent any valid Unicode character.
* Also, -1 is reserved for error indication and we don't use it. */
static void* memrchr(const void* s, int c, size_t n) {
char* cp = (char*)s;
for (int i = n - 1; i >= 0; i--)
if (cp[i] == c)
return cp + i;
return NULL;
}
static void* zalloc(size_t bytes) {
char* cp = malloc(bytes);
if (cp)
memset(cp, 0, bytes);
return cp;
}
static char* strchrnul(const char* s, int c) {
while (*s != '\0' && *s != c)
s++;
return (char*)s;
}
static uint64_t handle_errors(uint64_t v, char** endp) {
char next_ch = **endp;
/* errno is already set to ERANGE by strtoXXX if value overflowed */
if (next_ch) {
/* "1234abcg" or out-of-range? */
if (isalnum(next_ch) || errno)
return -1;
/* good number, just suspicious terminator */
errno = EINVAL;
}
return v;
}
static const char* msg_memory_exhausted = "out of memory";
static void error_msg_and_die(const char* s, ...) {
va_list p;
va_start(p, s);
vprintf(s, p);
putchar_raw('\n');
fflush(stdout);
va_end(p);
longjmp(die_jmp, 1);
}
static char* xvsnprintf(const char* format, ...) {
char c;
va_list va;
va_start(va, format);
int n = vsnprintf(&c, sizeof c, format, va);
va_end(va);
va_list p;
char* buf = malloc(n + 1);
va_start(va, format);
vsnprintf(buf, n + 1, format, va);
va_end(va);
return buf;
}
/* clang-format off */
enum {
KEYCODE_UP = -2,
KEYCODE_DOWN = -3,
KEYCODE_RIGHT = -4,
KEYCODE_LEFT = -5,
KEYCODE_HOME = -6,
KEYCODE_END = -7,
KEYCODE_INSERT = -8,
KEYCODE_DELETE = -9,
KEYCODE_PAGEUP = -10,
KEYCODE_PAGEDOWN = -11,
KEYCODE_BACKSPACE = -12, /* Used only if Alt/Ctrl/Shifted */
KEYCODE_D = -13, /* Used only if Alted */
KEYCODE_CTRL_RIGHT = KEYCODE_RIGHT & ~0x40,
KEYCODE_CTRL_LEFT = KEYCODE_LEFT & ~0x40,
KEYCODE_ALT_RIGHT = KEYCODE_RIGHT & ~0x20,
KEYCODE_ALT_LEFT = KEYCODE_LEFT & ~0x20,
KEYCODE_ALT_BACKSPACE = KEYCODE_BACKSPACE & ~0x20,
KEYCODE_ALT_D = KEYCODE_D & ~0x20,
KEYCODE_CURSOR_POS = -0x100, /* 0xfff..fff00 */
KEYCODE_BUFFER_SIZE = 16
};
/* clang-format on */
#define VI_MAX_SCREEN_LEN 4096
#define VI_UNDO_QUEUE_MAX 32
#define is_asciionly(a) ((uint32_t)((a)-0x20) <= 0x7e - 0x20)
enum {
MAX_TABSTOP = 32, // sanity limit
// User input len. Need not be extra big.
// Lines in file being edited *can* be bigger than this.
MAX_INPUT_LEN = 128,
// Sanity limits. We have only one buffer of this size.
MAX_SCR_COLS = VI_MAX_SCREEN_LEN,
MAX_SCR_ROWS = VI_MAX_SCREEN_LEN,
};
// VT102 ESC sequences.
// See "Xterm Control Sequences"
#define ESC "\033"
// Inverse/Normal text
#define ESC_BOLD_TEXT ESC "[7m"
#define ESC_NORM_TEXT ESC "[m"
// Bell
#define ESC_BELL "\007"
// Clear-to-end-of-line
#define ESC_CLEAR2EOL ESC "[K"
// Clear-to-end-of-screen.
// (We use default param here.
// Full sequence is "ESC [ <num> J",
// <num> is 0/1/2 = "erase below/above/all".)
#define ESC_CLEAR2EOS ESC "[J"
// Cursor to given coordinate (1,1: top left)
#define ESC_SET_CURSOR_POS ESC "[%u;%uH"
#define ESC_SET_CURSOR_TOPLEFT ESC "[H"
// cmds modifying text[]
static const char modifying_cmds[] = "aAcCdDiIJoOpPrRsxX<>~";
enum {
YANKONLY = false,
YANKDEL = true,
FORWARD = 1, // code depends on "1" for array index
BACK = -1, // code depends on "-1" for array index
LIMITED = 0, // char_search() only current line
FULL = 1, // char_search() to the end/beginning of entire text
PARTIAL = 0, // buffer contains partial line
WHOLE = 1, // buffer contains whole lines
MULTI = 2, // buffer may include newlines
S_BEFORE_WS = 1, // used in skip_thing() for moving "dot"
S_TO_WS = 2, // used in skip_thing() for moving "dot"
S_OVER_WS = 3, // used in skip_thing() for moving "dot"
S_END_PUNCT = 4, // used in skip_thing() for moving "dot"
S_END_ALNUM = 5, // used in skip_thing() for moving "dot"
C_END = -1, // cursor is at end of line due to '$' command
};
struct globals {
// many references - keep near the top of globals
char *text, *end; // pointers to the user data in memory
char* dot; // where all the action takes place
int text_size; // size of the allocated buffer
// the rest
int16_t vi_setops; // set by setops()
#define VI_AUTOINDENT (1 << 0)
#define VI_EXPANDTAB (1 << 1)
#define VI_ERR_METHOD (1 << 2)
#define VI_IGNORECASE (1 << 3)
#define VI_SHOWMATCH (1 << 4)
#define VI_TABSTOP (1 << 5)
#define autoindent (vi_setops & VI_AUTOINDENT)
#define expandtab (vi_setops & VI_EXPANDTAB)
#define err_method (vi_setops & VI_ERR_METHOD) // indicate error with beep or flash
#define ignorecase (vi_setops & VI_IGNORECASE)
#define showmatch (vi_setops & VI_SHOWMATCH)
// order of constants and strings must match
#define OPTS_STR \
"ai\0" \
"autoindent\0" \
"et\0" \
"expandtab\0" \
"fl\0" \
"flash\0" \
"ic\0" \
"ignorecase\0" \
"sm\0" \
"showmatch\0" \
"ts\0" \
"tabstop\0"
#define SET_READONLY_FILE(flags) ((void)0)
#define SET_READONLY_MODE(flags) ((void)0)
#define UNSET_READONLY_FILE(flags) ((void)0)
int16_t editing; // >0 while we are editing a file
// [code audit says "can be 0, 1 or 2 only"]
int16_t cmd_mode; // 0=command 1=insert 2=replace
int modified_count; // buffer contents changed if !0
int last_modified_count; // = -1;
int cmdcnt; // repetition count
uint32_t rows, columns; // the terminal screen is this size
int crow, ccol; // cursor is on Crow x Ccol
int offset; // chars scrolled off the screen to the left
int have_status_msg; // is default edit status needed?
// [don't make int16_t!]
int last_status_cksum; // hash of current status line
char* current_filename;
char* screenbegin; // index into text[], of top line on the screen
char* screen; // pointer to the virtual screen buffer
int screensize; // and its size
int tabstop;
int last_search_char; // last char searched for (int because of Unicode)
int16_t last_search_cmd; // command used to invoke last char search
char last_input_char; // last char read from user
char undo_queue_state; // One of UNDO_INS, UNDO_DEL, UNDO_EMPTY
int16_t adding2q; // are we currently adding user input to q
int lmc_len; // length of last_modifying_cmd
char *ioq, *ioq_start; // pointer to string for get_one_char to "read"
int dotcnt; // number of times to repeat '.' command
char* last_search_pattern; // last pattern from a '/' or '?' search
int indentcol; // column of recently autoindent, 0 or -1
int16_t cmd_error;
// former statics
char* edit_file_cur_line;
int refresh_old_offset;
int format_edit_status_tot;
// a few references only
uint16_t YDreg; //,Ureg;// default delete register and orig line for "U"
#define Ureg 27
char* reg[28]; // named register a-z, "D", and "U" 0-25,26,27
char regtype[28]; // buffer type: WHOLE, MULTI or PARTIAL
char* mark[28]; // user marks points somewhere in text[]- a-z and previous context ''
int cindex; // saved character index for up/down motion
int16_t keep_index; // retain saved character index
char readbuffer[KEYCODE_BUFFER_SIZE];
#define STATUS_BUFFER_LEN 200
char status_buffer[STATUS_BUFFER_LEN]; // messages to the user
char last_modifying_cmd[MAX_INPUT_LEN]; // last modifying cmd for "."
char get_input_line_buf[MAX_INPUT_LEN]; // former static
char scr_out_buf[MAX_SCR_COLS + MAX_TABSTOP * 2];
// undo_push() operations
#define UNDO_INS 0
#define UNDO_DEL 1
#define UNDO_INS_CHAIN 2
#define UNDO_DEL_CHAIN 3
#define UNDO_INS_QUEUED 4
#define UNDO_DEL_QUEUED 5
// Pass-through flags for functions that can be undone
#define NO_UNDO 0
#define ALLOW_UNDO 1
#define ALLOW_UNDO_CHAIN 2
#define ALLOW_UNDO_QUEUED 3
struct undo_object {
struct undo_object* prev; // Linking back avoids list traversal (LIFO)
int start; // Offset where the data should be restored/deleted
int length; // total data size
uint8_t u_type; // 0=deleted, 1=inserted, 2=swapped
char undo_text[1]; // text that was deleted (if deletion)
} * undo_stack_tail;
#define UNDO_USE_SPOS 32
#define UNDO_EMPTY 64
char* undo_queue_spos; // Start position of queued operation
int undo_q;
char undo_queue[VI_UNDO_QUEUE_MAX];
};
#define text (G.text)
#define text_size (G.text_size)
#define end (G.end)
#define dot (G.dot)
#define reg (G.reg)
#define vi_setops (G.vi_setops)
#define editing (G.editing)
#define cmd_mode (G.cmd_mode)
#define modified_count (G.modified_count)
#define last_modified_count (G.last_modified_count)
#define cmdcnt (G.cmdcnt)
#define rows (G.rows)
#define columns (G.columns)
#define crow (G.crow)
#define ccol (G.ccol)
#define offset (G.offset)
#define status_buffer (G.status_buffer)
#define have_status_msg (G.have_status_msg)
#define last_status_cksum (G.last_status_cksum)
#define current_filename (G.current_filename)
#define screen (G.screen)
#define screensize (G.screensize)
#define screenbegin (G.screenbegin)
#define tabstop (G.tabstop)
#define last_search_char (G.last_search_char)
#define last_search_cmd (G.last_search_cmd)
#define readonly_mode 0
#define adding2q (G.adding2q)
#define lmc_len (G.lmc_len)
#define ioq (G.ioq)
#define ioq_start (G.ioq_start)
#define dotcnt (G.dotcnt)
#define last_search_pattern (G.last_search_pattern)
#define indentcol (G.indentcol)
#define cmd_error (G.cmd_error)
#define edit_file_cur_line (G.edit_file_cur_line)
#define refresh_old_offset (G.refresh_old_offset)
#define format_edit_status_tot (G.format_edit_status_tot)
#define YDreg (G.YDreg)
#define regtype (G.regtype)
#define mark (G.mark)
#define restart (G.restart)
#define term_orig (G.term_orig)
#define cindex (G.cindex)
#define keep_index (G.keep_index)
#define initial_cmds (G.initial_cmds)
#define readbuffer (G.readbuffer)
#define scr_out_buf (G.scr_out_buf)
#define last_modifying_cmd (G.last_modifying_cmd)
#define get_input_line_buf (G.get_input_line_buf)
#define undo_stack_tail (G.undo_stack_tail)
#define undo_queue_state (G.undo_queue_state)
#define undo_q (G.undo_q)
#define undo_queue (G.undo_queue)
#define undo_queue_spos (G.undo_queue_spos)
static struct globals G;
// sleep for 'h' 1/100 seconds, return 1/0 if stdin is (ready for read)/(not ready)
static int sleep(int ms) {
if (ms)
busy_wait_us_32(ms * 1000);
return uart_is_readable(uart_default) ? 1 : 0;
}
//----- Terminal Drawing ---------------------------------------
// The terminal is made up of 'rows' line of 'columns' columns.
// classically this would be 24 x 80.
// screen coordinates
// 0,0 ... 0,79
// 1,0 ... 1,79
// . ... .
// . ... .
// 22,0 ... 22,79
// 23,0 ... 23,79 <- status line
//----- Move the cursor to row x col (count from 0, not 1) -------
static void place_cursor(int row, int col) {
char cm1[sizeof(ESC_SET_CURSOR_POS) + sizeof(int) * 3 * 2];
if (row < 0)
row = 0;
if (row >= rows)
row = rows - 1;
if (col < 0)
col = 0;
if (col >= columns)
col = columns - 1;
sprintf(cm1, ESC_SET_CURSOR_POS, row + 1, col + 1);
puts_no_eol(cm1);
}
//----- Erase from cursor to end of line -----------------------
static void clear_to_eol(void) { puts_no_eol(ESC_CLEAR2EOL); }
static void go_bottom_and_clear_to_eol(void) {
place_cursor(rows - 1, 0);
clear_to_eol();
}
//----- Start standout mode ------------------------------------
static void standout_start(void) { puts_no_eol(ESC_BOLD_TEXT); }
//----- End standout mode --------------------------------------
static void standout_end(void) { puts_no_eol(ESC_NORM_TEXT); }
//----- Text Movement Routines ---------------------------------
static char* begin_line(char* p) // return pointer to first char cur line
{
if (p > text) {
p = memrchr(text, '\n', p - text);
if (!p)
return text;
return p + 1;
}
return p;
}
static char* end_line(char* p) // return pointer to NL of cur line
{
if (p < end - 1) {
p = memchr(p, '\n', end - p - 1);
if (!p)
return end - 1;
}
return p;
}
static char* dollar_line(char* p) // return pointer to just before NL line
{
p = end_line(p);
// Try to stay off of the Newline
if (*p == '\n' && (p - begin_line(p)) > 0)
p--;
return p;
}
static char* prev_line(char* p) // return pointer first char prev line
{
p = begin_line(p); // goto beginning of cur line
if (p > text && p[-1] == '\n')
p--; // step to prev line
p = begin_line(p); // goto beginning of prev line
return p;
}
static char* next_line(char* p) // return pointer first char next line
{
p = end_line(p);
if (p < end - 1 && *p == '\n')
p++; // step to next line
return p;
}
//----- Text Information Routines ------------------------------
static char* end_screen(void) {
char* q;
int cnt;
// find new bottom line
q = screenbegin;
for (cnt = 0; cnt < rows - 2; cnt++)
q = next_line(q);
q = end_line(q);
return q;
}
// count line from start to stop
static int count_lines(char* start, char* stop) {
char* q;
int cnt;
if (stop < start) { // start and stop are backwards- reverse them
q = start;
start = stop;
stop = q;
}
cnt = 0;
stop = end_line(stop);
while (start <= stop && start <= end - 1) {
start = end_line(start);
if (*start == '\n')
cnt++;
start++;
}
return cnt;
}
static char* find_line(int li) // find beginning of line #li
{
char* q;
for (q = text; li > 1; li--) {
q = next_line(q);
}
return q;
}
static int next_tabstop(int col) { return col + ((tabstop - 1) - (col % tabstop)); }
static int prev_tabstop(int col) { return col - ((col % tabstop) ?: tabstop); }
static int next_column(char c, int co) {
if (c == '\t')
co = next_tabstop(co);
else if ((uint8_t)c < ' ' || c == 0x7f)
co++; // display as ^X, use 2 columns
return co + 1;
}
static int get_column(char* p) {
const char* r;
int co = 0;
for (r = begin_line(p); r < p; r++)
co = next_column(*r, co);
return co;
}
//----- Erase the Screen[] memory ------------------------------
static void screen_erase(void) {
memset(screen, ' ', screensize); // clear new screen
}
static void new_screen(int ro, int co) {
char* s;
if (screen)
free(screen);
screensize = ro * co + 8;
s = screen = malloc(screensize);
// initialize the new screen. assume this will be a empty file.
screen_erase();
// non-existent text[] lines start with a tilde (~).
// screen[(1 * co) + 0] = '~';
// screen[(2 * co) + 0] = '~';
//..
// screen[((ro-2) * co) + 0] = '~';
ro -= 2;
while (--ro >= 0) {
s += co;
*s = '~';
}
}
//----- Synchronize the cursor to Dot --------------------------
static void sync_cursor(char* d, int* row, int* col) {
char* beg_cur; // begin and end of "d" line
char* tp;
int cnt, ro, co;
beg_cur = begin_line(d); // first char of cur line
if (beg_cur < screenbegin) {
// "d" is before top line on screen
// how many lines do we have to move
cnt = count_lines(beg_cur, screenbegin);
sc1:
screenbegin = beg_cur;
if (cnt > (rows - 1) / 2) {
// we moved too many lines. put "dot" in middle of screen
for (cnt = 0; cnt < (rows - 1) / 2; cnt++) {
screenbegin = prev_line(screenbegin);
}
}
} else {
char* end_scr; // begin and end of screen
end_scr = end_screen(); // last char of screen
if (beg_cur > end_scr) {
// "d" is after bottom line on screen
// how many lines do we have to move
cnt = count_lines(end_scr, beg_cur);
if (cnt > (rows - 1) / 2)
goto sc1; // too many lines
for (ro = 0; ro < cnt - 1; ro++) {
// move screen begin the same amount
screenbegin = next_line(screenbegin);
// now, move the end of screen
end_scr = next_line(end_scr);
end_scr = end_line(end_scr);
}
}
}
// "d" is on screen- find out which row
tp = screenbegin;
for (ro = 0; ro < rows - 1; ro++) { // drive "ro" to correct row
if (tp == beg_cur)
break;
tp = next_line(tp);
}
// find out what col "d" is on
co = 0;
do { // drive "co" to correct column
if (*tp == '\n') // vda || *tp == '\0')
break;
co = next_column(*tp, co) - 1;
// inserting text before a tab, don't include its position
if (cmd_mode && tp == d - 1 && *d == '\t') {
co++;
break;
}
} while (tp++ < d && ++co);
// "co" is the column where "dot" is.
// The screen has "columns" columns.
// The currently displayed columns are 0+offset -- columns+ofset
// |-------------------------------------------------------------|
// ^ ^ ^
// offset | |------- columns ----------------|
//
// If "co" is already in this range then we do not have to adjust offset
// but, we do have to subtract the "offset" bias from "co".
// If "co" is outside this range then we have to change "offset".
// If the first char of a line is a tab the cursor will try to stay
// in column 7, but we have to set offset to 0.
if (co < 0 + offset) {
offset = co;
}
if (co >= columns + offset) {
offset = co - columns + 1;
}
// if the first char of the line is a tab, and "dot" is sitting on it
// force offset to 0.
if (d == beg_cur && *d == '\t') {
offset = 0;
}
co -= offset;
*row = ro;
*col = co;
}
//----- Format a text[] line into a buffer ---------------------
static char* format_line(char* src /*, int li*/) {
uint8_t c;
int co;
int ofs = offset;
char* dest = scr_out_buf; // [MAX_SCR_COLS + MAX_TABSTOP * 2]
c = '~'; // char in col 0 in non-existent lines is '~'
co = 0;
while (co < columns + tabstop) {
// have we gone past the end?
if (src < end) {
c = *src++;
if (c == '\n')
break;
if ((c & 0x80) && !is_asciionly(c)) {
c = '.';
}
if (c < ' ' || c == 0x7f) {
if (c == '\t') {
c = ' ';
// co % 8 != 7
while ((co % tabstop) != (tabstop - 1)) {
dest[co++] = c;
}
} else {
dest[co++] = '^';
if (c == 0x7f)
c = '?';
else
c += '@'; // Ctrl-X -> 'X'
}
}
}
dest[co++] = c;
// discard scrolled-off-to-the-left portion,
// in tabstop-sized pieces
if (ofs >= tabstop && co >= tabstop) {
memmove(dest, dest + tabstop, co);
co -= tabstop;
ofs -= tabstop;
}
if (src >= end)
break;
}
// check "short line, gigantic offset" case
if (co < ofs)
ofs = co;
// discard last scrolled off part
co -= ofs;
dest += ofs;
// fill the rest with spaces
if (co < columns)
memset(&dest[co], ' ', columns - co);
return dest;
}
//----- Refresh the changed screen lines -----------------------
// Copy the source line from text[] into the buffer and note
// if the current screenline is different from the new buffer.
// If they differ then that line needs redrawing on the terminal.
//
static void refresh(int full_screen) {
int li, changed;
char *tp, *sp; // pointer into text[] and screen[]
sync_cursor(dot, &crow, &ccol); // where cursor will be (on "dot")
tp = screenbegin; // index into text[] of top line
// compare text[] to screen[] and mark screen[] lines that need updating
for (li = 0; li < rows - 1; li++) {
int cs, ce; // column start & end
char* out_buf;
// format current text line
out_buf = format_line(tp /*, li*/);
// skip to the end of the current text[] line
if (tp < end) {
char* t = memchr(tp, '\n', end - tp);
if (!t)
t = end - 1;
tp = t + 1;
}
// see if there are any changes between virtual screen and out_buf
changed = false; // assume no change
cs = 0;
ce = columns - 1;
sp = &screen[li * columns]; // start of screen line
if (full_screen) {
// force re-draw of every single column from 0 - columns-1
goto re0;
}
// compare newly formatted buffer with virtual screen
// look forward for first difference between buf and screen
for (; cs <= ce; cs++) {
if (out_buf[cs] != sp[cs]) {
changed = true; // mark for redraw
break;
}
}
// look backward for last difference between out_buf and screen
for (; ce >= cs; ce--) {
if (out_buf[ce] != sp[ce]) {
changed = true; // mark for redraw
break;
}
}
// now, cs is index of first diff, and ce is index of last diff
// if horz offset has changed, force a redraw
if (offset != refresh_old_offset) {
re0:
changed = true;
}
// make a sanity check of columns indexes
if (cs < 0)
cs = 0;
if (ce > columns - 1)
ce = columns - 1;
if (cs > ce) {
cs = 0;
ce = columns - 1;
}
// is there a change between virtual screen and out_buf
if (changed) {
// copy changed part of buffer to virtual screen
memcpy(sp + cs, out_buf + cs, ce - cs + 1);
place_cursor(li, cs);
// write line out to terminal
fwrite(&sp[cs], ce - cs + 1, 1, stdout);
fflush(stdout);
}
}
place_cursor(crow, ccol);
if (!keep_index)
cindex = ccol + offset;
refresh_old_offset = offset;
}
static int safe_poll(uint8_t* buffer, int ms) {
int c;
absolute_time_t t;
if (ms < 0)
c = getchar();
else {
c = getchar_timeout_us(ms * 1000);
if (c == PICO_ERROR_TIMEOUT)
return 0;
}
*buffer = c;
return 1;
}
/* Known escape sequences for cursor and function keys.
* See "Xterm Control Sequences"
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* Array should be sorted from shortest to longest.
*/
static const char esccmds[] = {
'\x7f' | 0x80, KEYCODE_ALT_BACKSPACE, '\b' | 0x80, KEYCODE_ALT_BACKSPACE, 'd' | 0x80,
KEYCODE_ALT_D,
/* lineedit mimics bash: Alt-f and Alt-b are forward/backward
* word jumps. We cheat here and make them return ALT_LEFT/RIGHT
* keycodes. This way, lineedit need no special code to handle them.
* If we'll need to distinguish them, introduce new ALT_F/B keycodes,
* and update lineedit to react to them.
*/
'f' | 0x80, KEYCODE_ALT_RIGHT, 'b' | 0x80, KEYCODE_ALT_LEFT, 'O', 'A' | 0x80, KEYCODE_UP, 'O',
'B' | 0x80, KEYCODE_DOWN, 'O', 'C' | 0x80, KEYCODE_RIGHT, 'O', 'D' | 0x80, KEYCODE_LEFT, 'O',
'H' | 0x80, KEYCODE_HOME, 'O', 'F' | 0x80, KEYCODE_END,
'[', 'A' | 0x80, KEYCODE_UP, '[', 'B' | 0x80, KEYCODE_DOWN, '[', 'C' | 0x80, KEYCODE_RIGHT, '[',
'D' | 0x80, KEYCODE_LEFT,
/* ESC [ 1 ; 2 x, where x = A/B/C/D: Shift-<arrow> */
/* ESC [ 1 ; 3 x, where x = A/B/C/D: Alt-<arrow> - implemented below */
/* ESC [ 1 ; 4 x, where x = A/B/C/D: Alt-Shift-<arrow> */
/* ESC [ 1 ; 5 x, where x = A/B/C/D: Ctrl-<arrow> - implemented below */
/* ESC [ 1 ; 6 x, where x = A/B/C/D: Ctrl-Shift-<arrow> */
/* ESC [ 1 ; 7 x, where x = A/B/C/D: Ctrl-Alt-<arrow> */
/* ESC [ 1 ; 8 x, where x = A/B/C/D: Ctrl-Alt-Shift-<arrow> */
'[', 'H' | 0x80, KEYCODE_HOME, /* xterm */
'[', 'F' | 0x80, KEYCODE_END, /* xterm */
/* [ESC] ESC [ [2] H - [Alt-][Shift-]Home (End similarly?) */
/* '[','Z' |0x80,KEYCODE_SHIFT_TAB, */
'[', '1', '~' | 0x80, KEYCODE_HOME, /* vt100? linux vt? or what? */
'[', '2', '~' | 0x80, KEYCODE_INSERT,
/* ESC [ 2 ; 3 ~ - Alt-Insert */
'[', '3', '~' | 0x80, KEYCODE_DELETE,
/* [ESC] ESC [ 3 [;2] ~ - [Alt-][Shift-]Delete */
/* ESC [ 3 ; 3 ~ - Alt-Delete */
/* ESC [ 3 ; 5 ~ - Ctrl-Delete */
'[', '4', '~' | 0x80, KEYCODE_END, /* vt100? linux vt? or what? */
'[', '5', '~' | 0x80, KEYCODE_PAGEUP,
/* ESC [ 5 ; 3 ~ - Alt-PgUp */
/* ESC [ 5 ; 5 ~ - Ctrl-PgUp */
/* ESC [ 5 ; 7 ~ - Ctrl-Alt-PgUp */
'[', '6', '~' | 0x80, KEYCODE_PAGEDOWN, '[', '7', '~' | 0x80,
KEYCODE_HOME, /* vt100? linux vt? or what? */
'[', '8', '~' | 0x80, KEYCODE_END, /* vt100? linux vt? or what? */
/* '[','1',';','5','A' |0x80,KEYCODE_CTRL_UP , - unused */
/* '[','1',';','5','B' |0x80,KEYCODE_CTRL_DOWN , - unused */
'[', '1', ';', '5', 'C' | 0x80, KEYCODE_CTRL_RIGHT, '[', '1', ';', '5', 'D' | 0x80,
KEYCODE_CTRL_LEFT,
/* '[','1',';','3','A' |0x80,KEYCODE_ALT_UP , - unused */
/* '[','1',';','3','B' |0x80,KEYCODE_ALT_DOWN , - unused */
'[', '1', ';', '3', 'C' | 0x80, KEYCODE_ALT_RIGHT, '[', '1', ';', '3', 'D' | 0x80,
KEYCODE_ALT_LEFT,
/* '[','3',';','3','~' |0x80,KEYCODE_ALT_DELETE, - unused */
0};
int64_t read_key(char* buffer, int timeout) {
const char* seq;
int n, c;
buffer++; /* saved chars counter is in buffer[-1] now */
start_over:
errno = 0;
n = (unsigned char)buffer[-1];
if (n == 0) {
/* If no data, wait for input.
* If requested, wait TIMEOUT ms. TIMEOUT = -1 is useful
* if fd can be in non-blocking mode.
*
* It is tempting to read more than one byte here,
* but it breaks pasting. Example: at shell prompt,
* user presses "c","a","t" and then pastes "\nline\n".
* When we were reading 3 bytes here, we were eating
* "li" too, and cat was getting wrong input.
*/
n = safe_poll(buffer, timeout);
if (n <= 0) {
return -1;
}
}
{
unsigned char c = buffer[0];
n--;
if (n)
memmove(buffer, buffer + 1, n);
/* Only ESC starts ESC sequences */
if (c != 27) {
buffer[-1] = n;
return c;
}
}
/* Loop through known ESC sequences */
seq = esccmds;
while (*seq != '\0') {
/* n - position in sequence we did not read yet */
int i = 0; /* position in sequence to compare */
/* Loop through chars in this sequence */
while (1) {
/* So far escape sequence matched up to [i-1] */
if (n <= i) {
/* Need more chars, read another one if it wouldn't block.
* Note that escape sequences come in as a unit,
* so if we block for long it's not really an escape sequence.
* Timeout is needed to reconnect escape sequences
* split up by transmission over a serial console. */
errno = 0;
if (safe_poll(buffer + n, 2) <= 0) {
/* No more data!
* Array is sorted from shortest to longest,
* we can't match anything later in array -
* anything later is longer than this seq.
* Break out of both loops. */
if (n == 0)
return 27;
return -1;
}
n++;
}
if (buffer[i] != (seq[i] & 0x7f)) {
/* This seq doesn't match, go to next */
seq += i;
/* Forward to last char */
while (!(*seq & 0x80))
seq++;
/* Skip it and the keycode which follows */
seq += 2;
break;
}
if (seq[i] & 0x80) {
/* Entire seq matched */
n = 0;
/* n -= i; memmove(...);
* would be more correct,
* but we never read ahead that much,
* and n == i here. */
buffer[-1] = 0;
return (signed char)seq[i + 1];
}
i++;
}
}
/* We did not find matching sequence.
* We possibly read and stored more input in buffer[] by now.
* n = bytes read. Try to read more until we time out.
*/
got_all:
if (n <= 1) {
/* Alt-x is usually returned as ESC x.
* Report ESC, x is remembered for the next call.
*/
buffer[-1] = n;
return 27;
}
/* We were doing "buffer[-1] = n; return c;" here, but this results
* in unknown key sequences being interpreted as ESC + garbage.
* This was not useful. Pretend there was no key pressed,
* go and wait for a new keypress:
*/
buffer[-1] = 0;
goto start_over;
}
static int readit(void) // read (maybe cursor) key from stdin
{
fflush(stdout);
return read_key(readbuffer, -1);
}
static int get_one_char(void) {
int c;