-
-
Notifications
You must be signed in to change notification settings - Fork 487
/
bim.c
12130 lines (10877 loc) · 340 KB
/
bim.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
/* Bim - A Text Editor
*
* Copyright (C) 2012-2021 K. Lange
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "bim.h"
#define BIM_VERSION "3.1.0" TAG
#define BIM_COPYRIGHT "Copyright 2012-2021 K. Lange <\033[[email protected]\033[23m>"
#include <kuroko/kuroko.h>
#include <kuroko/vm.h>
#include <kuroko/debug.h>
#include <kuroko/util.h>
#include <kuroko/scanner.h>
global_config_t global_config = {
/* State */
.term_width = 0,
.term_height = 0,
.bottom_size = 2,
.yanks = NULL,
.yank_count = 0,
.yank_is_full_lines = 0,
.tty_in = STDIN_FILENO,
.bimrc_path = "~/.bim3rc",
.syntax_fallback = NULL, /* Syntax to fall back to if no other match applies */
.search = NULL,
.overlay_mode = OVERLAY_MODE_NONE,
.command_buffer = NULL,
.command_offset = 0,
.command_col_no = 0,
.history_point = -1,
.search_point = -1,
/* Bitset starts here */
.highlight_on_open = 1,
.initial_file_is_read_only = 0,
.go_to_line = 1,
.break_from_selection = 1,
/* Terminal capabilities */
.can_scroll = 1,
.can_hideshow = 1,
.can_altscreen = 1,
.can_mouse = 1,
.can_unicode = 1,
.can_bright = 1,
.can_title = 1,
.can_bce = 1,
.can_24bit = 1, /* can use 24-bit color */
.can_256color = 1, /* can use 265 colors */
.can_italic = 1, /* can use italics (without inverting) */
.can_insert = 0, /* ^[[L */
.can_bracketedpaste = 0, /* puts escapes before and after pasted stuff */
.can_sgrmouse = 0, /* Whether SGR mouse mode is availabe (large coordinates) */
/* Configuration options */
.history_enabled = 1,
.highlight_parens = 1, /* highlight parens/braces when cursor moves */
.smart_case = 1, /* smart case-sensitivity while searching */
.highlight_current_line = 1,
.shift_scrolling = 1, /* shift rather than moving cursor*/
.check_git = 0,
.color_gutter = 1, /* shows modified lines */
.relative_lines = 0,
.numbers = 1,
.horizontal_shift_scrolling = 0, /* Whether to shift the whole screen when scrolling horizontally */
.hide_statusbar = 0,
.tabs_visible = 1,
.autohide_tabs = 0,
.smart_complete = 0,
.has_terminal = 0,
.search_wraps = 1,
.had_error = 0,
.use_biminfo = 1,
/* Integer config values */
.cursor_padding = 4,
.split_percent = 50,
.scroll_amount = 5,
.tab_offset = 0,
.background_task = NULL,
.tail_task = NULL,
};
struct key_name_map KeyNames[] = {
{KEY_TIMEOUT, "[timeout]"},
{KEY_BACKSPACE, "<backspace>"},
{KEY_ENTER, "<enter>"},
{KEY_ESCAPE, "<escape>"},
{KEY_TAB, "<tab>"},
{' ', "<space>"},
/* These are mostly here for markdown output. */
{'`', "<backtick>"},
{'|', "<pipe>"},
{KEY_DELETE, "<del>"},
{KEY_MOUSE, "<mouse>"},
{KEY_MOUSE_SGR, "<mouse-sgr>"},
{KEY_F1, "<f1>"},{KEY_F2, "<f2>"},{KEY_F3, "<f3>"},{KEY_F4, "<f4>"},
{KEY_F5, "<f5>"},{KEY_F6, "<f6>"},{KEY_F7, "<f7>"},{KEY_F8, "<f8>"},
{KEY_F9, "<f9>"},{KEY_F10, "<f10>"},{KEY_F11, "<f11>"},{KEY_F12, "<f12>"},
{KEY_HOME,"<home>"},{KEY_END,"<end>"},{KEY_PAGE_UP,"<page-up>"},{KEY_PAGE_DOWN,"<page-down>"},
{KEY_UP, "<up>"},{KEY_DOWN, "<down>"},{KEY_RIGHT, "<right>"},{KEY_LEFT, "<left>"},
{KEY_SHIFT_UP, "<shift-up>"},{KEY_SHIFT_DOWN, "<shift-down>"},{KEY_SHIFT_RIGHT, "<shift-right>"},{KEY_SHIFT_LEFT, "<shift-left>"},
{KEY_CTRL_UP, "<ctrl-up>"},{KEY_CTRL_DOWN, "<ctrl-down>"},{KEY_CTRL_RIGHT, "<ctrl-right>"},{KEY_CTRL_LEFT, "<ctrl-left>"},
{KEY_ALT_UP, "<alt-up>"},{KEY_ALT_DOWN, "<alt-down>"},{KEY_ALT_RIGHT, "<alt-right>"},{KEY_ALT_LEFT, "<alt-left>"},
{KEY_ALT_SHIFT_UP, "<alt-shift-up>"},{KEY_ALT_SHIFT_DOWN, "<alt-shift-down>"},{KEY_ALT_SHIFT_RIGHT, "<alt-shift-right>"},{KEY_ALT_SHIFT_LEFT, "<alt-shift-left>"},
{KEY_SHIFT_TAB,"<shift-tab>"},
{KEY_PASTE_BEGIN,"<paste-begin>"},{KEY_PASTE_END,"<paste-end>"},
};
char * name_from_key(enum Key keycode) {
for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
if (KeyNames[i].keycode == keycode) return KeyNames[i].name;
}
static char keyNameTmp[8] = {0};
if (keycode <= KEY_CTRL_UNDERSCORE) {
keyNameTmp[0] = '^';
keyNameTmp[1] = '@' + keycode;
keyNameTmp[2] = 0;
return keyNameTmp;
}
to_eight(keycode, keyNameTmp);
return keyNameTmp;
}
#define S(c) (krk_copyString(c,sizeof(c)-1))
static KrkClass * syntaxStateClass = NULL;
struct SyntaxState {
KrkInstance inst;
struct syntax_state state;
};
static void schedule_complete_recalc(void);
/**
* Theming data
*
* This default set is pretty simple "default foreground on default background"
* except for search and selections which are black-on-white specifically.
*
* The theme colors get set by separate configurable theme scripts.
*/
const char * COLOR_FG = "@9";
const char * COLOR_BG = "@9";
const char * COLOR_ALT_FG = "@9";
const char * COLOR_ALT_BG = "@9";
const char * COLOR_NUMBER_FG = "@9";
const char * COLOR_NUMBER_BG = "@9";
const char * COLOR_STATUS_FG = "@9";
const char * COLOR_STATUS_BG = "@9";
const char * COLOR_STATUS_ALT= "@9";
const char * COLOR_TABBAR_BG = "@9";
const char * COLOR_TAB_BG = "@9";
const char * COLOR_ERROR_FG = "@9";
const char * COLOR_ERROR_BG = "@9";
const char * COLOR_SEARCH_FG = "@0";
const char * COLOR_SEARCH_BG = "@17";
const char * COLOR_KEYWORD = "@9";
const char * COLOR_STRING = "@9";
const char * COLOR_COMMENT = "@9";
const char * COLOR_TYPE = "@9";
const char * COLOR_PRAGMA = "@9";
const char * COLOR_NUMERAL = "@9";
const char * COLOR_SELECTFG = "@0";
const char * COLOR_SELECTBG = "@17";
const char * COLOR_RED = "@1";
const char * COLOR_GREEN = "@2";
const char * COLOR_BOLD = "@9";
const char * COLOR_LINK = "@9";
const char * COLOR_ESCAPE = "@9";
const char * current_theme = "none";
struct ColorName color_names[] = {
{"text-fg", &COLOR_FG},
{"text-bg", &COLOR_BG},
{"alternate-fg", &COLOR_ALT_FG},
{"alternate-bg", &COLOR_ALT_BG},
{"number-fg", &COLOR_NUMBER_FG},
{"number-bg", &COLOR_NUMBER_BG},
{"status-fg", &COLOR_STATUS_FG},
{"status-bg", &COLOR_STATUS_BG},
{"status-alt", &COLOR_STATUS_ALT},
{"tabbar-bg", &COLOR_TABBAR_BG},
{"tab-bg", &COLOR_TAB_BG},
{"error-fg", &COLOR_ERROR_FG},
{"error-bg", &COLOR_ERROR_BG},
{"search-fg", &COLOR_SEARCH_FG},
{"search-bg", &COLOR_SEARCH_BG},
{"keyword", &COLOR_KEYWORD},
{"string", &COLOR_STRING},
{"comment", &COLOR_COMMENT},
{"type", &COLOR_TYPE},
{"pragma", &COLOR_PRAGMA},
{"numeral", &COLOR_NUMERAL},
{"select-fg", &COLOR_SELECTFG},
{"select-bg", &COLOR_SELECTBG},
{"red", &COLOR_RED},
{"green", &COLOR_GREEN},
{"bold", &COLOR_BOLD},
{"link", &COLOR_LINK},
{"escape", &COLOR_ESCAPE},
{NULL,NULL},
};
#define FLEXIBLE_ARRAY(name, add_name, type, zero) \
int flex_ ## name ## _count = 0; \
int flex_ ## name ## _space = 0; \
type * name = NULL; \
void add_name (type input) { \
if (flex_ ## name ## _space == 0) { \
flex_ ## name ## _space = 4; \
name = calloc(sizeof(type), flex_ ## name ## _space); \
} else if (flex_ ## name ## _count + 1 == flex_ ## name ## _space) { \
flex_ ## name ## _space *= 2; \
name = realloc(name, sizeof(type) * flex_ ## name ## _space); \
for (int i = flex_ ## name ## _count; i < flex_ ## name ## _space; ++i) name[i] = zero; \
} \
name[flex_ ## name ## _count] = input; \
flex_ ## name ## _count ++; \
}
FLEXIBLE_ARRAY(mappable_actions, add_action, struct action_def, ((struct action_def){NULL,0,0,NULL}))
FLEXIBLE_ARRAY(regular_commands, add_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
FLEXIBLE_ARRAY(prefix_commands, add_prefix_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
FLEXIBLE_ARRAY(themes, add_colorscheme, struct theme_def, ((struct theme_def){NULL,NULL}))
/**
* Special implementation of getch with a timeout
*/
int _bim_unget = -1;
void bim_unget(int c) {
_bim_unget = c;
}
void redraw_statusbar(void);
int bim_getch_timeout(int timeout) {
fflush(stdout);
if (_bim_unget != -1) {
int out = _bim_unget;
_bim_unget = -1;
return out;
}
struct pollfd fds[1];
fds[0].fd = global_config.tty_in;
fds[0].events = POLLIN;
int ret = poll(fds,1,timeout);
if (ret > 0 && fds[0].revents & POLLIN) {
unsigned char buf[1];
read(global_config.tty_in, buf, 1);
return buf[0];
} else {
background_task_t * task = global_config.background_task;
if (task) {
global_config.background_task = task->next;
task->func(task);
free(task);
if (!global_config.background_task) {
global_config.tail_task = NULL;
redraw_statusbar();
}
}
return -1;
}
}
/**
* UTF-8 parser state
*/
static uint32_t codepoint_r;
static uint32_t state = 0;
#define UTF8_ACCEPT 0
#define UTF8_REJECT 1
static inline uint32_t decode(uint32_t* state, uint32_t* codep, unsigned char byte) {
static int state_table[32] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
1,1,1,1,1,1,1,1, /* 10xxxxxx */
2,2,2,2, /* 110xxxxx */
3,3, /* 1110xxxx */
4, /* 11110xxx */
1 /* 11111xxx */
};
static int mask_bytes[32] = {
0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x1F,0x1F,0x1F,0x1F,
0x0F,0x0F,
0x07,
0x00
};
static int next[5] = {
0,
1,
0,
2,
3
};
if (*state == UTF8_ACCEPT) {
*codep = byte & mask_bytes[byte >> 3];
*state = state_table[byte >> 3];
} else if (*state > 0) {
*codep = (byte & 0x3F) | (*codep << 6);
*state = next[*state];
}
return *state;
}
#define shift_key(i) _shift_key((i), this_buf, &timeout);
int _shift_key(int i, int this_buf[20], int *timeout) {
int thing = this_buf[*timeout-1];
(*timeout) = 0;
switch (thing) {
/* There are other combinations we can handle... */
case '2': return i + 4;
case '5': return i + 8;
case '3': return i + 12;
case '4': return i + 16;
default: return i;
}
}
int bim_getkey(int read_timeout) {
int timeout = 0;
int this_buf[20];
int cin;
uint32_t c;
uint32_t istate = 0;
while ((cin = bim_getch_timeout((timeout == 1) ? 50 : read_timeout))) {
if (cin == -1) {
if (timeout && this_buf[timeout-1] == '\033')
return KEY_ESCAPE;
return KEY_TIMEOUT;
}
if (!decode(&istate, &c, cin)) {
if (timeout == 0) {
switch (c) {
case '\033':
if (timeout == 0) {
this_buf[timeout] = c;
timeout++;
}
continue;
case KEY_LINEFEED: return KEY_ENTER;
case KEY_DELETE: return KEY_BACKSPACE;
}
return c;
} else {
if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '\033') {
bim_unget(c);
timeout = 0;
return KEY_ESCAPE;
}
if (timeout >= 1 && this_buf[0] == '\033' && c == 'O') {
this_buf[timeout] = c;
timeout++;
continue;
}
if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == 'O') {
switch (c) {
case 'P': return KEY_F1;
case 'Q': return KEY_F2;
case 'R': return KEY_F3;
case 'S': return KEY_F4;
}
timeout = 0;
continue;
}
if (timeout >= 1 && this_buf[timeout-1] == '\033' && c != '[') {
timeout = 0;
bim_unget(c);
return KEY_ESCAPE;
}
if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '[') {
timeout = 1;
this_buf[timeout] = c;
timeout++;
continue;
}
if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
(isdigit(c) || (c == ';'))) {
this_buf[timeout] = c;
timeout++;
continue;
}
if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
switch (c) {
case 'M': return KEY_MOUSE;
case '<': return KEY_MOUSE_SGR;
case 'A': return shift_key(KEY_UP);
case 'B': return shift_key(KEY_DOWN);
case 'C': return shift_key(KEY_RIGHT);
case 'D': return shift_key(KEY_LEFT);
case 'H': return KEY_HOME;
case 'F': return KEY_END;
case 'I': return KEY_PAGE_UP;
case 'G': return KEY_PAGE_DOWN;
case 'Z': return KEY_SHIFT_TAB;
case '~':
if (timeout == 3) {
switch (this_buf[2]) {
case '1': return KEY_HOME;
case '3': return KEY_DELETE;
case '4': return KEY_END;
case '5': return KEY_PAGE_UP;
case '6': return KEY_PAGE_DOWN;
}
} else if (timeout == 5) {
if (this_buf[2] == '2' && this_buf[3] == '0' && this_buf[4] == '0') {
return KEY_PASTE_BEGIN;
} else if (this_buf[2] == '2' && this_buf[3] == '0' && this_buf[4] == '1') {
return KEY_PASTE_END;
}
} else if (this_buf[2] == '1') {
switch (this_buf[3]) {
case '5': return KEY_F5;
case '7': return KEY_F6;
case '8': return KEY_F7;
case '9': return KEY_F8;
}
} else if (this_buf[2] == '2') {
switch (this_buf[3]) {
case '0': return KEY_F9;
case '1': return KEY_F10;
case '3': return KEY_F11;
case '4': return KEY_F12;
}
}
break;
}
}
timeout = 0;
continue;
}
} else if (istate == UTF8_REJECT) {
istate = 0;
}
}
return KEY_TIMEOUT;
}
enum Key key_from_name(const char * name) {
for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
if (!strcmp(KeyNames[i].name, name)) return KeyNames[i].keycode;
}
if (name[0] == '^' && name[1] && !name[2]) {
return name[1] - '@';
}
if (!name[1]) return name[0];
/* Try decoding */
uint32_t c, state = 0;
int candidate = -1;
while (*name) {
if (!decode(&state, &c, (unsigned char)*name)) {
if (candidate == -1) candidate = c;
else return -1; /* Reject `name` if it is multiple codepoints */
} else if (state == UTF8_REJECT) {
return -1;
}
}
return candidate;
}
/**
* Pointer to current active buffer
*/
buffer_t * env = NULL;
buffer_t * left_buffer = NULL;
buffer_t * right_buffer = NULL;
/**
* A buffer for holding a number (line, repetition count)
*/
#define NAV_BUFFER_MAX 10
char nav_buf[NAV_BUFFER_MAX+1];
int nav_buffer = 0;
/**
* Available buffers
*/
int buffers_len = 0;
int buffers_avail = 0;
buffer_t ** buffers = NULL;
/**
* Create a new buffer
*/
buffer_t * buffer_new(void) {
if (buffers_len == buffers_avail) {
/* If we are out of buffer space, expand the buffers vector */
buffers_avail *= 2;
buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
}
/* TODO: Clean up split support and support multiple splits... */
if (left_buffer) {
left_buffer->left = 0;
left_buffer->width = global_config.term_width;
right_buffer->left = 0;
right_buffer->width = global_config.term_width;
left_buffer = NULL;
right_buffer = NULL;
}
/* Allocate a new buffer */
buffers[buffers_len] = malloc(sizeof(buffer_t));
memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
buffers[buffers_len]->left = 0;
buffers[buffers_len]->width = global_config.term_width;
buffers[buffers_len]->highlighting_paren = -1;
buffers[buffers_len]->numbers = global_config.numbers;
buffers[buffers_len]->gutter = 1;
buffers_len++;
global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
return buffers[buffers_len-1];
}
/**
* Open the biminfo file.
*/
FILE * open_biminfo(void) {
if (!global_config.use_biminfo) return NULL;
char * home = getenv("HOME");
if (!home) {
/* ... but since it's not, we need $HOME, so fail if it isn't set. */
return NULL;
}
/* biminfo lives at ~/.biminfo */
char biminfo_path[PATH_MAX+1] = {0};
sprintf(biminfo_path,"%s/.biminfo",home);
/* Try to open normally first... */
FILE * biminfo = fopen(biminfo_path,"r+");
if (!biminfo) {
/* Otherwise, try to create it. */
biminfo = fopen(biminfo_path,"w+");
}
return biminfo;
}
/**
* Check if a file is open by examining the biminfo file
*/
int file_is_open(char * file) {
/* Get the absolute path of the file to normalize for lookup */
char * _file = file;
if (file[0] == '~') {
char * home = getenv("HOME");
if (home) {
_file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
sprintf(_file, "%s%s", home, file+1);
}
}
char tmp_path[PATH_MAX+2];
if (!realpath(_file, tmp_path)) {
if (_file != file) free(_file);
return 0; /* Assume not */
}
if (_file != file) free(_file);
strcat(tmp_path," ");
FILE * biminfo = open_biminfo();
if (!biminfo) return 0; /* Assume not */
/* Scan */
char line[PATH_MAX+64];
while (!feof(biminfo)) {
fpos_t start_of_line;
fgetpos(biminfo, &start_of_line);
fgets(line, PATH_MAX+63, biminfo);
if (line[0] != '%') {
continue;
}
if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
/* File is currently open */
int pid = -1;
sscanf(line+1+strlen(tmp_path)+1,"%d",&pid);
if (pid != -1 && pid != getpid()) {
if (!kill(pid, 0)) {
int key = 0;
render_error("biminfo indicates another instance may already be editing this file");
render_commandline_message("\n");
render_commandline_message("file path = %s\n", tmp_path);
render_commandline_message("pid = %d (still running)\n", pid);
render_commandline_message("Open file anyway? (y/N)");
while ((key = bim_getkey(DEFAULT_KEY_WAIT)) == KEY_TIMEOUT);
if (key != 'y') {
fclose(biminfo);
return 1;
}
}
}
fclose(biminfo);
return 0;
}
}
fclose(biminfo);
return 0;
}
/**
* Fetch the cursor position from a biminfo file
*/
int fetch_from_biminfo(buffer_t * buf) {
/* Can't fetch if we don't have a filename */
if (!buf->file_name) return 1;
char * file = buf->file_name;
char * _file = file;
if (file[0] == '~') {
char * home = getenv("HOME");
if (home) {
_file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
sprintf(_file, "%s%s", home, file+1);
}
}
/* Get the absolute path of the file to normalize for lookup */
char tmp_path[PATH_MAX+2];
if (!realpath(_file, tmp_path)) {
if (_file != file) free(_file);
return 1;
}
if (_file != file) free(_file);
strcat(tmp_path," ");
FILE * biminfo = open_biminfo();
if (!biminfo) return 1;
/* Scan */
char line[PATH_MAX+64];
while (!feof(biminfo)) {
fpos_t start_of_line;
fgetpos(biminfo, &start_of_line);
fgets(line, PATH_MAX+63, biminfo);
if (line[0] != '>') {
continue;
}
if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
/* Read */
sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
if (buf->line_no > buf->line_count) buf->line_no = buf->line_count;
if (buf->col_no > buf->lines[buf->line_no-1]->actual) buf->col_no = buf->lines[buf->line_no-1]->actual;
try_to_center();
fclose(biminfo);
return 0;
}
}
fclose(biminfo);
return 0;
}
/**
* Write a file containing the last cursor position of a buffer.
*/
int update_biminfo(buffer_t * buf, int is_open) {
if (!buf->file_name) return 1;
char * file = buf->file_name;
char * _file = file;
if (file[0] == '~') {
char * home = getenv("HOME");
if (home) {
_file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
sprintf(_file, "%s%s", home, file+1);
}
}
/* Get the absolute path of the file to normalize for lookup */
char tmp_path[PATH_MAX+1];
if (!realpath(_file, tmp_path)) {
if (_file != file) free(_file);
return 1;
}
if (_file != file) free(_file);
strcat(tmp_path," ");
FILE * biminfo = open_biminfo();
if (!biminfo) return 1;
/* Scan */
char line[PATH_MAX+64];
while (!feof(biminfo)) {
fpos_t start_of_line;
fgetpos(biminfo, &start_of_line);
fgets(line, PATH_MAX+63, biminfo);
if (line[0] != '>' && line[0] != '%') {
continue;
}
if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
/* Update */
fsetpos(biminfo, &start_of_line);
fprintf(biminfo,"%c%s %20d %20d\n", is_open ? '%' : '>', tmp_path,
is_open ? getpid() : buf->line_no, buf->col_no);
goto _done;
}
}
if (ftell(biminfo) == 0) {
/* New biminfo */
fprintf(biminfo, "# This is a biminfo file.\n");
fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
}
/* If we reach this point, we didn't find a record for this file
* and the write cursor should be at the end, so just add a new line */
fprintf(biminfo,"%c%s %20d %20d\n", is_open ? '%' : '>', tmp_path,
is_open ? getpid() : buf->line_no, buf->col_no);
_done:
fclose(biminfo);
return 0;
}
void cancel_background_tasks(buffer_t * buf) {
background_task_t * t = global_config.background_task;
background_task_t * last = NULL;
while (t) {
if (t->env == buf) {
if (last) {
last->next = t->next;
} else {
global_config.background_task = t->next;
}
if (!t->next) {
global_config.tail_task = last;
}
background_task_t * tmp = t->next;
free(t);
t = tmp;
} else {
last = t;
t = t->next;
}
}
}
/**
* Close a buffer
*/
buffer_t * buffer_close(buffer_t * buf) {
int i;
/* Locate the buffer in the buffer list */
for (i = 0; i < buffers_len; i++) {
if (buf == buffers[i])
break;
}
/* This buffer doesn't exist? */
if (i == buffers_len) {
return NULL;
}
/* Cancel any background tasks for this env */
cancel_background_tasks(buf);
update_biminfo(buf, 0);
/* Clean up lines used by old buffer */
for (int i = 0; i < buf->line_count; ++i) {
free(buf->lines[i]);
}
free(buf->lines);
if (buf->file_name) {
free(buf->file_name);
}
history_t * h = buf->history;
while (h->next) {
h = h->next;
}
while (h) {
history_t * x = h->previous;
free(h);
h = x;
}
/* Clean up the old buffer */
free(buf);
/* Remove the buffer from the vector, moving others up */
if (i != buffers_len - 1) {
memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i - 1));
}
/* There is one less buffer */
buffers_len--;
if (buffers_len && global_config.tab_offset >= buffers_len) global_config.tab_offset--;
global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
if (!buffers_len) {
/* There are no more buffers. */
return NULL;
}
/* If this was the last buffer in the list, return the previous last buffer */
if (i == buffers_len) {
return buffers[buffers_len-1];
}
/* Otherwise return the buffer in the same location */
return buffers[i];
}
/**
* Convert syntax highlighting flag to color code
*/
const char * flag_to_color(int _flag) {
int flag = _flag & FLAG_MASK_COLORS;
switch (flag) {
case FLAG_KEYWORD:
return COLOR_KEYWORD;
case FLAG_STRING:
return COLOR_STRING;
case FLAG_COMMENT:
return COLOR_COMMENT;
case FLAG_TYPE:
return COLOR_TYPE;
case FLAG_NUMERAL:
return COLOR_NUMERAL;
case FLAG_PRAGMA:
return COLOR_PRAGMA;
case FLAG_DIFFPLUS:
return COLOR_GREEN;
case FLAG_DIFFMINUS:
return COLOR_RED;
case FLAG_SELECT:
return COLOR_FG;
case FLAG_BOLD:
return COLOR_BOLD;
case FLAG_LINK_COLOR:
return COLOR_LINK;
case FLAG_ESCAPE:
return COLOR_ESCAPE;
default:
return COLOR_FG;
}
}
/**
* Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
* so it can be used for prefix checking for things that need further special handling.
*/
static int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
if (keyword_qualifier(lastchar())) return 0;
if (!keyword_qualifier(charat())) return 0;
int i = state->i;
int slen = 0;
while (i < state->line->actual || *keyword == '\0') {
if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
for (int j = 0; j < slen; ++j) {
paint(1, flag);
}
return 1;
}
if (*keyword != state->line->text[i].codepoint) return 0;
i++;
keyword++;
slen++;
}
return 0;
}
/**
* This is a basic character matcher for "keyword" characters.
*/
static int simple_keyword_qualifier(int c) {
return isalnum(c) || (c == '_');
}
/**
* These words can appear in comments and should be highlighted.
* Since there are a lot of comment highlighters, this is provided
* as a common function that can be used by multiple highlighters.
*/
static int common_comment_buzzwords(struct syntax_state * state) {
if (match_and_paint(state, "TODO", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
else if (match_and_paint(state, "XXX", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
else if (match_and_paint(state, "FIXME", FLAG_ERROR, simple_keyword_qualifier)) { return 1; }
return 0;
}
/**
* Paint a comment until end of line; assumes this comment can not continue.
* (Some languages have comments that can continue with a \ - don't use this!)
* Assumes you've already painted your comment start characters.
*/
static int paint_comment(struct syntax_state * state) {
while (charat() != -1) {
if (common_comment_buzzwords(state)) continue;
else { paint(1, FLAG_COMMENT); }
}
return -1;
}
/**
* Find and return a highlighter by name, or return NULL if none was found.
*/
static struct syntax_definition * find_syntax_calculator(const char * name) {
for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
if (!strcmp(s->name, name)) {
return s;
}
}
return NULL;
}
int syntax_count = 0;
int syntax_space = 0;
struct syntax_definition * syntaxes = NULL;
void add_syntax(struct syntax_definition def) {
/* See if a name match already exists for this def. */
for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
if (!strcmp(def.name,s->name)) {
*s = def;
return;
}
}
if (syntax_space == 0) {
syntax_space = 4;
syntaxes = calloc(sizeof(struct syntax_definition), syntax_space);
} else if (syntax_count +1 == syntax_space) {
syntax_space *= 2;
syntaxes = realloc(syntaxes, sizeof(struct syntax_definition) * syntax_space);
for (int i = syntax_count; i < syntax_space; ++i) syntaxes[i].name = NULL;
}
syntaxes[syntax_count] = def;
syntax_count++;
}
void redraw_all(void);
/**
* Calculate syntax highlighting for the given line, and lines after
* if their initial syntax state has changed by this recalculation.
*
* If `line_no` is -1, this line is taken to be a special line and not
* part of a buffer; search highlighting will not be processed and syntax
* highlighting will halt after the line is finished.
*
* If `env->slowop` is currently enabled, recalculation is skipped.
*/
void recalculate_syntax(line_t * line, int line_no) {
if (env->slowop) return;
/* Clear syntax for this line first */
int is_original = 1;
while (1) {
for (int i = 0; i < line->actual; ++i) {
line->text[i].flags = line->text[i].flags & (3 << 5);
}
if (!env->syntax) {
if (line_no != -1) rehighlight_search(line);
return;
}