-
Notifications
You must be signed in to change notification settings - Fork 22
/
tte.c
2168 lines (1941 loc) · 71.5 KB
/
tte.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
/*
* Copyright (C) 2017-* GrenderG
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*** Include section ***/
// We add them above our includes, because the header
// files we are including use the macros to decide what
// features to expose. These macros remove some compilation
// warnings. See
// https://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
// for more info.
#define _DEFAULT_SOURCE
#define _BSD_SOURCE
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
/*** Define section ***/
// This mimics the Ctrl + whatever behavior, setting the
// 3 upper bits of the character pressed to 0.
#define CTRL_KEY(k) ((k) & 0x1f)
// Empty buffer
#define ABUF_INIT {NULL, 0}
// Version code
#define TTE_VERSION "0.1.1"
// Length of a tab stop
#define TTE_TAB_STOP 4
// Times to press Ctrl-Q before exiting
#define TTE_QUIT_TIMES 2
// Highlight flags
#define HL_HIGHLIGHT_NUMBERS (1 << 0)
#define HL_HIGHLIGHT_STRINGS (1 << 1)
// Status print indicators
#define NO_STATUS false
#define STATUS_YES true
// Max Undo/Redo Operations
// Set to -1 for unlimited Undo
// Set to 0 to disable Undo
#define ACTIONS_LIST_MAX_SIZE 80
typedef struct ActionList ActionList;
/*** Data section ***/
typedef struct editor_row {
int idx; // Row own index within the file.
int size; // Size of the content (excluding NULL term)
int render_size; // Size of the rendered content
char* chars; // Row content
char* render; // Row content "rendered" for screen (for TABs).
unsigned char* highlight; // This will tell you if a character is part of a string, comment, number...
int hl_open_comment; // True if the line is part of a ML comment.
} editor_row;
struct editor_syntax {
// file_type field is the name of the filetype that will be displayed
// to the user in the status bar.
char* file_type;
// file_match is an array of strings, where each string contains a
// pattern to match a filename against. If the filename matches,
// then the file will be recognized as having that filetype.
char** file_match;
// This will be a NULL-terminated array of strings, each string containing
// a keyword. To differentiate between the two types of keywords,
// we’ll terminate the second type of keywords with a pipe (|)
// character (also known as a vertical bar).
char** keywords;
// We let each language specify its own single-line comment pattern.
char* singleline_comment_start;
// flags is a bit field that will contain flags for whether to
// highlight numbers and whether to highlight strings for that
// filetype.
char* multiline_comment_start;
char* multiline_comment_end;
int flags;
};
struct editor_config {
int cursor_x;
int cursor_y;
int render_x;
int row_offset; // Offset of row displayed.
int col_offset; // Offset of col displayed.
int screen_rows; // Number of rows that we can show
int screen_cols; // Number of cols that we can show
int num_rows; // Number of rows
editor_row* row;
int dirty; // To know if a file has been modified since opening.
unsigned use_tabs : 1; // 1 means use tabs as tabs, 0 means spaces
char* file_name;
char extension[10];
char status_msg[80];
time_t status_msg_time;
char* copied_char_buffer;
struct editor_syntax* syntax;
struct termios orig_termios;
ActionList* actions;
} ec;
// Having a dynamic buffer will allow us to write only one
// time once the screen is refreshing, instead of doing
// a lot of write's.
struct a_buf {
char* buf;
int len;
};
enum editor_key {
BACKSPACE = 0x7f, // 127
ARROW_LEFT = 0x3e8, // 1000, large value out of the range of a char.
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN,
PAGE_UP,
PAGE_DOWN,
HOME_KEY,
END_KEY,
DEL_KEY
};
enum editor_highlight {
HL_NORMAL = 0,
HL_SL_COMMENT,
HL_ML_COMMENT,
HL_KEYWORD_1,
HL_KEYWORD_2,
HL_STRING,
HL_NUMBER,
HL_MATCH
};
/*** Edit actions ***/
enum ActionType {
CutLine,
PasteLine,
FlipUp,
FlipDown,
NewLine,
InsertChar,
DelChar,
};
typedef enum ActionType ActionType;
/*** Filetypes ***/
char* C_HL_extensions[] = {".c", ".h", ".cpp", ".hpp", ".cc", NULL}; // Array must be terminated with NULL.
char* JAVA_HL_extensions[] = {".java", NULL};
char* PYTHON_HL_extensions[] = {".py",".pyw",".py3",".pyc",".pyo", NULL};
char* BASH_HL_extensions[] = {".sh", NULL};
char* JS_HL_extensions[] = {".js", ".jsx", NULL};
char* PHP_HL_extensions[] = {".php",".phtml", NULL};
char* JSON_HL_extensions[] = {".json", ".jsonp", NULL};
char* XML_HL_extensions[] = {".xml", NULL};
char* SQL_HL_extensions[] = {".sql", NULL};
char* RUBY_HL_extensions[] = {".rb", NULL};
char* C_HL_keywords[] = {
"switch", "if", "while", "for", "break", "continue", "return", "else",
"struct", "union", "typedef", "static", "enum", "case", "#include",
"volatile", "register", "sizeof", "typedef", "union", "goto", "const", "auto",
"#define", "#if", "#endif", "#error", "#ifdef", "#ifndef", "#undef",
"asm" /* in stdbool.h */ , "bool" , "true" , "fasle" , "inline" ,
// C++
"class" , "namespace" , "using" , "catch" , "delete" , "explicit" ,
"export" , "friend" , "mutable" , "new" , "public" , "protected" ,
"private" , "operator" , "this" , "template" , "virtual" , "throw" ,
"try" , "typeid" ,
"int|", "long|", "double|", "float|", "char|", "unsigned|", "signed|",
"void|", "bool|", NULL
};
char* JAVA_HL_keywords[] = {
"switch", "if", "while", "for", "break", "continue", "return", "else",
"in", "public", "private", "protected", "static", "final", "abstract",
"enum", "class", "case", "try", "catch", "do", "extends", "implements",
"finally", "import", "instanceof", "interface", "new", "package", "super",
"native", "strictfp",
"synchronized", "this", "throw", "throws", "transient", "volatile",
"byte|", "char|", "double|", "float|", "int|", "long|", "short|",
"boolean|", NULL
};
char* PYTHON_HL_keywords[] = {
"and", "as", "assert", "break", "class", "continue", "def", "del", "elif",
"else", "except", "exec", "finally", "for", "from", "global", "if", "import",
"in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try",
"while", "with", "yield",
"buffer|", "bytearray|", "complex|", "False|", "float|", "frozenset|", "int|",
"list|", "long|", "None|", "set|", "str|", "tuple|", "True|", "type|",
"unicode|", "xrange|", NULL
};
char* BASH_HL_keywords[] = {
"case", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if",
"in", "select", "then", "time", "until", "while", "alias", "bg", "bind", "break",
"builtin", "cd", "command", "continue", "declare", "dirs", "disown", "echo",
"enable", "eval", "exec", "exit", "export", "fc", "fg", "getopts", "hash", "help",
"history", "jobs", "kill", "let", "local", "logout", "popd", "pushd", "pwd", "read",
"readonly", "return", "set", "shift", "suspend", "test", "times", "trap", "type",
"typeset", "ulimit", "umask", "unalias", "unset", "wait", "printf", NULL
};
char* JS_HL_keywords[] = {
"break", "case", "catch", "class", "const", "continue", "debugger", "default",
"delete", "do", "else", "enum", "export", "extends", "finally", "for", "function",
"if", "implements", "import", "in", "instanceof", "interface", "let", "new",
"package", "private", "protected", "public", "return", "static", "super", "switch",
"this", "throw", "try", "typeof", "var", "void", "while", "with", "yield", "true",
"false", "null", "NaN", "global", "window", "prototype", "constructor", "document",
"isNaN", "arguments", "undefined",
"Infinity|", "Array|", "Object|", "Number|", "String|", "Boolean|", "Function|",
"ArrayBuffer|", "DataView|", "Float32Array|", "Float64Array|", "Int8Array|",
"Int16Array|", "Int32Array|", "Uint8Array|", "Uint8ClampedArray|", "Uint32Array|",
"Date|", "Error|", "Map|", "RegExp|", "Symbol|", "WeakMap|", "WeakSet|", "Set|", NULL
};
char* PHP_HL_keywords[] = {
"__halt_compiler", "break", "clone", "die", "empty", "endswitch", "final", "global",
"include_once", "list", "private", "return", "try", "xor", "abstract", "callable",
"const", "do", "enddeclare", "endwhile", "finally", "goto", "instanceof", "namespace",
"protected", "static", "unset", "yield", "and", "case", "continue", "echo", "endfor",
"eval", "for", "if", "insteadof", "new", "public", "switch", "use", "array", "catch",
"declare", "else", "endforeach", "exit", "foreach", "implements", "interface", "or",
"require", "throw", "var", "as", "class", "default", "elseif", "endif", "extends",
"function", "include", "isset", "print", "require_once", "trait", "while", NULL
};
char* JSON_HL_keywords[] = {
NULL
};
char* XML_HL_keywords[] = {
NULL
};
char* SQL_HL_keywords[] = {
"SELECT", "FROM", "DROP", "CREATE", "TABLE", "DEFAULT", "FOREIGN", "UPDATE", "LOCK",
"INSERT", "INTO", "VALUES", "LOCK", "UNLOCK", "WHERE", "DINSTINCT", "BETWEEN", "NOT",
"NULL", "TO", "ON", "ORDER", "GROUP", "IF", "BY", "HAVING", "USING", "UNION", "UNIQUE",
"AUTO_INCREMENT", "LIKE", "WITH", "INNER", "OUTER", "JOIN", "COLUMN", "DATABASE", "EXISTS",
"NATURAL", "LIMIT", "UNSIGNED", "MAX", "MIN", "PRECISION", "ALTER", "DELETE", "CASCADE",
"PRIMARY", "KEY", "CONSTRAINT", "ENGINE", "CHARSET", "REFERENCES", "WRITE",
"BIT|", "TINYINT|", "BOOL|", "BOOLEAN|", "SMALLINT|", "MEDIUMINT|", "INT|", "INTEGER|",
"BIGINT|", "DOUBLE|", "DECIMAL|", "DEC|" "FLOAT|", "DATE|", "DATETIME|", "TIMESTAMP|",
"TIME|", "YEAR|", "CHAR|", "VARCHAR|", "TEXT|", "ENUM|", "SET|", "BLOB|", "VARBINARY|",
"TINYBLOB|", "TINYTEXT|", "MEDIUMBLOB|", "MEDIUMTEXT|", "LONGTEXT|",
"select", "from", "drop", "create", "table", "default", "foreign", "update", "lock",
"insert", "into", "values", "lock", "unlock", "where", "dinstinct", "between", "not",
"null", "to", "on", "order", "group", "if", "by", "having", "using", "union", "unique",
"auto_increment", "like", "with", "inner", "outer", "join", "column", "database", "exists",
"natural", "limit", "unsigned", "max", "min", "precision", "alter", "delete", "cascade",
"primary", "key", "constraint", "engine", "charset", "references", "write",
"bit|", "tinyint|", "bool|", "boolean|", "smallint|", "mediumint|", "int|", "integer|",
"bigint|", "double|", "decimal|", "dec|" "float|", "date|", "datetime|", "timestamp|",
"time|", "year|", "char|", "varchar|", "text|", "enum|", "set|", "blob|", "varbinary|",
"tinyblob|", "tinytext|", "mediumblob|", "mediumtext|", "longtext|", NULL
};
char* RUBY_HL_keywords[] = {
"__ENCODING__", "__LINE__", "__FILE__", "BEGIN", "END", "alias", "and", "begin", "break",
"case", "class", "def", "defined?", "do", "else", "elsif", "end", "ensure", "for", "if",
"in", "module", "next", "not", "or", "redo", "rescue", "retry", "return", "self", "super",
"then", "undef", "unless", "until", "when", "while", "yield", NULL
};
struct editor_syntax HL_DB[] = {
{
"c",
C_HL_extensions,
C_HL_keywords,
"//",
"/*",
"*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"java",
JAVA_HL_extensions,
JAVA_HL_keywords,
"//",
"/*",
"*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"python",
PYTHON_HL_extensions,
PYTHON_HL_keywords,
"#",
"'''",
"'''",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"bash",
BASH_HL_extensions,
BASH_HL_keywords,
"#",
NULL,
NULL,
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"js",
JS_HL_extensions,
JS_HL_keywords,
"//",
"/*",
"*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"php",
PHP_HL_extensions,
PHP_HL_keywords,
"//",
"/*",
"*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"json",
JSON_HL_extensions,
JSON_HL_keywords,
NULL,
NULL,
NULL,
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"xml",
XML_HL_extensions,
XML_HL_keywords,
NULL,
NULL,
NULL,
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"sql",
SQL_HL_extensions,
SQL_HL_keywords,
"--",
"/*",
"*/",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
},
{
"ruby",
RUBY_HL_extensions,
RUBY_HL_keywords,
"#",
"=begin",
"=end",
HL_HIGHLIGHT_NUMBERS | HL_HIGHLIGHT_STRINGS
}
};
// Size of the "Hightlight Database" (HL_DB).
#define HL_DB_ENTRIES (sizeof(HL_DB) / sizeof(HL_DB[0]))
/*** Declarations section ***/
void editorClearScreen();
void editorRefreshScreen();
void editorSetStatusMessage(const char* msg, ...);
void consoleBufferOpen();
void abufFree();
void abufAppend();
char *editorPrompt(char* prompt, void (*callback)(char*, int));
void editorRowAppendString(editor_row* row, char* s, size_t len);
void editorInsertNewline();
/*** Terminal section ***/
void die(const char* s) {
editorClearScreen();
// perror looks for global errno variable and then prints
// a descriptive error mesage for it.
perror(s);
printf("\r\n");
exit(1);
}
void disableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &ec.orig_termios) == -1)
die("Failed to disable raw mode");
}
void enableRawMode() {
// Save original terminal state into orig_termios.
if (tcgetattr(STDIN_FILENO, &ec.orig_termios) == -1)
die("Failed to get current terminal state");
// At exit, restore the original state.
atexit(disableRawMode);
// Modify the original state to enter in raw mode.
struct termios raw = ec.orig_termios;
// This disables Ctrl-M, Ctrl-S and Ctrl-Q commands.
// (BRKINT, INPCK and ISTRIP are not estrictly mandatory,
// but it is recommended to turn them off in case any
// system needs it).
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
// Turning off all output processing (\r\n).
raw.c_oflag &= ~(OPOST);
// Setting character size to 8 bits per byte (it should be
// like that on most systems, but whatever).
raw.c_cflag |= (CS8);
// Using NOT operator on ECHO | ICANON | IEXTEN | ISIG and
// then bitwise-AND them with flags field in order to
// force c_lflag 4th bit to become 0. This disables
// chars being printed (ECHO) and let us turn off
// canonical mode in order to read input byte-by-byte
// instead of line-by-line (ICANON), ISIG disables
// Ctrl-C command and IEXTEN the Ctrl-V one.
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
// read() function now returns as soon as there is any
// input to be read.
raw.c_cc[VMIN] = 0;
// Forcing read() function to return every 1/10 of a
// second if there is nothing to read.
raw.c_cc[VTIME] = 1;
consoleBufferOpen();
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1)
die("Failed to set raw mode");
}
int editorReadKey() {
int nread;
char c;
while ((nread = read(STDIN_FILENO, &c, 1)) != 1) {
// Ignoring EAGAIN to make it work on Cygwin.
if (nread == -1 && errno != EAGAIN)
die("Error reading input");
}
// Check escape sequences, if first byte
// is an escape character then...
if (c == '\x1b') {
char seq[3];
if (read(STDIN_FILENO, &seq[0], 1) != 1 ||
read(STDIN_FILENO, &seq[1], 1) != 1)
return '\x1b';
if (seq[0] == '[') {
if (seq[1] >= '0' && seq[1] <= '9') {
if (read(STDIN_FILENO, &seq[2], 1) != 1)
return '\x1b';
if (seq[2] == '~') {
switch (seq[1]) {
// Home and End keys may be sent in many ways depending on the OS
// \x1b[1~, \x1b[7~, \x1b[4~, \x1b[8~
case '1':
case '7':
return HOME_KEY;
case '4':
case '8':
return END_KEY;
// Del key is sent as \x1b[3~
case '3':
return DEL_KEY;
// Page Up and Page Down send '\x1b', '[', '5' or '6' and '~'.
case '5': return PAGE_UP;
case '6': return PAGE_DOWN;
}
}
} else {
switch (seq[1]) {
// Arrow keys send multiple bytes starting with '\x1b', '[''
// and followed by an 'A', 'B', 'C' or 'D' depending on which
// arrow is pressed.
case 'A': return ARROW_UP;
case 'B': return ARROW_DOWN;
case 'C': return ARROW_RIGHT;
case 'D': return ARROW_LEFT;
// Home key can also be sent as \x1b[H
case 'H': return HOME_KEY;
// End key can also be sent as \x1b[F
case 'F': return END_KEY;
}
}
} else if (seq[0] == 'O') {
switch (seq[1]) {
// Yes, Home key can ALSO be sent as \x1bOH
case 'H': return HOME_KEY;
// And... End key as \x1bOF
case 'F': return END_KEY;
}
}
return '\x1b';
} else {
return c;
}
}
int getWindowSize(int* screen_rows, int* screen_cols) {
struct winsize ws;
// Getting window size thanks to ioctl into the given
// winsize struct.
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
return -1;
} else {
*screen_cols = ws.ws_col;
*screen_rows = ws.ws_row;
return 0;
}
}
void editorUpdateWindowSize() {
if (getWindowSize(&ec.screen_rows, &ec.screen_cols) == -1)
die("Failed to get window size");
ec.screen_rows -= 2; // Room for the status bar.
}
void editorHandleSigwinch() {
editorUpdateWindowSize();
if (ec.cursor_y > ec.screen_rows)
ec.cursor_y = ec.screen_rows - 1;
if (ec.cursor_x > ec.screen_cols)
ec.cursor_x = ec.screen_cols - 1;
editorRefreshScreen();
}
void editorHandleSigcont() {
disableRawMode();
consoleBufferOpen();
enableRawMode();
editorRefreshScreen();
}
void consoleBufferOpen() {
// Switch to another terminal buffer in order to be able to restore state at exit
// by calling consoleBufferClose().
if (write(STDOUT_FILENO, "\x1b[?47h", 6) == -1)
die("Error changing terminal buffer");
}
void consoleBufferClose() {
// Restore console to the state tte opened.
if (write(STDOUT_FILENO, "\x1b[?9l", 5) == -1 ||
write(STDOUT_FILENO, "\x1b[?47l", 6) == -1)
die("Error restoring buffer state");
/*struct a_buf ab = {.buf = NULL, .len = 0};
char* buf = NULL;
if (asprintf(&buf, "\x1b[%d;%dH\r\n", ec.screen_rows + 1, 1) == -1)
die("Error restoring buffer state");
abufAppend(&ab, buf, strlen(buf));
free(buf);
if (write(STDOUT_FILENO, ab.buf, ab.len) == -1)
die("Error restoring buffer state");
abufFree(&ab);*/
editorClearScreen();
}
/*** Syntax highlighting ***/
int isSeparator(int c) {
// strchr() looks to see if any one of the characters in the first string
// appear in the second string. If so, it returns a pointer to the
// character in the second string that matched. Otherwise, it
// returns NULL.
return isspace(c) || c == '\0' || strchr(",.()+-/*=~%<>[]:;", c) != NULL;
}
int isAlsoNumber(int c) {
return c == '.' || c == 'x' || c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f';
}
void editorUpdateSyntax(editor_row* row) {
row -> highlight = realloc(row -> highlight, row -> render_size);
// void * memset ( void * ptr, int value, size_t num );
// Sets the first num bytes of the block of memory pointed by ptr to
// the specified value. With this we set all characters to HL_NORMAL.
memset(row -> highlight, HL_NORMAL, row -> render_size);
if (ec.syntax == NULL)
return;
char** keywords = ec.syntax -> keywords;
char* scs = ec.syntax -> singleline_comment_start;
char* mcs = ec.syntax -> multiline_comment_start;
char* mce = ec.syntax -> multiline_comment_end;
int scs_len = scs ? strlen(scs) : 0;
int mcs_len = mcs ? strlen(mcs) : 0;
int mce_len = mce ? strlen(mce) : 0;
int prev_sep = 1; // True (1) if the previous char is a separator, false otherwise.
int in_string = 0; // If != 0, inside a string. We also keep track if it's ' or "
int in_comment = (row -> idx > 0 && ec.row[row -> idx - 1].hl_open_comment); // This is ONLY used on ML comments.
int i = 0;
while (i < row -> render_size) {
char c = row -> render[i];
// Highlight type of the previous character.
unsigned char prev_highlight = (i > 0) ? row -> highlight[i - 1] : HL_NORMAL;
if (scs_len && !in_string && !in_comment) {
// int strncmp ( const char * str1, const char * str2, size_t num );
// Compares up to num characters of the C string str1 to those of the C string str2.
// This function starts comparing the first character of each string. If they are
// equal to each other, it continues with the following pairs until the characters
// differ, until a terminating null-character is reached, or until num characters
// match in both strings, whichever happens first.
if (!strncmp(&row -> render[i], scs, scs_len)) {
memset(&row -> highlight[i], HL_SL_COMMENT, row -> render_size - i);
break;
}
}
if (mcs_len && mce_len && !in_string) {
if (in_comment) {
row -> highlight[i] = HL_ML_COMMENT;
if (!strncmp(&row -> render[i], mce, mce_len)) {
memset(&row -> highlight[i], HL_ML_COMMENT, mce_len);
i += mce_len;
in_comment = 0;
prev_sep = 1;
continue;
} else {
i++;
continue;
}
} else if (!strncmp(&row -> render[i], mcs, mcs_len)) {
memset(&row -> highlight[i], HL_ML_COMMENT, mcs_len);
i += mcs_len;
in_comment = 1;
continue;
}
}
if (ec.syntax -> flags & HL_HIGHLIGHT_STRINGS) {
if (in_string) {
row -> highlight[i] = HL_STRING;
// If we’re in a string and the current character is a backslash (\),
// and there’s at least one more character in that line that comes
// after the backslash, then we highlight the character that comes
// after the backslash with HL_STRING and consume it. We increment
// i by 2 to consume both characters at once.
if (c == '\\' && i + 1 < row -> render_size) {
row -> highlight[i + 1] = HL_STRING;
i += 2;
continue;
}
if (c == in_string)
in_string = 0;
i++;
prev_sep = 1;
continue;
} else {
if (c == '"' || c == '\'') {
in_string = c;
row -> highlight[i] = HL_STRING;
i++;
continue;
}
}
}
if (ec.syntax -> flags & HL_HIGHLIGHT_NUMBERS) {
if ((isdigit(c) && (prev_sep || prev_highlight == HL_NUMBER)) ||
(isAlsoNumber(c) && prev_highlight == HL_NUMBER)) {
row -> highlight[i] = HL_NUMBER;
i++;
prev_sep = 0;
continue;
}
}
if (prev_sep) {
int j;
for (j = 0; keywords[j]; j++) {
int kw_len = strlen(keywords[j]);
int kw_2 = keywords[j][kw_len - 1] == '|';
if (kw_2)
kw_len--;
// Keywords require a separator both before and after the keyword.
if (!strncmp(&row -> render[i], keywords[j], kw_len) &&
isSeparator(row -> render[i + kw_len])) {
memset(&row -> highlight[i], kw_2 ? HL_KEYWORD_2 : HL_KEYWORD_1, kw_len);
i += kw_len;
break;
}
}
if (keywords[j] != NULL) {
prev_sep = 0;
continue;
}
}
prev_sep = isSeparator(c);
i++;
}
int changed = (row -> hl_open_comment != in_comment);
// This tells us whether the row ended as an unclosed multi-line
// comment or not.
row -> hl_open_comment = in_comment;
// A user could comment out an entire file just by changing one line.
// So it seems like we need to update the syntax of all the lines
// following the current line. However, we know the highlighting
// of the next line will not change if the value of this line’s
// // // hl_open_comment did not change. So we check if it changed, and
// // only call editorUpdateSyntax() on the next line if
// hl_open_comment changed (and if there is a next line in the file).
// Because editorUpdateSyntax() keeps calling itself with the next
// line, the change will continue to propagate to more and more lines
// until one of them is unchanged, at which point we know that all
// the lines after that one must be unchanged as well.
if (changed && row -> idx + 1 < ec.num_rows)
editorUpdateSyntax(&ec.row[row -> idx + 1]);
}
int editorSyntaxToColor(int highlight) {
// We return ANSI codes for colors.
// See https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
// for a list of them.
switch (highlight) {
case HL_SL_COMMENT:
case HL_ML_COMMENT: return 36;
case HL_KEYWORD_1: return 31;
case HL_KEYWORD_2: return 32;
case HL_STRING: return 33;
case HL_NUMBER: return 35;
case HL_MATCH: return 34;
default: return 37;
}
}
void editorApplySyntaxHighlight() {
if (ec.syntax == NULL)
return;
int file_row;
for (file_row = 0; file_row < ec.num_rows; file_row++) {
editorUpdateSyntax(&ec.row[file_row]);
}
}
void editorSelectSyntaxHighlight() {
ec.syntax = NULL;
if (ec.file_name == NULL)
return;
char* ext_name = ec.extension[0] == '\0' ? ec.file_name : ec.extension;
for (unsigned int j = 0; j < HL_DB_ENTRIES; j++) {
struct editor_syntax* es = &HL_DB[j];
unsigned int i = 0;
while (es -> file_match[i]) {
char* p = strstr(ext_name, es -> file_match[i]);
if (p != NULL) {
// Returns a pointer to the first occurrence of str2 in str1,
// or a null pointer if str2 is not part of str1.
int pat_len = strlen(es -> file_match[i]);
if (es -> file_match[i][0] != '.' || p[pat_len] == '\0') {
ec.syntax = es;
size_t len = strlen(es -> file_match[i]);
strncpy(ec.extension, es -> file_match[i], len);
// Apply the highlighting
editorApplySyntaxHighlight();
return;
}
}
i++;
}
}
}
/*** Row operations ***/
int editorRowCursorXToRenderX(editor_row* row, int cursor_x) {
int render_x = 0;
int j;
// For each character, if its a tab we use rx % TTE_TAB_STOP
// to find out how many columns we are to the right of the last
// tab stop, and then subtract that from TTE_TAB_STOP - 1 to
// find out how many columns we are to the left of the next tab
// stop. We add that amount to rx to get just to the left of the
// next tab stop, and then the unconditional rx++ statement gets
// us right on the next tab stop. Notice how this works even if
// we are currently on a tab stop.
for (j = 0; j < cursor_x; j++) {
if (row -> chars[j] == '\t')
render_x += (TTE_TAB_STOP - 1) - (render_x % TTE_TAB_STOP);
render_x++;
}
return render_x;
}
int editorRowRenderXToCursorX(editor_row* row, int render_x) {
int cur_render_x = 0;
int cursor_x;
for (cursor_x = 0; cursor_x < row -> size; cursor_x++) {
if (row -> chars[cursor_x] == '\t')
cur_render_x += (TTE_TAB_STOP - 1) - (cur_render_x % TTE_TAB_STOP);
cur_render_x++;
if (cur_render_x > render_x)
return cursor_x;
}
return cursor_x;
}
void editorUpdateRow(editor_row* row) {
// First, we have to loop through the chars of the row
// and count the tabs in order to know how much memory
// to allocate for render. The maximum number of characters
// needed for each tab is 8. row->size already counts 1 for
// each tab, so we multiply the number of tabs by 7 and add
// that to row->size to get the maximum amount of memory we'll
// need for the rendered row.
int tabs = 0;
int j;
for (j = 0; j < row -> size; j++) {
if (row -> chars[j] == '\t')
tabs++;
}
free(row -> render);
row -> render = malloc(row -> size + tabs * (TTE_TAB_STOP - 1) + 1);
// After allocating the memory, we check whether the current character
// is a tab. If it is, we append one space (because each tab must
// advance the cursor forward at least one column), and then append
// spaces until we get to a tab stop, which is a column that is
// divisible by 8
int idx = 0;
for (j = 0; j < row -> size; j++) {
if (row -> chars[j] == '\t') {
row -> render[idx++] = ' ';
while (idx % TTE_TAB_STOP != 0)
row -> render[idx++] = ' ';
} else
row -> render[idx++] = row -> chars[j];
}
row -> render[idx] = '\0';
row -> render_size = idx;
editorUpdateSyntax(row);
}
void editorInsertRow(int at, char* s, size_t line_len) {
if (at < 0 || at > ec.num_rows)
return;
ec.row = realloc(ec.row, sizeof(editor_row) * (ec.num_rows + 1));
memmove(&ec.row[at + 1], &ec.row[at], sizeof(editor_row) * (ec.num_rows - at));
for (int j = at + 1; j <= ec.num_rows; j++) {
ec.row[j].idx++;
}
ec.row[at].idx = at;
ec.row[at].size = line_len;
ec.row[at].chars = malloc(line_len + 1); // We want to add terminator char '\0' at the end
memcpy(ec.row[at].chars, s, line_len);
ec.row[at].chars[line_len] = '\0';
ec.row[at].render_size = 0;
ec.row[at].render = NULL;
ec.row[at].highlight = NULL;
ec.row[at].hl_open_comment = 0;
editorUpdateRow(&ec.row[at]);
ec.num_rows++;
ec.dirty++;
}
void editorFreeRow(editor_row* row) {
free(row -> render);
free(row -> chars);
free(row -> highlight);
}
void editorDelRow(int at) {
if (at < 0 || at >= ec.num_rows)
return;
editorFreeRow(&ec.row[at]);
memmove(&ec.row[at], &ec.row[at + 1], sizeof(editor_row) * (ec.num_rows - at - 1));
for (int j = at; j < ec.num_rows - 1; j++) {
ec.row[j].idx--;
}
ec.num_rows--;
ec.dirty++;
}
// -1 down, 1 up
void editorFlipRow(int dir) {
editor_row c_row = ec.row[ec.cursor_y];
ec.row[ec.cursor_y] = ec.row[ec.cursor_y - dir];
ec.row[ec.cursor_y - dir] = c_row;
ec.row[ec.cursor_y].idx += dir;
ec.row[ec.cursor_y - dir].idx -= dir;
int first = (dir == 1) ? ec.cursor_y - 1 : ec.cursor_y;
editorUpdateSyntax(&ec.row[first]);
editorUpdateSyntax(&ec.row[first] + 1);
if (ec.num_rows - ec.cursor_y > 2)
editorUpdateSyntax(&ec.row[first] + 2);
ec.cursor_y -= dir;
ec.dirty++;
}
void editorCopy(bool printStatus) {
ec.copied_char_buffer = realloc(ec.copied_char_buffer, strlen(ec.row[ec.cursor_y].chars) + 1);
strcpy(ec.copied_char_buffer, ec.row[ec.cursor_y].chars);
if(printStatus) editorSetStatusMessage("Content copied");
}
void editorCut() {
editorDelRow(ec.cursor_y);
if (ec.num_rows - ec.cursor_y > 0)
editorUpdateSyntax(&ec.row[ec.cursor_y]);
if (ec.num_rows - ec.cursor_y > 1)
editorUpdateSyntax(&ec.row[ec.cursor_y + 1]);
ec.cursor_x = ec.cursor_y == ec.num_rows ? 0 : ec.row[ec.cursor_y].size;
editorSetStatusMessage("Content cut");
}
void editorPaste() {
if (ec.copied_char_buffer == NULL)
return;
if (ec.cursor_y == ec.num_rows)
editorInsertRow(ec.cursor_y, ec.copied_char_buffer, strlen(ec.copied_char_buffer));
else
editorRowAppendString(&ec.row[ec.cursor_y], ec.copied_char_buffer, strlen(ec.copied_char_buffer));
ec.cursor_x += strlen(ec.copied_char_buffer);
}
void editorRowInsertChar(editor_row* row, int at, int c) {
if (at < 0 || at > row -> size)
at = row -> size;
// We need to allocate 2 bytes because we also have to make room for
// the null byte.
row -> chars = realloc(row -> chars, row -> size + 2);
// memmove it's like memcpy(), but is safe to use when the source and
// destination arrays overlap