-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvi.c
4392 lines (4091 loc) · 117 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: */
/*
* tiny vi.c: A small 'vi' clone
* Copyright (C) 2000, 2001 Sterling Huxley <[email protected]>
*
* Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
* Revised: 4/23/20 [email protected] -- NULL ptr deref on missing previous regex
* Revised: 5/21/20 [email protected] -- extensive rework
* Revised: 2/14/24 Stefan Haubental -- added support for clang
*/
/*
* Things To Do:
* EXINIT
* $HOME/.exrc and ./.exrc
* add magic to search /foo.*bar
* add :help command
* :map macros
* if mark[] values were line numbers rather than pointers
* it would be easier to change the mark when add/delete lines
* More intelligence in refresh()
* ":r !cmd" and "!cmd" to filter text through an external command
* A true "undo" facility
* An "ex" line oriented mode- maybe using "cmdedit"
*/
#ifdef STANDALONE
#define BB_VER "version 2.63"
#define BB_BT "[email protected]"
#define _GNU_SOURCE
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <setjmp.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>
#include <ctype.h>
#include <termios.h>
#include <poll.h>
#define vi_main main
#define CONFIG_FEATURE_VI_MAX_LEN 4096
#define ENABLE_FEATURE_VI_COLON 1
#define ENABLE_FEATURE_VI_YANKMARK 1
#define ENABLE_FEATURE_VI_SEARCH 1
#define ENABLE_FEATURE_VI_USE_SIGNALS 1
#define ENABLE_FEATURE_VI_DOT_CMD 1
#define ENABLE_FEATURE_VI_READONLY 1
#define ENABLE_FEATURE_VI_SETOPTS 1
#define ENABLE_FEATURE_VI_SET 1
#define ENABLE_FEATURE_VI_WIN_RESIZE 1
#define ENABLE_LOCALE_SUPPORT 1
#define ENABLE_FEATURE_VI_8BIT 1
#define ENABLE_FEATURE_VI_YANKMARK 1
#define ENABLE_FEATURE_VI_SEARCH 1
#define ENABLE_FEATURE_ALLOW_EXEC 1
#undef ENABLE_FEATURE_VI_OPTIMIZE_CURSOR
#define USE_FEATURE_VI_COLON(...) __VA_ARGS__
#define USE_FEATURE_VI_READONLY(...) __VA_ARGS__
#define USE_FEATURE_VI_YANKMARK(...) __VA_ARGS__
#define USE_FEATURE_VI_SEARCH(...) __VA_ARGS__
#define ALIGN1
#define FALSE 0
#define TRUE 1
#define MAIN_EXTERNALLY_VISIBLE
#define ATTRIBUTE_UNUSED __attribute__ ((__unused__))
#undef isdigit
#define isdigit(a) ((unsigned)((a) - '0') <= 9)
#define ARRAY_SIZE(x) ((unsigned)(sizeof(x) / sizeof((x)[0])))
#define INIT_G()
struct globals G;
typedef signed char smallint;
#define bb_show_usage()
#define bb_perror_msg(msg) perror(msg)
// To test editor using CRASHME:
// vi -C filename
// To stop testing, wait until all to text[] is deleted, or
// Ctrl-Z and kill -9 %1
// while in the editor Ctrl-T will toggle the crashme function on and off.
//#define CONFIG_FEATURE_VI_CRASHME // randomly pick commands to execute
#ifdef __clang__
char *strchrnul(const char *s, int c_in)
{
char c = c_in;
while (*s && (*s != c))
s++;
return (char *) s;
}
void *memrchr(const void *s, int c_in, size_t n)
{
if (n != 0) {
const unsigned char *cp = (unsigned char *)s + n;
do {
if (*(--cp) == (unsigned char) c_in)
return (void *) cp;
} while (--n != 0);
}
return NULL;
}
#endif
#else //in busybox
#include "libbb.h"
#define G (*ptr_to_globals)
#define INIT_G() do { \
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
last_file_modified = -1; \
} while (0)
#endif
#include <limits.h>
/* the CRASHME code is unmaintained, and doesn't currently build */
#define ENABLE_FEATURE_VI_CRASHME 0
#if ENABLE_LOCALE_SUPPORT
#if ENABLE_FEATURE_VI_8BIT
#define Isprint(c) isprint(c)
#else
#define Isprint(c) (isprint(c) && (unsigned char)(c) < 0x7f)
#endif
#else
/* 0x9b is Meta-ESC */
#if ENABLE_FEATURE_VI_8BIT
#define Isprint(c) ((unsigned char)(c) >= ' ' && (c) != 0x7f && (unsigned char)(c) != 0x9b)
#else
#define Isprint(c) ((unsigned char)(c) >= ' ' && (unsigned char)(c) < 0x7f)
#endif
#endif
#if ENABLE_FEATURE_VI_READONLY
#define EDIT_STATUS "%s: %s%s%s line %d/%d %d%%"
#else
#define EDIT_STATUS "%s: %s%s line %d/%d %d%%"
#endif
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 = CONFIG_FEATURE_VI_MAX_LEN,
MAX_SCR_ROWS = CONFIG_FEATURE_VI_MAX_LEN,
};
// Misc. non-Ascii keys that report an escape sequence
#define VI_K_UP (char)128 // cursor key Up
#define VI_K_DOWN (char)129 // cursor key Down
#define VI_K_RIGHT (char)130 // Cursor Key Right
#define VI_K_LEFT (char)131 // cursor key Left
#define VI_K_HOME (char)132 // Cursor Key Home
#define VI_K_END (char)133 // Cursor Key End
#define VI_K_INSERT (char)134 // Cursor Key Insert
#define VI_K_DELETE (char)135 // Cursor Key Insert
#define VI_K_PAGEUP (char)136 // Cursor Key Page Up
#define VI_K_PAGEDOWN (char)137 // Cursor Key Page Down
#define VI_K_FUN1 (char)138 // Function Key F1
#define VI_K_FUN2 (char)139 // Function Key F2
#define VI_K_FUN3 (char)140 // Function Key F3
#define VI_K_FUN4 (char)141 // Function Key F4
#define VI_K_FUN5 (char)142 // Function Key F5
#define VI_K_FUN6 (char)143 // Function Key F6
#define VI_K_FUN7 (char)144 // Function Key F7
#define VI_K_FUN8 (char)145 // Function Key F8
#define VI_K_FUN9 (char)146 // Function Key F9
#define VI_K_FUN10 (char)147 // Function Key F10
#define VI_K_FUN11 (char)148 // Function Key F11
#define VI_K_FUN12 (char)149 // Function Key F12
/* vt102 typical ESC sequence */
/* terminal standout start/normal ESC sequence */
#define SOlen (4) //length of SO escape sequence
static const char SOs[] ALIGN1 = "\033[7m";
static const char SOn[] ALIGN1 = "\033[0m";
/* terminal bell sequence */
static const char bell[] ALIGN1 = "\007";
/* Clear-end-of-line and Clear-end-of-screen ESC sequence */
static const char Ceol[] ALIGN1 = "\033[0K";
static const char Ceos[] ALIGN1 = "\033[0J";
/* Cursor motion arbitrary destination ESC sequence */
static const char CMrc[] ALIGN1 = "\033[%d;%dH";
#if ENABLE_FEATURE_VI_WIN_RESIZE
/* Report cursor positon */
static const char CtextAreaQuery[] ALIGN1 = "\033[r\033[999;999H\033[6n";
#endif
#ifdef ENABLE_FEATURE_VI_OPTIMIZE_CURSOR
/* Cursor motion up and down ESC sequence */
static const char CMup[] ALIGN1 = "\033[A";
static const char CMdown[] ALIGN1 = "\n";
#endif
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, // how much of text[] in char_search
FULL = 1, // how much of text[] in char_search
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"
};
enum { //cmd_modes
CMODE_COMMAND,
CMODE_INSERT,
CMODE_REPLACE,
CMODES,
CMODE_LINE_INPUT = 1<<4
};
static const char *cmd_mode_indicator[] =
{"COMMAND", "INSERT", "REPLACE", "?!?" };
/* vi.c expects chars to be unsigned. */
/* busybox build system provides that, but it's better */
/* to audit and fix the source */
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 */
smallint vi_setops;
#define VI_AUTOINDENT 1
#define VI_SHOWMATCH 2
#define VI_IGNORECASE 4
#define VI_ERR_METHOD 8
#define autoindent (vi_setops & VI_AUTOINDENT)
#define showmatch (vi_setops & VI_SHOWMATCH )
#define ignorecase (vi_setops & VI_IGNORECASE)
/* indicate error with beep or flash */
#define err_method (vi_setops & VI_ERR_METHOD)
#if ENABLE_FEATURE_VI_READONLY
smallint readonly_mode;
#define SET_READONLY_FILE(flags) ((flags) |= 0x01)
#define SET_READONLY_MODE(flags) ((flags) |= 0x02)
#define UNSET_READONLY_FILE(flags) ((flags) &= 0xfe)
#else
#define SET_READONLY_FILE(flags) ((void)0)
#define SET_READONLY_MODE(flags) ((void)0)
#define UNSET_READONLY_FILE(flags) ((void)0)
#endif
smallint editing; // >0 while we are editing a file
// [code audit says "can be 0 or 1 only"]
smallint cmd_mode; // 0=command 1=insert 2=replace
int file_modified; // buffer contents changed (counter, not flag!)
int last_file_modified; // = -1;
int fn_start; // index of first cmd line file name
int save_argc; // how many file names on cmd line
int cmdcnt; // repetition count
unsigned 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
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;
char erase_char; // the users erase character
char last_input_char; // last char read from user
char last_forward_char; // last char searched for with 'f'
#if ENABLE_FEATURE_VI_DOT_CMD
smallint 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"
#endif
#if ENABLE_FEATURE_VI_OPTIMIZE_CURSOR
int last_row; // where the cursor was last moved to
#endif
#if ENABLE_FEATURE_VI_USE_SIGNALS || ENABLE_FEATURE_VI_CRASHME
int my_pid;
#endif
#if ENABLE_FEATURE_VI_DOT_CMD || ENABLE_FEATURE_VI_YANKMARK
char *modifying_cmds; // cmds that modify text[]
#endif
#if ENABLE_FEATURE_VI_SEARCH
char *last_search_pattern; // last pattern from a '/' or '?' search
#endif
int chars_to_parse;
/* former statics */
#if ENABLE_FEATURE_VI_YANKMARK
char *edit_file__cur_line;
#endif
int refresh__old_offset;
int format_edit_status__tot;
/* a few references only */
#if ENABLE_FEATURE_VI_YANKMARK
int YDreg, Ureg; // default delete register and orig line for "U"
char *reg[28]; // named register a-z, "D", and "U" 0-25,26,27
char *mark[28]; // user marks points somewhere in text[]- a-z and previous context ''
char *context_start, *context_end;
#endif
#if ENABLE_FEATURE_VI_USE_SIGNALS
sigjmp_buf restart; // catch_sig()
#endif
struct termios term_orig, term_vi; // remember what the cooked mode was
unsigned ticsPerChar; //# of 100hz tics per character received
#if ENABLE_FEATURE_VI_COLON
char *initial_cmds[3]; // currently 2 entries, NULL terminated
#endif
// Should be just enough to hold a key sequence,
// but CRASME mode uses it as generated command buffer too
char readbuffer[128];
#define STATUS_BUFFER_LEN 200
char status_buffer[STATUS_BUFFER_LEN]; // messages to the user
char displayed_buffer[STATUS_BUFFER_LEN]; // displayed status
#if ENABLE_FEATURE_VI_DOT_CMD
char last_modifying_cmd[MAX_INPUT_LEN]; // last modifying cmd for "."
#endif
char get_input_line__buf[MAX_INPUT_LEN]; /* former static */
char scr_out_buf[MAX_SCR_COLS + MAX_TABSTOP * 2];
};
#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 file_modified (G.file_modified )
#define last_file_modified (G.last_file_modified )
#define fn_start (G.fn_start )
#define save_argc (G.save_argc )
#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 displayed_buffer (G.displayed_buffer )
#define current_filename (G.current_filename )
#define screen (G.screen )
#define screensize (G.screensize )
#define screenbegin (G.screenbegin )
#define tabstop (G.tabstop )
#define erase_char (G.erase_char )
#define last_input_char (G.last_input_char )
#define last_forward_char (G.last_forward_char )
#if ENABLE_FEATURE_VI_READONLY
#define readonly_mode (G.readonly_mode )
#else
#define readonly_mode 0
#endif
#define adding2q (G.adding2q )
#define lmc_len (G.lmc_len )
#define ioq (G.ioq )
#define ioq_start (G.ioq_start )
#define last_row (G.last_row )
#define my_pid (G.my_pid )
#define modifying_cmds (G.modifying_cmds )
#define last_search_pattern (G.last_search_pattern)
#define chars_to_parse (G.chars_to_parse )
#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 Ureg (G.Ureg )
#define mark (G.mark )
#define context_start (G.context_start )
#define context_end (G.context_end )
#define restart (G.restart )
#define term_orig (G.term_orig )
#define ticsPerChar (G.ticsPerChar )
#define term_vi (G.term_vi )
#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)
static int init_text_buffer(char *); // init from file or create new
static void edit_file(char *); // edit one file
static void do_cmd(char); // execute a command
static int next_tabstop(int);
static void sync_cursor(char *, int *, int *); // synchronize the screen cursor to dot
static char *begin_line(char *); // return pointer to cur line B-o-l
static char *end_line(char *); // return pointer to cur line E-o-l
static char *prev_line(char *); // return pointer to prev line B-o-l
static char *next_line(char *); // return pointer to next line B-o-l
static char *end_screen(void); // get pointer to last char on screen
static int count_lines(char *, char *); // count line from start to stop
static char *find_line(int); // find begining of line #li
static char *move_to_col(char *, int); // move "p" to column l
static void dot_left(void); // move dot left- dont leave line
static void dot_right(void); // move dot right- dont leave line
static void dot_begin(void); // move dot to B-o-l
static void dot_end(void); // move dot to E-o-l
static void dot_next(void); // move dot to next line B-o-l
static void dot_prev(void); // move dot to prev line B-o-l
static void dot_scroll(int, int); // move the screen up or down
static void dot_skip_over_ws(void); // move dot pat WS
static void dot_delete(void); // delete the char at 'dot'
static char *bound_dot(char *); // make sure text[0] <= P < "end"
static char *new_screen(int, int); // malloc virtual screen memory
static char *char_insert(char *, char); // insert the char c at 'p'
static char *stupid_insert(char *, char); // stupidly insert the char c at 'p'
static int find_range(char **, char **, char); // return pointers for an object
static int st_test(char *, int, int, char *); // helper for skip_thing()
static char *skip_thing(char *, int, int, int); // skip some object
static char *find_pair(char *, char); // find matching pair () [] {}
static char *text_hole_delete(char *, char *); // at "p", delete a 'size' byte hole
static char *text_hole_make(char *, int); // at "p", make a 'size' byte hole
static char *yank_delete(char *, char *, int, int); // yank text[] into register then delete
static void show_help(void); // display some help info
static int rawmode(void); // set "raw" mode on tty
static void cookmode(void); // return to "cooked" mode on tty
static int awaitInput(int); //for specified number of 1/100th seconds
static char readit(void); // read (maybe cursor) key from stdin
static char get_one_char(void); // read 1 char from stdin
static int file_size(const char *); // what is the byte size of "fn"
#if ENABLE_FEATURE_VI_READONLY
static int file_insert(const char *, char *, int);
#else
static int file_insert(const char *, char *);
#endif
static int file_write(char *, char *, char *);
#if !ENABLE_FEATURE_VI_OPTIMIZE_CURSOR
#define place_cursor(a, b, optimize) place_cursor(a, b)
#endif
static void place_cursor(int, int, int);
static void screen_erase(void);
static void clear_to_eol(void);
static void clear_to_eos(void);
static void standout_start(void); // send "start reverse video" sequence
static void standout_end(void); // send "end reverse video" sequence
static void flash(int); // flash the terminal screen
static void show_status_line(void); // put a message on the bottom line
static void status_line(const char *, ...); // print to status buf
static void status_line_bold(const char *, ...);
static void not_implemented(const char *); // display "Not implemented" message
static int format_edit_status(const char *fmt); //file status on status line
static void redraw(void); // force a full screen refresh
static char* format_line(char* /*, int*/);
static void refresh(void); // update the terminal from screen[]
static void Indicate_Error(void); // use flash or beep to indicate error
#define indicate_error(c) Indicate_Error()
static void Hit_Return(void);
#if ENABLE_FEATURE_VI_SEARCH
static char *char_search(char *, const char *, int, int); // search for pattern starting at p
static int mycmp(const char *, const char *, int); // string cmp based in "ignorecase"
#endif
#if ENABLE_FEATURE_VI_COLON
static char *get_one_address(char *, int *); // get colon addr, if present
static char *get_address(char *, int *, int *); // get two colon addrs, if present
static void colon(char *); // execute the "colon" mode cmds
#endif
#if ENABLE_FEATURE_VI_USE_SIGNALS
static void winch_sig(int); // catch window size changes
static void suspend_sig(int); // catch ctrl-Z
static void catch_sig(int); // catch ctrl-C and alarm time-outs
static void quit_sig(int); // catch QUIT, TERM, PIPE, or HUP
#endif
#if ENABLE_FEATURE_VI_DOT_CMD
static void start_new_cmd_q(char); // new queue for command
static void end_cmd_q(void); // stop saving input chars
#else
#define end_cmd_q() ((void)0)
#endif
#if ENABLE_FEATURE_VI_SETOPTS
static void showmatching(char *); // show the matching pair () [] {}
#endif
#if ENABLE_FEATURE_VI_YANKMARK || (ENABLE_FEATURE_VI_COLON && ENABLE_FEATURE_VI_SEARCH) || ENABLE_FEATURE_VI_CRASHME
static char *string_insert(char *, char *); // insert the string at 'p'
#endif
#if ENABLE_FEATURE_VI_YANKMARK
static char *text_yank(char *, char *, int); // save copy of "p" into a register
static char what_reg(void); // what is letter of current YDreg
static void check_context(char); // remember context for '' command
#endif
#if ENABLE_FEATURE_VI_CRASHME
static void crash_dummy();
static void crash_test();
static int crashme = 0;
#endif
#ifdef STANDALONE
void *xmalloc(size_t size)
{
void *ptr = malloc(size);
if (ptr) return ptr;
perror("malloc");
exit(65);
}
void *xzalloc(size_t size)
{
return memset(xmalloc(size), 0, size);
}
void *xstrdup(const char *s)
{
void *ptr = strdup(s);
if (ptr) return ptr;
perror("strdup");
exit(66);
}
void *xstrndup(const char *s, size_t n)
{
void *ptr = strndup(s, n);
if (ptr) return ptr;
perror("strndup");
exit(67);
}
void *xrealloc(void *old, size_t size)
{
void *ptr = realloc(old, size);
if (ptr) return ptr;
perror("realloc");
exit(68);
}
/* Find out if the last character of a string matches the one given.
* Don't underrun the buffer if the string length is 0.
*/
char* last_char_is(const char *s, int c)
{
if (s && *s) {
size_t sz = strlen(s) - 1;
s += sz;
if ( (unsigned char)*s == c)
return (char*)s;
}
return NULL;
}
int bb_putchar(int ch)
{
return putc(ch, stdout);
}
/* Wrapper which restarts poll on EINTR or ENOMEM.
* On other errors does perror("poll") and returns.
* Warning! May take longer than timeout_ms to return! */
int safe_poll(struct pollfd *ufds, nfds_t nfds, int timeout)
{
while (1) {
int n = poll(ufds, nfds, timeout);
if (n >= 0)
return n;
/* Make sure we inch towards completion */
if (timeout > 0)
timeout--;
/* E.g. strace causes poll to return this */
if (errno == EINTR)
continue;
/* Kernel is very low on memory. Retry. */
/* I doubt many callers would handle this correctly! */
if (errno == ENOMEM)
continue;
bb_perror_msg("poll");
return n;
}
}
ssize_t safe_read(int fd, void *buf, size_t count)
{
ssize_t n;
do {
n = read(fd, buf, count);
} while (n < 0 && errno == EINTR);
return n;
}
ssize_t safe_write(int fd, const void *buf, size_t count)
{
ssize_t n;
do {
n = write(fd, buf, count);
} while (n < 0 && errno == EINTR);
return n;
}
ssize_t full_write(int fd, const void *buf, size_t len)
{
ssize_t cc;
ssize_t total;
total = 0;
while (len) {
cc = safe_write(fd, buf, len);
if (cc < 0) {
if (total) {
/* we already wrote some! */
/* user can do another write to know the error code */
return total;
}
return cc; /* write() returns -1 on failure. */
}
total += cc;
buf = ((const char *)buf) + cc;
len -= cc;
}
return total;
}
#endif
static void write1(const char *out)
{
fputs(out, stdout);
}
static void clear_screen(void)
{
place_cursor(0, 0, FALSE); // put cursor in correct place
clear_to_eos(); // tell terminal to erase display
}
static void gracefulExit(void)
{
cookmode();
place_cursor(rows-1, 0, FALSE); // go to bottom of screen
clear_to_eol(); // Erase to end of line
fflush(stdout);
}
void clampScreenSize(void)
{
if (rows < 2)
rows = 2;
else if (rows > MAX_SCR_ROWS)
rows = MAX_SCR_ROWS;
if (columns < 2)
columns = 2;
else if (columns > MAX_SCR_COLS)
columns = MAX_SCR_COLS;
}
#if ENABLE_FEATURE_VI_WIN_RESIZE
static const char *snchr(const char *s, int c, size_t n)
{
while (n--)
if (*s++ == c) return --s;
return NULL;
}
static ssize_t
readResponse(char *buf, size_t bufSize, int endByte)
//read response from STDIN into buf until timeout or endByte received
{
size_t cursor = 0;
while (cursor < bufSize) {
if (!awaitInput(ticsPerChar+9))
return -ETIME;
int r = safe_read(STDIN_FILENO, buf + cursor, bufSize - cursor);
if (r <= 0)
return r < 0 ? r : -EIO;
if (snchr(buf+cursor, endByte, r))
return cursor + r;
cursor += r;
}
return -E2BIG;
}
static void queueAnyInput(void)
//add any pending user input to readbuffer
{
if (awaitInput(0)) {
char *s = readbuffer + chars_to_parse;
int r = safe_read(STDIN_FILENO, s, readbuffer+sizeof(readbuffer) - s);
if (r > 0)
chars_to_parse += r;
}
}
void getScreenSize(void)
// assigns width and height to best guess as to actual screen size
// LINES and COLUMNS env vars take priority
// If either missing, query the terminal using VT100 escape codes
// If that fails, fall back to rows/cols info in the termios struct
// rows and columns retain their previous values if all methods fail
{
struct winsize win = { 0, 0, 0, 0 };
const char *lines = getenv("LINES");
const char *cols = getenv("COLUMNS");
if (!lines || !cols) { //if either missing in the environment
queueAnyInput();
if (!awaitInput(0)) { //can't query term if there's pending user input
write1(CtextAreaQuery);
char buf[16];
int rspLen = readResponse(buf, sizeof(buf)-1, 'R');
if (rspLen > 5 && buf[0]==27 && buf[1]=='[') {
buf[rspLen]=0; //terminate response string
char *term;
unsigned long ul = strtoul(buf+2, &term, 10);
if (*term == ';') {
win.ws_row = ul;
ul = strtoul(term+1, &term, 10);
if (*term == 'R') {
win.ws_col = ul;
}
}
}
}
if (!win.ws_row || !win.ws_col) //try termios if textAreaQuery failed
ioctl(STDIN_FILENO, TIOCGWINSZ, &win);
}
//environment variables trump all
if (lines)
rows = atoi(lines);
else if (win.ws_row)
rows = win.ws_row;
if (cols)
columns = atoi(cols);
else if (win.ws_col)
columns = win.ws_col;
}
#endif
static void createScreen(void)
{
#if ENABLE_FEATURE_VI_WIN_RESIZE
getScreenSize();
clampScreenSize();
#endif
new_screen(rows, columns); // get memory for virtual screen
}
int vi_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int vi_main(int argc, char **argv)
{
int c;
INIT_G();
rows = 24;
columns = 80;
#if !ENABLE_FEATURE_VI_WIN_RESIZE
{ //try to get terminal dimensions from environment
char *txt = getenv("LINES");
if (txt)
rows = atoi(txt);
txt = getenv("COLUMNS");
if (txt)
columns = atoi(txt);
clampScreenSize();
}
#endif
#if ENABLE_FEATURE_VI_USE_SIGNALS || ENABLE_FEATURE_VI_CRASHME
my_pid = getpid();
#endif
#if ENABLE_FEATURE_VI_CRASHME
srand((long) my_pid);
#endif
#ifdef NO_SUCH_APPLET_YET
/* If we aren't "vi", we are "view" */
if (ENABLE_FEATURE_VI_READONLY && applet_name[2]) {
SET_READONLY_MODE(readonly_mode);
}
#endif
vi_setops = VI_AUTOINDENT | VI_SHOWMATCH | VI_IGNORECASE;
#if ENABLE_FEATURE_VI_DOT_CMD || ENABLE_FEATURE_VI_YANKMARK
modifying_cmds = "aAcCdDiIJoOpPrRsxX<>~"; // cmds modifying text[]
#endif
// 1- process $HOME/.exrc file (not inplemented yet)
// 2- process EXINIT variable from environment
// 3- process command line args
#if ENABLE_FEATURE_VI_COLON
{
char *p = getenv("EXINIT");
if (p && *p)
initial_cmds[0] = xstrndup(p, MAX_INPUT_LEN);
}
#endif
while ((c = getopt(argc, argv, "hCRH-" USE_FEATURE_VI_COLON("c:"))) != -1) {
switch (c) {
#if ENABLE_FEATURE_VI_CRASHME
case 'C':
crashme = 1;
break;
#endif
#if ENABLE_FEATURE_VI_READONLY
case 'R': // Read-only flag
SET_READONLY_MODE(readonly_mode);
break;
#endif
#if ENABLE_FEATURE_VI_COLON
case 'c': // cmd line vi command
if (*optarg)
initial_cmds[initial_cmds[0] != 0] = xstrndup(optarg, MAX_INPUT_LEN);
break;
#endif
case 'H':
case '-':
show_help();
/* fall through */
default:
bb_show_usage();
return 1;
}
}
// The argv array can be used by the ":next" and ":rewind" commands
// save optind.
fn_start = optind; // remember first file name for :next and :rew
save_argc = argc;
//----- This is the main file handling loop --------------
if (optind >= argc) {
edit_file(0);
} else {
for (; optind < argc; optind++) {
edit_file(argv[optind]);
}
}
//-----------------------------------------------------------
return 0;
}
/* read text from file or create an empty buf */
/* will also update current_filename */
static int init_text_buffer(char *fn)
{
int rc;
int size = file_size(fn); // file size. -1 means does not exist.
/* allocate/reallocate text buffer */
free(text);
text_size = size + 10240;
screenbegin = dot = end = text = xzalloc(text_size);
if (fn != current_filename) {
free(current_filename);
current_filename = xstrdup(fn);
}
if (size < 0) {
// file dont exist. Start empty buf with dummy line
char_insert(text, '\n');
rc = 0;
} else {
rc = file_insert(fn, text
USE_FEATURE_VI_READONLY(, 1));
}
file_modified = 0;
last_file_modified = -1;
#if ENABLE_FEATURE_VI_YANKMARK
/* init the marks. */
memset(mark, 0, sizeof(mark));
#endif
return rc;
}
static void edit_file(char *fn)
{
#if ENABLE_FEATURE_VI_YANKMARK
#define cur_line edit_file__cur_line
#endif
char c;
editing = 1; // 0 = exit, 1 = one file, 2 = multiple files
if (rawmode()) {
perror("vi");
exit(5);
}
createScreen();
init_text_buffer(fn);
#if ENABLE_FEATURE_VI_YANKMARK
YDreg = 26; // default Yank/Delete reg
Ureg = 27; // hold orig line for "U" cmd
mark[26] = mark[27] = text; // init "previous context"
#endif
last_forward_char = last_input_char = '\0';
crow = 0;
ccol = 0;
tabstop = 8;
offset = 0; // no horizontal offset
clear_screen();
#if ENABLE_FEATURE_VI_USE_SIGNALS
catch_sig(0);
sigsetjmp(restart, 1);
signal(SIGWINCH, winch_sig);
signal(SIGTSTP, suspend_sig);
signal(SIGQUIT, quit_sig);
signal(SIGTERM, quit_sig);
signal(SIGPIPE, quit_sig);
signal(SIGHUP, quit_sig);
signal(SIGILL, quit_sig);
signal(SIGSEGV, quit_sig);
signal(SIGBUS, quit_sig);
signal(SIGABRT, quit_sig);
#endif
cmd_mode = CMODE_COMMAND;
cmdcnt = 0;
c = '\0';
#if ENABLE_FEATURE_VI_DOT_CMD
free(ioq_start);
ioq = ioq_start = NULL;
lmc_len = 0;
adding2q = 0;
#endif
#if ENABLE_FEATURE_VI_COLON
{
char *p, *q;
int n = 0;
while ((p = initial_cmds[n])) {
do {
q = p;
p = strchr(q, '\n');
if (p)
while (*p == '\n')
*p++ = '\0';
if (*q)
colon(q);
} while (p);
free(initial_cmds[n]);
initial_cmds[n] = NULL;
n++;
}
}
#endif
//------This is the main Vi cmd handling loop -----------------------
while (editing > 0) {
refresh();
#if ENABLE_FEATURE_VI_CRASHME
if (crashme > 0) {
if ((end - text) > 1) {
crash_dummy(); // generate a random command
} else {
crashme = 0;
dot = string_insert(text, // insert the string
"\n\n##### Ran out of text to work on. #####\n\n");
}
}
#endif
last_input_char = c = get_one_char(); // get a cmd from user
*status_buffer=0;
#if ENABLE_FEATURE_VI_YANKMARK
// save a copy of the current line- for the 'U" command
if (begin_line(dot) != cur_line) {
cur_line = begin_line(dot);
text_yank(begin_line(dot), end_line(dot), Ureg);
}
#endif
#if ENABLE_FEATURE_VI_DOT_CMD