-
-
Notifications
You must be signed in to change notification settings - Fork 10.8k
Expand file tree
/
Copy pathmarkdown.rs
More file actions
8242 lines (7470 loc) · 305 KB
/
Copy pathmarkdown.rs
File metadata and controls
8242 lines (7470 loc) · 305 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
pub mod html;
mod mermaid;
pub mod parser;
mod path_range;
mod selection;
use base64::Engine as _;
use gpui::EdgesRefinement;
use gpui::HitboxBehavior;
use gpui::UnderlineStyle;
use language::LanguageName;
use log::Level;
use mermaid::{
MermaidState, ParsedMarkdownMermaidDiagram, extract_mermaid_diagrams, render_mermaid_diagram,
};
pub use path_range::{LineCol, PathWithRange};
use settings::Settings as _;
use smallvec::SmallVec;
use theme_settings::ThemeSettings;
use util::maybe;
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::BTreeMap;
use std::mem;
use std::ops::Range;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use collections::{HashMap, HashSet};
use gpui::{
AnyElement, App, BorderStyle, Bounds, ClipboardItem, CursorStyle, DispatchPhase, Edges, Entity,
FocusHandle, Focusable, FontStyle, FontWeight, GlobalElementId, Hitbox, Hsla, Image,
ImageFormat, ImageSource, InputHandler, KeyContext, Length, MouseButton, MouseDownEvent,
MouseEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, ScrollHandle, Stateful,
StrikethroughStyle, StyleRefinement, StyledImage, StyledText, Subscription, Task, TextAlign,
TextLayout, TextRun, TextStyle, TextStyleRefinement, UTF16Selection, WrappedLineLayout,
actions, canvas, img, point, quad, relative, size,
};
use language::{
Bias, CharClassifier, Language, LanguageRegistry, OffsetUtf16, ResolvedHighlights, Rope,
};
use parser::CodeBlockMetadata;
use parser::{
MarkdownEvent, MarkdownTag, MarkdownTagEnd, ParsedMetadataBlock, parse_links_only,
parse_markdown_with_options,
};
use pulldown_cmark::{Alignment, BlockQuoteKind};
use sum_tree::TreeMap;
use theme::SyntaxTheme;
use ui::{Checkbox, CopyButton, ScrollAxes, Scrollbars, Tooltip, WithScrollbar, prelude::*};
use util::ResultExt;
use crate::parser::CodeBlockKind;
const MERMAID_MAX_ZOOM: f32 = 2.0;
/// Zoom levels within this distance of 1.0 snap back to exactly 1.0 so users
/// can easily return to the default size.
const MERMAID_ZOOM_SNAP_TOLERANCE: f32 = 0.05;
const MERMAID_ZOOM_DEBOUNCE: Duration = Duration::from_millis(300);
/// A callback function that can be used to customize the style of links based on the destination URL.
/// If the callback returns `None`, the default link style will be used.
type LinkStyleCallback = Rc<dyn Fn(&str, &App) -> Option<TextStyleRefinement>>;
pub type CodeSpanLinkCallback = Arc<dyn Fn(&str, &App) -> Option<SharedString> + 'static>;
type UrlHoverCallback = Rc<dyn Fn(Option<SharedString>, &mut Window, &mut App)>;
type SourceClickCallback = Box<dyn Fn(usize, usize, &mut Window, &mut App) -> bool>;
type CheckboxToggleCallback = Rc<dyn Fn(Range<usize>, bool, &mut Window, &mut App)>;
/// Invoked when a mermaid diagram's zoom level changes (via scroll gesture or
/// the reset button), so a scroll container can keep the diagram anchored.
pub type MermaidZoomCallback = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(Clone, Copy, Default)]
pub struct BlockQuoteKindColors {
pub note: Hsla,
pub tip: Hsla,
pub important: Hsla,
pub warning: Hsla,
pub caution: Hsla,
}
impl BlockQuoteKindColors {
fn for_kind(&self, kind: Option<BlockQuoteKind>, default: Hsla) -> Hsla {
match kind {
Some(BlockQuoteKind::Note) => self.note,
Some(BlockQuoteKind::Tip) => self.tip,
Some(BlockQuoteKind::Important) => self.important,
Some(BlockQuoteKind::Warning) => self.warning,
Some(BlockQuoteKind::Caution) => self.caution,
None => default,
}
}
}
#[derive(Clone, Default)]
pub struct HeadingLevelStyles {
pub h1: Option<TextStyleRefinement>,
pub h2: Option<TextStyleRefinement>,
pub h3: Option<TextStyleRefinement>,
pub h4: Option<TextStyleRefinement>,
pub h5: Option<TextStyleRefinement>,
pub h6: Option<TextStyleRefinement>,
}
#[derive(Clone)]
pub struct MarkdownStyle {
pub base_text_style: TextStyle,
pub container_style: StyleRefinement,
pub code_block: StyleRefinement,
pub code_block_overflow_x_scroll: bool,
pub inline_code: TextStyleRefinement,
pub block_quote: TextStyleRefinement,
pub link: TextStyleRefinement,
pub link_callback: Option<LinkStyleCallback>,
pub rule_color: Hsla,
pub block_quote_border_color: Hsla,
pub block_quote_kind_colors: BlockQuoteKindColors,
pub syntax: Arc<SyntaxTheme>,
pub selection_background_color: Hsla,
pub heading: StyleRefinement,
pub heading_level_styles: Option<HeadingLevelStyles>,
pub heading_border_color: Option<Hsla>,
pub paragraph_spacing: Pixels,
pub paragraph_line_height: DefiniteLength,
/// Bottom margin of top-level lists only
pub list_spacing: Pixels,
/// Horizontal (`x`) and vertical (`y`) padding of table cells
pub table_cell_padding: Point<Pixels>,
pub height_is_multiple_of_line_height: bool,
pub prevent_mouse_interaction: bool,
pub table_columns_min_size: bool,
pub soft_break_as_hard_break: bool,
}
impl Default for MarkdownStyle {
fn default() -> Self {
Self {
base_text_style: Default::default(),
container_style: Default::default(),
code_block: Default::default(),
code_block_overflow_x_scroll: false,
inline_code: Default::default(),
block_quote: Default::default(),
link: Default::default(),
link_callback: None,
rule_color: Default::default(),
block_quote_border_color: Default::default(),
block_quote_kind_colors: Default::default(),
syntax: Arc::new(SyntaxTheme::default()),
selection_background_color: Default::default(),
heading: Default::default(),
heading_level_styles: None,
heading_border_color: None,
paragraph_spacing: px(8.),
paragraph_line_height: rems(1.3).into(),
list_spacing: px(0.),
table_cell_padding: point(px(4.), px(2.)),
height_is_multiple_of_line_height: false,
prevent_mouse_interaction: false,
table_columns_min_size: false,
soft_break_as_hard_break: false,
}
}
}
#[derive(Clone, Copy)]
pub enum MarkdownFont {
Agent,
Editor,
Preview,
}
impl MarkdownStyle {
pub fn themed(font: MarkdownFont, window: &Window, cx: &App) -> Self {
let colors = cx.theme().colors();
let syntax = cx.theme().syntax().clone();
Self::themed_with_overrides(font, colors, &syntax, window, cx)
}
/// Like [`Self::themed`], but takes explicit [`ThemeColors`] and
/// [`SyntaxTheme`] so callers (e.g. the markdown preview) can render the
/// markdown using a theme other than the active editor theme.
pub fn themed_with_overrides(
font: MarkdownFont,
colors: &theme::ThemeColors,
syntax: &Arc<SyntaxTheme>,
window: &Window,
cx: &App,
) -> Self {
let theme_settings = ThemeSettings::get_global(cx);
let is_preview = matches!(font, MarkdownFont::Preview);
let buffer_font_weight = theme_settings.buffer_font.weight;
let (buffer_font_size, ui_font_size) = match font {
MarkdownFont::Agent => (
theme_settings.agent_buffer_font_size(cx),
theme_settings.agent_ui_font_size(cx),
),
MarkdownFont::Editor => (
theme_settings.buffer_font_size(cx),
theme_settings.ui_font_size(cx),
),
MarkdownFont::Preview => (
theme_settings.markdown_preview_font_size(cx),
theme_settings.ui_font_size(cx),
),
};
let body_font_family = match font {
MarkdownFont::Preview => theme_settings.markdown_preview_font_family().clone(),
MarkdownFont::Agent => theme_settings.agent_ui_font_family().clone(),
MarkdownFont::Editor => theme_settings.ui_font.family.clone(),
};
let code_font_family = match font {
MarkdownFont::Preview => theme_settings.markdown_preview_code_font_family().clone(),
MarkdownFont::Agent => theme_settings.agent_buffer_font_family().clone(),
MarkdownFont::Editor => theme_settings.buffer_font.family.clone(),
};
let mut text_style = window.text_style();
let line_height = buffer_font_size * 1.75;
text_style.refine(&TextStyleRefinement {
font_family: Some(body_font_family),
font_fallbacks: theme_settings.ui_font.fallbacks.clone(),
font_features: Some(theme_settings.ui_font.features.clone()),
font_size: Some(if is_preview {
rems(1.0).into()
} else {
ui_font_size.into()
}),
line_height: Some(line_height.into()),
color: Some(colors.text),
..Default::default()
});
let style = MarkdownStyle {
base_text_style: text_style.clone(),
syntax: syntax.clone(),
selection_background_color: colors.element_selection_background,
rule_color: colors.border,
block_quote_border_color: colors.border,
block_quote_kind_colors: {
let status = cx.theme().status();
BlockQuoteKindColors {
note: status.info,
tip: status.success,
important: status.info,
warning: status.warning,
caution: status.error,
}
},
code_block_overflow_x_scroll: true,
code_block: StyleRefinement {
padding: EdgesRefinement {
top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(8.)))),
},
margin: EdgesRefinement {
top: Some(Length::Definite(px(8.).into())),
left: Some(Length::Definite(px(0.).into())),
right: Some(Length::Definite(px(0.).into())),
bottom: Some(Length::Definite(px(12.).into())),
},
border_style: Some(BorderStyle::Solid),
border_widths: EdgesRefinement {
top: Some(AbsoluteLength::Pixels(px(1.))),
left: Some(AbsoluteLength::Pixels(px(1.))),
right: Some(AbsoluteLength::Pixels(px(1.))),
bottom: Some(AbsoluteLength::Pixels(px(1.))),
},
border_color: Some(colors.border_variant),
background: Some(colors.editor_background.into()),
text: TextStyleRefinement {
font_family: Some(code_font_family.clone()),
font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
font_features: Some(theme_settings.buffer_font.features.clone()),
font_size: Some(buffer_font_size.into()),
font_weight: Some(buffer_font_weight),
line_height: Some(relative(theme_settings.buffer_line_height.value())),
..Default::default()
},
..Default::default()
},
inline_code: TextStyleRefinement {
font_family: Some(code_font_family),
font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
font_features: Some(theme_settings.buffer_font.features.clone()),
font_size: Some(buffer_font_size.into()),
font_weight: Some(buffer_font_weight),
background_color: Some(colors.editor_foreground.opacity(0.08)),
..Default::default()
},
link: TextStyleRefinement {
background_color: Some(colors.editor_foreground.opacity(0.025)),
color: Some(colors.text_accent),
underline: Some(UnderlineStyle {
color: Some(colors.text_accent.opacity(0.5)),
thickness: px(1.),
..Default::default()
}),
..Default::default()
},
soft_break_as_hard_break: matches!(font, MarkdownFont::Agent),
heading_level_styles: matches!(font, MarkdownFont::Agent).then_some(
HeadingLevelStyles {
h1: Some(TextStyleRefinement {
font_size: Some(rems(1.15).into()),
..Default::default()
}),
h2: Some(TextStyleRefinement {
font_size: Some(rems(1.1).into()),
..Default::default()
}),
h3: Some(TextStyleRefinement {
font_size: Some(rems(1.05).into()),
..Default::default()
}),
h4: Some(TextStyleRefinement {
font_size: Some(rems(1.).into()),
..Default::default()
}),
h5: Some(TextStyleRefinement {
font_size: Some(rems(0.95).into()),
..Default::default()
}),
h6: Some(TextStyleRefinement {
font_size: Some(rems(0.875).into()),
..Default::default()
}),
},
),
..Default::default()
};
if is_preview {
style.with_preview_overrides(colors)
} else {
style
}
}
fn with_preview_overrides(mut self, colors: &theme::ThemeColors) -> Self {
let body_font_size = rems(1.0);
self.base_text_style.font_size = body_font_size.into();
self.container_style.text.font_size = Some(body_font_size.into());
self.base_text_style.color = colors.text;
self.base_text_style.line_height = relative(1.5);
self.paragraph_spacing = px(16.);
self.paragraph_line_height = relative(1.5);
self.list_spacing = px(12.);
self.table_cell_padding = point(px(10.), px(4.));
self.inline_code.color = Some(colors.text);
self.inline_code.font_size = Some(rems(0.875).into());
self.link.background_color = None;
self.block_quote.color = Some(colors.text_muted);
self.code_block.padding = EdgesRefinement {
top: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(12.)))),
left: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(12.)))),
right: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(12.)))),
bottom: Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(px(12.)))),
};
self.code_block.margin.top = Some(Length::Definite(px(16.).into()));
self.code_block.margin.bottom = Some(Length::Definite(px(16.).into()));
let code_block_corner_radius = AbsoluteLength::Pixels(px(6.));
self.code_block.corner_radii.top_left = Some(code_block_corner_radius);
self.code_block.corner_radii.top_right = Some(code_block_corner_radius);
self.code_block.corner_radii.bottom_left = Some(code_block_corner_radius);
self.code_block.corner_radii.bottom_right = Some(code_block_corner_radius);
self.heading.text.color = Some(colors.text);
self.heading.margin.top = Some(Length::Definite(px(24.).into()));
self.heading.margin.bottom = Some(Length::Definite(px(12.).into()));
let heading_text_style = |font_size: Rems| TextStyleRefinement {
font_size: Some(font_size.into()),
font_weight: Some(FontWeight::SEMIBOLD),
line_height: Some(relative(1.25)),
..Default::default()
};
self.heading_level_styles = Some(HeadingLevelStyles {
h1: Some(heading_text_style(rems(1.75))),
h2: Some(heading_text_style(rems(1.4))),
h3: Some(heading_text_style(rems(1.2))),
h4: Some(heading_text_style(rems(1.0))),
h5: Some(heading_text_style(rems(0.875))),
h6: Some(TextStyleRefinement {
color: Some(colors.text_muted),
..heading_text_style(rems(0.85))
}),
});
self.heading_border_color = Some(colors.border_variant);
self
}
pub fn with_buffer_font(mut self, cx: &App) -> Self {
let theme_settings = ThemeSettings::get_global(cx);
self.base_text_style.font_family = theme_settings.buffer_font.family.clone();
self.base_text_style.font_fallbacks = theme_settings.buffer_font.fallbacks.clone();
self.base_text_style.font_features = theme_settings.buffer_font.features.clone();
self.base_text_style.font_weight = theme_settings.buffer_font.weight;
self
}
pub fn with_agent_buffer_font(mut self, cx: &App) -> Self {
let theme_settings = ThemeSettings::get_global(cx);
self.base_text_style.font_family = theme_settings.agent_buffer_font_family().clone();
self.base_text_style.font_fallbacks = theme_settings.buffer_font.fallbacks.clone();
self.base_text_style.font_features = theme_settings.buffer_font.features.clone();
self.base_text_style.font_weight = theme_settings.buffer_font.weight;
self
}
pub fn with_muted_text(mut self, cx: &App) -> Self {
let colors = cx.theme().colors();
self.base_text_style.color = colors.text_muted;
self
}
}
/// Per-diagram view state, keyed by source offset in [`Markdown::mermaid_views`].
struct MermaidViewState {
/// Whether the source code is shown instead of the rendered diagram.
showing_code: bool,
/// The display scale relative to the diagram's natural size; 1.0 is 1:1.
zoom: f32,
/// Whether the user zoomed out to the fit-to-width floor. While set, the
/// zoom tracks the container width so the diagram stays fully visible
/// when the container is resized, instead of keeping a stale absolute
/// zoom computed against the old width.
zoomed_to_fit: bool,
/// Horizontal scroll position, used when the diagram overflows.
scroll_handle: ScrollHandle,
/// The pending debounced re-raster scheduled by the last zoom change.
debounce_task: Option<Task<()>>,
/// Overrides the scroll container width, which tests can't obtain from
/// the scroll handle since its bounds are only set during layout.
#[cfg(test)]
container_width_for_test: Option<Pixels>,
}
impl MermaidViewState {
/// The width of the diagram's scroll container as of the last layout,
/// if it has been laid out.
fn container_width(&self) -> Option<Pixels> {
#[cfg(test)]
if let Some(width) = self.container_width_for_test {
return Some(width);
}
Some(self.scroll_handle.bounds().size.width).filter(|width| *width > px(0.))
}
}
impl Default for MermaidViewState {
fn default() -> Self {
Self {
showing_code: false,
zoom: 1.0,
zoomed_to_fit: false,
scroll_handle: ScrollHandle::new(),
debounce_task: None,
#[cfg(test)]
container_width_for_test: None,
}
}
}
pub struct Markdown {
source: SharedString,
selection: Selection,
pressed_link: Option<RenderedLink>,
pressed_footnote_ref: Option<RenderedFootnoteRef>,
autoscroll_request: Option<usize>,
pending_heading_scroll: Option<SharedString>,
pending_autoscroll: Option<usize>,
active_root_block: Option<usize>,
parsed_markdown: ParsedMarkdown,
images_by_source_offset: HashMap<usize, Arc<Image>>,
should_reparse: bool,
pending_parse: Option<Task<()>>,
focus_handle: FocusHandle,
language_registry: Option<Arc<LanguageRegistry>>,
fallback_code_block_language: Option<LanguageName>,
options: MarkdownOptions,
mermaid_state: MermaidState,
_mermaid_theme_subscription: Option<Subscription>,
/// Per-diagram view state (current tab, zoom, scroll position, and pending
/// debounced re-raster) keyed by source offset. Distinct from
/// [`MermaidState`], which caches the rendered diagrams themselves keyed by
/// contents. All entries are retained against the parsed diagrams on each
/// reparse, so a single map keeps that bookkeeping in one place.
mermaid_views: HashMap<usize, MermaidViewState>,
copied_code_blocks: HashSet<ElementId>,
wrapped_code_blocks: HashSet<usize>,
code_block_scroll_handles: BTreeMap<usize, ScrollHandle>,
context_menu_link: Option<SharedString>,
context_menu_selected_text: Option<SharedString>,
context_menu_selected_markdown: Option<SharedString>,
search_highlights: Rc<[Range<usize>]>,
active_search_highlight: Option<usize>,
}
#[derive(Clone, Copy, Default)]
pub struct MarkdownOptions {
pub parse_links_only: bool,
pub parse_html: bool,
pub render_mermaid_diagrams: bool,
pub parse_heading_slugs: bool,
pub render_metadata_blocks: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum CopyButtonVisibility {
Hidden,
AlwaysVisible,
VisibleOnHover,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WrapButtonVisibility {
Hidden,
AlwaysVisible,
VisibleOnHover,
}
pub enum CodeBlockRenderer {
Default {
copy_button_visibility: CopyButtonVisibility,
wrap_button_visibility: WrapButtonVisibility,
border: bool,
},
Custom {
render: CodeBlockRenderFn,
/// A function that can modify the parent container after the code block
/// content has been appended as a child element.
transform: Option<CodeBlockTransformFn>,
},
}
pub type CodeBlockRenderFn = Arc<
dyn Fn(
&CodeBlockKind,
&ParsedMarkdown,
Range<usize>,
CodeBlockMetadata,
&mut Window,
&App,
) -> Div,
>;
pub type CodeBlockTransformFn =
Arc<dyn Fn(AnyDiv, Range<usize>, CodeBlockMetadata, &mut Window, &App) -> AnyDiv>;
actions!(
markdown,
[
/// Copies the selected text to the clipboard.
Copy,
/// Copies the selected text as markdown to the clipboard.
CopyAsMarkdown
]
);
enum EscapeAction {
PassThrough,
Nbsp(usize),
DoubleNewline,
PrefixBackslash,
}
impl EscapeAction {
fn output_len(&self, c: char) -> usize {
match self {
Self::PassThrough => c.len_utf8(),
Self::Nbsp(count) => count * '\u{00A0}'.len_utf8(),
Self::DoubleNewline => 2,
Self::PrefixBackslash => '\\'.len_utf8() + c.len_utf8(),
}
}
fn write_to(&self, c: char, output: &mut String) {
match self {
Self::PassThrough => output.push(c),
Self::Nbsp(count) => {
for _ in 0..*count {
output.push('\u{00A0}');
}
}
Self::DoubleNewline => {
output.push('\n');
output.push('\n');
}
Self::PrefixBackslash => {
// '\\' is a single backslash in Rust, e.g. '|' -> '\|'
output.push('\\');
output.push(c);
}
}
}
}
struct MarkdownEscaper {
in_leading_whitespace: bool,
}
impl MarkdownEscaper {
const TAB_SIZE: usize = 4;
fn new() -> Self {
Self {
in_leading_whitespace: true,
}
}
fn next(&mut self, c: char) -> EscapeAction {
let action = if self.in_leading_whitespace && c == '\t' {
EscapeAction::Nbsp(Self::TAB_SIZE)
} else if self.in_leading_whitespace && c == ' ' {
EscapeAction::Nbsp(1)
} else if c == '\n' {
EscapeAction::DoubleNewline
} else if c.is_ascii_punctuation() {
EscapeAction::PrefixBackslash
} else {
EscapeAction::PassThrough
};
self.in_leading_whitespace =
c == '\n' || (self.in_leading_whitespace && (c == ' ' || c == '\t'));
action
}
}
impl Markdown {
pub fn new(
source: SharedString,
language_registry: Option<Arc<LanguageRegistry>>,
fallback_code_block_language: Option<LanguageName>,
cx: &mut Context<Self>,
) -> Self {
Self::new_with_options(
source,
language_registry,
fallback_code_block_language,
MarkdownOptions::default(),
cx,
)
}
pub fn new_with_options(
source: SharedString,
language_registry: Option<Arc<LanguageRegistry>>,
fallback_code_block_language: Option<LanguageName>,
options: MarkdownOptions,
cx: &mut Context<Self>,
) -> Self {
let focus_handle = cx.focus_handle();
let theme_subscription = if options.render_mermaid_diagrams {
Some(
cx.observe_global::<theme::GlobalTheme>(|this: &mut Self, cx| {
this.invalidate_mermaid_cache(cx);
}),
)
} else {
None
};
let mut this = Self {
source,
selection: Selection::default(),
pressed_link: None,
pressed_footnote_ref: None,
autoscroll_request: None,
pending_heading_scroll: None,
pending_autoscroll: None,
active_root_block: None,
should_reparse: false,
images_by_source_offset: Default::default(),
parsed_markdown: ParsedMarkdown::default(),
pending_parse: None,
focus_handle,
language_registry,
fallback_code_block_language,
options,
mermaid_state: MermaidState::default(),
_mermaid_theme_subscription: theme_subscription,
mermaid_views: HashMap::default(),
copied_code_blocks: HashSet::default(),
wrapped_code_blocks: HashSet::default(),
code_block_scroll_handles: BTreeMap::default(),
context_menu_link: None,
context_menu_selected_text: None,
context_menu_selected_markdown: None,
search_highlights: Rc::default(),
active_search_highlight: None,
};
this.parse(cx);
this
}
pub fn new_text(source: SharedString, cx: &mut Context<Self>) -> Self {
Self::new_with_options(
source,
None,
None,
MarkdownOptions {
parse_links_only: true,
..Default::default()
},
cx,
)
}
fn is_code_block_wrapped(&self, id: usize) -> bool {
self.wrapped_code_blocks.contains(&id)
}
fn toggle_code_block_wrap(&mut self, id: usize) {
if !self.wrapped_code_blocks.remove(&id) {
self.wrapped_code_blocks.insert(id);
}
}
fn code_block_scroll_handle(&mut self, id: usize) -> Option<ScrollHandle> {
(!self.is_code_block_wrapped(id)).then(|| {
self.code_block_scroll_handles
.entry(id)
.or_insert_with(ScrollHandle::new)
.clone()
})
}
fn retain_code_block_scroll_handles(&mut self, ids: &HashSet<usize>) {
self.code_block_scroll_handles
.retain(|id, _| ids.contains(id));
}
pub fn invalidate_mermaid_cache(&mut self, cx: &mut Context<Self>) {
if !self.options.render_mermaid_diagrams || self.parsed_markdown.mermaid_diagrams.is_empty()
{
return;
}
self.mermaid_state.clear(cx);
let mermaid_views = &self.mermaid_views;
self.mermaid_state.update(
&self.parsed_markdown,
|source_offset| {
mermaid_views
.get(&source_offset)
.map_or(1.0, |view| view.zoom)
},
cx,
);
cx.notify();
}
pub(crate) fn is_mermaid_showing_code(&self, source_offset: usize) -> bool {
self.mermaid_views
.get(&source_offset)
.is_some_and(|view| view.showing_code)
}
pub(crate) fn toggle_mermaid_tab(&mut self, source_offset: usize) {
let view = self.mermaid_views.entry(source_offset).or_default();
view.showing_code = !view.showing_code;
}
pub(crate) fn mermaid_zoom_level(&self, source_offset: usize) -> f32 {
self.mermaid_views
.get(&source_offset)
.map_or(1.0, |view| view.zoom)
}
/// The smallest zoom level for a diagram: the scale that makes it span
/// the content width, capped at 1.0 so diagrams that already fit are
/// never zoomed out below their natural size. Falls back to 1.0 when the
/// diagram has no raster yet or the container hasn't been laid out.
fn mermaid_min_zoom_level(&self, source_offset: usize) -> f32 {
let Some(diagram) = self.parsed_markdown.mermaid_diagrams.get(&source_offset) else {
return 1.0;
};
let Some(natural_size) = self.mermaid_state.natural_size(&diagram.contents) else {
return 1.0;
};
let Some(container_width) = self
.mermaid_views
.get(&source_offset)
.and_then(|view| view.container_width())
else {
return 1.0;
};
if natural_size.width <= container_width {
return 1.0;
}
container_width / natural_size.width
}
pub(crate) fn set_mermaid_zoom_level(
&mut self,
source_offset: usize,
zoom: f32,
cx: &mut Context<Self>,
) {
let min_zoom = self.mermaid_min_zoom_level(source_offset);
let requested_zoom = zoom;
let mut zoom = zoom.clamp(min_zoom, MERMAID_MAX_ZOOM);
if (zoom - 1.0).abs() <= MERMAID_ZOOM_SNAP_TOLERANCE {
zoom = 1.0;
}
// The user zoomed out to (or past) the fit-to-width floor. From here
// on the zoom tracks the container width (see
// `effective_mermaid_zoom_level`), until the user zooms back in. A
// zoom landing exactly at 1.0 only sticks when it was clamped, so
// resetting to the natural size never turns tracking on.
let zoomed_to_fit = requested_zoom < min_zoom || (zoom <= min_zoom && zoom < 1.0);
let debounce_task = self.schedule_mermaid_rerasterize(source_offset, cx);
let view = self.mermaid_views.entry(source_offset).or_default();
view.zoom = zoom;
view.zoomed_to_fit = zoomed_to_fit;
view.debounce_task = Some(debounce_task);
cx.notify();
}
/// The zoom level to display a diagram at, syncing a fit-to-width zoom
/// with the current container width. Called at render time so that a
/// fully zoomed-out diagram stays stuck to the container width when the
/// container is resized, rather than keeping a stale absolute zoom.
pub(crate) fn effective_mermaid_zoom_level(
&mut self,
source_offset: usize,
cx: &mut Context<Self>,
) -> f32 {
let zoom = self.mermaid_zoom_level(source_offset);
let zoomed_to_fit = self
.mermaid_views
.get(&source_offset)
.is_some_and(|view| view.zoomed_to_fit);
if !zoomed_to_fit {
return zoom;
}
let min_zoom = self.mermaid_min_zoom_level(source_offset);
if (min_zoom - zoom).abs() < 0.001 {
return zoom;
}
let debounce_task = self.schedule_mermaid_rerasterize(source_offset, cx);
if let Some(view) = self.mermaid_views.get_mut(&source_offset) {
view.zoom = min_zoom;
view.debounce_task = Some(debounce_task);
}
min_zoom
}
/// Schedules a debounced re-raster of a diagram at its current zoom.
/// Storing the returned task in `MermaidViewState::debounce_task`
/// replaces (and thereby cancels) the previous timer, debouncing the
/// expensive re-raster until zoom changes settle. Until then, the
/// existing raster is displayed scaled to the new zoom.
fn schedule_mermaid_rerasterize(
&self,
source_offset: usize,
cx: &mut Context<Self>,
) -> Task<()> {
cx.spawn(async move |this, cx| {
cx.background_executor().timer(MERMAID_ZOOM_DEBOUNCE).await;
this.update(cx, |this, cx| {
if let Some(view) = this.mermaid_views.get_mut(&source_offset) {
view.debounce_task = None;
}
this.rerasterize_mermaid_diagram(source_offset, cx);
})
.ok();
})
}
pub(crate) fn mermaid_scroll_handle(&mut self, source_offset: usize) -> ScrollHandle {
self.mermaid_views
.entry(source_offset)
.or_default()
.scroll_handle
.clone()
}
/// Re-rasterizes a single mermaid diagram at exactly the scale it is
/// displayed at, reusing the cached parsed SVG so that neither mermaid
/// layout nor SVG parsing is re-run. While the new raster is pending, the
/// previous image keeps being displayed.
fn rerasterize_mermaid_diagram(&mut self, source_offset: usize, cx: &mut Context<Self>) {
let Some(diagram) = self.parsed_markdown.mermaid_diagrams.get(&source_offset) else {
return;
};
let contents = diagram.contents.clone();
let zoom = self.mermaid_zoom_level(source_offset);
self.mermaid_state.rerasterize_diagram(&contents, zoom, cx);
cx.notify();
}
fn clear_code_block_scroll_handles(&mut self) {
self.code_block_scroll_handles.clear();
}
fn autoscroll_code_block(&self, source_index: usize, cursor_position: Point<Pixels>) {
let Some((_, scroll_handle)) = self
.code_block_scroll_handles
.range(..=source_index)
.next_back()
else {
return;
};
let bounds = scroll_handle.bounds();
if cursor_position.y < bounds.top() || cursor_position.y > bounds.bottom() {
return;
}
let horizontal_delta = if cursor_position.x < bounds.left() {
bounds.left() - cursor_position.x
} else if cursor_position.x > bounds.right() {
bounds.right() - cursor_position.x
} else {
return;
};
let offset = scroll_handle.offset();
scroll_handle.set_offset(point(offset.x + horizontal_delta, offset.y));
}
pub fn is_parsing(&self) -> bool {
self.pending_parse.is_some()
}
pub fn scroll_to_heading_when_parsed(&mut self, slug: SharedString, cx: &mut Context<Self>) {
if self.pending_parse.is_some() || self.source.is_empty() {
self.pending_heading_scroll = Some(slug);
} else {
self.scroll_to_heading(&slug, cx);
}
}
pub fn scroll_to_heading(&mut self, slug: &str, cx: &mut Context<Self>) -> Option<usize> {
if let Some(source_index) = self.parsed_markdown.heading_slugs.get(slug).copied() {
self.autoscroll_request = Some(source_index);
cx.notify();
Some(source_index)
} else {
None
}
}
pub fn source(&self) -> &SharedString {
&self.source
}
pub fn non_rendered_source_ranges(&self) -> Vec<Range<usize>> {
if self.source != self.parsed_markdown.source {
return Vec::new();
}
self.parsed_markdown.non_rendered_source_ranges()
}
pub fn first_code_block_language(&self) -> Option<Arc<Language>> {
self.parsed_markdown.events.iter().find_map(|(_, event)| {
let MarkdownEvent::Start(MarkdownTag::CodeBlock { kind, .. }) = event else {
return None;
};
self.parsed_markdown.code_block_language(kind)
})
}
pub fn append(&mut self, text: &str, cx: &mut Context<Self>) {
self.source = SharedString::new(self.source.to_string() + text);
self.parse(cx);
}
pub fn replace(&mut self, source: impl Into<SharedString>, cx: &mut Context<Self>) {
self.source = source.into();
self.parse(cx);
}
pub fn request_autoscroll_to_source_index(
&mut self,
source_index: usize,
cx: &mut Context<Self>,
) {
if self.pending_parse.is_some() {