Skip to main content

egui_commonmark_backend/
misc.rs

1use crate::alerts::AlertBundle;
2use egui::{RichText, TextBuffer, TextStyle, Ui, text::LayoutJob};
3use std::collections::HashMap;
4
5use crate::pulldown::ScrollableCache;
6
7#[cfg(feature = "better_syntax_highlighting")]
8use syntect::{
9    easy::HighlightLines,
10    highlighting::{Theme, ThemeSet},
11    parsing::{SyntaxDefinition, SyntaxSet},
12    util::LinesWithEndings,
13};
14
15#[cfg(feature = "better_syntax_highlighting")]
16const DEFAULT_THEME_LIGHT: &str = "base16-ocean.light";
17#[cfg(feature = "better_syntax_highlighting")]
18const DEFAULT_THEME_DARK: &str = "base16-ocean.dark";
19
20pub struct CommonMarkOptions<'f> {
21    pub wrap: bool,
22    pub indentation_spaces: usize,
23    pub max_image_width: Option<usize>,
24    pub show_alt_text_on_hover: bool,
25    pub default_width: Option<usize>,
26    #[cfg(feature = "better_syntax_highlighting")]
27    pub theme_light: String,
28    #[cfg(feature = "better_syntax_highlighting")]
29    pub theme_dark: String,
30    pub use_explicit_uri_scheme: bool,
31    pub default_implicit_uri_scheme: String,
32    pub alerts: AlertBundle,
33    /// Whether to present a mutable ui for things like checkboxes
34    pub mutable: bool,
35    pub math_fn: Option<&'f crate::RenderMathFn>,
36    pub diagram_fn: Option<&'f dyn Fn(&mut Ui, &str)>,
37    pub html_fn: Option<&'f crate::RenderHtmlFn>,
38    pub image_gate: Option<&'f crate::ImageGateFn>,
39    /// Whether to enable scrolling to headings by their ID.
40    /// To give a heading an ID, use the syntax `# Heading {#myheadingid}`. Then links to `#myheadingid` e.g. `[click me!](#myheadingid)` will scroll to that heading.
41    pub enable_scroll_to_heading: bool,
42}
43
44impl std::fmt::Debug for CommonMarkOptions<'_> {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        let mut s = f.debug_struct("CommonMarkOptions");
47
48        s.field("indentation_spaces", &self.indentation_spaces)
49            .field("max_image_width", &self.max_image_width)
50            .field("show_alt_text_on_hover", &self.show_alt_text_on_hover)
51            .field("default_width", &self.default_width);
52
53        #[cfg(feature = "better_syntax_highlighting")]
54        s.field("theme_light", &self.theme_light)
55            .field("theme_dark", &self.theme_dark);
56
57        s.field("use_explicit_uri_scheme", &self.use_explicit_uri_scheme)
58            .field(
59                "default_implicit_uri_scheme",
60                &self.default_implicit_uri_scheme,
61            )
62            .field("alerts", &self.alerts)
63            .field("mutable", &self.mutable)
64            .finish()
65    }
66}
67
68impl Default for CommonMarkOptions<'_> {
69    fn default() -> Self {
70        Self {
71            wrap: true,
72            indentation_spaces: 4,
73            max_image_width: None,
74            show_alt_text_on_hover: true,
75            default_width: None,
76            #[cfg(feature = "better_syntax_highlighting")]
77            theme_light: DEFAULT_THEME_LIGHT.to_owned(),
78            #[cfg(feature = "better_syntax_highlighting")]
79            theme_dark: DEFAULT_THEME_DARK.to_owned(),
80            use_explicit_uri_scheme: false,
81            default_implicit_uri_scheme: "file://".to_owned(),
82            alerts: AlertBundle::gfm(),
83            mutable: false,
84            math_fn: None,
85            diagram_fn: None,
86            html_fn: None,
87            image_gate: None,
88            enable_scroll_to_heading: false,
89        }
90    }
91}
92
93impl CommonMarkOptions<'_> {
94    #[cfg(feature = "better_syntax_highlighting")]
95    pub fn curr_theme(&self, ui: &Ui) -> &str {
96        if ui.style().visuals.dark_mode {
97            &self.theme_dark
98        } else {
99            &self.theme_light
100        }
101    }
102
103    pub fn max_width(&self, ui: &Ui) -> f32 {
104        let available_width = ui.available_width();
105        let max_width = self
106            .max_image_width
107            .map_or(available_width, |width| available_width.min(width as f32));
108        if let Some(default_width) = self.default_width {
109            if default_width as f32 > max_width {
110                default_width as f32
111            } else {
112                max_width
113            }
114        } else {
115            max_width
116        }
117    }
118}
119
120#[derive(Default, Clone)]
121pub struct Style {
122    pub heading: Option<u8>,
123    pub strong: bool,
124    pub emphasis: bool,
125    pub strikethrough: bool,
126    pub quote: bool,
127    pub code: bool,
128}
129
130impl Style {
131    pub fn to_richtext(&self, ui: &Ui, text: &str) -> RichText {
132        let mut text = RichText::new(text);
133
134        if let Some(level) = self.heading {
135            let max_height = ui
136                .style()
137                .text_styles
138                .get(&TextStyle::Heading)
139                .map_or(32.0, |d| d.size);
140            let min_height = ui
141                .style()
142                .text_styles
143                .get(&TextStyle::Body)
144                .map_or(14.0, |d| d.size);
145            let diff = max_height - min_height;
146
147            match level {
148                0 => {
149                    text = text.strong().heading();
150                }
151                1 => {
152                    let size = min_height + diff * 0.835;
153                    text = text.strong().size(size);
154                }
155                2 => {
156                    let size = min_height + diff * 0.668;
157                    text = text.strong().size(size);
158                }
159                3 => {
160                    let size = min_height + diff * 0.501;
161                    text = text.strong().size(size);
162                }
163                4 => {
164                    let size = min_height + diff * 0.334;
165                    text = text.size(size);
166                }
167                // We only support 6 levels
168                5.. => {
169                    let size = min_height + diff * 0.167;
170                    text = text.size(size);
171                }
172            }
173        }
174
175        if self.quote {
176            text = text.weak();
177        }
178
179        if self.strong {
180            text = text.strong();
181        }
182
183        if self.emphasis {
184            // FIXME: Might want to add some space between the next text
185            text = text.italics();
186        }
187
188        if self.strikethrough {
189            text = text.strikethrough();
190        }
191
192        if self.code {
193            text = text.code();
194        }
195
196        text
197    }
198}
199
200#[derive(Default)]
201pub struct Link {
202    pub destination: String,
203    pub text: Vec<RichText>,
204}
205
206impl Link {
207    pub fn end(
208        self,
209        ui: &mut Ui,
210        cache: &mut CommonMarkCache,
211        _options: &CommonMarkOptions,
212        _scroll_to_heading: &mut Option<String>,
213    ) {
214        let Self { destination, text } = self;
215
216        // When a link wraps an image (`[![alt](img)](url)`), all text events are captured
217        // by the image widget and link.text is never populated. Rendering an empty Label in
218        // a wrapping layout resets cursor.min.x to 0, superimposing subsequent elements on
219        // the image that was just drawn. Nothing to render, so return early.
220        if text.is_empty() {
221            return;
222        }
223
224        let mut layout_job = LayoutJob::default();
225        for t in text {
226            t.append_to(
227                &mut layout_job,
228                ui.style(),
229                egui::FontSelection::Default,
230                egui::Align::LEFT,
231            );
232        }
233        for section in &mut layout_job.sections {
234            section.format.color = ui.visuals().hyperlink_color;
235            section.format.underline = egui::Stroke::new(1.0, ui.visuals().hyperlink_color);
236        }
237        let response = crate::navigation::label(ui, layout_job.into(), &mut cache.navigation, true)
238            .on_hover_cursor(egui::CursorIcon::PointingHand)
239            .on_hover_text(&destination);
240        if response.clicked() || response.middle_clicked() {
241            if cache.link_hooks().contains_key(&destination) {
242                cache.link_hooks_mut().insert(destination, true);
243            } else {
244                ui.ctx().open_url(egui::OpenUrl::new_tab(destination));
245            }
246        }
247    }
248}
249
250pub struct Image {
251    pub uri: String,
252    pub alt_text: Vec<RichText>,
253}
254
255impl Image {
256    // FIXME: string conversion
257    pub fn new(uri: &str, options: &CommonMarkOptions) -> Self {
258        let has_scheme = uri.contains("://") || uri.starts_with("data:");
259        let uri = if options.use_explicit_uri_scheme || has_scheme {
260            uri.to_string()
261        } else {
262            // Assume file scheme
263            format!("{}{uri}", options.default_implicit_uri_scheme)
264        };
265
266        Self {
267            uri,
268            alt_text: Vec::new(),
269        }
270    }
271
272    pub fn end(self, ui: &mut Ui, options: &CommonMarkOptions) {
273        let accessible_alt_text = self
274            .alt_text
275            .iter()
276            .map(egui::RichText::text)
277            .collect::<String>();
278        if options
279            .image_gate
280            .is_some_and(|gate| gate(ui, &self.uri, &accessible_alt_text))
281        {
282            return;
283        }
284        let image = egui::Image::from_uri(&self.uri)
285            .fit_to_original_size(1.0)
286            .max_width(options.max_width(ui))
287            .alt_text(&accessible_alt_text);
288        if let Err(error) = image.load_for_size(ui.ctx(), ui.available_size()) {
289            egui::Frame::group(ui.style()).show(ui, |ui| {
290                ui.horizontal_wrapped(|ui| {
291                    ui.spacing_mut().item_spacing.x = 6.0;
292                    let message = if accessible_alt_text.is_empty() {
293                        "Image unavailable".to_owned()
294                    } else {
295                        format!("Image unavailable: {accessible_alt_text}")
296                    };
297                    ui.label(message)
298                        .on_hover_text(format!("{}\n{error}", self.uri));
299                    if ui.small_button("Retry").clicked() {
300                        ui.ctx().forget_image(&self.uri);
301                        ui.ctx().request_repaint();
302                    }
303                });
304            });
305            return;
306        }
307        let response = ui.add(image);
308
309        if !self.alt_text.is_empty() && options.show_alt_text_on_hover {
310            response.on_hover_ui_at_pointer(|ui| {
311                for alt in self.alt_text {
312                    ui.label(alt);
313                }
314            });
315        }
316    }
317}
318
319pub struct CodeBlock {
320    pub lang: Option<String>,
321    pub content: String,
322}
323
324impl CodeBlock {
325    pub fn end(
326        &self,
327        ui: &mut Ui,
328        cache: &mut CommonMarkCache,
329        options: &CommonMarkOptions,
330        max_width: f32,
331    ) {
332        if self.lang.as_deref().is_some_and(|lang| {
333            lang.split_whitespace()
334                .next()
335                .is_some_and(|name| name.eq_ignore_ascii_case("mermaid"))
336        }) && let Some(render) = options.diagram_fn {
337            ui.vertical(|ui| {
338                render(ui, &self.content);
339                self.show_source(ui, cache, options, max_width);
340            });
341        } else {
342            self.show_source(ui, cache, options, max_width);
343        }
344    }
345
346    fn show_source(
347        &self,
348        ui: &mut Ui,
349        cache: &mut CommonMarkCache,
350        options: &CommonMarkOptions,
351        max_width: f32,
352    ) {
353        ui.scope(|ui| {
354            let position = ui.next_widget_position();
355            let highlighting = &mut cache.highlighting;
356            let mut layout = |ui: &Ui, string: &dyn TextBuffer, _wrap_width: f32| {
357                let mut job = if let Some(lang) = &self.lang {
358                    highlighting.layout(ui, position, lang, string.as_str())
359                } else {
360                    plain_highlighting(ui, string.as_str())
361                };
362
363                // Keep source text intact; only its layout changes with wrapping.
364                job.wrap.max_width = if options.wrap {
365                    (max_width - 16.0).max(1.0)
366                } else {
367                    f32::INFINITY
368                };
369                ui.fonts_mut(|f| f.layout_job(job))
370            };
371
372            crate::elements::code_block_with_navigation(
373                ui,
374                max_width,
375                &self.content,
376                &mut layout,
377                Some(&mut cache.navigation),
378            );
379            cache.navigation.separator("\n");
380        });
381    }
382}
383
384#[cfg(not(feature = "better_syntax_highlighting"))]
385#[allow(dead_code)]
386impl CodeBlock {
387    fn pre_syntax_highlighting(
388        _cache: &mut CommonMarkCache,
389        _options: &CommonMarkOptions,
390        ui: &mut Ui,
391    ) {
392        ui.style_mut().visuals.extreme_bg_color = ui.visuals().extreme_bg_color;
393    }
394
395    fn syntax_highlighting(
396        &self,
397        _cache: &mut CommonMarkCache,
398        _options: &CommonMarkOptions,
399        extension: &str,
400        ui: &Ui,
401        text: &str,
402    ) -> egui::text::LayoutJob {
403        simple_highlighting(ui, text, extension)
404    }
405}
406
407#[cfg(feature = "better_syntax_highlighting")]
408#[allow(dead_code)]
409impl CodeBlock {
410    fn pre_syntax_highlighting(
411        cache: &mut CommonMarkCache,
412        options: &CommonMarkOptions,
413        ui: &mut Ui,
414    ) {
415        let curr_theme = cache.curr_theme(ui, options);
416        let style = ui.style_mut();
417
418        style.visuals.extreme_bg_color = curr_theme
419            .settings
420            .background
421            .map(syntect_color_to_egui)
422            .unwrap_or(style.visuals.extreme_bg_color);
423
424        if let Some(color) = curr_theme.settings.selection_foreground {
425            style.visuals.selection.bg_fill = syntect_color_to_egui(color);
426        }
427    }
428
429    fn syntax_highlighting(
430        &self,
431        cache: &CommonMarkCache,
432        options: &CommonMarkOptions,
433        extension: &str,
434        ui: &Ui,
435        text: &str,
436    ) -> egui::text::LayoutJob {
437        if let Some(syntax) = cache.ps.find_syntax_by_extension(extension) {
438            let mut job = egui::text::LayoutJob::default();
439            let mut h = HighlightLines::new(syntax, cache.curr_theme(ui, options));
440
441            for line in LinesWithEndings::from(text) {
442                let ranges = h.highlight_line(line, &cache.ps).unwrap();
443                for v in ranges {
444                    let front = v.0.foreground;
445                    job.append(
446                        v.1,
447                        0.0,
448                        egui::TextFormat::simple(
449                            TextStyle::Monospace.resolve(ui.style()),
450                            syntect_color_to_egui(front),
451                        ),
452                    );
453                }
454            }
455
456            job
457        } else {
458            simple_highlighting(ui, text, extension)
459        }
460    }
461}
462
463fn simple_highlighting(ui: &Ui, text: &str, extension: &str) -> egui::text::LayoutJob {
464    egui_extras::syntax_highlighting::highlight(
465        ui.ctx(),
466        ui.style(),
467        &egui_extras::syntax_highlighting::CodeTheme::from_style(ui.style()),
468        text,
469        extension,
470    )
471}
472
473fn plain_highlighting(ui: &Ui, text: &str) -> egui::text::LayoutJob {
474    let mut job = egui::text::LayoutJob::default();
475    job.append(
476        text,
477        0.0,
478        egui::TextFormat::simple(
479            TextStyle::Monospace.resolve(ui.style()),
480            ui.style().visuals.text_color(),
481        ),
482    );
483    job
484}
485
486#[cfg(feature = "better_syntax_highlighting")]
487fn syntect_color_to_egui(color: syntect::highlighting::Color) -> egui::Color32 {
488    egui::Color32::from_rgb(color.r, color.g, color.b)
489}
490
491#[cfg(feature = "better_syntax_highlighting")]
492fn default_theme(ui: &Ui) -> &str {
493    if ui.style().visuals.dark_mode {
494        DEFAULT_THEME_DARK
495    } else {
496        DEFAULT_THEME_LIGHT
497    }
498}
499
500/// A cache used for storing content such as images.
501#[derive(Debug)]
502pub struct CommonMarkCache {
503    pub navigation: crate::navigation::Navigation,
504    pub(crate) highlighting: crate::highlighting::HighlightCache,
505    // Everything stored in `CommonMarkCache` must take into account that
506    // the cache is for multiple `CommonMarkviewer`s with different source_ids.
507    #[cfg(feature = "better_syntax_highlighting")]
508    ps: SyntaxSet,
509
510    #[cfg(feature = "better_syntax_highlighting")]
511    ts: ThemeSet,
512
513    /// The ID of the heading to scroll to. This is set when a link whose destination is a fragment (e.g. `#my-heading`) has been clicked.
514    scroll_to_id_target: Option<String>,
515    link_hooks: HashMap<String, bool>,
516
517    scroll: HashMap<egui::Id, ScrollableCache>,
518    pub(self) has_installed_loaders: bool,
519}
520
521#[allow(clippy::derivable_impls)]
522impl Default for CommonMarkCache {
523    fn default() -> Self {
524        Self {
525            #[cfg(feature = "better_syntax_highlighting")]
526            ps: SyntaxSet::load_defaults_newlines(),
527            #[cfg(feature = "better_syntax_highlighting")]
528            ts: ThemeSet::load_defaults(),
529            navigation: Default::default(),
530            highlighting: Default::default(),
531            link_hooks: HashMap::new(),
532            scroll: Default::default(),
533            scroll_to_id_target: None,
534            has_installed_loaders: false,
535        }
536    }
537}
538
539impl CommonMarkCache {
540    #[cfg(feature = "better_syntax_highlighting")]
541    pub fn add_syntax_from_folder(&mut self, path: &str) {
542        let mut builder = self.ps.clone().into_builder();
543        let _ = builder.add_from_folder(path, true);
544        self.ps = builder.build();
545    }
546
547    #[cfg(feature = "better_syntax_highlighting")]
548    pub fn add_syntax_from_str(
549        &mut self,
550        s: &str,
551        fallback_name: Option<&str>,
552    ) -> Result<(), syntect::parsing::ParseSyntaxError> {
553        let mut builder = self.ps.clone().into_builder();
554        SyntaxDefinition::load_from_str(s, true, fallback_name).map(|d| builder.add(d))?;
555        self.ps = builder.build();
556        Ok(())
557    }
558
559    #[cfg(feature = "better_syntax_highlighting")]
560    /// Add more color themes for code blocks(.tmTheme files). Set the color theme with
561    /// [`syntax_theme_dark`](CommonMarkViewer::syntax_theme_dark) and
562    /// [`syntax_theme_light`](CommonMarkViewer::syntax_theme_light)
563    pub fn add_syntax_themes_from_folder(
564        &mut self,
565        path: impl AsRef<std::path::Path>,
566    ) -> Result<(), syntect::LoadingError> {
567        self.ts.add_from_folder(path)
568    }
569
570    #[cfg(feature = "better_syntax_highlighting")]
571    /// Add color theme for code blocks(.tmTheme files). Set the color theme with
572    /// [`syntax_theme_dark`](CommonMarkViewer::syntax_theme_dark) and
573    /// [`syntax_theme_light`](CommonMarkViewer::syntax_theme_light)
574    pub fn add_syntax_theme_from_bytes(
575        &mut self,
576        name: impl Into<String>,
577        bytes: &[u8],
578    ) -> Result<(), syntect::LoadingError> {
579        let mut cursor = std::io::Cursor::new(bytes);
580        self.ts
581            .themes
582            .insert(name.into(), ThemeSet::load_from_reader(&mut cursor)?);
583        Ok(())
584    }
585
586    /// Get the desired fragment. This is the id which will be scrolled to if it is found in the markdown.
587    pub fn scroll_to_id_target(&self) -> Option<&str> {
588        self.scroll_to_id_target.as_deref()
589    }
590
591    /// Get mutable access to the desired fragment. Setting this will cause the viewer to scroll to the heading with this id if it exists. Setting it to None will prevent scrolling.
592    pub fn scroll_to_id_target_mut(&mut self) -> &mut Option<String> {
593        &mut self.scroll_to_id_target
594    }
595
596    /// Clear the cache for all scrollable elements
597    pub fn clear_scrollable(&mut self) {
598        self.scroll.clear();
599    }
600
601    /// Clear the cache for a specific scrollable viewer. Returns false if the
602    /// id was not in the cache.
603    pub fn clear_scrollable_with_id(&mut self, source_id: impl egui::AsId) -> bool {
604        self.scroll.remove(&egui::Id::new(source_id)).is_some()
605    }
606
607    /// If the user clicks on a link in the markdown render that has `name` as a link. The hook
608    /// specified with this method will be set to true. It's status can be acquired
609    /// with [`get_link_hook`](Self::get_link_hook). Be aware that all hook state is reset once
610    /// [`CommonMarkViewer::show`] gets called
611    ///
612    /// # Why use link hooks
613    ///
614    /// egui provides a method for checking links afterwards so why use this instead?
615    ///
616    /// ```rust
617    /// # use egui::__run_test_ctx;
618    /// # __run_test_ctx(|ctx| {
619    /// ctx.output_mut(|o| for command in &o.commands {
620    ///     matches!(command, egui::OutputCommand::OpenUrl(_));
621    /// });
622    /// # });
623    /// ```
624    ///
625    /// The main difference is that link hooks allows egui_commonmark to check for link hooks
626    /// while rendering. Normally when hovering over a link, egui_commonmark will display the full
627    /// url. With link hooks this feature is disabled, but to do that all hooks must be known.
628    // Works when displayed through egui_commonmark
629    #[allow(rustdoc::broken_intra_doc_links)]
630    pub fn add_link_hook<S: Into<String>>(&mut self, name: S) {
631        self.link_hooks.insert(name.into(), false);
632    }
633
634    /// Returns None if the link hook could not be found. Returns the last known status of the
635    /// hook otherwise.
636    pub fn remove_link_hook(&mut self, name: &str) -> Option<bool> {
637        self.link_hooks.remove(name)
638    }
639
640    /// Get status of link. Returns true if it was clicked
641    pub fn get_link_hook(&self, name: &str) -> Option<bool> {
642        self.link_hooks.get(name).copied()
643    }
644
645    /// Remove all link hooks
646    pub fn link_hooks_clear(&mut self) {
647        self.link_hooks.clear();
648    }
649
650    /// All link hooks
651    pub fn link_hooks(&self) -> &HashMap<String, bool> {
652        &self.link_hooks
653    }
654
655    /// Raw access to link hooks
656    pub fn link_hooks_mut(&mut self) -> &mut HashMap<String, bool> {
657        &mut self.link_hooks
658    }
659
660    /// Set all link hooks to false
661    fn deactivate_link_hooks(&mut self) {
662        for v in self.link_hooks.values_mut() {
663            *v = false;
664        }
665    }
666
667    #[cfg(feature = "better_syntax_highlighting")]
668    fn curr_theme(&self, ui: &Ui, options: &CommonMarkOptions) -> &Theme {
669        self.ts
670            .themes
671            .get(options.curr_theme(ui))
672            // Since we have called load_defaults, the default theme *should* always be available..
673            .unwrap_or_else(|| &self.ts.themes[default_theme(ui)])
674    }
675}
676
677pub fn scroll_cache<'a>(cache: &'a mut CommonMarkCache, id: &egui::Id) -> &'a mut ScrollableCache {
678    if !cache.scroll.contains_key(id) {
679        cache.scroll.insert(*id, Default::default());
680    }
681    cache.scroll.get_mut(id).unwrap()
682}
683
684/// Should be called before any rendering
685pub fn prepare_show(cache: &mut CommonMarkCache, ctx: &egui::Context) {
686    if !cache.has_installed_loaders {
687        // Even though the install function can be called multiple times, its not the cheapest
688        // so we ensure that we only call it once.
689        // This could be done at the creation of the cache, however it is better to keep the
690        // cache free from egui's Ui and Context types as this allows it to be created before
691        // any egui instances. It also keeps the API similar to before the introduction of the
692        // image loaders.
693        #[cfg(feature = "embedded_image")]
694        crate::data_url_loader::install_loader(ctx);
695
696        egui_extras::install_image_loaders(ctx);
697        cache.has_installed_loaders = true;
698    }
699
700    cache.deactivate_link_hooks();
701}