-
-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy patheditor.rs
More file actions
7091 lines (6474 loc) · 309 KB
/
Copy patheditor.rs
File metadata and controls
7091 lines (6474 loc) · 309 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
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
//! WYSIWYG Markdown Editor Widget
//!
//! This module provides a WYSIWYG (What You See Is What You Get) markdown editor
//! that renders markdown as editable egui widgets, allowing users to edit content
//! directly in rendered view.
//!
//! # Features
//! - Parses markdown into AST using the parser from Task 19
//! - Renders each AST node as an editable egui widget
//! - Propagates edits back to markdown source
//! - Supports toggling between raw and rendered modes
//! - Theme-aware styling
//! - Word processor-like keyboard interactions (Enter, Backspace, Tab, Shift+Tab)
//!
//! # Keyboard Interactions (WYSIWYG Mode)
//! - **Enter in Paragraph**: Splits the paragraph at cursor into two paragraphs
//! - **Enter in List Item**: Splits the list item, inserting a new item after
//! - **Enter on Empty List Item**: Exits the list, creates a paragraph after
//! - **Enter in Heading**: Creates a new paragraph below the heading
//! - **Backspace at List Item Start**: Merges with previous item or converts to paragraph
//! - **Tab in List Item**: Indents to create nested list
//! - **Shift+Tab in Nested List**: Outdents to parent level
//!
//! # Example
//! ```ignore
//! let output = MarkdownEditor::new(&mut content)
//! .with_settings(&settings)
//! .show(ui);
//!
//! if output.changed {
//! // Content was modified
//! }
//! ```
// Allow dead code and unused imports - this module has builder pattern methods and output fields for future extensibility
// The ast_ops imports are for planned WYSIWYG keyboard interactions (Enter, Backspace, Tab behavior)
// - too_many_arguments: Rendering functions need many parameters for proper configuration
// - only_used_in_recursion: Recursive rendering functions pass context through
// - ptr_arg: Using &mut String for direct source modification
// - needless_range_loop: Index loops are clearer for line-by-line source manipulation
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::only_used_in_recursion)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::needless_range_loop)]
use crate::config::{EditorFont, HeaderSpacing, MaxLineWidth, ParagraphIndent, Settings, Theme};
use crate::fonts;
use crate::markdown::ast_ops::{
exit_list_to_paragraph, heading_enter, indent_list_item, merge_with_previous_list_item,
outdent_list_item, split_list_item, split_paragraph, EditContext, EditNodeType, StructuralEdit,
};
use crate::markdown::cache;
use crate::markdown::code_execution::CodeExecutionUi;
use crate::markdown::rendered_session::{
self, BlockRef, CommitPolicy, PendingActivation, RenderedEditSession,
};
use crate::markdown::rendered_commit_undo;
use crate::markdown::parser::{
CalloutType, HeadingLevel, ListType, MarkdownNode, MarkdownNodeType,
};
use crate::markdown::widgets::{
build_inline_markdown_layout_job, map_displayed_to_raw, CodeBlockData, EditableCodeBlock,
EditableTable, MermaidBlock, MermaidBlockData, RenderedLinkState, RenderedLinkWidget,
TableData, TableEditState, WidgetColors,
};
use crate::ui::{render_nav_buttons, NavAction};
use eframe::egui::{
self, Color32, ColorImage, FontId, Key, Response, RichText, ScrollArea, TextEdit,
TextureHandle, TextureOptions, Ui, Vec2,
};
use log::{debug, warn};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
// Editor Mode
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
/// The editing mode for the markdown editor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EditorMode {
/// Raw markdown text editing mode
#[default]
Raw,
/// WYSIWYG rendered editing mode
Rendered,
}
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
// Editor Output
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
/// Result of showing the markdown editor widget.
pub struct MarkdownEditorOutput {
/// The egui response from the editor container.
pub response: Response,
/// Whether the content was modified.
pub changed: bool,
/// True when block-commit undo entries were queued this frame (see `rendered_commit_undo`).
pub undo_recorded: bool,
/// Current cursor position (line, column) - 0-indexed.
pub cursor_position: (usize, usize),
/// Current editing mode.
pub mode: EditorMode,
/// Focused element info for rendered mode (character range in source)
pub focused_element: Option<FocusedElement>,
/// Current scroll offset (for sync scrolling)
pub scroll_offset: f32,
/// Total content height inside the scroll area (for sync scrolling)
pub content_height: f32,
/// Viewport height of the scroll area (for sync scrolling)
pub viewport_height: f32,
/// Line-to-Y mappings for rendered mode (source_line -> rendered_y)
/// Used for accurate scroll sync between Raw and Rendered modes
pub line_mappings: Vec<LineMapping>,
/// Wikilink target that was clicked (for navigation).
/// When set, the caller should resolve this target to a file path and open it.
pub wikilink_clicked: Option<String>,
}
/// Maps a source line range to a rendered Y position range.
/// Used for scroll synchronization between Raw and Rendered views.
#[derive(Debug, Clone, Default)]
pub struct LineMapping {
/// Start line in source (1-indexed)
pub start_line: usize,
/// End line in source (1-indexed)
pub end_line: usize,
/// Y position where this element starts in rendered view
pub rendered_y: f32,
/// Height of this element in rendered view (pixels)
pub rendered_height: f32,
}
// ─────────────────────────────────────────────────────────────────────────────
// Viewport Culling
// ─────────────────────────────────────────────────────────────────────────────
/// Extra pixels above and below the viewport to pre-render, avoiding pop-in
/// during fast scrolling.
const VIEWPORT_OVERSCAN_PX: f32 = 500.0;
/// Spacing between rendered blocks (must match the `item_spacing.y` set during layout).
const BLOCK_ITEM_SPACING_Y: f32 = 1.0;
/// Extra vertical space after block-level paragraphs (and code blocks) so consecutive
/// paragraphs are visibly separated; ~0.5em at 32px line height. Included in viewport
/// block height measurements via `render_node` layout (not added to `BLOCK_ITEM_SPACING_Y`).
const PARAGRAPH_TRAILING_SPACE_Y: f32 = 16.0;
/// Max blocks to newly measure (via full egui render) per frame during the
/// progressive measurement pass. Keeps first-frame cost bounded for large
/// documents (10K+ blocks) while the scroll position self-corrects.
const MAX_NEW_MEASUREMENTS_PER_FRAME: usize = 20;
/// Baseline pixels-per-line used for heuristic height estimates when a block
/// has never been rendered. Roughly matches a 14 px body font with default
/// line spacing.
const ESTIMATED_LINE_HEIGHT_PX: f32 = 20.0;
/// Cached block positions for the rendered view, stored in egui temp memory.
/// Invalidated when content or available width changes.
#[derive(Clone)]
struct ViewportCullingState {
content_hash: u64,
available_width: f32,
/// Y offset where each block starts (includes inter-block spacing).
block_start_y: Vec<f32>,
/// Rendered height of each top-level block (excludes `BLOCK_ITEM_SPACING_Y` between
/// blocks; includes in-flow spacing such as [`PARAGRAPH_TRAILING_SPACE_Y`] after
/// paragraphs and code blocks).
block_heights: Vec<f32>,
/// Total content height (blocks + spacing), measured from the layout.
total_height: f32,
/// Per-block flag: `true` = height was obtained from a real egui render or
/// the block-height cache; `false` = heuristic estimate only.
block_measured: Vec<bool>,
/// `(start_line, end_line)` per top-level block — used to reuse layout when only
/// inline content changes (e.g. task checkbox toggles) without remeasuring.
block_line_ranges: Vec<(usize, usize)>,
}
fn block_line_ranges_from_nodes(children: &[MarkdownNode]) -> Vec<(usize, usize)> {
children
.iter()
.map(|n| (n.start_line, n.end_line))
.collect()
}
fn block_structure_matches(ranges: &[(usize, usize)], children: &[MarkdownNode]) -> bool {
!ranges.is_empty()
&& ranges.len() == children.len()
&& ranges
.iter()
.zip(children.iter())
.all(|(&(s, e), n)| n.start_line == s && n.end_line == e)
}
/// True when the user is actively scrolling (wheel or scrollbar drag), not merely clicking.
fn is_active_scroll_input(ui: &Ui) -> bool {
ui.input(|i| {
i.smooth_scroll_delta.y.abs() > 0.5
|| (i.pointer.any_down() && i.pointer.is_decidedly_dragging())
})
}
// ─────────────────────────────────────────────────────────────────────────────
// Block Source Extraction (for per-block height caching)
// ─────────────────────────────────────────────────────────────────────────────
/// Byte offset of the start of each line.
/// `offsets[0]` = byte start of line 1, `offsets[1]` = byte start of line 2, etc.
fn line_start_byte_offsets(content: &str) -> Vec<usize> {
let mut offsets = vec![0];
for (i, &b) in content.as_bytes().iter().enumerate() {
if b == b'\n' {
offsets.push(i + 1);
}
}
offsets
}
/// Extract the source text for a block spanning `start_line..=end_line` (1-indexed).
fn block_source_slice<'a>(
content: &'a str,
offsets: &[usize],
start_line: usize,
end_line: usize,
) -> &'a str {
if start_line == 0 || end_line == 0 || offsets.is_empty() {
return "";
}
let start = offsets
.get(start_line.saturating_sub(1))
.copied()
.unwrap_or(0);
let end = offsets.get(end_line).copied().unwrap_or(content.len());
&content[start..end.min(content.len())]
}
/// Heuristic height for a block that has never been rendered.
/// Uses `(end_line - start_line + 1) * ESTIMATED_LINE_HEIGHT_PX` as baseline,
/// with a small per-block minimum to avoid zero-height placeholders.
fn estimate_block_height(start_line: usize, end_line: usize) -> f32 {
let lines = if end_line >= start_line {
(end_line - start_line + 1) as f32
} else {
1.0
};
(lines * ESTIMATED_LINE_HEIGHT_PX).max(ESTIMATED_LINE_HEIGHT_PX)
}
// ─────────────────────────────────────────────────────────────────────────────
// Rendered View Search Highlight Overlay
// ─────────────────────────────────────────────────────────────────────────────
/// Converts a byte position in the source to a 1-indexed line number.
fn byte_pos_to_line_1indexed(line_offsets: &[usize], byte_pos: usize) -> usize {
match line_offsets.binary_search(&byte_pos) {
Ok(idx) => idx + 1,
Err(idx) => idx, // idx is the line whose start is > byte_pos, so line = idx
}
}
/// Paints search highlight overlays for matches that fall within a rendered block.
///
/// For table blocks, highlights are subdivided into per-row strips.
/// For other blocks (paragraphs, headings), a full-width strip is painted.
#[allow(clippy::too_many_arguments)]
fn paint_rendered_search_highlights(
ui: &Ui,
search_highlights: &[(usize, usize)],
current_match: usize,
content: &str,
line_offsets: &[usize],
node_start_line: usize,
node_end_line: usize,
block_y_top: f32,
block_y_bottom: f32,
block_left: f32,
block_right: f32,
is_table: bool,
is_dark: bool,
) {
if search_highlights.is_empty() || node_start_line == 0 {
return;
}
let block_start_byte = line_offsets
.get(node_start_line.saturating_sub(1))
.copied()
.unwrap_or(0);
let block_end_byte = line_offsets
.get(node_end_line)
.copied()
.unwrap_or(content.len());
let current_match_color = if is_dark {
Color32::from_rgba_unmultiplied(255, 200, 0, 100)
} else {
Color32::from_rgba_unmultiplied(255, 220, 0, 120)
};
let other_match_color = if is_dark {
Color32::from_rgba_unmultiplied(180, 150, 50, 60)
} else {
Color32::from_rgba_unmultiplied(255, 255, 100, 80)
};
let block_height = block_y_bottom - block_y_top;
let total_source_lines = node_end_line.saturating_sub(node_start_line) + 1;
if block_height <= 0.0 || total_source_lines == 0 {
return;
}
let painter = ui.painter();
for (idx, &(match_start, match_end)) in search_highlights.iter().enumerate() {
if match_end <= block_start_byte || match_start >= block_end_byte {
continue;
}
let color = if idx == current_match {
current_match_color
} else {
other_match_color
};
let match_line = byte_pos_to_line_1indexed(line_offsets, match_start);
if is_table {
// Table: subdivide into rows. Each source line = one visual row,
// except the separator line (start_line + 1) is collapsed.
let table_lines = total_source_lines;
let visual_rows = if table_lines > 2 {
table_lines - 1 // header + data rows (separator merged)
} else {
table_lines.max(1)
};
let row_height = block_height / visual_rows as f32;
let offset_from_start = match_line.saturating_sub(node_start_line);
let visual_row = if offset_from_start == 0 {
0 // header
} else if offset_from_start == 1 {
continue; // separator line — skip
} else {
offset_from_start - 1 // data rows shifted by 1 (separator removed)
};
let row_y = block_y_top + visual_row as f32 * row_height;
let highlight_rect = egui::Rect::from_min_max(
egui::Pos2::new(block_left, row_y),
egui::Pos2::new(block_right, row_y + row_height),
);
painter.rect_filled(highlight_rect, 2.0, color);
} else {
// Non-table block: paint a proportional strip
let line_frac =
(match_line.saturating_sub(node_start_line)) as f32 / total_source_lines as f32;
let approx_line_height = block_height / total_source_lines as f32;
let y = block_y_top + line_frac * block_height;
let highlight_rect = egui::Rect::from_min_max(
egui::Pos2::new(block_left, y),
egui::Pos2::new(block_right, (y + approx_line_height).min(block_y_bottom)),
);
painter.rect_filled(highlight_rect, 2.0, color);
}
}
}
/// Information about the currently focused element in rendered mode.
#[derive(Debug, Clone)]
pub struct FocusedElement {
/// Start character index in source markdown
pub start_char: usize,
/// End character index in source markdown
pub end_char: usize,
/// Selection within the element (relative to element start)
pub selection: Option<(usize, usize)>,
}
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
// Theme Colors
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
/// Theme-aware colors for the WYSIWYG editor.
#[derive(Debug, Clone)]
pub struct EditorColors {
/// Background color
pub background: Color32,
/// Primary text color
pub text: Color32,
/// Heading text color
pub heading: Color32,
/// Code background color
pub code_bg: Color32,
/// Code text color
pub code_text: Color32,
/// Block quote border color
pub quote_border: Color32,
/// Block quote text color
pub quote_text: Color32,
/// Link color
pub link: Color32,
/// Horizontal rule color
pub hr: Color32,
/// List bullet/number color
pub list_marker: Color32,
/// Task list checkbox color
pub checkbox: Color32,
}
impl EditorColors {
/// Create colors for the given theme and user accent. Hyperlink color stays standard blue.
pub fn from_theme(theme: Theme, visuals: &egui::Visuals, accent: Color32) -> Self {
let mut c = match theme {
Theme::Dark => Self::dark(),
Theme::Light => Self::light(),
Theme::System => {
if visuals.dark_mode {
Self::dark()
} else {
Self::light()
}
}
};
let dark = match theme {
Theme::Dark => true,
Theme::Light => false,
Theme::System => visuals.dark_mode,
};
c.heading = accent;
c.checkbox = accent;
c.link = crate::theme::accent::standard_link_color(dark);
c
}
/// Dark theme colors (default accent/link before `from_theme` overrides).
pub fn dark() -> Self {
Self {
background: Color32::from_rgb(30, 30, 30),
text: Color32::from_rgb(220, 220, 220),
heading: Color32::from_rgb(100, 180, 255),
code_bg: Color32::from_rgb(45, 45, 45),
code_text: Color32::from_rgb(200, 200, 150),
quote_border: Color32::from_rgb(80, 80, 80),
quote_text: Color32::from_rgb(180, 180, 180),
link: Color32::from_rgb(100, 180, 255),
hr: Color32::from_rgb(80, 80, 80),
list_marker: Color32::from_rgb(150, 150, 150),
checkbox: Color32::from_rgb(100, 180, 255),
}
}
/// Light theme colors.
pub fn light() -> Self {
Self {
background: Color32::from_rgb(255, 255, 255),
text: Color32::from_rgb(30, 30, 30),
heading: Color32::from_rgb(0, 100, 180),
code_bg: Color32::from_rgb(245, 245, 245),
code_text: Color32::from_rgb(80, 80, 80),
quote_border: Color32::from_rgb(200, 200, 200),
quote_text: Color32::from_rgb(100, 100, 100),
link: Color32::from_rgb(0, 100, 180),
hr: Color32::from_rgb(200, 200, 200),
list_marker: Color32::from_rgb(100, 100, 100),
checkbox: Color32::from_rgb(0, 100, 180),
}
}
}
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
// Editable Node State
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
/// State for an editable node in the WYSIWYG editor.
/// This tracks the text content and modification status of each editable element.
#[derive(Debug, Clone)]
struct EditableNode {
/// Unique ID for this node
id: usize,
/// The text content being edited
text: String,
/// Start line in source (for mapping back)
start_line: usize,
/// End line in source (for mapping back)
end_line: usize,
/// Whether this node was modified
modified: bool,
}
/// Tracks all editable nodes and their states.
#[derive(Debug, Clone, Default)]
struct EditState {
/// All editable nodes indexed by their ID
nodes: Vec<EditableNode>,
/// Counter for generating unique node IDs
next_id: usize,
/// Currently focused node ID
focused_node: Option<usize>,
/// Selection within the focused node (start, end) - relative to node text
focused_selection: Option<(usize, usize)>,
}
impl EditState {
fn new() -> Self {
Self::default()
}
fn add_node(&mut self, text: String, start_line: usize, end_line: usize) -> usize {
let id = self.next_id;
self.next_id += 1;
self.nodes.push(EditableNode {
id,
text,
start_line,
end_line,
modified: false,
});
id
}
fn get_node_mut(&mut self, id: usize) -> Option<&mut EditableNode> {
self.nodes.iter_mut().find(|n| n.id == id)
}
fn any_modified(&self) -> bool {
self.nodes.iter().any(|n| n.modified)
}
fn clear(&mut self) {
self.nodes.clear();
self.next_id = 0;
self.focused_node = None;
self.focused_selection = None;
}
/// Set the currently focused node and selection within it
fn set_focus(&mut self, node_id: usize, selection: Option<(usize, usize)>) {
self.focused_node = Some(node_id);
self.focused_selection = selection;
}
/// Get focused element info for the output
fn get_focused_element(&self, source: &str) -> Option<FocusedElement> {
let node_id = self.focused_node?;
let node = self.nodes.iter().find(|n| n.id == node_id)?;
// Convert line numbers to character indices
let start_char = line_to_char_index(source, node.start_line);
let end_char = line_to_char_index(source, node.end_line + 1).min(source.len());
Some(FocusedElement {
start_char,
end_char,
selection: self.focused_selection,
})
}
}
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
// Structural Edit State
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
/// Tracks the context of the currently focused editable widget for structural operations.
/// This enables word processor-like keyboard behavior (Enter, Backspace, Tab).
#[derive(Debug, Clone, Default)]
struct StructuralEditState {
/// Pending structural edit to apply at end of frame
pending_edit: Option<StructuralEdit>,
/// Current edit context (populated when a widget is focused)
current_context: Option<EditContext>,
}
impl StructuralEditState {
fn new() -> Self {
Self::default()
}
/// Set the current edit context (called when a widget gains focus or is edited)
fn set_context(&mut self, ctx: EditContext) {
self.current_context = Some(ctx);
}
/// Clear the current context
fn clear_context(&mut self) {
self.current_context = None;
}
/// Set a pending structural edit to apply
fn set_pending_edit(&mut self, edit: StructuralEdit) {
if edit.performed {
self.pending_edit = Some(edit);
}
}
/// Take the pending edit (returns and clears it)
fn take_pending_edit(&mut self) -> Option<StructuralEdit> {
self.pending_edit.take()
}
}
/// Result of checking for structural key presses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StructuralKeyAction {
/// No structural key was pressed
None,
/// Enter key pressed
Enter,
/// Backspace at position 0
BackspaceAtStart,
/// Tab key pressed
Tab,
/// Shift+Tab pressed
ShiftTab,
}
/// Check if a structural key was pressed given the input state.
fn check_structural_keys(ui: &Ui, cursor_at_start: bool) -> StructuralKeyAction {
ui.input(|i| {
// Check Enter (without modifiers to avoid conflicts with Shift+Enter for line break)
if i.key_pressed(Key::Enter) && !i.modifiers.shift && !i.modifiers.ctrl && !i.modifiers.alt
{
return StructuralKeyAction::Enter;
}
// Check Backspace at start of text
if i.key_pressed(Key::Backspace) && cursor_at_start {
return StructuralKeyAction::BackspaceAtStart;
}
// Check Tab (without Shift)
if i.key_pressed(Key::Tab) && !i.modifiers.shift {
return StructuralKeyAction::Tab;
}
// Check Shift+Tab
if i.key_pressed(Key::Tab) && i.modifiers.shift {
return StructuralKeyAction::ShiftTab;
}
StructuralKeyAction::None
})
}
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
// Markdown Editor Widget
// ââ€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬Ã¢â€â‚¬
/// A WYSIWYG markdown editor widget.
///
/// This widget provides two editing modes:
/// - **Raw mode**: Plain text editing of markdown source
/// - **Rendered mode**: Edit content through styled, semantic egui widgets
///
/// In rendered mode, each markdown element (headings, paragraphs, lists, etc.)
/// is rendered as an editable widget. Edits are synchronized back to the
/// underlying markdown source.
///
/// # Example
///
/// ```ignore
/// let output = MarkdownEditor::new(&mut content)
/// .mode(EditorMode::Rendered)
/// .font_size(14.0)
/// .show(ui);
/// ```
pub struct MarkdownEditor<'a> {
/// The markdown content being edited
content: &'a mut String,
/// Current editing mode
mode: EditorMode,
/// Font size for the editor
font_size: f32,
/// Font family for the editor
font_family: EditorFont,
/// Whether word wrap is enabled
word_wrap: bool,
/// Theme for styling
theme: Theme,
/// User accent (matches Settings.accent_color)
accent_rgb: [u8; 3],
/// Custom ID for the editor
id: Option<egui::Id>,
/// Line number to scroll to (1-indexed, from outline navigation)
scroll_to_line: Option<usize>,
/// Pending scroll offset to apply (for sync scrolling on mode switch)
pending_scroll_offset: Option<f32>,
/// Maximum line width setting for centering text column
max_line_width: MaxLineWidth,
/// Whether Zen Mode is enabled (centered text column)
zen_mode: bool,
/// Maximum column width in characters for Zen Mode centering
zen_max_column_width: f32,
/// CJK paragraph first-line indentation
paragraph_indent: ParagraphIndent,
/// Vertical spacing between headers in rendered view
header_spacing: HeaderSpacing,
/// File context for wikilink resolution (current file dir + workspace root)
wikilink_context: Option<WikilinkContext>,
/// Treat soft breaks as hard line breaks in rendered view
strict_line_breaks: bool,
/// Search match byte ranges for overlay highlighting in rendered view
search_highlights: Option<Vec<(usize, usize)>>,
/// Index of the currently focused search match
current_search_match: usize,
/// Gating and cwd for running fenced code from the preview (optional).
code_execution: Option<CodeExecutionUi>,
/// External-invalidation epoch from tab state; scopes rendered widget ids (see PRD).
source_epoch: u64,
}
/// Context for resolving wikilinks to actual files during rendering.
/// Stored in egui memory per-frame so `render_wikilink` can check file existence.
#[derive(Debug, Clone)]
pub struct WikilinkContext {
/// Directory of the currently open file (for relative resolution)
pub current_dir: Option<PathBuf>,
/// Workspace root (for workspace-wide resolution)
pub workspace_root: Option<PathBuf>,
}
impl<'a> MarkdownEditor<'a> {
/// Create a new markdown editor for the given content.
pub fn new(content: &'a mut String) -> Self {
Self {
content,
mode: EditorMode::Raw,
font_size: 14.0,
font_family: EditorFont::default(),
word_wrap: true,
theme: Theme::Light,
accent_rgb: crate::theme::accent::DEFAULT_ACCENT_RGB,
id: None,
scroll_to_line: None,
pending_scroll_offset: None,
max_line_width: MaxLineWidth::Off,
zen_mode: false,
zen_max_column_width: 80.0,
paragraph_indent: ParagraphIndent::Off,
header_spacing: HeaderSpacing::default(),
wikilink_context: None,
strict_line_breaks: false,
search_highlights: None,
current_search_match: 0,
code_execution: None,
source_epoch: 0,
}
}
/// Set the editing mode.
#[must_use]
pub fn mode(mut self, mode: EditorMode) -> Self {
self.mode = mode;
self
}
/// Set the font size.
#[must_use]
pub fn font_size(mut self, size: f32) -> Self {
self.font_size = size;
self
}
/// Set whether word wrap is enabled.
#[must_use]
pub fn word_wrap(mut self, wrap: bool) -> Self {
self.word_wrap = wrap;
self
}
/// Set the theme.
#[must_use]
pub fn theme(mut self, theme: Theme) -> Self {
self.theme = theme;
self
}
/// Set the font family.
#[must_use]
pub fn font_family(mut self, font_family: EditorFont) -> Self {
self.font_family = font_family;
self
}
/// Set a custom ID for the editor.
#[must_use]
pub fn id(mut self, id: egui::Id) -> Self {
self.id = Some(id);
self
}
/// Set a line to scroll to (1-indexed, for outline navigation).
#[must_use]
pub fn scroll_to_line(mut self, line: Option<usize>) -> Self {
self.scroll_to_line = line;
self
}
/// Set a pending scroll offset to apply (for sync scrolling on mode switch).
#[must_use]
pub fn pending_scroll_offset(mut self, offset: Option<f32>) -> Self {
self.pending_scroll_offset = offset;
self
}
/// Set the maximum line width for text centering.
///
/// When enabled and the viewport is wider than the specified width,
/// text is constrained to that width and centered horizontally.
#[must_use]
pub fn max_line_width(mut self, width: MaxLineWidth) -> Self {
self.max_line_width = width;
self
}
/// Enable Zen Mode with centered text column.
///
/// When enabled, the text content is centered horizontally with a maximum
/// column width (in characters), while the editor background fills the available space.
/// Zen Mode takes priority over max_line_width setting.
#[must_use]
pub fn zen_mode(mut self, enabled: bool, max_column_width: f32) -> Self {
self.zen_mode = enabled;
self.zen_max_column_width = max_column_width;
self
}
/// Set the CJK paragraph first-line indentation.
///
/// When enabled, paragraphs in rendered view will have first-line indentation
/// following Chinese (2em) or Japanese (1em) typography conventions.
#[must_use]
pub fn paragraph_indent(mut self, indent: ParagraphIndent) -> Self {
self.paragraph_indent = indent;
self
}
/// Set the vertical spacing between headers in rendered view.
#[must_use]
pub fn header_spacing(mut self, spacing: HeaderSpacing) -> Self {
self.header_spacing = spacing;
self
}
/// Set the wikilink resolution context (current file directory and workspace root).
///
/// When provided, wikilinks that cannot be resolved to existing files are
/// rendered with a distinct "broken link" visual style.
#[must_use]
pub fn wikilink_context(mut self, ctx: WikilinkContext) -> Self {
self.wikilink_context = Some(ctx);
self
}
#[must_use]
pub fn accent_rgb(mut self, rgb: [u8; 3]) -> Self {
self.accent_rgb = rgb;
self
}
/// Set strict line breaks mode.
///
/// When enabled, soft breaks (single newlines) in markdown source are
/// rendered as hard line breaks instead of being collapsed to spaces.
#[must_use]
pub fn strict_line_breaks(mut self, enabled: bool) -> Self {
self.strict_line_breaks = enabled;
self
}
/// Set search highlights to render as overlays in the rendered view.
#[must_use]
pub fn search_highlights(mut self, matches: Vec<(usize, usize)>, current: usize) -> Self {
self.search_highlights = Some(matches);
self.current_search_match = current;
self
}
/// Apply settings to the editor widget.
#[must_use]
pub fn with_settings(mut self, settings: &Settings) -> Self {
self.font_size = settings.font_size;
self.font_family = settings.font_family.clone();
self.word_wrap = settings.word_wrap;
self.theme = settings.theme;
self.max_line_width = settings.max_line_width;
self.paragraph_indent = settings.paragraph_indent;
self.strict_line_breaks = settings.strict_line_breaks;
self.accent_rgb = settings.accent_color;
self.code_execution = Some(CodeExecutionUi::from_settings(settings));
self
}
/// Snapshot for code-block **Run** (preview cwd, timeouts, and permission flags).
#[must_use]
pub fn code_execution(mut self, ctx: CodeExecutionUi) -> Self {
self.code_execution = Some(ctx);
self
}
/// Per-tab external invalidation epoch for stable rendered widget ids.
///
/// Bumps only on raw edits, undo/redo, reload, etc. — not on rendered WYSIWYG commits.
#[must_use]
pub fn source_epoch(mut self, epoch: u64) -> Self {
self.source_epoch = epoch;
self
}
/// Show the editor widget and return the output.
pub fn show(self, ui: &mut Ui) -> MarkdownEditorOutput {
let id = self.id.unwrap_or_else(|| ui.id().with("markdown_editor"));
let accent = Color32::from_rgb(self.accent_rgb[0], self.accent_rgb[1], self.accent_rgb[2]);
ui.ctx().data_mut(|d| {
d.insert_temp(crate::markdown::markdown_accent_temp_id(), accent);
});
let colors = EditorColors::from_theme(self.theme, ui.visuals(), accent);
match self.mode {
EditorMode::Raw => self.show_raw_editor(ui, id),
EditorMode::Rendered => self.show_rendered_editor(ui, id, &colors),
}
}
/// Show the raw text editor (plain markdown editing).
fn show_raw_editor(self, ui: &mut Ui, id: egui::Id) -> MarkdownEditorOutput {
let font_size = self.font_size;
let word_wrap = self.word_wrap;
let editor_font = self.font_family.clone();
let font_family = fonts::get_styled_font_family(false, false, &editor_font);
let scroll_output = ScrollArea::vertical()
.id_salt(id.with("scroll"))
.auto_shrink([false, false])
.show(ui, |ui| {
let font_family_clone = font_family.clone();
let mut layouter = move |ui: &Ui, buf: &dyn egui::TextBuffer, wrap_width: f32| {
let text = buf.as_str();
let font_id = FontId::new(font_size, font_family_clone.clone());
let layout_job = if word_wrap {
egui::text::LayoutJob::simple(
text.to_owned(),
font_id,
ui.visuals().text_color(),
wrap_width,
)
} else {
egui::text::LayoutJob::simple_singleline(
text.to_owned(),
font_id,
ui.visuals().text_color(),
)
};
ui.fonts_mut(|f| f.layout_job(layout_job))
};
TextEdit::multiline(self.content)
.id(id)
.frame(egui::Frame::NONE)
.font(FontId::new(font_size, font_family.clone()))
.desired_width(f32::INFINITY)
.layouter(&mut layouter)
.show(ui)
});
let text_output = scroll_output.inner;
let changed = text_output.response.changed();
let cursor_position = if let Some(cursor_range) = text_output.cursor_range {
let cursor = cursor_range.primary;
char_index_to_line_col(self.content, cursor.index)
} else {
(0, 0)
};
if changed {
debug!("Raw editor content changed");
}
MarkdownEditorOutput {
response: text_output.response.response,
changed,
undo_recorded: false,
cursor_position,
mode: EditorMode::Raw,
focused_element: None, // Raw mode doesn't use element tracking
scroll_offset: scroll_output.state.offset.y,
content_height: scroll_output.content_size.y,
viewport_height: scroll_output.inner_rect.height(),
line_mappings: Vec::new(), // Raw mode doesn't need line mappings
wikilink_clicked: None, // Raw mode doesn't have clickable wikilinks
}
}
/// Show the WYSIWYG rendered editor.