1use super::*;
4
5pub struct SourceText {
14 code: Arc<str>,
15 ranges: Rc<[Range<usize>]>,
16 hashes: Rc<[u64]>,
17 spans: Option<Rc<[Span]>>,
18 generation: u64,
21 highlighter: u64,
23 sized: RefCell<Option<Sized>>,
24}
25
26#[derive(Clone)]
28struct Sized {
29 at: (u32, Pixels, Pixels),
31 keys: Rc<[u64]>,
32 gaps: Rc<[Pixels]>,
33 guesses: Rc<[Guess]>,
34}
35
36pub struct SpanJob {
39 code: Arc<str>,
40 highlighter: Option<crate::Highlighter>,
41 generation: u64,
42}
43
44pub 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::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::highlight::generation(cx),
79 sized: RefCell::new(None),
80 }
81 }
82
83 pub fn text(&self) -> &str {
84 &self.code
85 }
86
87 pub fn lines(&self) -> usize {
89 self.ranges.len()
90 }
91
92 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 pub fn spans(&self) -> Option<&[(Range<usize>, theme::HighlightKind)]> {
103 self.spans.as_deref()
104 }
105
106 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 pub fn rehighlight(&mut self, cx: &App) -> Option<SpanJob> {
182 (self.highlighter != crate::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::highlight::generation(cx);
188 SpanJob {
189 code: self.code.clone(),
190 highlighter: crate::highlight::installed(cx),
191 generation: self.generation,
192 }
193 }
194
195 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
228fn 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
264fn 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
274pub fn render_source(source: &SourceText, editing: Editing, cx: &mut App) -> AnyElement {
284 let code: &str = &source.code;
285 let Editing {
286 selection,
287 caret_on,
288 layouts,
289 annotations,
290 typography,
291 keep,
292 scroll,
293 ..
294 } = editing;
295 let mut theme = Theme::of(cx).clone();
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 window_active: cx.active_window().is_some(),
309 layouts,
310 annotations,
311 placeholder: None,
312 caption: Caption::default(),
313 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 copy: CopyButton::Hidden,
324 base: None,
325 highlight: crate::marks::highlight_paint_of(cx),
326 find: crate::find::find_paint_of(cx),
327 comment: crate::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 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 = RowPaint {
385 hollow: !window.is_window_active(),
386 ..paint.clone()
387 };
388 let styled = code_line(&code[span.clone()], span.start, spans.as_deref(), &theme);
389 let layout = styled.layout().clone();
390 let sink = sink.clone();
391 let over = {
392 let (span, layout, paint) = (span.clone(), layout.clone(), paint.clone());
393 canvas(
394 |_, _, _| (),
395 move |_, _, window, _| paint.paint_over(&span, &layout, window),
396 )
397 .absolute()
398 .size_full()
399 };
400 let underlay = canvas(
401 |_, _, _| (),
402 move |_, _, window, _| {
403 sink.record(
404 0,
405 Part::Code,
406 span.clone(),
407 layout.clone(),
408 Shown::default(),
409 );
410 paint.paint_under(&span, &layout, window);
411 },
412 )
413 .absolute()
414 .size_full();
415 let text = div().relative().child(underlay).child(styled).child(over);
416 div()
417 .px(px(CODE_PADDING_X))
418 .child(gutter.row(index, text.into_any_element()))
419 .into_any_element()
420 }),
421 };
422 div()
423 .flex()
424 .flex_col()
425 .py(px(CODE_PADDING_Y))
426 .text_size(px(typography.code.size()))
427 .line_height(line)
428 .child(column)
429 .into_any_element()
430}
431
432#[derive(Clone)]
434struct Gutter {
435 shown: bool,
436 width: f32,
437 gap: f32,
438 color: Hsla,
439 font: SharedString,
440}
441
442impl Gutter {
443 fn new(
444 style: &crate::SourceStyle,
445 lines: usize,
446 typography: &Typography,
447 theme: &Theme,
448 ) -> Self {
449 let digits = lines.to_string().len().max(style.gutter_min_digits);
450 let gap = style.gutter_gap.max(0.0) * typography.code.size();
451 Self {
452 shown: style.line_numbers,
453 width: digits as f32 * typography.code.size() + gap,
454 gap,
455 color: style.gutter_color.unwrap_or(theme.text_faint),
456 font: theme.font_mono.clone(),
457 }
458 }
459
460 fn width(&self) -> f32 {
461 if self.shown { self.width } else { 0.0 }
462 }
463
464 fn row(&self, index: usize, line: AnyElement) -> AnyElement {
467 if !self.shown {
468 return line;
469 }
470 div()
471 .flex()
472 .items_start()
473 .child(
474 div()
475 .w(px(self.width))
476 .flex_shrink_0()
477 .pr(px(self.gap))
478 .font_family(self.font.clone())
479 .text_color(self.color)
480 .text_right()
481 .child((index + 1).to_string()),
482 )
483 .child(div().flex_1().min_w_0().child(line))
484 .into_any_element()
485 }
486}
487
488pub(super) fn code_lines(
491 language: Option<&str>,
492 code: &str,
493 overlay: Overlay,
494 typography: &Typography,
495 theme: &Theme,
496 cx: &App,
497) -> (AnyElement, AnyElement, Vec<AnyElement>) {
498 let ix = overlay.block;
499 let spans = crate::highlight::spans(cx, language, code).or_else(|| {
504 language
505 .filter(|language| crate::source::is_markdown(language))
506 .map(|_| crate::source::spans(code))
507 });
508 let paint = RowPaint::new(&overlay, code, typography.code.size(), theme);
513 let mut rows: Vec<(Range<usize>, TextLayout)> = Vec::new();
514 let mut offset = 0usize;
515 let lines: Vec<AnyElement> = code
516 .split('\n')
517 .map(|line| {
518 let start = offset;
519 offset += line.len() + 1;
520 let styled = code_line(line, start, spans.as_deref(), theme);
521 rows.push((start..start + line.len(), styled.layout().clone()));
522 styled.into_any_element()
523 })
524 .collect();
525
526 let sink = overlay.layouts.cloned();
527 let over = {
528 let (rows, paint) = (rows.clone(), paint.clone());
529 canvas(
530 |_, _, _| (),
531 move |_, _, window, _| {
532 for (span, layout) in &rows {
533 paint.paint_over(span, layout, window);
534 }
535 },
536 )
537 .absolute()
538 .size_full()
539 };
540 let underlay = canvas(
541 |_, _, _| (),
542 move |_, _, window, _| {
543 for (span, layout) in &rows {
544 if let Some(sink) = &sink {
545 sink.record(
546 ix,
547 Part::Code,
548 span.clone(),
549 layout.clone(),
550 Shown::default(),
551 );
552 }
553 paint.paint_under(span, layout, window);
554 }
555 },
556 )
557 .absolute()
558 .size_full();
559
560 (underlay.into_any_element(), over.into_any_element(), lines)
561}
562
563type Span = (Range<usize>, theme::HighlightKind);
565
566fn code_line(line: &str, start: usize, spans: Option<&[Span]>, theme: &Theme) -> StyledText {
571 let mono = font(theme.font_mono.clone());
572 let run = |len: usize, color: Hsla| TextRun {
573 len,
574 font: mono.clone(),
575 color,
576 background_color: None,
577 underline: None,
578 strikethrough: None,
579 };
580 let mut runs = Vec::new();
581 let mut pos = 0usize;
582 if let Some(spans) = spans {
583 let end = start + line.len();
584 for (range, kind) in spans.iter().filter(|(r, _)| r.end > start && r.start < end) {
585 let s = range.start.clamp(start, end) - start;
586 let e = range.end.min(end) - start;
587 if s > pos {
588 runs.push(run(s - pos, theme.text));
589 }
590 runs.push(run(e - s, theme.syntax.color(*kind)));
591 pos = e;
592 }
593 }
594 if pos < line.len() {
595 runs.push(run(line.len() - pos, theme.text));
596 }
597 if runs.is_empty() {
598 runs.push(run(0, theme.text));
599 }
600 StyledText::new(SharedString::from(line.to_string())).with_runs(runs)
601}
602
603#[derive(Clone)]
607struct RowPaint {
608 caret: Option<usize>,
609 glyph: Option<Range<usize>>,
611 affinity: Affinity,
612 shape: ui::input::CaretShape,
613 height: ui::input::CaretHeight,
614 hollow: bool,
615 font: SharedString,
616 selected: Option<Range<usize>>,
617 annotated: Vec<(Range<usize>, Hsla)>,
618 caret_color: Hsla,
619 cover: Hsla,
620 selection_color: Hsla,
621 code_size: f32,
622}
623
624impl RowPaint {
625 fn new(overlay: &Overlay, code: &str, code_size: f32, theme: &Theme) -> Self {
626 let caret = overlay.caret_painted();
627 Self {
628 caret,
629 glyph: caret.and_then(|offset| overlay.covered(code, offset)),
630 affinity: overlay.affinity(),
631 shape: overlay.caret_shape,
632 height: overlay.caret_height,
633 hollow: overlay.caret_hollow(),
634 font: theme.font_mono.clone(),
635 selected: overlay.selected(code.len()),
636 annotated: overlay.annotated(code.len(), theme),
637 caret_color: theme.caret,
638 cover: theme.bg,
639 selection_color: theme.selection,
640 code_size,
641 }
642 }
643
644 fn cut(&self) -> Option<&Range<usize>> {
646 self.glyph
647 .as_ref()
648 .filter(|_| self.shape.cuts_out(self.hollow))
649 }
650
651 fn paint_under(&self, span: &Range<usize>, layout: &TextLayout, window: &mut Window) {
652 let wash = |range: &Range<usize>, color: Hsla, window: &mut Window| {
653 let (from, to) = (range.start.max(span.start), range.end.min(span.end));
654 if from < to {
655 for rect in range_rects(layout, &(from - span.start..to - span.start), 0.0, 0.0) {
656 window.paint_quad(quad(
657 rect,
658 px(2.0),
659 color,
660 px(0.0),
661 gpui::transparent_black(),
662 BorderStyle::default(),
663 ));
664 }
665 }
666 };
667 for (range, color) in &self.annotated {
668 wash(range, *color, window);
669 }
670 if let Some(range) = &self.selected {
671 wash(range, self.selection_color, window);
672 }
673 }
674
675 fn paint_over(&self, span: &Range<usize>, layout: &TextLayout, window: &mut Window) {
676 if let Some(offset) = self.caret.filter(|at| span.contains(at) || *at == span.end) {
677 let glyph = self
678 .cut()
679 .map(|glyph| glyph.start - span.start..glyph.end - span.start);
680 paint_caret(
681 layout,
682 offset - span.start,
683 self.affinity,
684 glyph.as_ref(),
685 CaretPaint {
686 shape: self.shape,
687 height: self.height,
688 hollow: self.hollow,
689 color: self.caret_color,
690 cover: self.cover,
691 size: self.code_size,
692 face: font(self.font.clone()),
693 },
694 window,
695 );
696 }
697 }
698}
699
700pub(super) fn code_block(
701 language: Option<&str>,
702 code: &str,
703 overlay: Overlay,
704 typography: &Typography,
705 theme: &Theme,
706 window: &mut Window,
707 cx: &mut App,
708) -> AnyElement {
709 let ix = overlay.block;
710 let (underlay, over, lines) = code_lines(language, code, overlay, typography, theme, cx);
711 let body = code_body(
712 ix,
713 underlay,
714 over,
715 lines,
716 typography,
717 cx.markdown_layout().wrap_code,
718 );
719
720 fence_panel(theme)
721 .child(
725 fence_band(theme)
726 .text_color(match language {
727 Some(_) => theme.text_muted,
728 None => theme.text_faint,
729 })
730 .child(
734 div()
735 .relative()
736 .children(overlay.layouts.map(|layouts| {
737 let layouts = layouts.clone();
738 canvas(
739 move |bounds, _, _| layouts.record_language(ix, bounds),
740 |_, _, _, _| (),
741 )
742 .absolute()
743 .size_full()
744 }))
745 .child(SharedString::from(
746 language.unwrap_or(PLAIN_LANGUAGE).to_string(),
747 )),
748 ),
749 )
750 .child(body)
751 .children(
752 (overlay.copy == CopyButton::Shown).then(|| copy_button(code, ix, theme, window, cx)),
753 )
754 .into_any_element()
755}
756
757pub fn fence_panel(theme: &Theme) -> gpui::Div {
759 div()
760 .rounded(px(Theme::panel_radius()))
761 .bg(theme.ink(0.035))
762 .border_1()
763 .border_color(theme.border)
764 .overflow_hidden()
765 .relative()
766}
767
768pub fn fence_band(theme: &Theme) -> gpui::Div {
771 div()
772 .relative()
773 .flex()
774 .flex_row()
775 .items_center()
776 .px(px(CODE_PADDING_X))
777 .py(px(5.0))
778 .border_b_1()
779 .border_color(theme.border)
780 .bg(theme.ink(0.02))
781 .text_style(TextStyle::Subheadline)
782}
783
784pub(super) fn code_body(
786 ix: usize,
787 underlay: AnyElement,
788 over: AnyElement,
789 lines: Vec<AnyElement>,
790 typography: &Typography,
791 wrap: bool,
792) -> AnyElement {
793 let column = div()
794 .flex()
795 .flex_col()
796 .px(px(CODE_PADDING_X))
797 .children(lines);
798 let body = div()
799 .id(ElementId::named_usize("md-code", ix))
800 .relative()
801 .py(px(CODE_PADDING_Y))
802 .text_size(px(typography.code.size()))
803 .line_height(px(typography.code.line_height()))
804 .child(underlay);
805 if wrap {
806 body.child(column.w_full()).child(over).into_any_element()
809 } else {
810 ui::scroll::Viewport::new(
811 format!("md-code-scroll-{ix}"),
812 body.flex()
813 .flex_row()
814 .whitespace_nowrap()
815 .child(column.items_start())
822 .child(over),
823 gpui::Axis::Horizontal,
824 )
825 .into_any_element()
826 }
827}
828
829pub(crate) fn copy_button(
836 code: &str,
837 ix: usize,
838 theme: &Theme,
839 window: &mut Window,
840 cx: &mut App,
841) -> AnyElement {
842 let copied = window.use_keyed_state(ElementId::named_usize("md-copied", ix), cx, |_, _| false);
843 let showing = *copied.read(cx);
844 let text: SharedString = code.to_string().into();
845
846 div()
847 .id(ElementId::named_usize("md-copy", ix))
848 .absolute()
849 .top(px(3.0))
850 .right(px(5.0))
851 .h(px(20.0))
852 .px(px(6.0))
853 .rounded(px(5.0))
854 .flex()
855 .items_center()
856 .cursor_pointer()
857 .text_style(TextStyle::Caption)
858 .text_color(theme.text_muted)
859 .hover(|el| el.bg(theme.element_hover))
860 .child(if showing { "Copied" } else { "Copy" })
861 .on_click({
862 let copied = copied.clone();
863 move |_, _, cx| {
864 cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.to_string()));
865 copied.update(cx, |state, cx| {
866 *state = true;
867 cx.notify();
868 });
869 }
870 })
871 .on_hover(move |hovering, _, cx| {
872 if !*hovering && *copied.read(cx) {
873 copied.update(cx, |state, cx| {
874 *state = false;
875 cx.notify();
876 });
877 }
878 })
879 .into_any_element()
880}