-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patheditor.cpp
1690 lines (1480 loc) · 62.7 KB
/
editor.cpp
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 "editor.h"
#include "util/bookmarks.h"
#include "files.h"
#include "util/settings.h"
#include "util/line_jump.h"
#include <algorithm>
#include <iostream>
int GetCharIndexFromCoords(const std::string &text, const ImVec2 &click_pos,
const ImVec2 &text_start_pos,
const std::vector<int> &line_starts,
float line_height);
void HandleCursorMovement(const std::string &text, EditorState &state,
const ImVec2 &text_pos, float line_height,
float window_height, float window_width);
Editor gEditor;
void UpdateLineStarts(const std::string &text, std::vector<int> &line_starts) {
line_starts.clear();
line_starts.reserve(text.size() / 40); // Estimate average line length
line_starts.push_back(0);
size_t pos = 0;
while ((pos = text.find('\n', pos)) != std::string::npos) {
line_starts.push_back(pos + 1);
++pos;
}
}
int GetLineFromPos(const std::vector<int> &line_starts, int pos) {
auto it = std::upper_bound(line_starts.begin(), line_starts.end(), pos);
return std::distance(line_starts.begin(), it) - 1;
}
// Selection and cursor movement functions
void StartSelection(EditorState &state) {
state.is_selecting = true;
state.selection_start = state.cursor_pos;
state.selection_end = state.cursor_pos;
}
void UpdateSelection(EditorState &state) {
if (state.is_selecting) {
state.selection_end = state.cursor_pos;
}
}
void EndSelection(EditorState &state) { state.is_selecting = false; }
int GetSelectionStart(const EditorState &state) {
return std::min(state.selection_start, state.selection_end);
}
int GetSelectionEnd(const EditorState &state) {
return std::max(state.selection_start, state.selection_end);
}
float GetCursorYPosition(const EditorState &state, float line_height) {
int cursor_line = GetLineFromPos(state.line_starts, state.cursor_pos);
return cursor_line * line_height;
}
// Copy, cut, and paste functions
void CopySelectedText(const std::string& text, const EditorState& state) {
if (state.selection_start != state.selection_end) {
int start = GetSelectionStart(state);
int end = GetSelectionEnd(state);
std::string selected_text = text.substr(start, end - start);
ImGui::SetClipboardText(selected_text.c_str());
}
}
float CalculateCursorXPosition(const ImVec2 &text_pos, const std::string &text,
int cursor_pos) {
float x = text_pos.x;
for (int i = 0; i < cursor_pos; i++) {
if (text[i] == '\n') {
x = text_pos.x;
} else {
x += ImGui::CalcTextSize(&text[i], &text[i + 1]).x;
}
}
return x;
}
ScrollChange EnsureCursorVisible(const ImVec2 &text_pos,
const std::string &text, EditorState &state,
float line_height, float window_height,
float window_width) {
float cursor_y =
(GetLineFromPos(state.line_starts, state.cursor_pos) * line_height);
float cursor_x = CalculateCursorXPosition(text_pos, text, state.cursor_pos);
float scroll_y = ImGui::GetScrollY();
float scroll_x = ImGui::GetScrollX();
float visible_start_x =
text_pos.x + scroll_x; // Use text_pos.x as the reference point
float visible_end_x = visible_start_x + window_width;
ScrollChange changed = {false, false};
// Vertical scrolling
if (cursor_y <
scroll_y + line_height) { // Start scrolling up one line earlier
state.scroll_pos.y = std::max(0.0f, cursor_y - line_height);
changed.vertical = true;
} else if (cursor_y >
scroll_y + window_height -
line_height * 2) { // Start scrolling down one line earlier
state.scroll_pos.y = cursor_y - window_height + line_height * 2;
changed.vertical = true;
}
// Horizontal scrolling
float buffer = ImGui::GetFontSize() * 5.0f; // Increased buffer
float target_scroll_x = scroll_x;
if (cursor_x < visible_start_x + buffer) {
// Scrolling left - immediately jump
state.scroll_x = cursor_x - text_pos.x - buffer * 2; // Double buffer on left
changed.horizontal = true;
} else if (cursor_x > visible_end_x - buffer * 1.5f) { // Start scrolling earlier
// Scrolling right - immediately jump
state.scroll_x = cursor_x - window_width + buffer * 2; // More space on right
changed.horizontal = true;
}
// Ensure we don't scroll past the start of the text
state.scroll_x = std::max(0.0f, state.scroll_x);
return changed;
}
void SelectAllText(EditorState &state, const std::string &text) {
const size_t MAX_SELECTION_SIZE = 100000; // Adjust this value as needed
state.is_selecting = true;
state.selection_start = 0;
state.cursor_pos = std::min(text.size(), MAX_SELECTION_SIZE);
state.selection_end = state.cursor_pos;
}
void CutSelectedText(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed) {
if (state.selection_start != state.selection_end) {
int start = GetSelectionStart(state);
int end = GetSelectionEnd(state);
std::string selected_text = text.substr(start, end - start);
ImGui::SetClipboardText(selected_text.c_str());
text.erase(start, end - start);
colors.erase(colors.begin() + start, colors.begin() + end);
state.cursor_pos = start;
state.selection_start = state.selection_end = start;
text_changed = true;
}
}
void CutWholeLine(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed) {
int line = GetLineFromPos(state.line_starts, state.cursor_pos);
int line_start = state.line_starts[line];
int line_end = (line + 1 < state.line_starts.size())
? state.line_starts[line + 1]
: text.size();
std::string line_text = text.substr(line_start, line_end - line_start);
ImGui::SetClipboardText(line_text.c_str());
text.erase(line_start, line_end - line_start);
colors.erase(colors.begin() + line_start, colors.begin() + line_end);
state.cursor_pos = line > 0 ? state.line_starts[line] : 0;
text_changed = true;
UpdateLineStarts(text, state.line_starts);
}
void PasteText(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed) {
const char *clipboard_text = ImGui::GetClipboardText();
if (clipboard_text != nullptr) {
std::string paste_content = clipboard_text;
if (!paste_content.empty()) {
int paste_start = state.cursor_pos;
int paste_end = paste_start + paste_content.size();
if (state.selection_start != state.selection_end) {
int start = GetSelectionStart(state);
int end = GetSelectionEnd(state);
text.replace(start, end - start, paste_content);
colors.erase(colors.begin() + start, colors.begin() + end);
colors.insert(colors.begin() + start, paste_content.size(),
ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
paste_start = start;
paste_end = start + paste_content.size();
} else {
text.insert(state.cursor_pos, paste_content);
colors.insert(colors.begin() + state.cursor_pos, paste_content.size(),
ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
}
state.cursor_pos = paste_end;
state.selection_start = state.selection_end = state.cursor_pos;
text_changed = true;
// Trigger syntax highlighting for the pasted content
gEditor.highlightContent(text, colors, paste_start, paste_end);
}
}
}
void HandleMouseInput(const std::string &text, EditorState &state,
const ImVec2 &text_start_pos, float line_height) {
static bool is_dragging = false;
static int drag_start_pos = -1;
ImVec2 mouse_pos = ImGui::GetMousePos();
int char_index = GetCharIndexFromCoords(text, mouse_pos, text_start_pos,
state.line_starts, line_height);
if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) {
if (ImGui::GetIO().KeyShift) {
// Shift-click selection
if (!state.is_selecting) {
state.selection_start = state.cursor_pos;
state.is_selecting = true;
}
state.selection_end = char_index;
} else {
// Regular click
state.cursor_pos = char_index;
state.selection_start = state.selection_end = char_index;
state.is_selecting = false;
}
is_dragging = true;
drag_start_pos = char_index;
} else if (ImGui::IsMouseDragging(ImGuiMouseButton_Left) && is_dragging) {
// Click-and-drag selection
state.is_selecting = true;
state.selection_start = drag_start_pos;
state.selection_end = char_index;
state.cursor_pos = char_index;
} else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) {
is_dragging = false;
drag_start_pos = -1;
}
}
void MoveCursorLeft(EditorState &state) {
if (state.cursor_pos > 0) {
state.cursor_pos--;
}
}
void MoveCursorRight(const std::string &text, EditorState &state) {
if (state.cursor_pos < text.size()) {
state.cursor_pos++;
}
}
void MoveCursorUp(const std::string &text, EditorState &state,
float line_height, float window_height) {
int current_line = GetLineFromPos(state.line_starts, state.cursor_pos);
if (current_line > 0) {
int current_column = state.cursor_pos - state.line_starts[current_line];
state.cursor_pos =
std::min(state.line_starts[current_line - 1] + current_column,
state.line_starts[current_line] - 1);
state.scroll_pos.y = std::max(0.0f, state.scroll_pos.y - line_height);
}
}
void MoveCursorDown(const std::string &text, EditorState &state,
float line_height, float window_height) {
int current_line = GetLineFromPos(state.line_starts, state.cursor_pos);
if (current_line < state.line_starts.size() - 1) {
int current_column = state.cursor_pos - state.line_starts[current_line];
state.cursor_pos =
std::min(state.line_starts[current_line + 1] + current_column,
static_cast<int>(text.size()));
state.scroll_pos.y = state.scroll_pos.y + line_height;
}
}
void MoveCursorVertically(std::string &text, EditorState &state,
int line_delta) {
int current_line = GetLineFromPos(state.line_starts, state.cursor_pos);
int target_line =
std::max(0, std::min(static_cast<int>(state.line_starts.size()) - 1,
current_line + line_delta));
// Calculate the current column (horizontal position)
int current_column = state.cursor_pos - state.line_starts[current_line];
// Set the new cursor position
int new_line_start = state.line_starts[target_line];
int new_line_end = (target_line + 1 < state.line_starts.size())
? state.line_starts[target_line + 1] - 1
: text.size();
// Try to maintain the same column, but don't go past the end of the new line
state.cursor_pos = std::min(new_line_start + current_column, new_line_end);
}
void HandleCursorMovement(const std::string &text, EditorState &state,
const ImVec2 &text_pos, float line_height,
float window_height, float window_width) {
float visible_start_y = ImGui::GetScrollY();
float visible_end_y = visible_start_y + window_height;
float visible_start_x = ImGui::GetScrollX();
float visible_end_x = visible_start_x + window_width;
bool shift_pressed = ImGui::GetIO().KeyShift;
state.current_line = GetLineFromPos(state.line_starts, state.cursor_pos);
// Start a new selection only if Shift is pressed and we're not already
// selecting
if (shift_pressed && !state.is_selecting) {
state.is_selecting = true;
state.selection_start = state.cursor_pos;
}
// Clear selection only if a movement key is pressed without Shift
if (!shift_pressed && (ImGui::IsKeyPressed(ImGuiKey_UpArrow) ||
ImGui::IsKeyPressed(ImGuiKey_DownArrow) ||
ImGui::IsKeyPressed(ImGuiKey_LeftArrow) ||
ImGui::IsKeyPressed(ImGuiKey_RightArrow))) {
state.is_selecting = false;
state.selection_start = state.selection_end = state.cursor_pos;
}
if (ImGui::IsKeyPressed(ImGuiKey_UpArrow)) {
MoveCursorUp(text, state, line_height, window_height);
}
if (ImGui::IsKeyPressed(ImGuiKey_DownArrow)) {
MoveCursorDown(text, state, line_height, window_height);
}
if (ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) {
MoveCursorLeft(state);
}
if (ImGui::IsKeyPressed(ImGuiKey_RightArrow)) {
MoveCursorRight(text, state);
}
if (state.is_selecting) {
state.selection_end = state.cursor_pos;
}
// Ensure cursor stays in view after movement
float cursor_y =
text_pos.y +
(GetLineFromPos(state.line_starts, state.cursor_pos) * line_height);
float cursor_x = CalculateCursorXPosition(text_pos, text, state.cursor_pos);
if (cursor_y < visible_start_y) {
state.scroll_pos.y = cursor_y - text_pos.y;
} else if (cursor_y + line_height > visible_end_y) {
state.scroll_pos.y = cursor_y + line_height - window_height;
}
if (cursor_x < visible_start_x) {
state.scroll_x = cursor_x - text_pos.x;
} else if (cursor_x > visible_end_x) {
state.scroll_x = cursor_x - window_width + ImGui::GetFontSize();
}
}
// Text input handling
void HandleCharacterInput(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed,
int &input_start, int &input_end) {
ImGuiIO &io = ImGui::GetIO();
std::string input;
input.reserve(io.InputQueueCharacters.Size);
for (int n = 0; n < io.InputQueueCharacters.Size; n++) {
char c = static_cast<char>(io.InputQueueCharacters[n]);
if (c != 0 && c >= 32) {
input += c;
}
}
if (!input.empty()) {
// Clear any existing selection
if (state.selection_start != state.selection_end) {
int start = GetSelectionStart(state);
int end = GetSelectionEnd(state);
if (start < 0 || end > static_cast<int>(text.size()) || start > end) {
std::cerr << "Error: Invalid selection range in HandleCharacterInput"
<< std::endl;
return;
}
text.erase(start, end - start);
colors.erase(colors.begin() + start, colors.begin() + end);
state.cursor_pos = start;
}
// Insert new text
if (state.cursor_pos < 0 ||
state.cursor_pos > static_cast<int>(text.size())) {
std::cerr << "Error: Invalid cursor position in HandleCharacterInput"
<< std::endl;
return;
}
text.insert(state.cursor_pos, input);
colors.insert(colors.begin() + state.cursor_pos, input.size(),
ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
state.cursor_pos += input.size();
// Reset selection state
state.selection_start = state.selection_end = state.cursor_pos;
state.is_selecting = false;
text_changed = true;
input_end = state.cursor_pos;
}
}
void HandleEnterKey(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed, int &input_end) {
if (gLineJump.hasJustJumped()) {
return;
}
if (ImGui::IsKeyPressed(ImGuiKey_Enter)) {
// Insert the newline character
text.insert(state.cursor_pos, 1, '\n');
// Safely insert the color
if (state.cursor_pos <= colors.size()) {
colors.insert(colors.begin() + state.cursor_pos, 1,
ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
} else {
std::cerr << "Warning: Invalid cursor position for colors" << std::endl;
colors.push_back(ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
}
state.cursor_pos++;
state.selection_start = state.selection_end = state.cursor_pos;
state.is_selecting = false;
text_changed = true;
input_end = state.cursor_pos;
}
}
void HandleDeleteKey(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed, int &input_end) {
if (ImGui::IsKeyPressed(ImGuiKey_Delete)) {
if (state.selection_start != state.selection_end) {
// There's a selection, delete it
int start = GetSelectionStart(state);
int end = GetSelectionEnd(state);
text.erase(start, end - start);
colors.erase(colors.begin() + start, colors.begin() + end - 1);
state.cursor_pos = start;
text_changed = true;
input_end = start;
} else if (state.cursor_pos < text.size()) {
// No selection, delete the character at cursor position
text.erase(state.cursor_pos, 1);
colors.erase(colors.begin() + state.cursor_pos - 1);
text_changed = true;
input_end = state.cursor_pos + 1;
}
// Clear selection after deletion
state.selection_start = state.selection_end = state.cursor_pos;
state.is_selecting = false;
}
}
void HandleBackspaceKey(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed,
int &input_start) {
if (ImGui::IsKeyPressed(ImGuiKey_Backspace)) {
if (state.selection_start != state.selection_end) {
// There's a selection, delete it
int start = GetSelectionStart(state);
int end = GetSelectionEnd(state);
text.erase(start, end - start);
colors.erase(colors.begin() + start, colors.begin() + end);
state.cursor_pos = start;
text_changed = true;
input_start = start;
} else if (state.cursor_pos > 0) {
// No selection, delete the character before cursor position
text.erase(state.cursor_pos - 1, 1);
colors.erase(colors.begin() + state.cursor_pos - 1);
state.cursor_pos--;
text_changed = true;
input_start = state.cursor_pos;
}
// Clear selection after deletion
state.selection_start = state.selection_end = state.cursor_pos;
state.is_selecting = false;
}
}
void HandleTabKey(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed, int &input_end) {
if (ImGui::IsKeyPressed(ImGuiKey_Tab)) {
if (state.is_selecting) {
// Handle multi-line indentation
int start = std::min(state.selection_start, state.selection_end);
int end = std::max(state.selection_start, state.selection_end);
// Find the start of the first line
int firstLineStart = start;
while (firstLineStart > 0 && text[firstLineStart - 1] != '\n') {
firstLineStart--;
}
// Find the end of the last line
int lastLineEnd = end;
while (lastLineEnd < text.length() && text[lastLineEnd] != '\n') {
lastLineEnd++;
}
int tabsInserted = 0;
int lineStart = firstLineStart;
while (lineStart < lastLineEnd) {
// Insert tab at the beginning of the line
text.insert(lineStart, 1, '\t');
colors.insert(colors.begin() + lineStart, 1,
ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
tabsInserted++;
// Move to the next line
lineStart = text.find('\n', lineStart) + 1;
if (lineStart == 0)
break; // If we've reached the end of the text
}
// Adjust cursor and selection positions
state.cursor_pos += (state.cursor_pos >= start) ? tabsInserted : 0;
state.selection_start +=
(state.selection_start > start) ? tabsInserted : 0;
state.selection_end += tabsInserted;
input_end = lastLineEnd + tabsInserted;
} else {
// Insert a single tab character at cursor position
text.insert(state.cursor_pos, 1, '\t');
colors.insert(colors.begin() + state.cursor_pos, 1,
ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
state.cursor_pos++;
state.selection_start = state.selection_end = state.cursor_pos;
input_end = state.cursor_pos;
}
// Mark text as changed and update
text_changed = true;
UpdateLineStarts(text, state.line_starts);
gFileExplorer.setUnsavedChanges(true);
// Trigger syntax highlighting for the affected area
gEditor.highlightContent(
text, colors, std::min(state.selection_start, state.selection_end),
std::max(state.selection_end, input_end));
}
}
void Editor::moveWordForward(const std::string &text, EditorState &state) {
size_t pos = state.cursor_pos;
size_t len = text.length();
// Skip current word
while (pos < len && std::isalnum(text[pos]))
pos++;
// Skip spaces
while (pos < len && std::isspace(text[pos]))
pos++;
// Find start of next word
while (pos < len && !std::isalnum(text[pos]) && !std::isspace(text[pos]))
pos++;
// If we've reached the end, wrap around to the beginning
if (pos == len)
pos = 0;
state.cursor_pos = pos;
state.selection_start = state.selection_end = pos;
}
void Editor::moveWordBackward(const std::string &text, EditorState &state) {
size_t pos = state.cursor_pos;
// If at the beginning, wrap around to the end
if (pos == 0)
pos = text.length();
// Move back to the start of the current word
while (pos > 0 && !std::isalnum(text[pos - 1]))
pos--;
while (pos > 0 && std::isalnum(text[pos - 1]))
pos--;
state.cursor_pos = pos;
state.selection_start = state.selection_end = pos;
}
void Editor::removeIndentation(std::string &text, EditorState &state) {
int start, end;
if (state.is_selecting) {
start = std::min(state.selection_start, state.selection_end);
end = std::max(state.selection_start, state.selection_end);
} else {
// If no selection, work on the current line
start = end = state.cursor_pos;
}
// Find the start of the first line
int firstLineStart = start;
while (firstLineStart > 0 && text[firstLineStart - 1] != '\n') {
firstLineStart--;
}
// Find the end of the last line
int lastLineEnd = end;
while (lastLineEnd < text.length() && text[lastLineEnd] != '\n') {
lastLineEnd++;
}
int totalSpacesRemoved = 0;
std::string newText;
newText.reserve(text.length());
// Copy text before the affected lines
newText.append(text.substr(0, firstLineStart));
// Process each line
size_t lineStart = firstLineStart;
while (lineStart <= lastLineEnd) {
// Check for spaces or tab at the beginning of the line
int spacesToRemove = 0;
if (lineStart + 4 <= text.length() && text.substr(lineStart, 4) == " ") {
spacesToRemove = 4;
} else if (lineStart < text.length() && text[lineStart] == '\t') {
spacesToRemove = 1;
}
// Append the line without leading indentation
size_t lineEnd = text.find('\n', lineStart);
if (lineEnd == std::string::npos || lineEnd > lastLineEnd)
lineEnd = lastLineEnd;
newText.append(text.substr(lineStart + spacesToRemove,
lineEnd - lineStart - spacesToRemove));
if (lineEnd < lastLineEnd)
newText.push_back('\n');
totalSpacesRemoved += spacesToRemove;
lineStart = lineEnd + 1;
}
// Copy text after the affected lines
newText.append(text.substr(lastLineEnd));
// Update text and adjust cursor and selection
text = std::move(newText);
state.cursor_pos =
std::max(state.cursor_pos - totalSpacesRemoved, firstLineStart);
if (state.is_selecting) {
state.selection_start =
std::max(state.selection_start - totalSpacesRemoved, firstLineStart);
state.selection_end =
std::max(state.selection_end - totalSpacesRemoved, firstLineStart);
} else {
state.selection_start = state.selection_end = state.cursor_pos;
}
// Update colors vector
auto &colors = gFileExplorer.getFileColors();
colors.erase(colors.begin() + firstLineStart, colors.begin() + lastLineEnd);
colors.insert(colors.begin() + firstLineStart,
lastLineEnd - firstLineStart - totalSpacesRemoved,
ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); // Insert default color
// Update line starts
UpdateLineStarts(text, state.line_starts);
// Mark text as changed
gFileExplorer.setUnsavedChanges(true);
// Trigger syntax highlighting for the affected area
gEditor.highlightContent(text, colors, firstLineStart,
lastLineEnd - totalSpacesRemoved);
}
void HandleTextInput(std::string &text, std::vector<ImVec4> &colors,
EditorState &state, bool &text_changed) {
int input_start = state.cursor_pos;
int input_end = state.cursor_pos;
// Handle selection deletion only for Enter key
if (state.selection_start != state.selection_end &&
ImGui::IsKeyPressed(ImGuiKey_Enter)) {
int start = GetSelectionStart(state);
int end = GetSelectionEnd(state);
text.erase(start, end - start);
colors.erase(colors.begin() + start, colors.begin() + end);
state.cursor_pos = start;
state.selection_start = state.selection_end = start;
text_changed = true;
input_start = input_end = start;
}
HandleCharacterInput(text, colors, state, text_changed, input_start,
input_end);
HandleEnterKey(text, colors, state, text_changed, input_end);
HandleBackspaceKey(text, colors, state, text_changed, input_start);
HandleDeleteKey(text, colors, state, text_changed, input_end);
HandleTabKey(text, colors, state, text_changed, input_end);
if (text_changed) {
// Get the start of the line where the change began
int line_start =
state.line_starts[GetLineFromPos(state.line_starts, input_start)];
// Get the end of the line where the change ended (or the end of the text if
// it's the last line)
int line_end =
input_end < text.size()
? state.line_starts[GetLineFromPos(state.line_starts, input_end)]
: text.size();
// Update syntax highlighting only for the affected lines
gEditor.highlightContent(text, colors, line_start, line_end);
// Update line starts
UpdateLineStarts(text, state.line_starts);
// Add undo state with change range
gFileExplorer.addUndoState(line_start, line_end);
}
}
// Rendering functions
void RenderTextWithSelection(ImDrawList *drawList, const ImVec2 &pos,
const std::string &text,
const std::vector<ImVec4> &colors,
const EditorState &state, float line_height) {
ImVec2 text_pos = pos;
int selection_start = GetSelectionStart(state);
int selection_end = GetSelectionEnd(state);
const int MAX_HIGHLIGHT_CHARS = 100000; // Adjust this value as needed
// Calculate visible range
float scroll_y = ImGui::GetScrollY();
float window_height = ImGui::GetWindowHeight();
int start_line = static_cast<int>(scroll_y / line_height);
int end_line = start_line + static_cast<int>(window_height / line_height) + 1;
int current_line = 0;
for (size_t i = 0; i < text.size(); i++) {
if (i >= colors.size()) {
std::cerr << "Error: Color index out of bounds in RenderTextWithSelection"
<< std::endl;
break;
}
if (text[i] == '\n') {
current_line++;
if (current_line > end_line)
break; // Stop if we've passed the visible area
text_pos.x = pos.x;
text_pos.y += line_height;
} else if (current_line >= start_line && current_line <= end_line) {
// Only render if we're in the visible range
bool should_highlight =
(i >= selection_start && i < selection_end &&
(selection_end - selection_start) <= MAX_HIGHLIGHT_CHARS);
if (should_highlight) {
ImVec2 sel_start = text_pos;
ImVec2 sel_end =
ImVec2(text_pos.x + ImGui::CalcTextSize(&text[i], &text[i + 1]).x,
text_pos.y + line_height);
drawList->AddRectFilled(sel_start, sel_end,
ImGui::ColorConvertFloat4ToU32(ImVec4(1.0f, 0.1f, 0.7f, 0.3f))); // Pink with 30% alpha
}
char buf[2] = {text[i], '\0'};
ImU32 color = ImGui::ColorConvertFloat4ToU32(colors[i]);
drawList->AddText(text_pos, color, buf);
text_pos.x += ImGui::CalcTextSize(buf).x;
}
}
}
void RenderCursor(ImDrawList *draw_list, const ImVec2 &cursor_screen_pos,
float line_height, float blink_time) {
float blink_alpha =
(sinf(blink_time * 4.0f) + 1.0f) * 0.5f; // Blink frequency
ImU32 cursor_color;
bool rainbow_mode = gSettings.getRainbowMode(); // Get setting here
if (rainbow_mode) {
ImVec4 rainbow = GetRainbowColor(blink_time * 2.0f); // Rainbow frequency
cursor_color = ImGui::ColorConvertFloat4ToU32(rainbow);
} else {
cursor_color = IM_COL32(255, 255, 255, (int)(blink_alpha * 255));
}
draw_list->AddLine(
cursor_screen_pos,
ImVec2(cursor_screen_pos.x, cursor_screen_pos.y + line_height),
cursor_color);
}
int GetCharIndexFromCoords(const std::string &text, const ImVec2 &click_pos,
const ImVec2 &text_start_pos,
const std::vector<int> &line_starts,
float line_height) {
int clicked_line =
static_cast<int>((click_pos.y - text_start_pos.y) / line_height);
clicked_line = std::max(
0, std::min(clicked_line, static_cast<int>(line_starts.size()) - 1));
int line_start = line_starts[clicked_line];
int line_end = (clicked_line + 1 < line_starts.size())
? line_starts[clicked_line + 1] - 1
: text.size();
float x = text_start_pos.x;
for (int i = line_start; i < line_end; ++i) {
char buf[2] = {text[i], '\0'};
float char_width = ImGui::CalcTextSize(buf).x;
if (x + char_width / 2 > click_pos.x) {
return i;
}
x += char_width;
}
return line_end;
}
void RenderLineNumbers(const ImVec2 &pos, float line_number_width,
float line_height, int num_lines, float scroll_y,
float window_height, const EditorState &editor_state,
float blink_time) {
static char line_number_buffer[16];
ImDrawList *draw_list = ImGui::GetWindowDrawList();
const ImU32 default_line_number_color = IM_COL32(128, 128, 128, 255);
const ImU32 current_line_color = IM_COL32(255, 255, 255, 255);
const ImU32 selected_line_color = IM_COL32(0, 40, 255, 200); // Neon pink color
int start_line = static_cast<int>(scroll_y / line_height);
int end_line =
std::min(num_lines,
static_cast<int>((scroll_y + window_height) / line_height) + 1);
// Pre-calculate rainbow color
ImU32 rainbow_color = current_line_color;
bool rainbow_mode = gSettings.getRainbowMode(); // Get setting here
if (rainbow_mode) {
// Update color less frequently
static float last_update_time = 0.0f;
static ImU32 last_rainbow_color = current_line_color;
if (blink_time - last_update_time > 0.05f) { // Update every 50ms
ImVec4 rainbow = GetRainbowColor(blink_time * 2.0f);
last_rainbow_color = ImGui::ColorConvertFloat4ToU32(rainbow);
last_update_time = blink_time;
}
rainbow_color = last_rainbow_color;
}
// Determine the selected lines, accounting for selection direction
int selection_start =
std::min(editor_state.selection_start, editor_state.selection_end);
int selection_end =
std::max(editor_state.selection_start, editor_state.selection_end);
int selection_start_line =
std::lower_bound(editor_state.line_starts.begin(),
editor_state.line_starts.end(), selection_start) -
editor_state.line_starts.begin();
int selection_end_line =
std::lower_bound(editor_state.line_starts.begin(),
editor_state.line_starts.end(), selection_end) -
editor_state.line_starts.begin();
for (int i = start_line; i < end_line; i++) {
float y_pos = pos.y + (i * line_height) - scroll_y;
snprintf(line_number_buffer, sizeof(line_number_buffer), "%d", i + 1);
ImU32 line_number_color;
if (i >= selection_start_line && i < selection_end_line &&
editor_state.is_selecting) {
line_number_color = selected_line_color; // Use neon pink for selected lines
} else if (i == editor_state.current_line) {
line_number_color = rainbow_mode ? rainbow_color : current_line_color;
} else {
line_number_color = default_line_number_color;
}
// Calculate the position for right-aligned text
float text_width = ImGui::CalcTextSize(line_number_buffer).x;
float x_pos = pos.x + line_number_width - text_width -
8.0f; // 4.0f is a small right margin
draw_list->AddText(ImVec2(x_pos, y_pos), line_number_color,
line_number_buffer);
}
}
float CalculateTextWidth(const std::string &text,
const std::vector<int> &line_starts) {
float max_width = 0.0f;
for (size_t i = 0; i < line_starts.size(); ++i) {
int start = line_starts[i];
int end =
(i + 1 < line_starts.size()) ? line_starts[i + 1] - 1 : text.size();
float line_width =
ImGui::CalcTextSize(text.c_str() + start, text.c_str() + end).x;
max_width = std::max(max_width, line_width);
}
return max_width;
}
void HandleEditorInput(std::string &text, EditorState &state,
const ImVec2 &text_start_pos, float line_height,
bool &text_changed, std::vector<ImVec4> &colors,
CursorVisibility &ensure_cursor_visible) {
bool ctrl_pressed = ImGui::GetIO().KeyCtrl;
bool shift_pressed = ImGui::GetIO().KeyShift;
// bookmarks
gBookmarks.handleBookmarkInput(gFileExplorer, state);
if (ImGui::IsWindowFocused() && !state.blockInput) {
// remove indent shift tab
if (shift_pressed &&
ImGui::IsKeyPressed(ImGuiKey_Tab, false)) { // false to not repeat
gEditor.removeIndentation(text, state);
text_changed = true;
ensure_cursor_visible.horizontal = true;
ensure_cursor_visible.vertical = true;
ImGui::SetKeyboardFocusHere(-1); // Prevent default tab behavior
return; // Exit the function to prevent further processing
}
if (ctrl_pressed) {
if (ImGui::IsKeyPressed(ImGuiKey_Equal)) { // '+' key
float currentSize = gSettings.getFontSize();
gSettings.setFontSize(currentSize + 2.0f);
ensure_cursor_visible.vertical = true;
ensure_cursor_visible.horizontal = true;
std::cout << "Cmd++: Font size increased to " << gSettings.getFontSize()
<< std::endl;
} else if (ImGui::IsKeyPressed(ImGuiKey_Minus)) { // '-' key
float currentSize = gSettings.getFontSize();
gSettings.setFontSize(
std::max(currentSize - 2.0f,
8.0f)); // Prevent font size from becoming too small
ensure_cursor_visible.vertical = true;
ensure_cursor_visible.horizontal = true;
std::cout << "Cmd+-: Font size decreased to " << gSettings.getFontSize()
<< std::endl;
}
}
if (ctrl_pressed) {
// select all cmd a
if (ImGui::IsKeyPressed(ImGuiKey_A)) {
SelectAllText(state, text);
ensure_cursor_visible.vertical = true;
ensure_cursor_visible.horizontal = true;
std::cout << "Ctrl+A: Selected all text" << std::endl;
}
// cmd z undo
if (ImGui::IsKeyPressed(ImGuiKey_Z)) {
std::cout << "Z key pressed. Ctrl: " << ctrl_pressed
<< ", Shift: " << shift_pressed << std::endl;
// Store the current cursor position and line
int oldCursorPos = state.cursor_pos;
int oldLine = GetLineFromPos(state.line_starts, oldCursorPos);
int oldColumn = oldCursorPos - state.line_starts[oldLine];
if (shift_pressed) {
std::cout << "Attempting Redo" << std::endl;
gFileExplorer.handleRedo();
} else {
std::cout << "Attempting Undo" << std::endl;
gFileExplorer.handleUndo();
}
// Update text and colors
text = gFileExplorer.getFileContent();
colors = gFileExplorer.getFileColors();
// Update line starts
UpdateLineStarts(text, state.line_starts);
// Recalculate cursor position
int newLine =
std::min(oldLine, static_cast<int>(state.line_starts.size()) - 1);
int lineStart = state.line_starts[newLine];
int lineEnd = (newLine + 1 < state.line_starts.size())
? state.line_starts[newLine + 1] - 1
: text.size();
int lineLength = lineEnd - lineStart;
// Try to maintain the same column position
state.cursor_pos = lineStart + std::min(oldColumn, lineLength);
state.selection_start = state.selection_end = state.cursor_pos;
text_changed = true;
ensure_cursor_visible.vertical = true;
ensure_cursor_visible.horizontal = true;
gFileExplorer.currentUndoManager
->printStacks(); // Print stack sizes for debugging
}
// cmd w next word
if (ImGui::IsKeyPressed(ImGuiKey_W)) {
if (shift_pressed) {
gEditor.moveWordBackward(text, state);
} else {
gEditor.moveWordForward(text, state);
}