-
Notifications
You must be signed in to change notification settings - Fork 594
/
vi.c
5052 lines (4727 loc) · 131 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 <sterling@europa.com>
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//
//Things To Do:
// ./.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
// An "ex" line oriented mode- maybe using "cmdedit"
//config:config VI
//config: bool "vi (23 kb)"
//config: default y
//config: help
//config: 'vi' is a text editor. More specifically, it is the One True
//config: text editor <grin>. It does, however, have a rather steep
//config: learning curve. If you are not already comfortable with 'vi'
//config: you may wish to use something else.
//config:
//config:config FEATURE_VI_MAX_LEN
//config: int "Maximum screen width"
//config: range 256 16384
//config: default 4096
//config: depends on VI
//config: help
//config: Contrary to what you may think, this is not eating much.
//config: Make it smaller than 4k only if you are very limited on memory.
//config:
//config:config FEATURE_VI_8BIT
//config: bool "Allow to display 8-bit chars (otherwise shows dots)"
//config: default n
//config: depends on VI
//config: help
//config: If your terminal can display characters with high bit set,
//config: you may want to enable this. Note: vi is not Unicode-capable.
//config: If your terminal combines several 8-bit bytes into one character
//config: (as in Unicode mode), this will not work properly.
//config:
//config:config FEATURE_VI_COLON
//config: bool "Enable \":\" colon commands (no \"ex\" mode)"
//config: default y
//config: depends on VI
//config: help
//config: Enable a limited set of colon commands. This does not
//config: provide an "ex" mode.
//config:
//config:config FEATURE_VI_COLON_EXPAND
//config: bool "Expand \"%\" and \"#\" in colon commands"
//config: default y
//config: depends on FEATURE_VI_COLON
//config: help
//config: Expand the special characters \"%\" (current filename)
//config: and \"#\" (alternate filename) in colon commands.
//config:
//config:config FEATURE_VI_YANKMARK
//config: bool "Enable yank/put commands and mark cmds"
//config: default y
//config: depends on VI
//config: help
//config: This enables you to use yank and put, as well as mark.
//config:
//config:config FEATURE_VI_SEARCH
//config: bool "Enable search and replace cmds"
//config: default y
//config: depends on VI
//config: help
//config: Select this if you wish to be able to do search and replace.
//config:
//config:config FEATURE_VI_REGEX_SEARCH
//config: bool "Enable regex in search and replace"
//config: default n # Uses GNU regex, which may be unavailable. FIXME
//config: depends on FEATURE_VI_SEARCH
//config: help
//config: Use extended regex search.
//config:
//config:config FEATURE_VI_USE_SIGNALS
//config: bool "Catch signals"
//config: default y
//config: depends on VI
//config: help
//config: Selecting this option will make vi signal aware. This will support
//config: SIGWINCH to deal with Window Changes, catch ^Z and ^C and alarms.
//config:
//config:config FEATURE_VI_DOT_CMD
//config: bool "Remember previous cmd and \".\" cmd"
//config: default y
//config: depends on VI
//config: help
//config: Make vi remember the last command and be able to repeat it.
//config:
//config:config FEATURE_VI_READONLY
//config: bool "Enable -R option and \"view\" mode"
//config: default y
//config: depends on VI
//config: help
//config: Enable the read-only command line option, which allows the user to
//config: open a file in read-only mode.
//config:
//config:config FEATURE_VI_SETOPTS
//config: bool "Enable settable options, ai ic showmatch"
//config: default y
//config: depends on VI
//config: help
//config: Enable the editor to set some (ai, ic, showmatch) options.
//config:
//config:config FEATURE_VI_SET
//config: bool "Support :set"
//config: default y
//config: depends on VI
//config:
//config:config FEATURE_VI_WIN_RESIZE
//config: bool "Handle window resize"
//config: default y
//config: depends on VI
//config: help
//config: Behave nicely with terminals that get resized.
//config:
//config:config FEATURE_VI_ASK_TERMINAL
//config: bool "Use 'tell me cursor position' ESC sequence to measure window"
//config: default y
//config: depends on VI
//config: help
//config: If terminal size can't be retrieved and $LINES/$COLUMNS are not set,
//config: this option makes vi perform a last-ditch effort to find it:
//config: position cursor to 999,999 and ask terminal to report real
//config: cursor position using "ESC [ 6 n" escape sequence, then read stdin.
//config: This is not clean but helps a lot on serial lines and such.
//config:
//config:config FEATURE_VI_UNDO
//config: bool "Support undo command \"u\""
//config: default y
//config: depends on VI
//config: help
//config: Support the 'u' command to undo insertion, deletion, and replacement
//config: of text.
//config:
//config:config FEATURE_VI_UNDO_QUEUE
//config: bool "Enable undo operation queuing"
//config: default y
//config: depends on FEATURE_VI_UNDO
//config: help
//config: The vi undo functions can use an intermediate queue to greatly lower
//config: malloc() calls and overhead. When the maximum size of this queue is
//config: reached, the contents of the queue are committed to the undo stack.
//config: This increases the size of the undo code and allows some undo
//config: operations (especially un-typing/backspacing) to be far more useful.
//config:
//config:config FEATURE_VI_UNDO_QUEUE_MAX
//config: int "Maximum undo character queue size"
//config: default 256
//config: range 32 65536
//config: depends on FEATURE_VI_UNDO_QUEUE
//config: help
//config: This option sets the number of bytes used at runtime for the queue.
//config: Smaller values will create more undo objects and reduce the amount
//config: of typed or backspaced characters that are grouped into one undo
//config: operation; larger values increase the potential size of each undo
//config: and will generally malloc() larger objects and less frequently.
//config: Unless you want more (or less) frequent "undo points" while typing,
//config: you should probably leave this unchanged.
//config:
//config:config FEATURE_VI_VERBOSE_STATUS
//config: bool "Enable verbose status reporting"
//config: default y
//config: depends on VI
//config: help
//config: Enable more verbose reporting of the results of yank, change,
//config: delete, undo and substitution commands.
//applet:IF_VI(APPLET(vi, BB_DIR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_VI) += vi.o
//usage:#define vi_trivial_usage
//usage: IF_FEATURE_VI_COLON("[-c CMD] ")IF_FEATURE_VI_READONLY("[-R] ")"[-H] [FILE]..."
//usage:#define vi_full_usage "\n\n"
//usage: "Edit FILE\n"
//usage: IF_FEATURE_VI_COLON(
//usage: "\n -c CMD Initial command to run ($EXINIT and ~/.exrc also available)"
//usage: )
//usage: IF_FEATURE_VI_READONLY(
//usage: "\n -R Read-only"
//usage: )
//usage: "\n -H List available features"
// note: non-standard, "vim -H" is Hebrew mode (bidi support)
#include "libbb.h"
// Should be after libbb.h: on some systems regex.h needs sys/types.h:
#if ENABLE_FEATURE_VI_REGEX_SEARCH
# include <regex.h>
#endif
// the CRASHME code is unmaintained, and doesn't currently build
#define ENABLE_FEATURE_VI_CRASHME 0
#define IF_FEATURE_VI_CRASHME(...)
#if ENABLE_LOCALE_SUPPORT
#if ENABLE_FEATURE_VI_8BIT
//FIXME: this does not work properly for Unicode anyway
# define Isprint(c) (isprint)(c)
#else
# define Isprint(c) isprint_asciionly(c)
#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
#define isbackspace(c) ((c) == term_orig.c_cc[VERASE] || (c) == 8 || (c) == 127)
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,
};
// VT102 ESC sequences.
// See "Xterm Control Sequences"
// http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
#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"
//UNUSED
//// Cursor up and down
//#define ESC_CURSOR_UP ESC"[A"
//#define ESC_CURSOR_DOWN "\n"
#if ENABLE_FEATURE_VI_DOT_CMD
// cmds modifying text[]
static const char modifying_cmds[] ALIGN1 = "aAcCdDiIJoOpPrRs""xX<>~";
#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, // 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
};
// 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
#if ENABLE_FEATURE_VI_SETOPTS
smallint 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"
#else
#define autoindent (0)
#define expandtab (0)
#define err_method (0)
#define ignorecase (0)
#endif
#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, 1 or 2 only"]
smallint cmd_mode; // 0=command 1=insert 2=replace
int modified_count; // buffer contents changed if !0
int last_modified_count; // = -1;
int cmdline_filecnt; // how many file names on cmd line
int cmdcnt; // repetition count
char *rstart; // start of text in Replace mode
unsigned rows, columns; // the terminal screen is this size
#if ENABLE_FEATURE_VI_ASK_TERMINAL
int get_rowcol_error;
#endif
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 smallint!]
int last_status_cksum; // hash of current status line
char *current_filename;
#if ENABLE_FEATURE_VI_COLON_EXPAND
char *alt_filename;
#endif
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)
smallint last_search_cmd; // command used to invoke last char search
#if ENABLE_FEATURE_VI_CRASHME
char last_input_char; // last char read from user
#endif
#if ENABLE_FEATURE_VI_UNDO_QUEUE
char undo_queue_state; // One of UNDO_INS, UNDO_DEL, UNDO_EMPTY
#endif
#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"
int dotcnt; // number of times to repeat '.' command
#endif
#if ENABLE_FEATURE_VI_SEARCH
char *last_search_pattern; // last pattern from a '/' or '?' search
#endif
#if ENABLE_FEATURE_VI_SETOPTS
int char_insert__indentcol; // column of recent autoindent or 0
int newindent; // autoindent value for 'O'/'cc' commands
// or -1 to use indent from previous line
#endif
smallint cmd_error;
// 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
smalluint 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 ''
#endif
#if ENABLE_FEATURE_VI_USE_SIGNALS
sigjmp_buf restart; // int_handler() jumps to location remembered here
#endif
struct termios term_orig; // remember what the cooked mode was
int cindex; // saved character index for up/down motion
smallint keep_index; // retain saved character index
#if ENABLE_FEATURE_VI_COLON
llist_t *initial_cmds;
#endif
// Should be just enough to hold a key sequence,
// but CRASHME mode uses it as generated command buffer too
#if ENABLE_FEATURE_VI_CRASHME
char readbuffer[128];
#else
char readbuffer[KEYCODE_BUFFER_SIZE];
#endif
#define STATUS_BUFFER_LEN 200
char status_buffer[STATUS_BUFFER_LEN]; // messages to the user
#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];
#if ENABLE_FEATURE_VI_UNDO
// undo_push() operations
#define UNDO_INS 0
#define UNDO_DEL 1
#define UNDO_INS_CHAIN 2
#define UNDO_DEL_CHAIN 3
# if ENABLE_FEATURE_VI_UNDO_QUEUE
#define UNDO_INS_QUEUED 4
#define UNDO_DEL_QUEUED 5
# endif
// Pass-through flags for functions that can be undone
#define NO_UNDO 0
#define ALLOW_UNDO 1
#define ALLOW_UNDO_CHAIN 2
# if ENABLE_FEATURE_VI_UNDO_QUEUE
#define ALLOW_UNDO_QUEUED 3
# else
// If undo queuing disabled, don't invoke the missing queue logic
#define ALLOW_UNDO_QUEUED ALLOW_UNDO
# endif
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;
# if ENABLE_FEATURE_VI_UNDO_QUEUE
#define UNDO_USE_SPOS 32
#define UNDO_EMPTY 64
char *undo_queue_spos; // Start position of queued operation
int undo_q;
char undo_queue[CONFIG_FEATURE_VI_UNDO_QUEUE_MAX];
# endif
#endif /* ENABLE_FEATURE_VI_UNDO */
};
#define G (*ptr_to_globals)
#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 cmdline_filecnt (G.cmdline_filecnt )
#define cmdcnt (G.cmdcnt )
#define rstart (G.rstart )
#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 alt_filename (G.alt_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 )
#if ENABLE_FEATURE_VI_CRASHME
#define last_input_char (G.last_input_char )
#endif
#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 dotcnt (G.dotcnt )
#define last_search_pattern (G.last_search_pattern)
#define char_insert__indentcol (G.char_insert__indentcol)
#define newindent (G.newindent )
#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 Ureg (G.Ureg )
#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)
#if ENABLE_FEATURE_VI_UNDO
#define undo_stack_tail (G.undo_stack_tail )
# if ENABLE_FEATURE_VI_UNDO_QUEUE
#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 )
# endif
#endif
#define INIT_G() do { \
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
last_modified_count--; \
/* "" but has space for 2 chars: */ \
IF_FEATURE_VI_SEARCH(last_search_pattern = xzalloc(2);) \
tabstop = 8; \
IF_FEATURE_VI_SETOPTS(newindent--;) \
} while (0)
#if ENABLE_FEATURE_VI_CRASHME
static int crashme = 0;
#endif
static void show_status_line(void); // put a message on the bottom line
static void status_line_bold(const char *, ...);
static void show_help(void)
{
puts("These features are available:"
#if ENABLE_FEATURE_VI_SEARCH
"\n\tPattern searches with / and ?"
#endif
#if ENABLE_FEATURE_VI_DOT_CMD
"\n\tLast command repeat with ."
#endif
#if ENABLE_FEATURE_VI_YANKMARK
"\n\tLine marking with 'x"
"\n\tNamed buffers with \"x"
#endif
#if ENABLE_FEATURE_VI_READONLY
//not implemented: "\n\tReadonly if vi is called as \"view\""
//redundant: usage text says this too: "\n\tReadonly with -R command line arg"
#endif
#if ENABLE_FEATURE_VI_SET
"\n\tSome colon mode commands with :"
#endif
#if ENABLE_FEATURE_VI_SETOPTS
"\n\tSettable options with \":set\""
#endif
#if ENABLE_FEATURE_VI_USE_SIGNALS
"\n\tSignal catching- ^C"
"\n\tJob suspend and resume with ^Z"
#endif
#if ENABLE_FEATURE_VI_WIN_RESIZE
"\n\tAdapt to window re-sizes"
#endif
);
}
static void write1(const char *out)
{
fputs_stdout(out);
}
#if ENABLE_FEATURE_VI_WIN_RESIZE
static int query_screen_dimensions(void)
{
int err = get_terminal_width_height(STDIN_FILENO, &columns, &rows);
if (rows > MAX_SCR_ROWS)
rows = MAX_SCR_ROWS;
if (columns > MAX_SCR_COLS)
columns = MAX_SCR_COLS;
return err;
}
#else
static ALWAYS_INLINE int query_screen_dimensions(void)
{
return 0;
}
#endif
// sleep for 'h' 1/100 seconds, return 1/0 if stdin is (ready for read)/(not ready)
static int mysleep(int hund)
{
struct pollfd pfd[1];
if (hund != 0)
fflush_all();
pfd[0].fd = STDIN_FILENO;
pfd[0].events = POLLIN;
return safe_poll(pfd, 1, hund*10) > 0;
}
//----- Set terminal attributes --------------------------------
static void rawmode(void)
{
// no TERMIOS_CLEAR_ISIG: leave ISIG on - allow signals
set_termios_to_raw(STDIN_FILENO, &term_orig, TERMIOS_RAW_CRNL);
}
static void cookmode(void)
{
fflush_all();
tcsetattr_stdin_TCSANOW(&term_orig);
}
//----- 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);
write1(cm1);
}
//----- Erase from cursor to end of line -----------------------
static void clear_to_eol(void)
{
write1(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)
{
write1(ESC_BOLD_TEXT);
}
//----- End standout mode --------------------------------------
static void standout_end(void)
{
write1(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 ((unsigned char)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;
free(screen);
screensize = ro * co + 8;
s = screen = xmalloc(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*/)
{
unsigned char 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) && !Isprint(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)
{
#define old_offset refresh__old_offset
int li, changed;
char *tp, *sp; // pointer into text[] and screen[]
if (ENABLE_FEATURE_VI_WIN_RESIZE IF_FEATURE_VI_ASK_TERMINAL(&& !G.get_rowcol_error) ) {