Skip to main content

markdown/
marks.rs

1//! The inline marks an app spells itself.
2//!
3//! [`Mark`](crate::Mark) is closed — bold, italic, strike, code, links — because
4//! every one of those has a spelling CommonMark already reads. Underline,
5//! highlight and a colour do not, so they cannot be variants here without this
6//! crate inventing markdown for everyone. An app that wants them registers a
7//! name and the delimiter that spells it, and the parse and the serializer take
8//! it from there:
9//!
10//! ```
11//! let marks = markdown::Marks::new().with("highlight", "==");
12//! let doc = markdown::parse_with("a ==lit== word", &marks);
13//! assert_eq!(markdown::serialize_with(&doc, &marks), "a ==lit== word");
14//! ```
15//!
16//! The registry is a *parameter* rather than a global because [`parse_with`]
17//! and [`serialize_with`] are pure — the same reason the highlighter is a
18//! function pointer rather than a dependency. [`set_marks`] is the gpui-side
19//! half, for the editing surface, which has a `cx` and no other way to know.
20//!
21//! A delimiter markdown already spells (`*`, `_`, `` ` ``, `~`, `[`) is yours to
22//! avoid: CommonMark reads it first and the registration never fires.
23//!
24//! [`parse_with`]: crate::parse_with
25//! [`serialize_with`]: crate::serialize_with
26
27use gpui::{App, FontWeight, Global, Hsla, SharedString};
28use theme::Theme;
29
30/// The custom marks a document is read and written with.
31#[derive(Clone, Debug, Default, PartialEq, Eq)]
32pub struct Marks {
33    entries: Vec<Entry>,
34}
35
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub(crate) struct Entry {
38    pub(crate) name: SharedString,
39    pub(crate) delimiter: SharedString,
40}
41
42impl Marks {
43    pub fn new() -> Self {
44        Self::default()
45    }
46
47    /// Register `name`, spelled by `delimiter` on both sides — `==lit==`.
48    ///
49    /// An empty delimiter, or a second registration of a name or a delimiter
50    /// already taken, is ignored: a registry that can hold two answers for one
51    /// spelling has no reading of a document to offer.
52    pub fn with(
53        mut self,
54        name: impl Into<SharedString>,
55        delimiter: impl Into<SharedString>,
56    ) -> Self {
57        let (name, delimiter) = (name.into(), delimiter.into());
58        let taken = self
59            .entries
60            .iter()
61            .any(|entry| entry.name == name || entry.delimiter == delimiter);
62        if !delimiter.is_empty() && !taken {
63            self.entries.push(Entry { name, delimiter });
64        }
65        self
66    }
67
68    pub fn is_empty(&self) -> bool {
69        self.entries.is_empty()
70    }
71
72    /// Every registered name, in the order they were added.
73    pub fn names(&self) -> impl Iterator<Item = &SharedString> {
74        self.entries.iter().map(|entry| &entry.name)
75    }
76
77    /// What spells `name`, for a caller writing its own markdown.
78    pub fn delimiter(&self, name: &str) -> Option<&str> {
79        self.entries
80            .iter()
81            .find(|entry| entry.name == name)
82            .map(|entry| entry.delimiter.as_ref())
83    }
84
85    /// The entries, longest delimiter first — `===` has to be tried before `==`
86    /// or it is never reached.
87    pub(crate) fn sorted(&self) -> Vec<&Entry> {
88        let mut entries: Vec<&Entry> = self.entries.iter().collect();
89        entries.sort_by_key(|entry| std::cmp::Reverse(entry.delimiter.len()));
90        entries
91    }
92
93    pub(crate) fn index(&self, ix: usize) -> Option<&Entry> {
94        self.entries.get(ix)
95    }
96
97    pub(crate) fn position(&self, entry: &Entry) -> Option<usize> {
98        self.entries.iter().position(|row| row == entry)
99    }
100
101    /// What the editing surface reads a document with, or nothing registered.
102    pub fn of(cx: &App) -> Self {
103        cx.try_global::<Installed>()
104            .map_or_else(Self::default, |installed| installed.0.clone())
105    }
106}
107
108struct Installed(Marks);
109
110impl Global for Installed {}
111
112/// `markdown::set_marks(cx, my_marks)` — call once at boot, so the editing
113/// surface reads and writes the same markdown the app's own calls do.
114pub fn set_marks(cx: &mut App, marks: Marks) {
115    cx.set_global(Installed(marks));
116}
117
118/// How a custom mark paints. Everything a [`gpui::TextRun`] can carry, and
119/// nothing a layout would have to move for.
120#[derive(Clone, Copy, Debug, Default, PartialEq)]
121pub struct MarkPaint {
122    pub color: Option<Hsla>,
123    pub background: Option<Hsla>,
124    pub weight: Option<FontWeight>,
125    pub italic: bool,
126    pub underline: bool,
127    pub strikethrough: bool,
128}
129
130/// What a registered mark looks like. `None` for a name this build does not
131/// paint, which reads as ordinary text.
132pub type Painter = fn(name: &str, theme: &Theme) -> Option<MarkPaint>;
133
134struct InstalledPaint(Painter);
135
136impl Global for InstalledPaint {}
137
138/// `markdown::set_mark_paint(cx, my_paint)` — call once at boot. Without it a
139/// custom mark round trips and paints as the text it wraps, which is what an
140/// unknown mark should look like rather than a hole.
141pub fn set_mark_paint(cx: &mut App, paint: Painter) {
142    cx.set_global(InstalledPaint(paint));
143}
144
145pub(crate) fn paint_of(cx: &App, name: &str, theme: &Theme) -> Option<MarkPaint> {
146    (cx.try_global::<InstalledPaint>()?.0)(name, theme)
147}