Skip to main content

markdown/render/
source.rs

1//! Source mode.
2
3use super::*;
4
5/// A source text and what [`render_source`] reads off it every frame: its
6/// lines, a hash of each, and its highlight spans.
7///
8/// [`SourceText::new`] walks and highlights the whole text.
9/// [`SourceText::edit`] redoes only the lines an edit touched and shifts the
10/// spans around it; the [`SpanJob`] it answers highlights the new text in full,
11/// on any thread, for [`SourceText::set_spans`]. [`SourceText::rehighlight`]
12/// answers one when the installed highlighter has changed.
13pub struct SourceText {
14    code: Arc<str>,
15    ranges: Rc<[Range<usize>]>,
16    hashes: Rc<[u64]>,
17    spans: Option<Rc<[Span]>>,
18    /// Moved by every edit and rehighlight. A [`SpanJob`] carries the one it
19    /// was taken at.
20    generation: u64,
21    /// The highlighter generation the last [`SpanJob`], or the build, used.
22    highlighter: u64,
23    sized: RefCell<Option<Sized>>,
24}
25
26/// The per-line tables that also depend on what the text is set at.
27#[derive(Clone)]
28struct Sized {
29    /// The text size, line height and indent these were built for.
30    at: (u32, Pixels, Pixels),
31    keys: Rc<[u64]>,
32    gaps: Rc<[Pixels]>,
33    guesses: Rc<[Guess]>,
34}
35
36/// Highlighting a [`SourceText`] in full. `Send`, so it can run off the thread
37/// that paints.
38pub struct SpanJob {
39    code: Arc<str>,
40    highlighter: Option<crate::Highlighter>,
41    generation: u64,
42}
43
44/// What a [`SpanJob`] found, for [`SourceText::set_spans`].
45pub struct Spans {
46    spans: Option<Vec<Span>>,
47    generation: u64,
48}
49
50impl SpanJob {
51    pub fn run(self) -> Spans {
52        Spans {
53            spans: highlight_source(self.highlighter, &self.code),
54            generation: self.generation,
55        }
56    }
57}
58
59fn highlight_source(highlighter: Option<crate::Highlighter>, code: &str) -> Option<Vec<Span>> {
60    let language = crate::source::LANGUAGES[0];
61    highlighter
62        .and_then(|highlighter| highlighter(language, code))
63        .or_else(|| crate::source::is_markdown(language).then(|| crate::source::spans(code)))
64}
65
66impl SourceText {
67    pub fn new(code: impl Into<Arc<str>>, cx: &App) -> Self {
68        let code: Arc<str> = code.into();
69        let spans = highlight_source(crate::fence::highlight::installed(cx), &code).map(Into::into);
70        let ranges = split_lines(&code, 0..code.len());
71        let hashes = ranges.iter().map(|range| hash_line(&code, range)).collect();
72        Self {
73            code,
74            ranges: ranges.into(),
75            hashes,
76            spans,
77            generation: 0,
78            highlighter: crate::fence::highlight::generation(cx),
79            sized: RefCell::new(None),
80        }
81    }
82
83    pub fn text(&self) -> &str {
84        &self.code
85    }
86
87    /// Lines, counting the empty one after a trailing newline.
88    pub fn lines(&self) -> usize {
89        self.ranges.len()
90    }
91
92    /// The line holding byte `offset`; past the end, the last line.
93    pub fn line_of(&self, offset: usize) -> usize {
94        self.ranges
95            .partition_point(|range| range.end < offset)
96            .min(self.ranges.len() - 1)
97    }
98
99    /// The highlight spans, in bytes and in order. Between an [`Self::edit`]
100    /// and the [`Self::set_spans`] that follows it, the spans from before the
101    /// edit, shifted past it, and none over the bytes it replaced.
102    pub fn spans(&self) -> Option<&[(Range<usize>, theme::HighlightKind)]> {
103        self.spans.as_deref()
104    }
105
106    /// Make the text `code`. The change is taken to be the one run of bytes
107    /// between the longest prefix and suffix the two texts share. `None` when
108    /// the text is unchanged.
109    pub fn edit(&mut self, code: &str, cx: &App) -> Option<SpanJob> {
110        let old = self.code.as_bytes();
111        let new = code.as_bytes();
112        let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
113        if prefix == old.len() && prefix == new.len() {
114            return None;
115        }
116        let room = old.len().min(new.len()) - prefix;
117        let suffix = old
118            .iter()
119            .rev()
120            .zip(new.iter().rev())
121            .take(room)
122            .take_while(|(a, b)| a == b)
123            .count();
124        let old_end = old.len() - suffix;
125        let delta = (new.len() - suffix) as isize - old_end as isize;
126        let shift = |at: usize| at.wrapping_add_signed(delta);
127
128        let first = self.line_of(prefix);
129        let last = self.line_of(old_end);
130        let code: Arc<str> = code.into();
131        let lines = split_lines(
132            &code,
133            self.ranges[first].start..shift(self.ranges[last].end),
134        );
135        let hashes: Vec<u64> = lines.iter().map(|range| hash_line(&code, range)).collect();
136        let cut = first..last + 1;
137
138        if let Some(sized) = self.sized.get_mut() {
139            let (size, line, indent) = sized.at;
140            sized.keys = splice(
141                &sized.keys,
142                cut.clone(),
143                hashes.iter().map(|hash| key(*hash, size)),
144            );
145            sized.guesses = splice(
146                &sized.guesses,
147                cut.clone(),
148                lines.iter().map(|range| guess(range, line, indent)),
149            );
150            sized.gaps = vec![px(0.0); sized.keys.len()].into();
151        }
152        self.hashes = splice(&self.hashes, cut.clone(), hashes);
153        self.ranges = self.ranges[..first]
154            .iter()
155            .cloned()
156            .chain(lines)
157            .chain(
158                self.ranges[last + 1..]
159                    .iter()
160                    .map(|range| shift(range.start)..shift(range.end)),
161            )
162            .collect();
163        self.spans = self.spans.as_ref().map(|spans| {
164            let mut kept = Vec::with_capacity(spans.len());
165            for (range, kind) in spans.iter() {
166                if range.start < prefix {
167                    kept.push((range.start..range.end.min(prefix), *kind));
168                }
169                if range.end > old_end {
170                    kept.push((shift(range.start.max(old_end))..shift(range.end), *kind));
171                }
172            }
173            kept.into()
174        });
175        self.code = code;
176        Some(self.span_job(cx))
177    }
178
179    /// Highlight the text again if the installed highlighter has changed since
180    /// it was last highlighted. The spans stand until the job's land.
181    pub fn rehighlight(&mut self, cx: &App) -> Option<SpanJob> {
182        (self.highlighter != crate::fence::highlight::generation(cx)).then(|| self.span_job(cx))
183    }
184
185    fn span_job(&mut self, cx: &App) -> SpanJob {
186        self.generation += 1;
187        self.highlighter = crate::fence::highlight::generation(cx);
188        SpanJob {
189            code: self.code.clone(),
190            highlighter: crate::fence::highlight::installed(cx),
191            generation: self.generation,
192        }
193    }
194
195    /// Take what a [`SpanJob`] found. `false`, and nothing taken, when the text
196    /// has been edited or rehighlighted since the job was made.
197    pub fn set_spans(&mut self, spans: Spans) -> bool {
198        if spans.generation != self.generation {
199            return false;
200        }
201        self.spans = spans.spans.map(Into::into);
202        true
203    }
204
205    fn sized(&self, size: f32, line: Pixels, indent: Pixels) -> Sized {
206        let at = (size.to_bits(), line, indent);
207        let mut held = self.sized.borrow_mut();
208        if let Some(sized) = held.as_ref()
209            && sized.at == at
210        {
211            return sized.clone();
212        }
213        let sized = Sized {
214            at,
215            keys: self.hashes.iter().map(|hash| key(*hash, at.0)).collect(),
216            gaps: vec![px(0.0); self.ranges.len()].into(),
217            guesses: self
218                .ranges
219                .iter()
220                .map(|range| guess(range, line, indent))
221                .collect(),
222        };
223        *held = Some(sized.clone());
224        sized
225    }
226}
227
228/// The lines of `code` within `within`, which starts at a line's start and
229/// ends at a line's end.
230fn split_lines(code: &str, within: Range<usize>) -> Vec<Range<usize>> {
231    let mut ranges = Vec::new();
232    let mut at = within.start;
233    for line in code[within].split('\n') {
234        ranges.push(at..at + line.len());
235        at += line.len() + 1;
236    }
237    ranges
238}
239
240fn hash_line(code: &str, range: &Range<usize>) -> u64 {
241    let mut hasher = DefaultHasher::new();
242    "source".hash(&mut hasher);
243    code[range.clone()].hash(&mut hasher);
244    hasher.finish()
245}
246
247fn key(hash: u64, size: u32) -> u64 {
248    let mut hasher = DefaultHasher::new();
249    hash.hash(&mut hasher);
250    size.hash(&mut hasher);
251    hasher.finish()
252}
253
254fn guess(range: &Range<usize>, line: Pixels, indent: Pixels) -> Guess {
255    Guess {
256        chars: range.len(),
257        line,
258        rows: 0,
259        extra: px(0.0),
260        indent,
261    }
262}
263
264/// `old` with `cut` replaced by `new`.
265fn splice<T: Clone>(old: &[T], cut: Range<usize>, new: impl IntoIterator<Item = T>) -> Rc<[T]> {
266    old[..cut.start]
267        .iter()
268        .cloned()
269        .chain(new)
270        .chain(old[cut.end..].iter().cloned())
271        .collect()
272}
273
274/// Paint a document's own markdown source: a fence's caret, selection and hit
275/// testing, without a fence's box, band or copy button.
276///
277/// The caret is a [`Cursor`] at block 0 in [`Part::Code`] — what a document
278/// held as one fence answers to, which is how an editor holds its source.
279/// Wrapping is not optional here: a paragraph is one line of markdown, and a
280/// source view that scrolled sideways would hide most of it.
281///
282/// Set at [`Typography::body`]'s size and leading, in [`Theme::font_body`].
283pub fn render_source(source: &SourceText, editing: Editing, cx: &mut App) -> AnyElement {
284    let code: &str = &source.code;
285    let mut theme = editing.theme(cx);
286    let Editing {
287        selection,
288        caret_on,
289        layouts,
290        annotations,
291        typography,
292        keep,
293        scroll,
294        ..
295    } = editing;
296    theme.font_mono = theme.font_body.clone();
297    let mut typography = typography.unwrap_or_else(|| cx.typography());
298    typography.code = typography.body;
299    let overlay = Overlay {
300        block: 0,
301        part: Part::Code,
302        selection,
303        caret_on,
304        caret_shape: cx.caret_shape(),
305        caret_height: cx.caret_height(),
306        caret_inactive: cx.inactive_caret(),
307        // No window reaches here; a source view's rows read their own below.
308        window_active: cx.active_window().is_some(),
309        layouts,
310        annotations,
311        placeholder: None,
312        caption: Caption::default(),
313        // The source view is one fence and holds no task block.
314        toggle: None,
315        image: None,
316        image_menu: None,
317        image_overlay: None,
318        image_overlay_corner: ImageOverlayCorner::BottomRight,
319        fence: None,
320        sizing: None,
321        table_controls: false,
322        // It paints no band, so there is nowhere for the button to float.
323        copy: CopyButton::Hidden,
324        base: None,
325        highlight: crate::paint::marks::highlight_paint_of(cx),
326        find: crate::paint::find::find_paint_of(cx),
327        comment: crate::paint::comment::comment_paint_of(cx),
328        jump: None,
329    };
330    let style = cx.source_style();
331    let count = source.ranges.len();
332    let gutter = Gutter::new(&style, count, &typography, &theme);
333
334    let Some(layouts) = layouts else {
335        let (underlay, over, lines) = code_lines(
336            Some(crate::source::LANGUAGES[0]),
337            code,
338            overlay,
339            &typography,
340            &theme,
341            cx,
342        );
343        let lines = lines
344            .into_iter()
345            .enumerate()
346            .map(|(index, line)| gutter.row(index, line))
347            .collect();
348        return div()
349            .flex()
350            .flex_col()
351            .child(code_body(0, underlay, over, lines, &typography, true))
352            .into_any_element();
353    };
354
355    // Built a line at a time by the same column the blocks are: a line is to
356    // this text what a block is to a document.
357    let spans = source.spans.clone();
358    let ranges = source.ranges.clone();
359    let mut kept: Vec<usize> = keep.to_vec();
360    if let Some(selection) = selection {
361        kept.push(source.line_of(selection.head.offset));
362        kept.push(source.line_of(selection.anchor.offset));
363    }
364    let line = px(typography.code.line_height());
365    let indent = px(gutter.width() + 2.0 * CODE_PADDING_X);
366    let sized = source.sized(typography.code.size(), line, indent);
367    layouts.prune(&sized.keys);
368    let paint = RowPaint::new(&overlay, code, typography.code.size(), &theme);
369    let code = source.code.clone();
370    let sink = layouts.clone();
371    let column = Column {
372        layouts: layouts.clone(),
373        keys: sized.keys,
374        gaps: sized.gaps,
375        guesses: sized.guesses,
376        keep: kept,
377        scroll: scroll.cloned(),
378        item_of: {
379            let ranges = ranges.clone();
380            Rc::new(move |at| ranges.partition_point(|line| line.end < at.offset))
381        },
382        build: Box::new(move |index, window, _| {
383            let span = ranges[index].clone();
384            let paint = paint.hollow(!window.is_window_active());
385            let (styled, runs) =
386                code_line(&code[span.clone()], span.start, spans.as_deref(), &theme);
387            let layout = styled.layout().clone();
388            let sink = sink.clone();
389            let over = {
390                let (span, layout, paint) = (span.clone(), layout.clone(), paint.clone());
391                canvas(
392                    |_, _, _| (),
393                    move |_, _, window, _| paint.paint_over(&span, &layout, &runs, window),
394                )
395                .absolute()
396                .size_full()
397            };
398            let underlay = canvas(
399                |_, _, _| (),
400                move |_, _, window, _| {
401                    sink.record(
402                        0,
403                        Part::Code,
404                        span.clone(),
405                        layout.clone(),
406                        Shown::default(),
407                    );
408                    paint.paint_under(&span, &layout, window);
409                },
410            )
411            .absolute()
412            .size_full();
413            let text = div().relative().child(underlay).child(styled).child(over);
414            div()
415                .px(px(CODE_PADDING_X))
416                .child(gutter.row(index, text.into_any_element()))
417                .into_any_element()
418        }),
419    };
420    div()
421        .flex()
422        .flex_col()
423        .py(px(CODE_PADDING_Y))
424        .text_size(px(typography.code.size()))
425        .line_height(line)
426        .child(column)
427        .into_any_element()
428}
429
430/// The line numbers beside a source view, when it shows them.
431#[derive(Clone)]
432struct Gutter {
433    shown: bool,
434    width: f32,
435    gap: f32,
436    color: Hsla,
437    font: SharedString,
438}
439
440impl Gutter {
441    fn new(
442        style: &crate::SourceStyle,
443        lines: usize,
444        typography: &Typography,
445        theme: &Theme,
446    ) -> Self {
447        let digits = lines.to_string().len().max(style.gutter_min_digits);
448        let gap = style.gutter_gap.max(0.0) * typography.code.size();
449        Self {
450            shown: style.line_numbers,
451            width: digits as f32 * typography.code.size() + gap,
452            gap,
453            color: style.gutter_color.unwrap_or(theme.text_faint),
454            font: theme.font_mono.clone(),
455        }
456    }
457
458    fn width(&self) -> f32 {
459        if self.shown { self.width } else { 0.0 }
460    }
461
462    /// Keeps each number beside its source line, including wrapped and empty
463    /// lines.
464    fn row(&self, index: usize, line: AnyElement) -> AnyElement {
465        if !self.shown {
466            return line;
467        }
468        div()
469            .flex()
470            .items_start()
471            .child(
472                div()
473                    .w(px(self.width))
474                    .flex_shrink_0()
475                    .pr(px(self.gap))
476                    .font_family(self.font.clone())
477                    .text_color(self.color)
478                    .text_right()
479                    .child((index + 1).to_string()),
480            )
481            .child(div().flex_1().min_w_0().child(line))
482            .into_any_element()
483    }
484}