forked from goossens/ImGuiColorTextEdit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextEditor.cpp
8214 lines (7020 loc) · 236 KB
/
TextEditor.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
// TextEditor - A syntax highlighting text editor for ImGui
// Copyright (c) 2024-2025 Johan A. Goossens. All rights reserved.
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
//
// Include files
//
#include <cmath>
#include <limits>
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui.h"
#include "TextEditor.h"
//
// TextEditor::setText
//
void TextEditor::setText(const std::string_view &text) {
// load text into document and reset subsystems
document.setText(text);
transactions.reset();
bracketeer.reset();
cursors.clearAll();
makeCursorVisible();
}
//
// TextEditor::render
//
void TextEditor::render(const char* title, const ImVec2& size, bool border) {
// update color palette (if required)
if (paletteAlpha != ImGui::GetStyle().Alpha) {
updatePalette();
}
// get font information and determine horizontal offsets for line numbers, decorations and text
font = ImGui::GetFont();
fontSize = ImGui::GetFontSize();
glyphSize = ImVec2(font->CalcTextSizeA(fontSize, FLT_MAX, -1.0f, "#").x, ImGui::GetTextLineHeightWithSpacing() * lineSpacing);
lineNumberLeftOffset = leftMargin * glyphSize.x;
if (showLineNumbers) {
int digits = static_cast<int>(std::log10(document.lineCount() + 1) + 1.0f);
lineNumberRightOffset = lineNumberLeftOffset + digits * glyphSize.x;
decorationOffset = lineNumberRightOffset + decorationMargin * glyphSize.x;
} else {
lineNumberRightOffset = lineNumberLeftOffset;
decorationOffset = lineNumberLeftOffset;
}
if (decoratorWidth > 0.0f) {
textOffset = decorationOffset + decoratorWidth + decorationMargin * glyphSize.x;
} else {
textOffset = decorationOffset + textMargin * glyphSize.x;
}
// get current position and total/visible editor size
auto pos = ImGui::GetCursorPos();
auto totalSize = ImVec2(textOffset + document.getMaxColumn() * glyphSize.x + cursorWidth, document.size() * glyphSize.y);
auto visibleSize = ImGui::GetContentRegionAvail();
if (size.x > 0.0f) {
visibleSize.x = std::min(visibleSize.x, size.x);
} else if (size.x < 0.0f) {
visibleSize.x = std::max(visibleSize.x + size.x, 0.0f);
}
if (size.y > 0.0f) {
visibleSize.y = std::min(visibleSize.y, size.y);
} else if (size.y < 0.0f) {
visibleSize.y = std::max(visibleSize.y + size.y, 0.0f);
}
// see if we have scrollbars
float scrollbarSize = ImGui::GetStyle().ScrollbarSize;
float verticalScrollBarSize = (totalSize.y > visibleSize.y) ? scrollbarSize : 0.0f;
float horizontalScrollBarSize = (totalSize.x > visibleSize.x) ? scrollbarSize : 0.0f;
// determine visible lines and columns
visibleWidth = visibleSize.x - textOffset - verticalScrollBarSize;
visibleColumns = std::max(static_cast<int>(std::ceil(visibleWidth / glyphSize.x)), 0);
visibleHeight = visibleSize.y - horizontalScrollBarSize;
visibleLines = std::max(static_cast<int>(std::ceil(visibleHeight / glyphSize.y)), 0);
// determine scrolling requirements
float scrollX = -1.0f;
float scrollY = -1.0f;
// ensure cursor is visible (if requested)
if (ensureCursorIsVisible) {
auto cursor = cursors.getCurrent().getInteractiveEnd();
if (cursor.line <= firstVisibleLine + 1) {
scrollY = std::max(0.0f, (cursor.line - 2.0f) * glyphSize.y);
} else if (cursor.line >= lastVisibleLine - 1) {
scrollY = std::max(0.0f, (cursor.line + 2.0f) * glyphSize.y - visibleHeight);
}
if (cursor.column <= firstVisibleColumn + 1) {
scrollX = std::max(0.0f, (cursor.column - 2.0f) * glyphSize.x);
} else if (cursor.column >= lastVisibleColumn - 1) {
scrollX = std::max(0.0f, (cursor.column + 2.0f) * glyphSize.x - visibleWidth);
}
ensureCursorIsVisible = false;
}
// scroll to specified line (if required)
if (scrollToLineNumber >= 0) {
scrollToLineNumber = std::min(scrollToLineNumber, document.lineCount());
scrollX = 0.0f;
switch (scrollToAlignment) {
case Scroll::alignTop:
scrollY = std::max(0.0f, static_cast<float>(scrollToLineNumber) * glyphSize.y);
break;
case Scroll::alignMiddle:
scrollY = std::max(0.0f, static_cast<float>(scrollToLineNumber - visibleLines / 2) * glyphSize.y);
break;
case Scroll::alignBottom:
scrollY = std::max(0.0f, static_cast<float>(scrollToLineNumber - (visibleLines - 1)) * glyphSize.y);
break;
}
scrollToLineNumber = -1;
}
// set style
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(palette.get(Color::background)));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));
// ensure editor has focus (if required)
if (focusOnEditor) {
ImGui::SetNextWindowFocus();
focusOnEditor = false;
}
// set scroll (if required)
if (scrollX >= 0.0f || scrollY >= 0.0f) {
ImGui::SetNextWindowScroll(ImVec2(scrollX, scrollY));
}
// start a new child window
// this must be done before we handle keyboard and mouse interactions to ensure correct ImGui context
ImGui::SetNextWindowContentSize(totalSize);
ImGui::BeginChild(title, size, border, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoNavInputs);
// handle keyboard and mouse inputs
handleKeyboardInputs();
handleMouseInteractions();
// ensure cursors are up to date (sorted and merged if required)
if (cursors.anyHasUpdate()) {
cursors.update();
}
// recolorize entire document and reset brackets (if required)
if (showMatchingBracketsChanged || languageChanged) {
colorizer.updateEntireDocument(document, language);
bracketeer.reset();
}
// was document changed during this frame?
auto documentChanged = document.isUpdated();
if (language) {
if (documentChanged) {
// recolorize updated lines
colorizer.updateChangedLines(document, language);
}
if (showMatchingBrackets && (documentChanged || showMatchingBracketsChanged || languageChanged)) {
// rebuild bracket list
bracketeer.update(document);
}
}
// reset changed states
showMatchingBracketsChanged = false;
languageChanged = false;
// determine view parameters
firstVisibleColumn = std::max(static_cast<int>(std::floor(ImGui::GetScrollX() / glyphSize.x)), 0);
lastVisibleColumn = static_cast<int>(std::floor((ImGui::GetScrollX() + visibleWidth) / glyphSize.x));
firstVisibleLine = std::max(static_cast<int>(std::floor(ImGui::GetScrollY() / glyphSize.y)), 0);
lastVisibleLine = std::min(static_cast<int>(std::floor((ImGui::GetScrollY() + visibleHeight) / glyphSize.y)), document.lineCount() - 1);
// render editor parts
renderSelections();
renderMarkers();
renderMatchingBrackets();
renderText();
renderCursors();
renderMargin();
renderLineNumbers();
renderDecorations();
if (ImGui::BeginPopup("LineNumberContextMenu")) {
lineNumberContextMenuCallback(contextMenuLine);
ImGui::EndPopup();
}
if (ImGui::BeginPopup("TextContextMenu")) {
textContextMenuCallback(contextMenuLine, contextMenuColumn);
ImGui::EndPopup();
}
ImGui::EndChild();
ImGui::PopStyleVar();
ImGui::PopStyleColor();
// render find/replace popup
renderFindReplace(pos, visibleSize);
}
//
// TextEditor::renderSelections
//
void TextEditor::renderSelections() {
auto drawList = ImGui::GetWindowDrawList();
ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos();
// draw background for selections
for (auto& cursor : cursors) {
if (cursor.hasSelection()) {
auto start = cursor.getSelectionStart();
auto end = cursor.getSelectionEnd();
if (end.line >= firstVisibleLine && start.line <= lastVisibleLine) {
auto first = std::max(start.line, firstVisibleLine);
auto last = std::min(end.line, lastVisibleLine);
for (auto line = first; line <= last; line++) {
auto x = cursorScreenPos.x + textOffset;
auto left = x + (line == first ? start.column : 0) * glyphSize.x;
auto right = x + (line == last ? end.column : document[line].maxColumn) * glyphSize.x;
auto y = cursorScreenPos.y + line * glyphSize.y;
drawList->AddRectFilled(ImVec2(left, y), ImVec2(right, y + glyphSize.y), palette.get(Color::selection));
}
}
}
}
}
//
// TextEditor::renderMarkers
//
void TextEditor::renderMarkers() {
if (markers.size()) {
auto drawList = ImGui::GetWindowDrawList();
ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos();
for (int line = firstVisibleLine; line <= lastVisibleLine; line++) {
if (document[line].marker) {
auto& marker = markers[document[line].marker - 1];
auto y = cursorScreenPos.y + line * glyphSize.y;
if (((marker.lineNumberColor >> IM_COL32_A_SHIFT) & 0xFF) != 0) {
auto left = cursorScreenPos.x + lineNumberLeftOffset;
auto right = cursorScreenPos.x + lineNumberRightOffset;
auto start = ImVec2(left, y);
auto end = ImVec2(right, y + glyphSize.y);
drawList->AddRectFilled(start, end, marker.lineNumberColor);
if (marker.lineNumberTooltip.size() && ImGui::IsMouseHoveringRect(start, end)) {
ImGui::PushStyleColor(ImGuiCol_PopupBg, marker.lineNumberColor);
ImGui::BeginTooltip();
ImGui::TextUnformatted(marker.lineNumberTooltip.c_str());
ImGui::EndTooltip();
ImGui::PopStyleColor();
}
}
if (((marker.textColor >> IM_COL32_A_SHIFT) & 0xFF) != 0) {
auto left = cursorScreenPos.x + textOffset;
auto right = left + lastVisibleColumn * glyphSize.x;
auto start = ImVec2(left, y);
auto end = ImVec2(right, y + glyphSize.y);
drawList->AddRectFilled(start, end, marker.textColor);
if (marker.textTooltip.size() && ImGui::IsMouseHoveringRect(start, end)) {
ImGui::PushStyleColor(ImGuiCol_PopupBg, marker.textColor);
ImGui::BeginTooltip();
ImGui::TextUnformatted(marker.textTooltip.c_str());
ImGui::EndTooltip();
ImGui::PopStyleColor();
}
}
}
}
}
}
//
// TextEditor::renderMatchingBrackets
//
void TextEditor::renderMatchingBrackets() {
if (showMatchingBrackets) {
if (bracketeer.size()) {
auto drawList = ImGui::GetWindowDrawList();
ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos();
// render bracket pair lines
for (auto& bracket : bracketeer) {
if ((bracket.end.line - bracket.start.line) > 1 &&
bracket.start.line <= lastVisibleLine &&
bracket.end.line > firstVisibleLine) {
auto lineX = cursorScreenPos.x + textOffset + std::min(bracket.start.column, bracket.end.column) * glyphSize.x;
auto startY = cursorScreenPos.y + (bracket.start.line + 1) * glyphSize.y;
auto endY = cursorScreenPos.y + bracket.end.line * glyphSize.y;
drawList->AddLine(ImVec2(lineX, startY), ImVec2(lineX, endY), palette.get(Color::whitespace), 1.0f);
}
}
// render active bracket pair
auto active = bracketeer.getEnclosingBrackets(cursors.getMain().getInteractiveEnd());
if (active != bracketeer.end() &&
active->start.line <= lastVisibleLine &&
active->end.line > firstVisibleLine) {
auto x1 = cursorScreenPos.x + textOffset + active->start.column * glyphSize.x;
auto y1 = cursorScreenPos.y + active->start.line * glyphSize.y;
drawList->AddRectFilled(ImVec2(x1, y1), ImVec2(x1 + glyphSize.x, y1 + glyphSize.y), palette.get(Color::matchingBracketBackground));
auto x2 = cursorScreenPos.x + textOffset + active->end.column * glyphSize.x;
auto y2 = cursorScreenPos.y + active->end.line * glyphSize.y;
drawList->AddRectFilled(ImVec2(x2, y2), ImVec2(x2 + glyphSize.x, y2 + glyphSize.y), palette.get(Color::matchingBracketBackground));
if (active->end.line - active->start.line > 1) {
auto lineX = std::min(x1, x2);
drawList->AddLine(ImVec2(lineX, y1 + glyphSize.y), ImVec2(lineX, y2), palette.get(Color::matchingBracketActive), 1.0f);
}
}
}
}
}
//
// TextEditor::renderText
//
void TextEditor::renderText() {
auto drawList = ImGui::GetWindowDrawList();
ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos();
ImVec2 lineScreenPos = cursorScreenPos + ImVec2(textOffset, firstVisibleLine * glyphSize.y);
auto tabSize = document.getTabSize();
auto firstRenderableColumn = (firstVisibleColumn / tabSize) * tabSize;
for (int i = firstVisibleLine; i <= lastVisibleLine; i++) {
auto& line = document[i];
// draw colored glyphs for current line
auto column = firstRenderableColumn;
auto index = document.getIndex(line, column);
auto lineSize = line.size();
while (index < lineSize && column <= lastVisibleColumn) {
auto& glyph = line[index];
auto codepoint = glyph.codepoint;
ImVec2 glyphPos{lineScreenPos.x + column * glyphSize.x, lineScreenPos.y};
if (codepoint == '\t') {
if (showWhitespaces) {
const auto x1 = glyphPos.x + glyphSize.x * 0.3f;
const auto y = glyphPos.y + fontSize * 0.5f;
const auto x2 = glyphPos.x + glyphSize.x;
ImVec2 p1, p2, p3, p4;
p1 = ImVec2(x1, y);
p2 = ImVec2(x2, y);
p3 = ImVec2(x2 - fontSize * 0.16f, y - fontSize * 0.16f);
p4 = ImVec2(x2 - fontSize * 0.16f, y + fontSize * 0.16f);
drawList->AddLine(p1, p2, palette.get(Color::whitespace));
drawList->AddLine(p2, p3, palette.get(Color::whitespace));
drawList->AddLine(p2, p4, palette.get(Color::whitespace));
}
} else if (codepoint == ' ') {
if (showWhitespaces) {
const auto x = glyphPos.x + glyphSize.x * 0.5f;
const auto y = glyphPos.y + fontSize * 0.5f;
drawList->AddCircleFilled(ImVec2(x, y), 1.5f, palette.get(Color::whitespace), 4);
}
} else {
font->RenderChar(drawList, fontSize, glyphPos, palette.get(glyph.color), codepoint);
}
index++;
column += (codepoint == '\t') ? tabSize - (column % tabSize) : 1;
}
lineScreenPos.y += glyphSize.y;
}
}
//
// TextEditor::renderCursors
//
void TextEditor::renderCursors() {
// update cursor animation timer
cursorAnimationTimer = std::fmod(cursorAnimationTimer + ImGui::GetIO().DeltaTime, 1.0f);
if (ImGui::IsWindowFocused()) {
ImVec2 cursorScreenPos = ImGui::GetCursorScreenPos();
if (!ImGui::GetIO().ConfigInputTextCursorBlink || cursorAnimationTimer < 0.5f) {
auto drawList = ImGui::GetWindowDrawList();
for (auto& cursor : cursors) {
auto pos = cursor.getInteractiveEnd();
if (pos.line >= firstVisibleLine && pos.line <= lastVisibleLine) {
auto x = cursorScreenPos.x + textOffset + pos.column * glyphSize.x - 1;
auto y = cursorScreenPos.y + pos.line * glyphSize.y;
drawList->AddRectFilled(ImVec2(x, y), ImVec2(x + cursorWidth, y + glyphSize.y), palette.get(Color::cursor));
}
}
}
// notify OS of text input position for advanced Input Method Editor (IME)
// this is very hackish but required for SDL3 backend as it will not report
// text input events unless we do this
if (!readOnly && ImGui::GetPlatformIO().Platform_SetImeDataFn) {
auto pos = cursors.getCurrent().getInteractiveEnd();
auto x = cursorScreenPos.x + textOffset + pos.column * glyphSize.x - 1;
auto y = cursorScreenPos.y + pos.line * glyphSize.y;
ImGuiPlatformImeData data;
data.WantVisible = true;
data.InputPos = ImVec2(x, y);
data.InputLineHeight = glyphSize.y;
ImGui::GetPlatformIO().Platform_SetImeDataFn(ImGui::GetIO().Ctx, ImGui::GetMainViewport(), &data);
}
}
}
//
// TextEditor::renderMargin
//
void TextEditor::renderMargin() {
if ((decoratorWidth > 0.0f && decoratorCallback) || showLineNumbers) {
// erase background in case we are scrolling horizontally
if (ImGui::GetScrollX() > 0.0f) {
ImGui::GetWindowDrawList()->AddRectFilled(
ImGui::GetWindowPos(),
ImGui::GetWindowPos() + ImVec2(textOffset, ImGui::GetWindowSize().y),
palette.get(Color::background));
}
}
}
//
// TextEditor::renderLineNumbers
//
void TextEditor::renderLineNumbers() {
if (showLineNumbers) {
auto drawList = ImGui::GetWindowDrawList();
auto cursorScreenPos = ImGui::GetCursorScreenPos();
auto curserLine = cursors.getCurrent().getInteractiveEnd().line;
auto position = ImVec2(ImGui::GetWindowPos().x + lineNumberRightOffset, cursorScreenPos.y);
for (int i = firstVisibleLine; i <= lastVisibleLine; i++) {
auto width = static_cast<int>(std::log10(i + 1) + 1.0f) * glyphSize.x;
auto foreground = (i == curserLine) ? Color::currentLineNumber : Color::lineNumber;
auto number = std::to_string(i + 1);
drawList->AddText(position + ImVec2(-width, i * glyphSize.y), palette.get(foreground), number.c_str());
}
}
}
//
// TextEditor::renderDecorations
//
void TextEditor::renderDecorations() {
if (decoratorWidth > 0.0f && decoratorCallback) {
auto cursorScreenPos = ImGui::GetCursorScreenPos();
auto position = ImVec2(ImGui::GetWindowPos().x + decorationOffset, cursorScreenPos.y + glyphSize.y * firstVisibleLine);
Decorator decorator{0, decoratorWidth, glyphSize.y};
for (int i = firstVisibleLine; i <= lastVisibleLine; i++) {
decorator.line = i;
ImGui::SetCursorScreenPos(position);
ImGui::PushID(i);
decoratorCallback(decorator);
ImGui::PopID();
position.y += glyphSize.y;
}
ImGui::SetCursorScreenPos(cursorScreenPos);
}
}
//
// latchButton
//
static bool latchButton(const char* label, bool* value, const ImVec2& size) {
bool changed = false;
ImVec4* colors = ImGui::GetStyle().Colors;
if (*value) {
ImGui::PushStyleColor(ImGuiCol_Button, colors[ImGuiCol_ButtonActive]);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors[ImGuiCol_ButtonActive]);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, colors[ImGuiCol_TableBorderLight]);
} else {
ImGui::PushStyleColor(ImGuiCol_Button, colors[ImGuiCol_TableBorderLight]);
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, colors[ImGuiCol_TableBorderLight]);
ImGui::PushStyleColor(ImGuiCol_ButtonActive, colors[ImGuiCol_ButtonActive]);
}
ImGui::Button(label, size);
if (ImGui::IsItemClicked(ImGuiMouseButton_Left)) {
*value = !*value;
changed = true;
}
ImGui::PopStyleColor(3);
return changed;
}
//
// inputString
//
static bool inputString(const char* label, std::string* value, ImGuiInputTextFlags flags=ImGuiInputTextFlags_None) {
flags |=
ImGuiInputTextFlags_NoUndoRedo |
ImGuiInputTextFlags_CallbackResize;
return ImGui::InputText(label, (char*) value->c_str(), value->capacity() + 1, flags, [](ImGuiInputTextCallbackData* data) {
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) {
std::string* value = (std::string*) data->UserData;
value->resize(data->BufTextLen);
data->Buf = (char*) value->c_str();
}
return 0;
}, value);
}
//
// TextEditor::renderFindReplace
//
void TextEditor::renderFindReplace(ImVec2 pos, ImVec2 contentSize) {
// render find/replace window (if required)
if (findReplaceVisible) {
// save current screen position
auto currentScreenPosition = ImGui::GetCursorScreenPos();
// calculate sizes
auto& style = ImGui::GetStyle();
auto fieldWidth = 250.0f;
auto button1Width = ImGui::CalcTextSize(findButtonLabel.c_str()).x + style.ItemSpacing.x * 2.0f;
auto button2Width = ImGui::CalcTextSize(findAllButtonLabel.c_str()).x + style.ItemSpacing.x * 2.0f;
auto optionWidth = ImGui::CalcTextSize("Aa").x + style.ItemSpacing.x * 2.0f;
if (!readOnly) {
button1Width = std::max(button1Width, ImGui::CalcTextSize(replaceButtonLabel.c_str()).x + style.ItemSpacing.x * 2.0f);
button2Width = std::max(button2Width, ImGui::CalcTextSize(replaceAllButtonLabel.c_str()).x + style.ItemSpacing.x * 2.0f);
}
auto windowHeight =
style.ChildBorderSize * 2.0f +
style.WindowPadding.y * 2.0f +
ImGui::GetFrameHeight() +
(readOnly ? 0.0f : (style.ItemSpacing.y + ImGui::GetFrameHeight()));
auto windowWidth =
style.ChildBorderSize * 2.0f +
style.WindowPadding.x * 2.0f +
fieldWidth + style.ItemSpacing.x +
button1Width + style.ItemSpacing.x +
button2Width + style.ItemSpacing.x +
optionWidth * 3.0f + style.ItemSpacing.x * 2.0f;
// create window
ImGui::SetCursorPos(ImVec2(
pos.x + contentSize.x - windowWidth - style.ScrollbarSize - style.ItemSpacing.x,
pos.y + style.ItemSpacing.y * 2.0f));
ImGui::SetNextWindowBgAlpha(0.6f);
ImGui::BeginChild("find-replace", ImVec2(windowWidth, windowHeight), ImGuiChildFlags_Borders);
ImGui::SetNextItemWidth(fieldWidth);
if (focusOnFind) {
ImGui::SetKeyboardFocusHere();
focusOnFind = false;
}
if (inputString("###find", &findText, ImGuiInputTextFlags_AutoSelectAll)) {
if (findText.size()) {
selectFirstOccurrenceOf(findText, caseSensitiveFind, wholeWordFind);
} else {
cursors.clearAll();
}
}
if (ImGui::IsItemDeactivated() && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))){
focusOnEditor = true;
}
bool disableFindButtons = !findText.size();
if (disableFindButtons) {
ImGui::BeginDisabled();
}
ImGui::SameLine();
if (ImGui::Button(findButtonLabel.c_str(), ImVec2(button1Width, 0.0f))) {
find();
}
ImGui::SameLine();
if (ImGui::Button(findAllButtonLabel.c_str(), ImVec2(button2Width, 0.0f))) {
findAll();
}
if (disableFindButtons) {
ImGui::EndDisabled();
}
ImGui::SameLine();
if (latchButton("Aa", &caseSensitiveFind, ImVec2(optionWidth, 0.0f))) {
find();
}
ImGui::SameLine();
if (latchButton("[]", &wholeWordFind, ImVec2(optionWidth, 0.0f))) {
find();
}
ImGui::SameLine();
if (ImGui::Button("x", ImVec2(optionWidth, 0.0f))) {
findReplaceVisible = false;
focusOnEditor = true;
}
if (!readOnly) {
ImGui::SetNextItemWidth(fieldWidth);
inputString("###replace", &replaceText);
ImGui::SameLine();
bool disableReplaceButtons = !findText.size() || !replaceText.size();
if (disableReplaceButtons) {
ImGui::BeginDisabled();
}
if (ImGui::Button(replaceButtonLabel.c_str(), ImVec2(button1Width, 0.0f))) {
replace();
}
ImGui::SameLine();
if (ImGui::Button(replaceAllButtonLabel.c_str(), ImVec2(button2Width, 0.0f))) {
replaceAll();
}
if (disableReplaceButtons) {
ImGui::EndDisabled();
}
}
ImGui::EndChild();
ImGui::SetCursorScreenPos(currentScreenPosition);
}
}
//
// TextEditor::handleKeyboardInputs
//
void TextEditor::handleKeyboardInputs() {
if (ImGui::IsWindowFocused()) {
ImGuiIO& io = ImGui::GetIO();
io.WantCaptureKeyboard = true;
io.WantTextInput = true;
// get state of modifier keys
auto shift = ImGui::IsKeyDown(ImGuiMod_Shift);
auto ctrl = ImGui::IsKeyDown(ImGuiMod_Ctrl);
auto alt = ImGui::IsKeyDown(ImGuiMod_Alt);
auto isNoModifiers = !ctrl && !shift && !alt;
auto isShortcut = ctrl && !shift && !alt;
auto isShiftShortcut = ctrl && shift && !alt;
auto isOptionalShiftShortcut = ctrl && !alt;
auto isAltOnly = !ctrl && !shift && alt;
auto isShiftOnly = !ctrl && shift && !alt;
auto isOptionalShift = !ctrl && !alt;
auto isOptionalAlt = !ctrl && !shift;
#if __APPLE__
// Dear ImGui switches the Cmd(Super) and Ctrl keys on MacOS
auto super = ImGui::IsKeyDown(ImGuiMod_Super);
auto isCtrlShift = !ctrl && shift && !alt && super;
auto isOptionalAltShift = !ctrl;
#else
auto isShiftAlt = !ctrl && shift && alt;
auto isOptionalCtrlShift = !alt;
#endif
// cursor movements and selections
if (isOptionalShift && ImGui::IsKeyPressed(ImGuiKey_UpArrow)) { moveUp(1, shift); }
else if (isOptionalShift && ImGui::IsKeyPressed(ImGuiKey_DownArrow)) { moveDown(1, shift); }
#if __APPLE__
else if (isCtrlShift && ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) { shrinkSelectionsToCurlyBrackets(true); }
else if (isCtrlShift && ImGui::IsKeyPressed(ImGuiKey_RightArrow)) { growSelectionsToCurlyBrackets(true); }
else if (isOptionalAltShift && ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) { moveLeft(shift, alt); }
else if (isOptionalAltShift && ImGui::IsKeyPressed(ImGuiKey_RightArrow)) { moveRight(shift, alt); }
#else
else if (isShiftAlt && ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) { shrinkSelectionsToCurlyBrackets(true); }
else if (isShiftAlt && ImGui::IsKeyPressed(ImGuiKey_RightArrow)) { growSelectionsToCurlyBrackets(true); }
else if (isOptionalCtrlShift && ImGui::IsKeyPressed(ImGuiKey_LeftArrow)) { moveLeft(shift, ctrl); }
else if (isOptionalCtrlShift && ImGui::IsKeyPressed(ImGuiKey_RightArrow)) { moveRight(shift, ctrl); }
#endif
else if (isOptionalShift && ImGui::IsKeyPressed(ImGuiKey_PageUp)) { moveUp(visibleLines - 2, shift); }
else if (isOptionalShift && ImGui::IsKeyPressed(ImGuiKey_PageDown)) { moveDown(visibleLines - 2, shift); }
else if (isOptionalShiftShortcut && ImGui::IsKeyPressed(ImGuiKey_UpArrow)) { moveToTop(shift); }
else if (isOptionalShiftShortcut && ImGui::IsKeyPressed(ImGuiKey_Home)) { moveToTop(shift); }
else if (isOptionalShiftShortcut && ImGui::IsKeyPressed(ImGuiKey_DownArrow)) { moveToBottom(shift); }
else if (isOptionalShiftShortcut && ImGui::IsKeyPressed(ImGuiKey_End)) { moveToBottom(shift); }
else if (isOptionalShift && ImGui::IsKeyPressed(ImGuiKey_Home)) { moveToStartOfLine(shift); }
else if (isOptionalShift && ImGui::IsKeyPressed(ImGuiKey_End)) { moveToEndOfLine(shift); }
else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_A)) { selectAll(); }
else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_D) && cursors.currentCursorHasSelection()) { addNextOccurrence(); }
// clipboard operations
else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_X)) { cut(); }
else if (isShiftOnly && ImGui::IsKeyPressed(ImGuiKey_Delete)) { cut(); }
else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_C)) { copy() ;}
else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_Insert)) { copy(); }
else if (!readOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_V)) { paste(); }
else if (!readOnly && isShiftOnly && ImGui::IsKeyPressed(ImGuiKey_Insert)) { paste(); }
else if (!readOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) { undo(); }
else if (!readOnly && isShiftShortcut && ImGui::IsKeyPressed(ImGuiKey_Z)) { redo(); }
else if (!readOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Y)) { redo(); }
// remove text
else if (!readOnly && isOptionalAlt && ImGui::IsKeyPressed(ImGuiKey_Delete)) { handleDelete(alt); }
else if (!readOnly && isOptionalAlt && ImGui::IsKeyPressed(ImGuiKey_Backspace)) { handleBackspace(alt); }
else if (!readOnly && isShiftShortcut && ImGui::IsKeyPressed(ImGuiKey_K)) { removeSelectedLines(); }
// text manipulation
else if (!readOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_LeftBracket)) { deindentLines(); }
else if (!readOnly && isShortcut && ImGui::IsKeyPressed(ImGuiKey_RightBracket)) { indentLines(); }
else if (!readOnly && isAltOnly && ImGui::IsKeyPressed(ImGuiKey_UpArrow)) { moveUpLines(); }
else if (!readOnly && isAltOnly && ImGui::IsKeyPressed(ImGuiKey_DownArrow)) { moveDownLines(); }
else if (!readOnly && language && isShortcut && ImGui::IsKeyPressed(ImGuiKey_Slash)) { toggleComments(); }
// find/replace support
else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_F)) { openFindReplace(); }
else if (isShiftShortcut && ImGui::IsKeyPressed(ImGuiKey_F)) { findAll(); }
else if (isShortcut && ImGui::IsKeyPressed(ImGuiKey_G)) { findNext(); }
// change insert mode
else if (isNoModifiers && ImGui::IsKeyPressed(ImGuiKey_Insert)) { overwrite = !overwrite; }
// handle new line
else if (!readOnly && isNoModifiers && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) { handleCharacter('\n'); }
else if (!readOnly && isShortcut && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) { insertLineBelow(); }
else if (!readOnly && isShiftShortcut && (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_KeypadEnter))) { insertLineAbove(); }
// handle tabs
else if (!readOnly && isOptionalShift && ImGui::IsKeyPressed(ImGuiKey_Tab)) {
if (cursors.anyHasSelection()) {
if (shift) {
deindentLines();
} else {
indentLines();
}
} else {
handleCharacter('\t');
}
}
// handle regular text
if (!readOnly && !io.InputQueueCharacters.empty()) {
for (int i = 0; i < io.InputQueueCharacters.size(); i++) {
auto character = io.InputQueueCharacters[i];
if (character == '\n' || character >= 32) {
handleCharacter(character);
}
}
io.InputQueueCharacters.resize(0);
}
}
}
//
// TextEditor::handleMouseInteractions
//
void TextEditor::handleMouseInteractions() {
// ignore interactions when the editor is not hovered
if (ImGui::IsWindowHovered()) {
auto io = ImGui::GetIO();
ImVec2 mousePos = ImGui::GetMousePos() - ImGui::GetCursorScreenPos();
ImVec2 absoluteMousePos = ImGui::GetMousePos() - ImGui::GetWindowPos();
bool overLineNumbers = showLineNumbers && absoluteMousePos.x > lineNumberLeftOffset && absoluteMousePos.x < lineNumberRightOffset;
bool overText = mousePos.x - ImGui::GetScrollX() > textOffset;
auto mouseCoord = document.normalizeCoordinate(Coordinate(
static_cast<int>(std::floor(mousePos.y / glyphSize.y)),
static_cast<int>(std::round((mousePos.x - textOffset) / glyphSize.x))));
auto mouseCoordAbs = document.normalizeCoordinate(Coordinate(
static_cast<int>(std::floor(mousePos.y / glyphSize.y)),
static_cast<int>(std::floor((mousePos.x - textOffset) / glyphSize.x))));
// show text cursor if required
if (ImGui::IsWindowFocused() && overText) {
ImGui::SetMouseCursor(ImGuiMouseCursor_TextInput);
}
if (ImGui::IsMouseDragging(ImGuiMouseButton_Left)) {
// update selection with dragging left mouse button
io.WantCaptureMouse = true;
if (overLineNumbers) {
auto& cursor = cursors.getCurrent();
auto start = Coordinate(mouseCoord.line, 0);
auto end = document.getDown(start);
cursor.update(cursor.getInteractiveEnd() < cursor.getInteractiveStart() ? start : end);
} else {
cursors.updateCurrentCursor(mouseCoord);
}
makeCursorVisible();
} else if (ImGui::IsMouseDragging(ImGuiMouseButton_Middle) && overText) {
// pan with dragging middle mouse button
ImVec2 mouseDelta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Middle);
ImGui::SetScrollX(ImGui::GetScrollX() - mouseDelta.x);
ImGui::SetScrollY(ImGui::GetScrollY() - mouseDelta.y);
ImGui::ResetMouseDragDelta(ImGuiMouseButton_Middle);
} else if (ImGui::IsMouseClicked(ImGuiMouseButton_Right)) {
// handle right clicks by setting up context menu (if required)
if (overLineNumbers && lineNumberContextMenuCallback) {
contextMenuLine = mouseCoordAbs.line;
ImGui::OpenPopup("LineNumberContextMenu");
} else if (overText && textContextMenuCallback) {
contextMenuLine = mouseCoordAbs.line;
contextMenuColumn = mouseCoordAbs.column;
ImGui::OpenPopup("TextContextMenu");
}
} else {
// handle left mouse button actions
auto click = ImGui::IsMouseClicked(ImGuiMouseButton_Left);
auto doubleClick = ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left);
auto now = static_cast<float>(ImGui::GetTime());
auto tripleClick = click && !doubleClick && (lastClickTime != -1.0f && (now - lastClickTime) < io.MouseDoubleClickTime);
if (click || doubleClick || tripleClick) {
lastClickTime = tripleClick ? -1.0f : now;
}
if (tripleClick) {
// left mouse button triple click
if (overText) {
auto start = document.getStartOfLine(mouseCoord);
auto end = document.getDown(start);
cursors.updateCurrentCursor(start, end);
}
} else if (doubleClick) {
// left mouse button double click
if (overText) {
auto codepoint = document.getCodePoint(mouseCoordAbs);
bool handled = false;
// select bracketed section (if required)
if (Bracketeer::isBracketOpener(codepoint)) {
auto brackets = bracketeer.getEnclosingBrackets(document.getRight(mouseCoordAbs));
if (brackets != bracketeer.end()) {
cursors.setCursor(brackets->start, document.getRight(brackets->end));
handled = true;
}
} else if (Bracketeer::isBracketCloser(codepoint)) {
auto brackets = bracketeer.getEnclosingBrackets(mouseCoordAbs);
if (brackets != bracketeer.end()) {
cursors.setCursor(brackets->start, document.getRight(brackets->end));
handled = true;
}
}
// select word if it wasn't a bracketed section
if (!handled) {
auto start = document.findWordStart(mouseCoordAbs);
auto end = document.findWordEnd(mouseCoordAbs);
cursors.updateCurrentCursor(start, end);
}
}
} else if (click) {
// left mouse button single click
auto extendCursor = ImGui::IsKeyDown(ImGuiMod_Shift);
#if __APPLE__
auto addCursor = ImGui::IsKeyDown(ImGuiMod_Alt);
#else
auto addCursor = ImGui::IsKeyDown(ImGuiMod_Ctrl);
#endif
if (overLineNumbers) {
// handle line number clicks
auto start = Coordinate(mouseCoord.line, 0);
auto end = document.getDown(start);
if (extendCursor) {
auto& cursor = cursors.getCurrent();
cursor.update(cursor.getInteractiveEnd() < cursor.getInteractiveStart() ? start : end);
} else if (addCursor) {
cursors.addCursor(start, end);
} else {
cursors.setCursor(start, end);
}
makeCursorVisible();
} else if (overText) {
// handle mouse clicks in text
if (extendCursor) {
cursors.updateCurrentCursor(mouseCoord);
} else if (addCursor) {
cursors.addCursor(mouseCoord);
} else {
cursors.setCursor(mouseCoord);