Skip to main content

egui_commonmark/
lib.rs

1//! A commonmark viewer for egui
2//!
3//! # Example
4//!
5//! ```
6//! # use egui_commonmark::*;
7//! # use egui::__run_test_ui;
8//! let markdown =
9//! r"# Hello world
10//!
11//! * A list
12//! * [ ] Checkbox
13//! ";
14//!
15//! # __run_test_ui(|ui| {
16//! let mut cache = CommonMarkCache::default();
17//! CommonMarkViewer::new().show(ui, &mut cache, markdown);
18//! # });
19//!
20//! ```
21//!
22//! Remember to opt into the image formats you want to use!
23//!
24//! ```toml
25//! image = { version = "0.25", default-features = false, features = ["png"] }
26//! ```
27//! # FAQ
28//!
29//! ## URL is not displayed when hovering over a link
30//!
31//! By default egui does not show urls when you hover hyperlinks. To enable it,
32//! you can do the following before calling any ui related functions:
33//!
34//! ```
35//! # use egui::__run_test_ui;
36//! # __run_test_ui(|ui| {
37//! ui.style_mut().url_in_tooltip = true;
38//! # });
39//! ```
40//!
41//!
42//! This maintained fork supports runtime Markdown parsing. Upstream compile-time
43//! Markdown macros are not included.
44#![cfg_attr(feature = "document-features", doc = "# Features")]
45#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
46
47use egui::{self, Id};
48
49mod parsers;
50
51pub use egui_commonmark_backend::RenderHtmlFn;
52pub use egui_commonmark_backend::RenderMathFn;
53pub use egui_commonmark_backend::alerts::{Alert, AlertBundle};
54pub use egui_commonmark_backend::misc::CommonMarkCache;
55
56#[cfg(feature = "better_syntax_highlighting")]
57pub use egui_commonmark_backend::syntect;
58
59use egui_commonmark_backend::*;
60
61#[derive(Debug, Default)]
62pub struct CommonMarkViewer<'f> {
63    options: CommonMarkOptions<'f>,
64}
65
66impl<'f> CommonMarkViewer<'f> {
67    pub fn new() -> Self {
68        Self::default()
69    }
70
71    /// Wrap prose, table cells, and code to the available width.
72    pub fn wrap(mut self, wrap: bool) -> Self {
73        self.options.wrap = wrap;
74        self
75    }
76
77    /// The amount of spaces a bullet point is indented. By default this is 4
78    /// spaces.
79    pub fn indentation_spaces(mut self, spaces: usize) -> Self {
80        self.options.indentation_spaces = spaces;
81        self
82    }
83
84    /// The maximum size images are allowed to be. They will be scaled down if
85    /// they are larger
86    pub fn max_image_width(mut self, width: Option<usize>) -> Self {
87        self.options.max_image_width = width;
88        self
89    }
90
91    /// The default width of the ui. This is only respected if this is larger than
92    /// the [`max_image_width`](Self::max_image_width)
93    pub fn default_width(mut self, width: Option<usize>) -> Self {
94        self.options.default_width = width;
95        self
96    }
97
98    /// Show alt text when hovering over images. By default this is enabled.
99    pub fn show_alt_text_on_hover(mut self, show: bool) -> Self {
100        self.options.show_alt_text_on_hover = show;
101        self
102    }
103
104    /// Allows changing the default implicit `file://` uri scheme.
105    /// This does nothing if [`explicit_image_uri_scheme`](`Self::explicit_image_uri_scheme`) is enabled
106    ///
107    /// # Example
108    /// ```
109    /// # use egui_commonmark::CommonMarkViewer;
110    /// CommonMarkViewer::new().default_implicit_uri_scheme("https://example.org/");
111    /// ```
112    pub fn default_implicit_uri_scheme<S: Into<String>>(mut self, scheme: S) -> Self {
113        self.options.default_implicit_uri_scheme = scheme.into();
114        self
115    }
116
117    /// By default any image without a uri scheme such as `foo://` is assumed to
118    /// be of the type `file://`. This assumption can sometimes be wrong or be done
119    /// incorrectly, so if you want to always be explicit with the scheme then set
120    /// this to `true`
121    pub fn explicit_image_uri_scheme(mut self, use_explicit: bool) -> Self {
122        self.options.use_explicit_uri_scheme = use_explicit;
123        self
124    }
125
126    #[cfg(feature = "better_syntax_highlighting")]
127    /// Set the syntax theme to be used inside code blocks in light mode
128    pub fn syntax_theme_light<S: Into<String>>(mut self, theme: S) -> Self {
129        self.options.theme_light = theme.into();
130        self
131    }
132
133    #[cfg(feature = "better_syntax_highlighting")]
134    /// Set the syntax theme to be used inside code blocks in dark mode
135    pub fn syntax_theme_dark<S: Into<String>>(mut self, theme: S) -> Self {
136        self.options.theme_dark = theme.into();
137        self
138    }
139
140    /// Specify what kind of alerts are supported. This can also be used to localize alerts.
141    ///
142    /// By default [github flavoured markdown style alerts](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#alerts)
143    /// are used
144    pub fn alerts(mut self, alerts: AlertBundle) -> Self {
145        self.options.alerts = alerts;
146        self
147    }
148
149    /// Allows rendering math. This has to be done manually as you might want a different
150    /// implementation for the web and native.
151    ///
152    /// The example is template code for rendering a svg image. Make sure to enable the
153    /// `egui_extras/svg` feature for the result to show up.
154    ///
155    /// ## Example
156    ///
157    /// ```
158    /// # use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};
159    /// # use egui_commonmark::CommonMarkViewer;
160    /// let mut math_images = Rc::new(RefCell::new(HashMap::new()));
161    /// CommonMarkViewer::new()
162    ///     .render_math_fn(Some(&move |ui, math, inline| {
163    ///         let mut map = math_images.borrow_mut();
164    ///         let svg = map
165    ///             .entry(math.to_string())
166    ///             .or_insert_with(|| {
167    ///                 if inline {
168    ///                     // render as inline
169    ///                     // dummy data for the example
170    ///                     Arc::new([0])
171    ///                 } else {
172    ///                     Arc::new([0])
173    ///                 }
174    ///             });
175    ///
176    ///     let uri = format!("{}.svg", egui::Id::from(math.to_string()).value());
177    ///     ui.add(
178    ///          egui::Image::new(egui::ImageSource::Bytes {
179    ///             uri: uri.into(),
180    ///             bytes: egui::load::Bytes::Shared(svg.clone()),
181    ///          })
182    ///          .fit_to_original_size(1.0),
183    ///     );
184    ///     }));
185    /// ```
186    pub fn render_math_fn(mut self, func: Option<&'f RenderMathFn>) -> Self {
187        self.options.math_fn = func;
188        self
189    }
190
191    /// Render a Mermaid diagram above its original source code block.
192    pub fn render_diagram_fn(mut self, func: Option<&'f dyn Fn(&mut egui::Ui, &str)>) -> Self {
193        self.options.diagram_fn = func;
194        self
195    }
196
197    /// Intercept images before any texture or network lookup.
198    pub fn image_gate(mut self, gate: Option<&'f egui_commonmark_backend::ImageGateFn>) -> Self {
199        self.options.image_gate = gate;
200        self
201    }
202
203    /// Allows custom handling of html. Enabling this will disable plain text rendering
204    /// of html blocks. Nodes are included in the provided text
205    pub fn render_html_fn(mut self, func: Option<&'f RenderHtmlFn>) -> Self {
206        self.options.html_fn = func;
207        self
208    }
209
210    /// Enable scrolling to headings by their ID.
211    /// 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.
212    pub fn enable_scroll_to_heading(mut self, enable: bool) -> Self {
213        self.options.enable_scroll_to_heading = enable;
214        self
215    }
216
217    /// Shows rendered markdown
218    pub fn show(
219        self,
220        ui: &mut egui::Ui,
221        cache: &mut CommonMarkCache,
222        text: &str,
223    ) -> egui::InnerResponse<()> {
224        egui_commonmark_backend::prepare_show(cache, ui.ctx());
225
226        let (response, _) = parsers::pulldown::CommonMarkViewerInternal::new().show(
227            ui,
228            cache,
229            &self.options,
230            text,
231            None,
232        );
233
234        response
235    }
236
237    /// Shows rendered markdown, and allows the rendered ui to mutate the source text.
238    ///
239    /// The only currently implemented mutation is allowing checkboxes to be toggled through the ui.
240    pub fn show_mut(
241        mut self,
242        ui: &mut egui::Ui,
243        cache: &mut CommonMarkCache,
244        text: &mut String,
245    ) -> egui::InnerResponse<()> {
246        self.options.mutable = true;
247        egui_commonmark_backend::prepare_show(cache, ui.ctx());
248
249        let (mut inner_response, checkmark_events) =
250            parsers::pulldown::CommonMarkViewerInternal::new().show(
251                ui,
252                cache,
253                &self.options,
254                text,
255                None,
256            );
257
258        // Update source text for checkmarks that were clicked
259        for ev in checkmark_events {
260            if ev.checked {
261                text.replace_range(ev.span, "[x]")
262            } else {
263                text.replace_range(ev.span, "[ ]")
264            }
265
266            inner_response.response.mark_changed();
267        }
268
269        inner_response
270    }
271
272    /// Shows markdown inside a [`ScrollArea`].
273    /// This function is much more performant than just calling [`show`] inside a [`ScrollArea`],
274    /// because it only renders elements that are visible.
275    ///
276    /// # Caveat
277    ///
278    /// This assumes that the markdown is static. If it does change, you have to clear the cache
279    /// by using [`clear_scrollable_with_id`](CommonMarkCache::clear_scrollable_with_id) or
280    /// [`clear_scrollable`](CommonMarkCache::clear_scrollable). If the content changes every frame,
281    /// it's faster to call [`show`] directly.
282    ///
283    /// [`ScrollArea`]: egui::ScrollArea
284    /// [`show`]: crate::CommonMarkViewer::show
285    #[doc(hidden)] // Buggy in scenarios more complex than the example application
286    #[cfg(feature = "pulldown_cmark")]
287    pub fn show_scrollable(
288        self,
289        source_id: impl egui::AsId,
290        ui: &mut egui::Ui,
291        cache: &mut CommonMarkCache,
292        text: &str,
293    ) {
294        egui_commonmark_backend::prepare_show(cache, ui.ctx());
295        parsers::pulldown::CommonMarkViewerInternal::new().show_scrollable(
296            Id::new(source_id),
297            ui,
298            cache,
299            &self.options,
300            text,
301        );
302    }
303}
304
305pub(crate) struct ListLevel {
306    current_number: Option<u64>,
307}
308
309#[derive(Default)]
310pub(crate) struct List {
311    items: Vec<ListLevel>,
312    has_list_begun: bool,
313}
314
315impl List {
316    pub fn start_level_with_number(&mut self, start_number: u64) {
317        self.items.push(ListLevel {
318            current_number: Some(start_number),
319        });
320    }
321
322    pub fn start_level_without_number(&mut self) {
323        self.items.push(ListLevel {
324            current_number: None,
325        });
326    }
327
328    pub fn is_inside_a_list(&self) -> bool {
329        !self.items.is_empty()
330    }
331
332    pub fn is_last_level(&self) -> bool {
333        self.items.len() == 1
334    }
335
336    pub fn start_item(&mut self, ui: &mut egui::Ui, options: &CommonMarkOptions) {
337        // To ensure that newlines are only inserted within the list and not before it
338        if self.has_list_begun {
339            newline(ui);
340        } else {
341            self.has_list_begun = true;
342        }
343
344        let len = self.items.len();
345        if let Some(item) = self.items.last_mut() {
346            ui.label(" ".repeat((len - 1) * options.indentation_spaces));
347
348            if let Some(number) = &mut item.current_number {
349                number_point(ui, &number.to_string());
350                *number += 1;
351            } else if len > 1 {
352                bullet_point_hollow(ui);
353            } else {
354                bullet_point(ui);
355            }
356        } else {
357            unreachable!();
358        }
359
360        ui.add_space(4.0);
361    }
362
363    pub fn end_level(&mut self, ui: &mut egui::Ui, insert_newline: bool) {
364        self.items.pop();
365
366        if self.items.is_empty() && insert_newline {
367            newline(ui);
368        }
369    }
370}