forked from shnupta/bric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bric.c
1854 lines (1662 loc) · 64.9 KB
/
bric.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
#include "bric.h"
static struct editor_config Editor;
static struct termios orig_termios; // so we can restore original at exit
// Low level terminal handling
void disable_raw_mode(int fd)
{
// dont bother checking the return value as its too late
if (Editor.rawmode) {
tcsetattr(fd, TCSAFLUSH, &orig_termios);
write(fd, "\033[2J\033[H\033[?1049l", 15);
Editor.rawmode = 0;
}
}
void editor_at_exit(void)
{
disable_raw_mode(STDIN_FILENO);
}
int enable_raw_mode(int fd)
{
struct termios raw;
if(Editor.rawmode) return 0; //already enabled
if(!isatty(fd)) goto fatal;
atexit(editor_at_exit);
if(tcgetattr(fd, &orig_termios) == -1) goto fatal;
raw = orig_termios; // modify the original mode
/* input modes: no break, no CR to NL, no parity check, no strip char,
* * no start/stop output control. */
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
// output modes - disable post processing
raw.c_oflag &= ~(OPOST);
//control modes - set 8 bit chars
raw.c_cflag |= (CS8);
//local modes, choing off, canonical off, no extended functions, no signal chars (, etc)
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
//control chars - set return condition: min number of bytes and a timer
raw.c_cc[VMIN] = 0; // return each byte, or zero for a timeout
raw.c_cc[VTIME] = 1; //100ms timeout
//put terminal in raw mode after flushing
if(tcsetattr(fd, TCSAFLUSH, &raw) < 0) goto fatal;
//if(write(fd, "\033[?1049h\033[2J\033[H", 15) != 15) goto fatal;
Editor.rawmode = 1;
return 0;
fatal:
errno = ENOTTY;
return -1;
}
// read a key from terminal input in raw mode and handle
int editor_read_key(int fd)
{
int nread;
char c, seq[3];
while((nread = read(fd, &c, 1)) == 0);
if(nread == -1) exit(1);
while(1) {
switch(c) {
case ESC: // escape sequence
// if its an escape then we timeout here
if(read(fd, seq, 1) == 0) return ESC;
if(read(fd, seq+1, 1) == 0) return ESC;
// ESC [ sequences
if(seq[0] == '[') {
if(seq[1] >= '0' && seq[1] <= '9') {
// extended escape so read additional byte
if(read(fd, seq+2, 1) == 0) return ESC;
if(seq[2] == '~') {
switch(seq[1]) {
case '3': return DEL_KEY;
case '5': return PAGE_UP;
case '6': return PAGE_DOWN;
}
}
} else {
switch(seq[1]) {
case 'A': return ARROW_UP;
case 'B': return ARROW_DOWN;
case 'C': return ARROW_RIGHT;
case 'D': return ARROW_LEFT;
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
}
// ESC 0 sequences
else if(seq[0] == 'O') {
switch (seq[1]) {
case 'H': return HOME_KEY;
case 'F': return END_KEY;
}
}
break;
default:
return c;
}
}
}
/* Use the ESC [6n escape sequence to query the horizontal cursor position
* * and return it. On error -1 is returned, on success the position of the
* * cursor is stored at *rows and *cols and 0 is returned. */
int get_cursor_pos(int ifd, int ofd, int *rows, int *columns)
{
char buf[32];
unsigned int i = 0;
// report cursor location
if (write(ofd, "\x1b[6n", 4) != 4) return -1;
// read the response: ESC [ rows; columns R
while(i < sizeof(buf)-1) {
if( read(ifd, buf+i, 1) != 1) break;
if(buf[i] == 'R') break;
i++;
}
buf[i] = '\0';
// parse it
if (buf[0] != ESC || buf[1] != '[') return -1;
if (sscanf(buf+2,"%d;%d",rows,columns) != 2) return -1;
return 0;
}
// try to get the number of columns in the window
int get_window_size(int ifd, int ofd, int *rows, int *columns)
{
struct winsize ws;
if(ioctl(1, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
// ioctl() failed so query the terminal itself
int original_row, original_column, retval;
// get the initail position to store for later
retval = get_cursor_pos(ifd, ofd, &original_row, &original_column);
if(retval == -1) goto failed;
// go to the right bottom margin and get position
if(write(ofd, "\x1b[999C\x1b[999B", 12) != 12) goto failed;
retval = get_cursor_pos(ifd, ofd, rows, columns);
if(retval == -1) goto failed;
// restore the cursor position
char seq[32];
snprintf(seq, 32, "\x1b[%d;%dH", original_row, original_column);
if(write(ofd, seq, strlen(seq)) == -1) {
// cant recover the cursor pos ....
}
return 0;
} else {
*columns = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
failed:
return -1;
}
/// SYNTAX HIGHLIGHTING!!
int is_separator(int c)
{
return c == '\0' || isspace(c) || strchr(",.()+_/*=%[];", c) != NULL;
}
// return true if the specified row's last char is part of a multiline comment that spans to the next row
int editing_row_has_open_comment(editing_row *row)
{
if(row->hl && row->rendered_size && row->hl[row->rendered_size-1] == HL_MLCOMMENT && (row->rendered_size < 2 || (row->rendered_chars[row->rendered_size-2] != '*' || row->rendered_chars[row->rendered_size-1] != '/'))) return 1;
return 0;
}
// set every byte of row->hl (every character in the line) to the right syntax type defined by HL_*
void editor_update_syntax(editing_row *row)
{
row->hl = realloc(row->hl, row->rendered_size);
memset(row->hl, HL_NORMAL, row->rendered_size);
if(Editor.syntax == NULL) return; //no syntax in this line, everything is HL_NORMAL
int i, prev_sep, in_string, in_comment;
char *p;
char **keywords = Editor.syntax->keywords;
char *scs = Editor.syntax->singleline_comment_start;
char *mcs = Editor.syntax->multiline_comment_start;
char *mce = Editor.syntax->multiline_comment_end;
// point to the first non space char
p = row->rendered_chars;
i = 0; // current char offset in row
while (*p && isspace(*p)) {
p++;
i++;
}
prev_sep = 1; // tell the parser if 'i' points to the start of a word
in_string = 0; // is the character in a string "" or ''
in_comment = 0; // is the char in an open multiline comment
//if the previous line has open open comment then this line start with an open comment state
if(row->index > 0 && editing_row_has_open_comment(&Editor.row[row->index-1])) in_comment = 1;
while (*p) {
//handle single line comments
if(prev_sep && *p == scs[0] && *(p+1) == scs[1]) {
// from here to the end of the row is a comment
memset(row->hl+i, HL_COMMENT, row->rendered_size-i);
return;
}
// handle multiline comments
if(in_comment) {
row->hl[i] = HL_MLCOMMENT;
if(*p == mce[0] && *(p+1) == mce[1]) {
row->hl[i+1] = HL_MLCOMMENT;
p += 2; i+= 2;
in_comment = 0;
prev_sep = 1;
continue;
} else {
prev_sep = 0;
p++; i++;
continue;
}
} else if(*p == mcs[0] && *(p+1) == mcs[1]) {
row->hl[i] = HL_MLCOMMENT;
row->hl[i+1] = HL_MLCOMMENT;
p += 2; i += 2;
in_comment = 1;
prev_sep = 0;
continue;
}
// handle "" and ''
if(in_string) {
row->hl[i] = HL_STRING;
if(*p == '\\') {
row->hl[i+1] = HL_STRING;
p += 2; i += 2;
prev_sep = 0;
continue;
}
if(*p == in_string) in_string = 0;
p++; i++;
continue;
} else {
if(*p == '"' || *p == '\'') {
in_string = *p;
row->hl[i] = HL_STRING;
p++; i++;
prev_sep = 0;
continue;
}
}
// handle non printable chars
if(!isprint(*p)) {
row->hl[i] = HL_NONPRINT;
p++; i++;
prev_sep = 0;
continue;
}
//handle numbers
if((isdigit(*p) && (prev_sep || row->hl[i-1] == HL_NUMBER)) || (*p == '.' && i > 0 && row->hl[i-1] == HL_NUMBER)) {
row->hl[i] = HL_NUMBER;
p++; i++;
prev_sep = 0;
continue;
}
//handle keywords and lib calls
if(prev_sep) {
int j;
for(j = 0; keywords[j]; j++) {
int klen = strlen(keywords[j]);
int pp = keywords[j][klen-1] == '|'; // preprocessor keyword
int cond = keywords[j][klen-1] == '~'; // condition
int retu = keywords[j][klen-1] == '#';
int adapter = keywords[j][klen-1] == '^'; //adapter keywords
int loopy = keywords[j][klen-1] == '@';
if(pp || cond || retu || adapter || loopy) klen--;
if(!memcmp(p, keywords[j], klen) && is_separator(*(p+klen))) {
// keyword
if(pp) memset(row->hl+i, HL_KEYWORD_PP, klen);
else if(cond) memset(row->hl+i, HL_KEYWORD_COND, klen);
else if(retu) memset(row->hl+i, HL_KEYWORD_RETURN, klen);
else if(adapter) memset(row->hl+i, HL_KEYWORD_ADAPTER, klen);
else if(loopy) memset(row->hl+i, HL_KEYWORD_LOOP, klen);
else memset(row->hl+i, HL_KEYWORD_TYPE, klen);
p += klen;
i += klen;
break;
}
}
if(keywords[j] != NULL) {
prev_sep = 0;
continue; // we had a keyword match
}
}
// not special chars
prev_sep = is_separator(*p);
p++; i++;
}
// propagate a syntax change to the next row if the open comment state is changed
int oc = editing_row_has_open_comment(row);
if(row->hl_open_comment != oc && row->index+1 < Editor.num_of_rows) editor_update_syntax(&Editor.row[row->index+1]);
row->hl_open_comment = oc;
}
// map thee syntax highlight types to terminal colours
int editor_syntax_to_colour(int highlight)
{
switch(highlight) {
case HL_COMMENT: return Editor.colours.hl_comment_colour;
case HL_MLCOMMENT: return Editor.colours.hl_mlcomment_colour;
case HL_KEYWORD_COND: return Editor.colours.hl_keyword_cond_colour;
case HL_KEYWORD_TYPE: return Editor.colours.hl_keyword_type_colour;
case HL_KEYWORD_PP: return Editor.colours.hl_keyword_pp_colour;
case HL_KEYWORD_RETURN: return Editor.colours.hl_keyword_return_colour;
case HL_KEYWORD_ADAPTER: return Editor.colours.hl_keyword_adapter_colour;
case HL_KEYWORD_LOOP: return Editor.colours.hl_keyword_loop_colour;
case HL_STRING: return Editor.colours.hl_string_colour;
case HL_NUMBER: return Editor.colours.hl_number_colour;
case HL_MATCH: return Editor.colours.hl_match_colour;
case HL_BACKGROUND_DEFAULT: return Editor.colours.hl_background_colour;
default: return Editor.colours.hl_default_colour;
}
}
// select the syntax highlight scheme depending on the filename
void editor_select_syntax_highlight(char *filename)
{
for(unsigned int j = 0; j < HIGHLIGHT_DB_ENTRIES; j++) {
struct editor_syntax *s = highlight_db+j;
unsigned int i = 0;
while(s->filematch[i]) {
char *p;
int patlen = strlen(s->filematch[i]);
if((p = strstr(filename, s->filematch[i])) != NULL) {
if(s->filematch[i][0] != '.' || p[patlen] == '\0') {
Editor.syntax = s;
return;
}
}
i++;
}
}
}
// Editor rows implementation
// update the rendered version and the syntax highlight of a row
void editor_update_row(editing_row *row)
{
int tabs = 0, nonprint = 0, j, index;
//create a version of the row that we can directly print on the screen
free(row->rendered_chars);
for(j = 0; j < row->size; j++)
if( row->chars[j] == TAB) tabs++;
row->rendered_chars = malloc(row->size + tabs*8 + nonprint*9 + 1);
index = 0;
for(j = 0; j < row->size; j++) {
if(row->chars[j] == TAB) {
row->rendered_chars[index++] = ' ';
while((index+1) % 8 != 0) row->rendered_chars[index++] = ' ';
} else {
row->rendered_chars[index++] = row->chars[j];
}
}
row->rendered_size = index;
row->rendered_chars[index] = '\0';
// update the syntax highlighting of the row
editor_update_syntax(row);
}
// insert row
void editor_insert_row(int at, char *s, size_t length)
{
if(at > Editor.num_of_rows) return;
Editor.row = realloc(Editor.row, sizeof(editing_row)*(Editor.num_of_rows+1));
if(at != Editor.num_of_rows) {
memmove(Editor.row + at + 1, Editor.row + at, sizeof(Editor.row[0])*(Editor.num_of_rows-at));
for(int j = at+1; j <= Editor.num_of_rows; j++) Editor.row[j].index++;
}
Editor.row[at].size = length;
Editor.row[at].chars = malloc(length+1);
memcpy(Editor.row[at].chars, s, length+1);
Editor.row[at].hl = NULL;
Editor.row[at].hl_open_comment = 0;
Editor.row[at].rendered_chars = NULL;
Editor.row[at].rendered_size = 0;
Editor.row[at].index = at;
editor_update_row(Editor.row+at);
Editor.num_of_rows++;
Editor.dirty++;
}
// free the rows heap allocated data
void editor_free_row(editing_row *row)
{
free(row->rendered_chars);
free(row->chars);
free(row->hl);
}
// remove row at specified position
void editor_delete_row(int at)
{
editing_row *row;
if(at >= Editor.num_of_rows) return;
row = Editor.row+at;
editor_free_row(row);
memmove(Editor.row+at, Editor.row+at+1, sizeof(Editor.row[0])*(Editor.num_of_rows-at-1));
for(int j = at; j < Editor.num_of_rows-1; j++) Editor.row[j].index++;
Editor.num_of_rows--;
Editor.dirty++;
}
// turn editor rows into single heap allocated string
char *editor_rows_to_string(int *buflen)
{
char *buf = NULL, *p;
int totlen = 0;
int j;
// compute count of bytes
for(j = 0; j < Editor.num_of_rows; j++)
totlen += Editor.row[j].size+1; // +1 is for \n at end of every row
*buflen = totlen;
totlen++; // make space for null terminator
p = buf = malloc(totlen);
for(j = 0; j < Editor.num_of_rows; j++) {
memcpy(p, Editor.row[j].chars, Editor.row[j].size);
p += Editor.row[j].size;
*p = '\n';
p++;
}
*p = '\0';
return buf;
}
// insert char at the specified position in row
void editor_row_insert_char(editing_row *row, int at, int c)
{
if(at > row->size) {
// pad the string with spaces if the insert location is outside the current length by more than one char
int padlen = at-row->size;
row->chars = realloc(row->chars, row->size+padlen+2); // +2 for null term and newline
memset(row->chars+row->size, ' ', padlen);
row->chars[row->size+padlen+1] = '\0';
row->size += padlen+1;
} else {
// in the middle of string so make empty space for char
row->chars = realloc(row->chars, row->size+2);
memmove(row->chars+at+1, row->chars+at, row->size-at+1);
row->size++;
}
row->chars[at] = c;
editor_update_row(row);
Editor.dirty++;
}
// append the string s to the end of the row
void editor_row_append_string(editing_row *row, char *s, size_t len)
{
row->chars = realloc(row->chars, row->size+len+1);
memcpy(row->chars+row->size, s, len);
row->size += len;
row->chars[row->size] = '\0';
editor_update_row(row);
Editor.dirty++;
}
// delete the character at the offset 'at' from the specified row
void editor_row_delete_char(editing_row *row, int at)
{
if(row->size <= at) return;
memmove(row->chars+at, row->chars+at+1, row->size-at);
editor_update_row(row);
row->size--;
Editor.dirty++;
}
// insert char at current prompt position
void editor_insert_char(int c)
{
int filerow = Editor.row_offset+Editor.cursor_y;
int filecol = Editor.column_offset+Editor.cursor_x;
editing_row *row = (filerow >= Editor.num_of_rows) ? NULL : &Editor.row[filerow];
// if the row where rthe cursor is currently located does not exist, add enough empty rows as needed
if(!row) {
while(Editor.num_of_rows <= filerow)
editor_insert_row(Editor.num_of_rows, "", 0);
}
row = &Editor.row[filerow];
editor_row_insert_char(row, filecol, c);
if(Editor.cursor_x == Editor.screen_columns-1)
Editor.column_offset++;
else
Editor.cursor_x++;
Editor.dirty++;
}
char *get_indent_prefix(char *s, int max_length)
{
int ptr = 0;
while (s[ptr] == ' ' || s[ptr] == '\t') ptr++;
if (ptr > max_length) ptr = max_length;
char *res = (char*)malloc((ptr + 1) * sizeof(char));
memcpy(res, s, ptr * sizeof(char));
res[ptr] = '\0';
return res;
}
char *set_indent_prefix(char *text, char *prefix)
{
int result_length = strlen(text) + strlen(prefix);
int ptr = 0;
while (text[ptr] == ' ' || text[ptr] == '\t') ptr++;
result_length -= ptr;
char *res = (char*)malloc((result_length + 1) * sizeof(char));
res[0] = '\0';
res = strcat(res, prefix);
res = strcat(res, text + ptr);
return res;
}
/*
* This function copies the current line to a separate buffer.
*/
void editor_yank_row() {
int filerow = Editor.row_offset+Editor.cursor_y;
editing_row *row = (filerow >= Editor.num_of_rows) ? NULL : &Editor.row[filerow];
if (row) {
Editor.yank_buffer_len = row->size+1;
if (!Editor.yank_buffer) {
if ((Editor.yank_buffer = (char*) malloc(Editor.yank_buffer_len)) != NULL ) {
memcpy(Editor.yank_buffer, row->chars, Editor.yank_buffer_len);
} else {
perror("Error allocating memory.");
exit(1);
}
} else {
if ((Editor.yank_buffer = (char*) realloc(Editor.yank_buffer, Editor.yank_buffer_len)) != NULL ) {
memcpy(Editor.yank_buffer, row->chars, Editor.yank_buffer_len);
} else {
perror("Error allocating memory.");
exit(1);
}
}
editor_delete_row(filerow);
}
}
void editor_paste_row() {
int filerow = Editor.row_offset+Editor.cursor_y;
editor_insert_row(filerow, Editor.yank_buffer, Editor.yank_buffer_len-1); // note -1 to account for the null terminator
}
/* Inserting a newline is slightly complex as we have to handle inserting a
* * newline in the middle of a line, splitting the line as needed. */
void editor_insert_newline(void)
{
int filerow = Editor.row_offset+Editor.cursor_y;
int filecol = Editor.column_offset+Editor.cursor_x;
editing_row *row = (filerow >= Editor.num_of_rows) ? NULL : &Editor.row[filerow];
if (!row) {
if(filerow == Editor.num_of_rows) {
editor_insert_row(filerow, "", 0);
goto fixcursor;
}
return;
}
char *indent_prefix = NULL;
if (Editor.indent)
{
indent_prefix = get_indent_prefix(row->chars, filecol + 1);
}
else
{
indent_prefix = get_indent_prefix(row->chars, 0);
}
// if the cursor is over the line size then we conceptually think its just over the last character
if(filecol >= row->size) filecol = row->size;
if(filecol == 0) {
editor_insert_row(filerow, indent_prefix, strlen(indent_prefix));
} else {
// we are in the middle of a line, split it between two rows
char *new_row = set_indent_prefix(row->chars+filecol, indent_prefix);
editor_insert_row(filerow+1, new_row, strlen(new_row));
free(new_row);
row = &Editor.row[filerow];
row->chars[filecol] = '\0';
row->size = filecol;
editor_update_row(row);
}
fixcursor:
if(Editor.cursor_y == Editor.screen_rows-1)
Editor.row_offset++;
else
Editor.cursor_y++;
Editor.cursor_x = strlen(indent_prefix) % Editor.screen_columns;
Editor.column_offset = strlen(indent_prefix) / Editor.screen_columns;
free(indent_prefix);
}
// delete the char at the current position
void editor_delete_char()
{
int filerow = Editor.row_offset+Editor.cursor_y;
int filecol = Editor.column_offset+Editor.cursor_x;
editing_row *row = (filerow >= Editor.num_of_rows) ? NULL : &Editor.row[filerow];
if(!row || (filecol == 0 && filerow == 0)) return;
if(filecol == 0) {
/* Handle the case of column 0, we need to move the current line
* * on the right of the previous one. */
filecol = Editor.row[filerow-1].size;
editor_row_append_string(&Editor.row[filerow-1], row->chars, row->size);
editor_delete_row(filerow);
row = NULL;
if(Editor.cursor_y == 0)
Editor.row_offset--;
else
Editor.cursor_y--;
Editor.cursor_x = filecol;
if(Editor.cursor_x >= Editor.screen_columns) {
int shift = (Editor.screen_columns-Editor.cursor_x)+1;
Editor.cursor_x -= shift;
Editor.column_offset += shift;
}
}
else {
editor_row_delete_char(row, filecol-1);
if(Editor.cursor_x == 0 && Editor.column_offset)
Editor.column_offset--;
else
Editor.cursor_x--;
}
if(row) editor_update_row(row);
Editor.dirty++;
}
void parse_argument(char *arg)
{
int ptr = 0;
while (arg[ptr] != '\0')
{
switch (arg[ptr])
{
case 'l':
Editor.line_numbers = 1;
break;
case 'i':
Editor.indent = 1;
break;
default:
// TODO: warning of unrecognised argument
break;
}
ptr++;
}
}
// load the specified progam in the editor memory
int editor_open(char *filename)
{
FILE *fp;
Editor.dirty = 0;
free(Editor.filename);
Editor.filename = strdup(filename);
fp = fopen(filename, "r");
if(!fp) {
if(errno != ENOENT) {
perror("Opening file");
exit(1);
}
return 1;
}
char *line = NULL;
size_t linecap = 0;
ssize_t linelen;
while((linelen = getline(&line, &linecap, fp)) != -1) {
if(linelen && (line[linelen-1] == '\n' || line[linelen-1] == '\r'))
line[--linelen] = '\0';
editor_insert_row(Editor.num_of_rows, line, linelen);
}
free(line);
fclose(fp);
Editor.dirty = 0;
return 0;
}
// save the current file on disk
int editor_save(void)
{
int len;
char *buf = editor_rows_to_string(&len);
int fd = open(Editor.filename, O_RDWR|O_CREAT, 0644);
if(fd == -1) goto writeerr;
/* Use truncate + a single write(2) call in order to make saving
* * a bit safer, under the limits of what we can do in a small editor. */
if(ftruncate(fd, len) == -1) goto writeerr;
if(write(fd, buf, len) != len) goto writeerr;
close(fd);
free(buf);
Editor.dirty = 0;
editor_set_status_message("%d bytes written on disk", len);
return 0;
writeerr:
free(buf);
if(fd != -1) close(fd);
editor_set_status_message("Cannot save! I/O error: %s", strerror(errno));
return 1;
}
// TERMINAL UPDATING
void ab_append(struct append_buf *ab, char *s, int length)
{
char *new = realloc(ab->b, ab->length+length);
if(new == NULL) return;
memcpy(new+ab->length, s, length);
ab->b = new;
ab->length += length;
}
void ab_free(struct append_buf *ab)
{
free(ab->b);
}
void copy_to_clipboard(void)
{
free(Editor.clipboard);
int lx = Editor.cursor_x + Editor.column_offset;
int ly = Editor.cursor_y + Editor.row_offset;
int rx = Editor.selected_base_x;
int ry = Editor.selected_base_y;
if (ly > ry || (ly == ry && lx > rx))
{
int t = lx;
lx = rx;
rx = t;
t = ly;
ly = ry;
ry = t;
}
int clipboard_length = 1;
for (int i = ly; i <= ry; i++)
{
int left_border = 0, right_border = Editor.row[i].size - 1;
if (i == ly) left_border = lx;
if (i == ry && rx < right_border) right_border = rx;
clipboard_length += right_border - left_border + 1;
if (i != ry) clipboard_length++;
}
Editor.clipboard = (char*)malloc(clipboard_length * sizeof(char));
int ptr = 0;
for (int i = ly; i <= ry; i++)
{
int left_border = 0, right_border = Editor.row[i].size - 1;
if (i == ly) left_border = lx;
if (i == ry && rx < right_border) right_border = rx;
for (int j = left_border; j <= right_border; j++)
{
Editor.clipboard[ptr] = Editor.row[i].chars[j];
ptr++;
}
if (i != ry)
{
Editor.clipboard[ptr] = '\n';
ptr++;
}
}
Editor.clipboard[ptr] = '\0';
}
void paste_from_clipboard(void)
{
if (Editor.clipboard == NULL) return;
int length = strlen(Editor.clipboard);
for (int i = 0; i < length; i++)
{
if (Editor.clipboard[i] == '\n')
{
editor_insert_newline();
}
else
{
editor_insert_char(Editor.clipboard[i]);
}
}
}
int is_char_selected(int x, int y)
{
int lx = Editor.cursor_x + Editor.column_offset;
int ly = Editor.cursor_y + Editor.row_offset;
int rx = Editor.selected_base_x;
int ry = Editor.selected_base_y;
if (ly > ry || (ly == ry && lx > rx))
{
int t = lx;
lx = rx;
rx = t;
t = ly;
ly = ry;
ry = t;
}
if (ly == ry)
{
return y == ly && x >= lx && x <= rx;
}
else if (y == ly)
{
return x >= lx;
}
else if (y == ry)
{
return x <= rx;
}
else
{
return y >= ly && y <= ry;
}
}
// this function writes the whole screen using VT100 escape characters starting
// from the logical state of the editor in the global state 'Editor'
void editor_refresh_screen(void)
{
int y;
editing_row *row;
char buf[32];
struct append_buf ab = ABUF_INIT;
ab_append(&ab, "\x1b[?25l", 6); //hide cursor
ab_append(&ab, "\x1b[H", 3); // go home
for(y = 0; y < Editor.screen_rows; y++) {
int filerow = Editor.row_offset+y;
ab_append(&ab, "\x1b[49m", 5);
ab_append(&ab, "\x1b[39m", 5);
if (Editor.line_numbers)
{
sprintf(buf, LINE_NUMBER_FORMAT, filerow + 1);
ab_append(&ab, buf, strlen(buf));
}
if(filerow >= Editor.num_of_rows) {
if(Editor.num_of_rows == 0 && y == Editor.screen_rows/3) {
char welcome[80];
int welcomelen = snprintf(welcome, sizeof(welcome), "Bric editor -- version %s\x1b[0K\r\n", BRIC_VERSION);
int padding = (Editor.screen_columns-welcomelen)/2;
if(padding) {
ab_append(&ab, "~", 1);
padding--;
}
while(padding--) ab_append(&ab, " ", 1);
ab_append(&ab, welcome, welcomelen);
} else {
ab_append(&ab, "~\x1b[0K\r\n", 7);
}
continue;
}
row = &Editor.row[filerow];
int len = row->rendered_size - Editor.column_offset;
int current_colour = -1, background_colour = -1;
if(len > 0) {
if(len > Editor.screen_columns) len = Editor.screen_columns;
char *c = row->rendered_chars+Editor.column_offset;
unsigned char *hl = row->hl+Editor.column_offset;
int j;
for (j = 0; j < len; j++) {
if (Editor.mode == SELECTION_MODE && is_char_selected(j + Editor.column_offset, filerow)) {
if (background_colour == -1)
{
ab_append(&ab, "\x1b[47m", 5);
background_colour = 47;
}
if (current_colour != 30)
{
ab_append(&ab, "\x1b[30m", 5);
current_colour = 30;
}
ab_append(&ab, c+j, 1);
} else if(hl[j] == HL_NONPRINT) {
if (background_colour != -1)
{
ab_append(&ab, "\x1b[49m", 5);
background_colour = -1;
}
char sym;
ab_append(&ab, "\x1b[7m", 4);
if(c[j] <= 26)
sym = '@'+c[j];
else
sym = '?';
ab_append(&ab, &sym, 1);
ab_append(&ab, "\x1b[0m", 4);
} else if (hl[j] == HL_NORMAL) {
if (background_colour != -1)
{
ab_append(&ab, "\x1b[49m", 5);
background_colour = -1;
}
if(current_colour != -1) {
ab_append(&ab, "\x1b[39m", 5);
current_colour = -1;
}
ab_append(&ab, c+j, 1);
} else {
int colour = editor_syntax_to_colour(hl[j]);
if (background_colour != -1)
{
ab_append(&ab, "\x1b[49m", 5);
background_colour = -1;
}
if(colour != current_colour) {
char buf[16];
int clen = snprintf(buf, sizeof(buf), "\x1b[%dm", colour);
current_colour = colour;
ab_append(&ab, buf, clen);
}
ab_append(&ab, c+j, 1);
}
}
}
ab_append(&ab, "\x1b[39m", 5);
ab_append(&ab, "\x1b[0K", 4);
ab_append(&ab, "\r\n", 2);
}