egui_commonmark/lib.rs
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
//! A commonmark viewer for egui
//!
//! # Example
//!
//! ```
//! # use egui_commonmark::*;
//! # use egui::__run_test_ui;
//! let markdown =
//! r"# Hello world
//!
//! * A list
//! * [ ] Checkbox
//! ";
//!
//! # __run_test_ui(|ui| {
//! let mut cache = CommonMarkCache::default();
//! CommonMarkViewer::new().show(ui, &mut cache, markdown);
//! # });
//!
//! ```
//!
//! Remember to opt into the image formats you want to use!
//!
//! ```toml
//! image = { version = "0.25", default-features = false, features = ["png"] }
//! ```
//!
//! By default egui does not show urls when you hover hyperlinks. To enable it,
//! you can do the following before calling any ui related functions:
//!
//! ```
//! # use egui::__run_test_ui;
//! # __run_test_ui(|ui| {
//! ui.style_mut().url_in_tooltip = true;
//! # });
//! ```
//!
//!
//! # Compile time evaluation of markdown
//!
//! If you want to embed markdown directly the binary then you can enable the `macros` feature.
//! This will do the parsing of the markdown at compile time and output egui widgets.
//!
//! ## Example
//!
//! ```
//! use egui_commonmark::{CommonMarkCache, commonmark};
//! # egui::__run_test_ui(|ui| {
//! let mut cache = CommonMarkCache::default();
//! let _response = commonmark!(ui, &mut cache, "# ATX Heading Level 1");
//! # });
//! ```
//!
//! Alternatively you can embed a file
//!
//!
//! ## Example
//!
//! ```rust,ignore
//! use egui_commonmark::{CommonMarkCache, commonmark_str};
//! # egui::__run_test_ui(|ui| {
//! let mut cache = CommonMarkCache::default();
//! commonmark_str!(ui, &mut cache, "content.md");
//! # });
//! ```
//!
//! For more information check out the documentation for
//! [egui_commonmark_macros](https://docs.rs/crate/egui_commonmark_macros/latest)
#![cfg_attr(feature = "document-features", doc = "# Features")]
#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]
use egui::{self, Id};
mod parsers;
pub use egui_commonmark_backend::alerts::{Alert, AlertBundle};
pub use egui_commonmark_backend::misc::CommonMarkCache;
#[cfg(feature = "macros")]
pub use egui_commonmark_macros::*;
#[cfg(feature = "macros")]
// Do not rely on this directly!
#[doc(hidden)]
pub use egui_commonmark_backend;
use egui_commonmark_backend::*;
#[derive(Debug, Default)]
pub struct CommonMarkViewer {
options: CommonMarkOptions,
}
impl CommonMarkViewer {
pub fn new() -> Self {
Self::default()
}
/// The amount of spaces a bullet point is indented. By default this is 4
/// spaces.
pub fn indentation_spaces(mut self, spaces: usize) -> Self {
self.options.indentation_spaces = spaces;
self
}
/// The maximum size images are allowed to be. They will be scaled down if
/// they are larger
pub fn max_image_width(mut self, width: Option<usize>) -> Self {
self.options.max_image_width = width;
self
}
/// The default width of the ui. This is only respected if this is larger than
/// the [`max_image_width`](Self::max_image_width)
pub fn default_width(mut self, width: Option<usize>) -> Self {
self.options.default_width = width;
self
}
/// Show alt text when hovering over images. By default this is enabled.
pub fn show_alt_text_on_hover(mut self, show: bool) -> Self {
self.options.show_alt_text_on_hover = show;
self
}
/// Allows changing the default implicit `file://` uri scheme.
/// This does nothing if [`explicit_image_uri_scheme`](`Self::explicit_image_uri_scheme`) is enabled
///
/// # Example
/// ```
/// # use egui_commonmark::CommonMarkViewer;
/// CommonMarkViewer::new().default_implicit_uri_scheme("https://example.org/");
/// ```
pub fn default_implicit_uri_scheme<S: Into<String>>(mut self, scheme: S) -> Self {
self.options.default_implicit_uri_scheme = scheme.into();
self
}
/// By default any image without a uri scheme such as `foo://` is assumed to
/// be of the type `file://`. This assumption can sometimes be wrong or be done
/// incorrectly, so if you want to always be explicit with the scheme then set
/// this to `true`
pub fn explicit_image_uri_scheme(mut self, use_explicit: bool) -> Self {
self.options.use_explicit_uri_scheme = use_explicit;
self
}
#[cfg(feature = "better_syntax_highlighting")]
/// Set the syntax theme to be used inside code blocks in light mode
pub fn syntax_theme_light<S: Into<String>>(mut self, theme: S) -> Self {
self.options.theme_light = theme.into();
self
}
#[cfg(feature = "better_syntax_highlighting")]
/// Set the syntax theme to be used inside code blocks in dark mode
pub fn syntax_theme_dark<S: Into<String>>(mut self, theme: S) -> Self {
self.options.theme_dark = theme.into();
self
}
/// Specify what kind of alerts are supported. This can also be used to localize alerts.
///
/// 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)
/// are used
pub fn alerts(mut self, alerts: AlertBundle) -> Self {
self.options.alerts = alerts;
self
}
/// Shows rendered markdown
pub fn show(
self,
ui: &mut egui::Ui,
cache: &mut CommonMarkCache,
text: &str,
) -> egui::InnerResponse<()> {
egui_commonmark_backend::prepare_show(cache, ui.ctx());
let (response, _) = parsers::pulldown::CommonMarkViewerInternal::new().show(
ui,
cache,
&self.options,
text,
None,
);
response
}
/// Shows rendered markdown, and allows the rendered ui to mutate the source text.
///
/// The only currently implemented mutation is allowing checkboxes to be toggled through the ui.
pub fn show_mut(
mut self,
ui: &mut egui::Ui,
cache: &mut CommonMarkCache,
text: &mut String,
) -> egui::InnerResponse<()> {
self.options.mutable = true;
egui_commonmark_backend::prepare_show(cache, ui.ctx());
let (response, checkmark_events) = parsers::pulldown::CommonMarkViewerInternal::new().show(
ui,
cache,
&self.options,
text,
None,
);
// Update source text for checkmarks that were clicked
for ev in checkmark_events {
if ev.checked {
text.replace_range(ev.span, "[x]")
} else {
text.replace_range(ev.span, "[ ]")
}
}
response
}
/// Shows markdown inside a [`ScrollArea`].
/// This function is much more performant than just calling [`show`] inside a [`ScrollArea`],
/// because it only renders elements that are visible.
///
/// # Caveat
///
/// This assumes that the markdown is static. If it does change, you have to clear the cache
/// by using [`clear_scrollable_with_id`](CommonMarkCache::clear_scrollable_with_id) or
/// [`clear_scrollable`](CommonMarkCache::clear_scrollable). If the content changes every frame,
/// it's faster to call [`show`] directly.
///
/// [`ScrollArea`]: egui::ScrollArea
/// [`show`]: crate::CommonMarkViewer::show
#[doc(hidden)] // Buggy in scenarios more complex than the example application
#[cfg(feature = "pulldown_cmark")]
pub fn show_scrollable(
self,
source_id: impl std::hash::Hash,
ui: &mut egui::Ui,
cache: &mut CommonMarkCache,
text: &str,
) {
egui_commonmark_backend::prepare_show(cache, ui.ctx());
parsers::pulldown::CommonMarkViewerInternal::new().show_scrollable(
Id::new(source_id),
ui,
cache,
&self.options,
text,
);
}
}
pub(crate) struct ListLevel {
current_number: Option<u64>,
}
#[derive(Default)]
pub(crate) struct List {
items: Vec<ListLevel>,
has_list_begun: bool,
}
impl List {
pub fn start_level_with_number(&mut self, start_number: u64) {
self.items.push(ListLevel {
current_number: Some(start_number),
});
}
pub fn start_level_without_number(&mut self) {
self.items.push(ListLevel {
current_number: None,
});
}
pub fn is_inside_a_list(&self) -> bool {
!self.items.is_empty()
}
pub fn start_item(&mut self, ui: &mut egui::Ui, options: &CommonMarkOptions) {
// To ensure that newlines are only inserted within the list and not before it
if self.has_list_begun {
newline(ui);
} else {
self.has_list_begun = true;
}
let len = self.items.len();
if let Some(item) = self.items.last_mut() {
ui.label(" ".repeat((len - 1) * options.indentation_spaces));
if let Some(number) = &mut item.current_number {
number_point(ui, &number.to_string());
*number += 1;
} else if len > 1 {
bullet_point_hollow(ui);
} else {
bullet_point(ui);
}
} else {
unreachable!();
}
ui.add_space(4.0);
}
pub fn end_level(&mut self, ui: &mut egui::Ui, insert_newline: bool) {
self.items.pop();
if self.items.is_empty() && insert_newline {
newline(ui);
}
}
}