-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor.c
More file actions
914 lines (789 loc) · 25.6 KB
/
editor.c
File metadata and controls
914 lines (789 loc) · 25.6 KB
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
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <sys/select.h>
#include <sys/ioctl.h>
/*** Defines ***/
#define CTRL_KEY(k) ((k) & 0x1f)
#define MAX_LINES 100
#define MAX_SEARCH_LEN 80
/*** Terminal ***/
struct termios orig_termios;
volatile sig_atomic_t window_resized = 1;
void die(const char *s);
void disableRawMode();
void enableRawMode();
void handleWinch(int sig) {
window_resized = 1;
}
void setupResizeHandler() {
struct sigaction sa;
sa.sa_handler = handleWinch;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGWINCH, &sa, NULL) == -1) {
die("sigaction");
}
}
/*** Editor State ***/
int cx;
int cy;
char *lines[MAX_LINES];
int num_lines;
const char *current_filename;
char statusmsg[80];
int visual_mode;
int sx, sy; // selection start coordinates
char *clipboard; // buffer for copied text
int clip_len; // length of clipboard content
int rowoff; // row offset for scrolling
int editor_rows = 24;
int editor_cols = 80;
int search_mode; // 0 = not searching, 1 = entering query, 2 = active search
char search_query[MAX_SEARCH_LEN];
int search_query_len;
struct { int x, y; } search_matches[MAX_LINES * 10]; // store match positions
int num_matches;
int current_match; // index of current match in search_matches
/*** Input ***/
enum EditorKey {
ARROW_LEFT = 1000,
ARROW_RIGHT,
ARROW_UP,
ARROW_DOWN
};
int readKey();
void moveCursor(int key);
void insertChar(int c);
void deleteChar();
void insertNewline();
void processKeypress();
void toggleVisualMode();
void copySelection();
void cutSelection();
void deleteSelection();
void pasteClipboard();
void enterSearchMode();
void exitSearchMode();
void performSearch();
void findNext();
void findPrevious();
/*** Output ***/
void editorDrawRows();
void drawStatusBar();
void editorRefreshScreen();
/*** File I/O ***/
void saveFile(const char *filename);
void loadFile(const char *filename);
/*** Terminal Setup ***/
void die(const char *s) {
perror(s);
exit(1);
}
void disableRawMode() {
tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
}
void enableRawMode() {
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1) die("tcgetattr");
atexit(disableRawMode);
struct termios raw = orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= (CS8);
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
raw.c_cc[VMIN] = 0;
raw.c_cc[VTIME] = 1;
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
}
/*** Search Functions ***/
void enterSearchMode() {
search_mode = 1;
search_query[0] = '\0';
search_query_len = 0;
num_matches = 0;
current_match = -1;
snprintf(statusmsg, sizeof(statusmsg), "[Search Mode] Enter query: ");
editorRefreshScreen();
}
void exitSearchMode() {
search_mode = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Normal Mode]");
editorRefreshScreen();
}
void performSearch() {
if (search_query_len == 0) {
exitSearchMode();
return;
}
num_matches = 0;
current_match = -1;
for (int y = 0; y < num_lines; y++) {
if (!lines[y]) continue;
char *pos = lines[y];
while ((pos = strstr(pos, search_query)) != NULL) {
if (num_matches < MAX_LINES * 10) {
search_matches[num_matches].x = pos - lines[y];
search_matches[num_matches].y = y;
num_matches++;
}
pos++; // move past current match
}
}
if (num_matches > 0) {
current_match = 0;
cx = search_matches[0].x;
cy = search_matches[0].y;
// adjust scroll to show match
if (cy < rowoff) rowoff = cy;
if (cy >= rowoff + editor_rows) rowoff = cy - editor_rows + 1;
snprintf(statusmsg, sizeof(statusmsg), "[Search Mode] %d matches found", num_matches);
} else {
snprintf(statusmsg, sizeof(statusmsg), "[Search Mode] No matches found");
}
search_mode = 2;
editorRefreshScreen();
}
void findNext() {
if (search_mode != 2 || num_matches == 0) return;
current_match = (current_match + 1) % num_matches;
cx = search_matches[current_match].x;
cy = search_matches[current_match].y;
// adjust scroll to show match
if (cy < rowoff) rowoff = cy;
if (cy >= rowoff + editor_rows) rowoff = cy - editor_rows + 1;
snprintf(statusmsg, sizeof(statusmsg), "[Search Mode] Match %d/%d", current_match + 1, num_matches);
editorRefreshScreen();
}
void findPrevious() {
if (search_mode != 2 || num_matches == 0) return;
current_match = (current_match - 1);
if (current_match < 0) current_match = num_matches - 1;
cx = search_matches[current_match].x;
cy = search_matches[current_match].y;
// adjust scroll to show match
if (cy < rowoff) rowoff = cy;
if (cy >= rowoff + editor_rows) rowoff = cy - editor_rows + 1;
snprintf(statusmsg, sizeof(statusmsg), "[Search Mode] Match %d/%d", current_match + 1, num_matches);
editorRefreshScreen();
}
/*** Input Functions ***/
int readKey() {
char c;
struct timeval tv = {0, 1000}; // 1ms timeout
fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
// Wait for input with timeout
if (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) <= 0) {
return 0; // no input ready
}
if (read(STDIN_FILENO, &c, 1) != 1) {
return 0; // read failed
}
if (c == '\x1b') {
char seq[2];
// Check for next character
if (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) <= 0) {
return '\x1b';
}
if (read(STDIN_FILENO, &seq[0], 1) != 1) return '\x1b';
if (seq[0] == '[') {
if (select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv) <= 0) {
return '\x1b';
}
if (read(STDIN_FILENO, &seq[1], 1) != 1) return '\x1b';
switch (seq[1]) {
case 'A': return ARROW_UP;
case 'B': return ARROW_DOWN;
case 'C': return ARROW_RIGHT;
case 'D': return ARROW_LEFT;
}
}
return '\x1b'; // consume unrecognized sequences
}
return c;
}
void moveCursor(int key) {
switch (key) {
case ARROW_LEFT:
if (cx > 0) cx--;
break;
case ARROW_RIGHT:
if (cx < editor_cols - 1) cx++;
break;
case ARROW_UP:
if (cy > 0) cy--;
break;
case ARROW_DOWN:
if (cy < num_lines - 1) cy++;
break;
}
// adjust scroll offset
if (cy < rowoff) {
rowoff = cy;
}
if (cy >= rowoff + editor_rows) {
rowoff = cy - editor_rows + 1;
}
// ensure cursor x doesn't exceed line length
int len = lines[cy] ? strlen(lines[cy]) : 0;
if (cx > len) cx = len;
}
void insertChar(int c) {
if (cy >= MAX_LINES) return;
if (lines[cy] == NULL) {
lines[cy] = malloc(1);
lines[cy][0] = '\0';
}
int len = strlen(lines[cy]);
if (cx > len) cx = len;
lines[cy] = realloc(lines[cy], len + 2);
memmove(&lines[cy][cx + 1], &lines[cy][cx], len - cx + 1);
lines[cy][cx] = c;
cx++;
if (cy >= num_lines) num_lines = cy + 1;
}
void deleteChar() {
if (cy >= num_lines || !lines[cy]) return;
if (cx > 0) {
int len = strlen(lines[cy]);
memmove(&lines[cy][cx - 1], &lines[cy][cx], len - cx + 1);
lines[cy] = realloc(lines[cy], len);
cx--;
} else if (cy > 0) {
int prev_len = strlen(lines[cy - 1]);
int curr_len = strlen(lines[cy]);
lines[cy - 1] = realloc(lines[cy - 1], prev_len + curr_len + 1);
strcat(lines[cy - 1], lines[cy]);
free(lines[cy]);
for (int i = cy; i < num_lines - 1; i++) {
lines[i] = lines[i + 1];
}
lines[num_lines - 1] = NULL;
num_lines--;
cy--;
cx = prev_len;
}
}
void insertNewline() {
if (cy >= MAX_LINES - 1) return;
char *line = lines[cy];
if (!line) {
cy++;
cx = 0;
return;
}
int len = strlen(line);
char *left = malloc(cx + 1);
char *right = malloc(len - cx + 1);
memcpy(left, line, cx);
left[cx] = '\0';
strcpy(right, &line[cx]);
lines[cy] = left;
for (int i = num_lines; i > cy + 1; i--) {
lines[i] = lines[i - 1];
}
lines[cy + 1] = right;
num_lines++;
cy++;
cx = 0;
}
void toggleVisualMode() {
if (visual_mode) {
visual_mode = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Normal Mode]");
} else {
visual_mode = 1;
sx = cx;
sy = cy;
snprintf(statusmsg, sizeof(statusmsg), "[Visual Mode]");
}
}
void copySelection() {
if (!visual_mode) return;
// free previous clipboard content
if (clipboard) free(clipboard);
// boundarys of selection
int start_y = sy < cy ? sy : cy;
int end_y = sy < cy ? cy : sy;
int start_x = (sy < cy || (sy == cy && sx <= cx)) ? sx : cx;
int end_x = (sy < cy || (sy == cy && sx <= cx)) ? cx : sx;
// handle same-line selection
if (start_y == end_y && start_x == end_x) {
clipboard = malloc(1);
clipboard[0] = '\0';
clip_len = 0;
visual_mode = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Copied 0 chars]");
return;
}
// calculate total length needed
clip_len = 0;
for (int y = start_y; y <= end_y; y++) {
if (lines[y]) {
int len = strlen(lines[y]);
int x_start = (y == start_y) ? start_x : 0;
int x_end = (y == end_y) ? end_x : len;
clip_len += x_end - x_start;
if (y < end_y) clip_len++; // For newline
}
}
// allocate and copy to clipboard
clipboard = malloc(clip_len + 1);
int pos = 0;
for (int y = start_y; y <= end_y; y++) {
if (lines[y]) {
int len = strlen(lines[y]);
int x_start = (y == start_y) ? start_x : 0;
int x_end = (y == end_y) ? end_x : len;
for (int x = x_start; x < x_end; x++) {
clipboard[pos++] = lines[y][x];
}
if (y < end_y && pos < clip_len) clipboard[pos++] = '\n';
}
}
clipboard[pos] = '\0';
clip_len = pos;
// exit visual mode
visual_mode = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Copied %d chars]", clip_len);
}
void cutSelection() {
if (!visual_mode) return;
// copy selection to clipboard first
copySelection();
// determine selection boundaries
int start_y = sy < cy ? sy : cy;
int end_y = sy < cy ? cy : sy;
int start_x = (sy < cy || (sy == cy && sx <= cx)) ? sx : cx;
int end_x = (sy < cy || (sy == cy && sx <= cx)) ? cx : sx;
// handle same-line selection
if (start_y == end_y) {
if (start_x == end_x) {
visual_mode = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Cut 0 chars]");
return;
}
int len = strlen(lines[start_y]);
memmove(&lines[start_y][start_x], &lines[start_y][end_x], len - end_x + 1);
lines[start_y] = realloc(lines[start_y], len - (end_x - start_x) + 1);
cx = start_x;
cy = start_y;
} else {
// handle multi-line selection
// first line: keep text before start_x
int first_len = strlen(lines[start_y]);
lines[start_y] = realloc(lines[start_y], start_x + 1);
lines[start_y][start_x] = '\0';
// last line: keep text after end_x
int last_len = strlen(lines[end_y]);
char *last_part = malloc(last_len - end_x + 1);
strcpy(last_part, &lines[end_y][end_x]);
free(lines[end_y]);
lines[end_y] = last_part;
// concatenate first and last lines
int new_len = strlen(lines[start_y]) + strlen(lines[end_y]) + 1;
lines[start_y] = realloc(lines[start_y], new_len);
strcat(lines[start_y], lines[end_y]);
free(lines[end_y]);
// shift lines up
for (int i = end_y; i < num_lines - 1; i++) {
lines[i] = lines[i + 1];
}
lines[num_lines - 1] = NULL;
// remove intermediate lines
for (int i = start_y + 1; i < end_y; i++) {
free(lines[i]);
lines[i] = NULL;
}
for (int i = start_y + 1; i < num_lines - (end_y - start_y); i++) {
lines[i] = lines[i + (end_y - start_y)];
}
for (int i = num_lines - (end_y - start_y); i < num_lines; i++) {
lines[i] = NULL;
}
num_lines -= (end_y - start_y);
cx = start_x;
cy = start_y;
}
// exit visual mode
visual_mode = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Cut %d chars]", clip_len);
// adjust scroll offset
if (cy < rowoff) {
rowoff = cy;
}
if (cy >= rowoff + editor_rows) {
rowoff = cy - editor_rows + 1;
}
}
void deleteSelection() {
if (!visual_mode) return;
// determine selection boundaries
int start_y = sy < cy ? sy : cy;
int end_y = sy < cy ? cy : sy;
int start_x = (sy < cy || (sy == cy && sx <= cx)) ? sx : cx;
int end_x = (sy < cy || (sy == cy && sx <= cx)) ? cx : sx;
// calculate deleted chars for status message
int deleted_chars = 0;
for (int y = start_y; y <= end_y; y++) {
if (lines[y]) {
int len = strlen(lines[y]);
int x_start = (y == start_y) ? start_x : 0;
int x_end = (y == end_y) ? end_x : len;
deleted_chars += x_end - x_start;
if (y < end_y) deleted_chars++; // For newline
}
}
// handle same-line selection
if (start_y == end_y) {
if (start_x == end_x) {
visual_mode = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Deleted 0 chars]");
return;
}
int len = strlen(lines[start_y]);
memmove(&lines[start_y][start_x], &lines[start_y][end_x], len - end_x + 1);
lines[start_y] = realloc(lines[start_y], len - (end_x - start_x) + 1);
cx = start_x;
cy = start_y;
} else {
// handle multi-line selection
// first line: keep text before start_x
int first_len = strlen(lines[start_y]);
lines[start_y] = realloc(lines[start_y], start_x + 1);
lines[start_y][start_x] = '\0';
// last line: keep text after end_x
int last_len = strlen(lines[end_y]);
char *last_part = malloc(last_len - end_x + 1);
strcpy(last_part, &lines[end_y][end_x]);
free(lines[end_y]);
lines[end_y] = last_part;
// concatenate first and last lines
int new_len = strlen(lines[start_y]) + strlen(lines[end_y]) + 1;
lines[start_y] = realloc(lines[start_y], new_len);
strcat(lines[start_y], lines[end_y]);
free(lines[end_y]);
// shift lines up
for (int i = end_y; i < num_lines - 1; i++) {
lines[i] = lines[i + 1];
}
lines[num_lines - 1] = NULL;
// remove intermediate lines
for (int i = start_y + 1; i < end_y; i++) {
free(lines[i]);
lines[i] = NULL;
}
for (int i = start_y + 1; i < num_lines - (end_y - start_y); i++) {
lines[i] = lines[i + (end_y - start_y)];
}
for (int i = num_lines - (end_y - start_y); i < num_lines; i++) {
lines[i] = NULL;
}
num_lines -= (end_y - start_y);
cx = start_x;
cy = start_y;
}
// exit visual mode
visual_mode = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Deleted %d chars]", deleted_chars);
// adjust scroll offset
if (cy < rowoff) {
rowoff = cy;
}
if (cy >= rowoff + editor_rows) {
rowoff = cy - editor_rows + 1;
}
}
void pasteClipboard() {
if (!clipboard) return;
for (int i = 0; i < clip_len; i++) {
if (clipboard[i] == '\n') {
insertNewline();
} else {
insertChar(clipboard[i]);
}
}
snprintf(statusmsg, sizeof(statusmsg), "[Pasted %d chars]", clip_len);
}
void saveFile(const char *filename) {
FILE *file = fopen(filename, "w");
if (!file) {
snprintf(statusmsg, sizeof(statusmsg), "Can't save! fopen error.");
return;
}
for (int i = 0; i < num_lines; i++) {
if (lines[i]) {
fprintf(file, "%s\n", lines[i]);
}
}
fclose(file);
snprintf(statusmsg, sizeof(statusmsg), "[Saved to %s]", filename);
}
void loadFile(const char *filename) {
FILE *file = fopen(filename, "r");
if (!file) {
file = fopen(filename, "w");
if (!file) {
die("fopen");
}
fclose(file);
return;
}
char *line = NULL;
size_t len = 0;
ssize_t nread;
num_lines = 0;
while ((nread = getline(&line, &len, file)) != -1) {
line[strcspn(line, "\n")] = 0;
lines[num_lines] = malloc(strlen(line) + 1);
strcpy(lines[num_lines], line);
num_lines++;
}
free(line);
fclose(file);
}
void processKeypress() {
int c = readKey();
// no input, skip
if (c == 0) return;
// Esc always returns to normal mode
if (c == '\x1b') {
visual_mode = 0;
if (search_mode) exitSearchMode();
else snprintf(statusmsg, sizeof(statusmsg), "[Normal Mode]");
editorRefreshScreen();
return;
}
if (search_mode == 1) {
// entering search query
if (c == '\r') { // Enter
performSearch();
} else if (c == 127) { // Backspace
if (search_query_len > 0) {
search_query[--search_query_len] = '\0';
snprintf(statusmsg, sizeof(statusmsg), "[Search Mode] Enter query: %s", search_query);
editorRefreshScreen();
}
} else if (c >= 32 && c <= 126 && search_query_len < MAX_SEARCH_LEN - 1) {
search_query[search_query_len++] = c;
search_query[search_query_len] = '\0';
snprintf(statusmsg, sizeof(statusmsg), "[Search Mode] Enter query: %s", search_query);
editorRefreshScreen();
}
return;
} else if (search_mode == 2) {
// active search mode
if (c == 'n') {
findNext();
} else if (c == 'p') {
findPrevious();
}
return;
}
if (c == CTRL_KEY('q')) {
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
exit(0);
} else if (c == CTRL_KEY('f')) {
enterSearchMode();
} else if ((c == CTRL_KEY('v') || c == 'v') && !visual_mode) {
toggleVisualMode();
editorRefreshScreen();
} else if (c == 'y' && visual_mode) {
copySelection();
editorRefreshScreen();
} else if (c == 'c' && visual_mode) {
cutSelection();
editorRefreshScreen();
} else if (c == 'd' && visual_mode) {
deleteSelection();
editorRefreshScreen();
} else if (c == 'p' && !visual_mode) {
pasteClipboard();
editorRefreshScreen();
} else if (visual_mode) {
moveCursor(c); // allow cursor movement in visual mode
editorRefreshScreen();
} else if (c == 127) { // backspace
deleteChar();
editorRefreshScreen();
} else if (c == '\r') { // Enter
insertNewline();
editorRefreshScreen();
} else if (c == CTRL_KEY('s')) {
saveFile(current_filename);
editorRefreshScreen();
} else if (c == CTRL_KEY('o')) { // Open
loadFile(current_filename);
editorRefreshScreen();
} else if (c >= 32 && c <= 126) {
insertChar(c);
editorRefreshScreen();
} else {
moveCursor(c);
editorRefreshScreen();
}
}
void editorDrawRows() {
for (int y = 0; y < editor_rows; y++) {
int file_y = y + rowoff;
if (file_y < num_lines && lines[file_y]) {
if (visual_mode) {
// determine if this row is within the selection
int start_y = sy < cy ? sy : cy;
int end_y = sy < cy ? cy : sy;
if (file_y >= start_y && file_y <= end_y) {
int start_x, end_x;
if (sy == cy) {
// same-line selection
start_x = sx < cx ? sx : cx;
end_x = sx < cx ? cx : sx;
} else if (file_y == start_y) {
// first line of multi-line selection
start_x = (file_y == sy) ? sx : (file_y == cy) ? cx : 0;
end_x = strlen(lines[file_y]);
} else if (file_y == end_y) {
// last line of multi-line selection
start_x = 0;
end_x = (file_y == sy) ? sx : (file_y == cy) ? cx : strlen(lines[file_y]);
} else {
// middle line of multi-line selection
start_x = 0;
end_x = strlen(lines[file_y]);
}
// write line with highlighting
int len = strlen(lines[file_y]);
for (int x = 0; x < len; x++) {
if (x >= start_x && x < end_x) {
write(STDOUT_FILENO, "\x1b[7m", 4); // reverse video (highlight)
write(STDOUT_FILENO, &lines[file_y][x], 1);
write(STDOUT_FILENO, "\x1b[0m", 4); // reset
} else {
write(STDOUT_FILENO, &lines[file_y][x], 1);
}
}
} else {
write(STDOUT_FILENO, lines[file_y], strlen(lines[file_y]));
}
} else if (search_mode == 2 && num_matches > 0) {
// highlight search matches
int len = strlen(lines[file_y]);
int x = 0;
while (x < len) {
int is_match = 0;
for (int i = 0; i < num_matches; i++) {
if (search_matches[i].y == file_y && search_matches[i].x == x) {
is_match = 1;
break;
}
}
if (is_match) {
write(STDOUT_FILENO, "\x1b[44m", 5); // blue background
for (int j = 0; j < search_query_len && x + j < len; j++) {
write(STDOUT_FILENO, &lines[file_y][x + j], 1);
}
write(STDOUT_FILENO, "\x1b[0m", 4); // reset
x += search_query_len;
} else {
write(STDOUT_FILENO, &lines[file_y][x], 1);
x++;
}
}
} else {
write(STDOUT_FILENO, lines[file_y], strlen(lines[file_y]));
}
} else {
write(STDOUT_FILENO, "~", 1);
}
write(STDOUT_FILENO, "\r\n", 2);
}
}
void updateWindowSize() {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
// If ioctl fails or reports 0, use defaults
editor_rows = 24;
editor_cols = 80;
} else {
// Subtract 1 row for the status bar
editor_rows = ws.ws_row - 1;
editor_cols = ws.ws_col;
}
window_resized = 0;
}
void drawStatusBar() {
updateWindowSize();
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1) {
// fallback to a reasonable default if ioctl fails
ws.ws_row = editor_rows + 1;
ws.ws_col = editor_cols;
}
// move to the bottom row
char buf[32];
snprintf(buf, sizeof(buf), "\x1b[%d;1H", ws.ws_row);
write(STDOUT_FILENO, buf, strlen(buf));
// clear the line and enable reverse video
write(STDOUT_FILENO, "\x1b[K", 3); // Clear line
write(STDOUT_FILENO, "\x1b[7m", 4); // Reverse video
// write status message, truncate if too long
int msg_len = strlen(statusmsg);
if (msg_len > ws.ws_col) msg_len = ws.ws_col;
write(STDOUT_FILENO, statusmsg, msg_len);
// Pad with spaces to fill the row
for (int i = msg_len; i < ws.ws_col; i++) {
write(STDOUT_FILENO, " ", 1);
}
// reset attributes
write(STDOUT_FILENO, "\x1b[0m", 4);
}
void editorRefreshScreen() {
write(STDOUT_FILENO, "\x1b[2J", 4);
write(STDOUT_FILENO, "\x1b[H", 3);
// draw editor content and status bar at bottom
editorDrawRows();
drawStatusBar();
// move cursor to editor position
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1) {
ws.ws_row = editor_rows + 1;
}
char buf[32];
if (search_mode == 1) {
// keep cursor at status bar for query input
snprintf(buf, sizeof(buf), "\x1b[%d;%dH", ws.ws_row, (int)strlen(statusmsg) + 1);
} else {
snprintf(buf, sizeof(buf), "\x1b[%d;%dH", cy - rowoff + 1, cx + 1);
}
write(STDOUT_FILENO, buf, strlen(buf));
fflush(stdout); // ensure immediate output
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return 1;
}
current_filename = argv[1];
loadFile(current_filename);
visual_mode = 0;
search_mode = 0;
clipboard = NULL;
clip_len = 0;
rowoff = 0;
snprintf(statusmsg, sizeof(statusmsg), "[Normal Mode]");
setupResizeHandler();
enableRawMode();
editorRefreshScreen();
while (1) {
if (window_resized) {
editorRefreshScreen();
}
processKeypress();
}
return 0;
}