1use std::{
2 borrow::Cow,
3 collections::HashMap,
4 ops::Range,
5 sync::{Arc, Mutex, OnceLock},
6};
7
8use gpui::{
9 AnyElement, App, Axis, Bounds, DefiniteLength, Div, Element, ElementId, FontStyle, FontWeight,
10 GlobalElementId, HighlightStyle, Hsla, Image, ImageFormat, ImageSource, InspectorElementId,
11 InteractiveElement as _, IntoElement, IsZero as _, LayoutId, ObjectFit, Overflow,
12 ParentElement, Pixels, Point, Refineable as _, Rems, ScrollHandle, SharedString, SharedUri,
13 StatefulInteractiveElement, StyleRefinement, Styled, StyledImage as _, TextStyleRefinement,
14 WhiteSpace, Window, div, img, prelude::FluentBuilder as _, px, relative, rems,
15};
16use markdown::mdast;
17
18use crate::{
19 GlobalState, ScrollableMask, Scrollbar, StyledExt, h_flex,
20 scrollable_mask::horizontal_scroll_area,
21 text::{
22 CodeBlockActionsFn, CodeBlockHighlighterFn, Link, LinkClickHandlerFn, LinkFn,
23 MarkdownExtensions, MarkdownNode, TableActionsFn, TaskToggleEvent, TaskToggleHandlerFn,
24 document::{NodeRenderOptions, PrevBlock, flow_position},
25 inline::{
26 Inline, InlineHighlight, InlineState, code_insets, combine_highlights, fade_highlights,
27 foreground_highlights, point_in_text_selection, text_runs, text_size_ranges,
28 },
29 inline_flow::{InlineFlow, InlineFlowItem, slice_ranges},
30 range_highlight::{RangeHighlightFrame, RevealAt, RevealRequest},
31 stream_fade::{StreamFadeFrame, TextLeafKey},
32 text_view::linked_image,
33 },
34 theme::ActiveTheme as _,
35};
36
37use super::{
38 SelectionFormat, TextViewStyle,
39 utils::{data_url_image, list_item_prefix, ordered_list_ordinal},
40};
41
42const CHECK_SVG_LIGHT: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none"><path d="m3.25 8.25 3 3 6.5-7" stroke="white" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>"#;
43const CHECK_SVG_DARK: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none"><path d="m3.25 8.25 3 3 6.5-7" stroke="black" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>"#;
44
45#[derive(Debug, Clone, PartialEq)]
52#[non_exhaustive]
53pub enum BlockNode {
54 Root {
56 children: Vec<BlockNode>,
57 span: Option<Span>,
58 },
59 Paragraph(Paragraph),
60 Heading {
61 level: u8,
62 children: Paragraph,
63 span: Option<Span>,
64 },
65 Blockquote {
66 children: Vec<BlockNode>,
67 span: Option<Span>,
68 },
69 Surface {
76 name: SharedString,
78 children: Vec<BlockNode>,
79 span: Option<Span>,
81 },
82 List {
83 children: Vec<BlockNode>,
85 ordered: bool,
86 start: Option<u32>,
88 span: Option<Span>,
89 },
90 ListItem {
91 children: Vec<BlockNode>,
92 spread: bool,
93 checked: Option<bool>,
95 task_marker: Option<Span>,
97 span: Option<Span>,
98 },
99 CodeBlock(CodeBlock),
100 Custom {
102 node: MarkdownNode,
103 state: BlockState,
104 },
105 Table(Table),
106 Break {
107 html: bool,
108 span: Option<Span>,
109 },
110 HorizontalRule {
111 span: Option<Span>,
112 },
113 Definition {
115 identifier: SharedString,
116 url: SharedString,
117 title: Option<SharedString>,
118 span: Option<Span>,
119 },
120 Unknown,
121}
122
123#[derive(Debug, Clone, Default)]
128pub struct BlockState {
129 selection: Arc<Mutex<Option<BlockSelection>>>,
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134enum BlockSelection {
135 Empty,
136 Full,
137}
138
139impl BlockState {
140 fn selection(&self) -> Option<BlockSelection> {
141 self.selection.lock().ok().and_then(|selection| *selection)
142 }
143
144 fn set_selection(&self, value: Option<BlockSelection>) {
145 if let Ok(mut selection) = self.selection.lock() {
146 *selection = value;
147 }
148 }
149
150 fn is_selected(&self) -> bool {
151 self.selection() == Some(BlockSelection::Full)
152 }
153
154 fn has_selection_observation(&self) -> bool {
155 self.selection().is_some()
156 }
157
158 fn clear_selection(&self) {
159 self.set_selection(None);
160 }
161}
162
163impl PartialEq for BlockState {
164 fn eq(&self, _: &Self) -> bool {
165 true
167 }
168}
169
170pub(super) struct CustomBlockSelectionProjection {
171 state: BlockState,
172 bounds: Bounds<Pixels>,
173}
174
175impl CustomBlockSelectionProjection {
176 pub(super) fn project(&self, start: Point<Pixels>, end: Point<Pixels>) {
177 self.state
178 .set_selection(custom_block_selection(self.bounds, start, end));
179 }
180
181 pub(super) fn deselect(&self) {
182 self.state.set_selection(None);
183 }
184}
185
186fn custom_block_selection(
187 bounds: Bounds<Pixels>,
188 start: Point<Pixels>,
189 end: Point<Pixels>,
190) -> Option<BlockSelection> {
191 if bounds.size.width <= Pixels::ZERO
192 || bounds.size.height <= Pixels::ZERO
193 || bounds.bottom() <= start.y.min(end.y)
194 || bounds.top() > start.y.max(end.y)
195 {
196 return None;
197 }
198 Some(if custom_block_is_selected(bounds, start, end) {
199 BlockSelection::Full
200 } else {
201 BlockSelection::Empty
202 })
203}
204
205struct TableCellElement(AnyElement);
208
209impl Element for TableCellElement {
210 type RequestLayoutState = ();
211 type PrepaintState = ();
212
213 fn id(&self) -> Option<ElementId> {
214 None
215 }
216
217 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
218 None
219 }
220
221 fn request_layout(
222 &mut self,
223 _: Option<&GlobalElementId>,
224 _: Option<&InspectorElementId>,
225 window: &mut Window,
226 cx: &mut App,
227 ) -> (LayoutId, ()) {
228 (self.0.request_layout(window, cx), ())
229 }
230
231 fn prepaint(
232 &mut self,
233 _: Option<&GlobalElementId>,
234 _: Option<&InspectorElementId>,
235 bounds: Bounds<Pixels>,
236 _: &mut (),
237 window: &mut Window,
238 cx: &mut App,
239 ) {
240 if let Some(view) = GlobalState::global(cx).text_view_state() {
243 view.read(cx)
244 .selection_adapter
245 .record_table_cell(bounds, cx);
246 }
247 GlobalState::global(cx).push_table_cell(bounds);
248 self.0.prepaint(window, cx);
249 GlobalState::global(cx).pop_table_cell();
250 }
251
252 fn paint(
253 &mut self,
254 _: Option<&GlobalElementId>,
255 _: Option<&InspectorElementId>,
256 bounds: Bounds<Pixels>,
257 _: &mut (),
258 _: &mut (),
259 window: &mut Window,
260 cx: &mut App,
261 ) {
262 GlobalState::global(cx).push_table_cell(bounds);
263 self.0.paint(window, cx);
264 GlobalState::global(cx).pop_table_cell();
265 }
266}
267
268struct CustomBlockElement {
270 content: AnyElement,
271 state: BlockState,
272 reveal: Option<RevealAt>,
275}
276
277impl Element for CustomBlockElement {
278 type RequestLayoutState = ();
279 type PrepaintState = ();
280
281 fn id(&self) -> Option<ElementId> {
282 None
283 }
284
285 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
286 None
287 }
288
289 fn request_layout(
290 &mut self,
291 _: Option<&GlobalElementId>,
292 _: Option<&InspectorElementId>,
293 window: &mut Window,
294 cx: &mut App,
295 ) -> (LayoutId, ()) {
296 (self.content.request_layout(window, cx), ())
297 }
298
299 fn prepaint(
300 &mut self,
301 _: Option<&GlobalElementId>,
302 _: Option<&InspectorElementId>,
303 bounds: Bounds<Pixels>,
304 _: &mut (),
305 window: &mut Window,
306 cx: &mut App,
307 ) {
308 self.content.prepaint(window, cx);
309 if let Some(reveal) = &self.reveal {
310 let slack = px(0.5);
313 let view = window.content_mask().bounds;
314 let inside =
315 bounds.top() >= view.top() - slack && bounds.bottom() <= view.bottom() + slack;
316 let fills =
319 bounds.top() <= view.top() + slack && bounds.bottom() >= view.bottom() - slack;
320 let visible = inside || fills;
321 if !visible {
322 window.request_autoscroll(bounds);
323 }
324 reveal.report(bounds, visible);
325 }
326 }
327
328 fn paint(
329 &mut self,
330 _: Option<&GlobalElementId>,
331 _: Option<&InspectorElementId>,
332 bounds: Bounds<Pixels>,
333 _: &mut (),
334 _: &mut (),
335 window: &mut Window,
336 cx: &mut App,
337 ) {
338 let view = GlobalState::global(cx).text_view_state();
339 let selection = view.as_ref().and_then(|view| {
340 let state = view.read(cx);
341 if !state.is_selectable() {
342 return None;
343 }
344 if state.is_all_selected() {
345 return Some(BlockSelection::Full);
346 }
347 if state.preserve_inline_selection {
348 return self.state.selection();
349 }
350 let (start, end) = state.painted_selection_points(cx)?;
351 custom_block_selection(bounds, start, end)
352 });
353 self.state.set_selection(selection);
354 if let Some(view) = &view {
355 if view.read(cx).is_selectable() {
356 view.read(cx).selection_adapter.register_copy_projection(
357 super::selection_adapter::CopyProjection::CustomBlock(
358 CustomBlockSelectionProjection {
359 state: self.state.clone(),
360 bounds,
361 },
362 ),
363 cx,
364 );
365 }
366 let visible = bounds.intersect(&window.content_mask().bounds);
367 if view.read(cx).is_selectable()
368 && visible.size.width > Pixels::ZERO
369 && visible.size.height > Pixels::ZERO
370 {
371 view.read(cx)
372 .selection_adapter
373 .register_inline(vec![visible]);
374 }
375 }
376 self.content.paint(window, cx);
377 if selection == Some(BlockSelection::Full) {
378 let color = view.as_ref().unwrap().read(cx).text_view_style.selection();
379 window.paint_quad(gpui::fill(bounds, color));
380 }
381 }
382}
383
384fn custom_block_is_selected(
390 bounds: Bounds<Pixels>,
391 start: Point<Pixels>,
392 end: Point<Pixels>,
393) -> bool {
394 let (start_inside, end_inside) = (bounds.contains(&start), bounds.contains(&end));
395 start != end
396 && !(start_inside && end_inside)
397 && (start_inside
398 || end_inside
399 || point_in_text_selection(
400 bounds.origin,
401 bounds.size.width,
402 start,
403 end,
404 bounds.size.height,
405 ))
406}
407
408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
412pub(super) enum SelectionStyles {
413 None,
414 One,
415 Mixed,
416}
417
418impl SelectionStyles {
419 fn merge(&mut self, other: Self) {
422 *self = match (*self, other) {
423 (Self::None, other) | (other, Self::None) => other,
424 _ => Self::Mixed,
425 };
426 }
427}
428
429#[derive(Clone, Copy)]
430enum BlockTextKind {
431 All,
432 Selected,
433 SelectedSource,
436}
437
438impl BlockNode {
439 pub(super) fn is_list_item(&self) -> bool {
440 matches!(self, Self::ListItem { .. })
441 }
442
443 fn draws_nothing(&self) -> bool {
445 match self {
446 Self::Definition { .. } | Self::Break { .. } | Self::Unknown => true,
447 Self::Root { children, .. } => children.iter().all(Self::draws_nothing),
448 Self::Paragraph(paragraph) => paragraph.children().iter().all(|inline| {
449 inline.as_image().is_none()
450 && inline.as_custom().is_none()
451 && inline.text().trim().is_empty()
452 }),
453 _ => false,
454 }
455 }
456
457 pub(super) fn compact(self) -> BlockNode {
459 match self {
460 Self::Root { mut children, .. } if children.len() == 1 => children.remove(0).compact(),
461 _ => self,
462 }
463 }
464
465 pub fn span(&self) -> Option<Span> {
467 match self {
468 BlockNode::Root { span, .. } => *span,
469 BlockNode::Paragraph(paragraph) => paragraph.span,
470 BlockNode::Heading { span, .. } => *span,
471 BlockNode::Blockquote { span, .. } => *span,
472 BlockNode::Surface { span, .. } => *span,
473 BlockNode::List { span, .. } => *span,
474 BlockNode::ListItem { span, .. } => *span,
475 BlockNode::CodeBlock(code_block) => code_block.span,
476 BlockNode::Custom { node, .. } => node.span,
477 BlockNode::Table(table) => table.span,
478 BlockNode::Break { span, .. } => *span,
479 BlockNode::HorizontalRule { span, .. } => *span,
480 BlockNode::Definition { span, .. } => *span,
481 BlockNode::Unknown { .. } => None,
482 }
483 }
484
485 pub(super) fn text(&self) -> String {
486 self.text_by_kind(BlockTextKind::All)
487 }
488
489 pub(super) fn selected_text(&self, format: SelectionFormat) -> String {
494 self.text_by_kind(match format {
495 SelectionFormat::Plain => BlockTextKind::Selected,
496 SelectionFormat::Source | SelectionFormat::SourceAcrossStyles => {
497 BlockTextKind::SelectedSource
498 }
499 })
500 }
501
502 pub(super) fn selection_styles(&self) -> SelectionStyles {
504 let mut styles = SelectionStyles::None;
505 match self {
506 BlockNode::Root { children, .. }
507 | BlockNode::Blockquote { children, .. }
508 | BlockNode::Surface { children, .. }
509 | BlockNode::List { children, .. }
510 | BlockNode::ListItem { children, .. } => {
511 for child in children {
512 styles.merge(child.selection_styles());
513 }
514 }
515 BlockNode::Paragraph(paragraph) => styles = paragraph.selection_styles(),
516 BlockNode::Heading { children, .. } => styles = children.selection_styles(),
517 BlockNode::Table(table) => {
518 for row in &table.children {
519 for cell in &row.children {
520 styles.merge(cell.children.selection_styles());
521 }
522 }
523 }
524 BlockNode::CodeBlock(code_block) => {
525 if code_block.has_selection() {
526 styles = SelectionStyles::One;
527 }
528 }
529 BlockNode::Custom { state, .. } => {
531 if state.is_selected() {
532 styles = SelectionStyles::Mixed;
533 }
534 }
535 BlockNode::Definition { .. }
536 | BlockNode::Break { .. }
537 | BlockNode::HorizontalRule { .. }
538 | BlockNode::Unknown => {}
539 }
540 styles
541 }
542
543 pub(super) fn selected_source_range(&self) -> SourceRangeSelection {
544 let mut selected = SourceRangeSelection::Unselected;
545 match self {
546 BlockNode::Root { children, .. }
547 | BlockNode::Blockquote { children, .. }
548 | BlockNode::Surface { children, .. }
549 | BlockNode::List { children, .. }
550 | BlockNode::ListItem { children, .. } => {
551 for child in children {
552 selected.merge(child.selected_source_range());
553 }
554 }
555 BlockNode::Paragraph(paragraph) => selected = paragraph.selected_source_range(),
556 BlockNode::Heading { children, .. } => selected = children.selected_source_range(),
557 BlockNode::Table(table) => {
558 for row in &table.children {
559 for cell in &row.children {
560 selected.merge(cell.children.selected_source_range());
561 }
562 }
563 }
564 BlockNode::CodeBlock(code_block) => selected = code_block.selected_source_range(),
565 BlockNode::Custom { node, state } => {
566 if state.is_selected() {
567 selected = node
568 .source_range()
569 .map_or(SourceRangeSelection::Unmapped, SourceRangeSelection::Mapped);
570 }
571 }
572 BlockNode::Definition { .. }
573 | BlockNode::Break { .. }
574 | BlockNode::HorizontalRule { .. }
575 | BlockNode::Unknown => {}
576 }
577 selected
578 }
579
580 fn text_by_kind(&self, kind: BlockTextKind) -> String {
581 let mut text = String::new();
582 match self {
583 BlockNode::Root { children, .. } => {
584 let block_text = Self::children_text(children, kind);
585 if !block_text.is_empty() {
586 text.push_str(&block_text);
587 text.push('\n');
588 }
589 }
590 BlockNode::Paragraph(paragraph) => {
591 let block_text = match kind {
592 BlockTextKind::All => paragraph.text(),
593 BlockTextKind::Selected => paragraph.selected_text(),
594 BlockTextKind::SelectedSource => paragraph.selected_source(),
595 };
596 if !block_text.is_empty() {
597 text.push_str(&block_text);
598 text.push('\n');
599 }
600 }
601 BlockNode::Heading {
602 level, children, ..
603 } => {
604 let block_text = match kind {
605 BlockTextKind::All => children.text(),
606 BlockTextKind::Selected => children.selected_text(),
607 BlockTextKind::SelectedSource => children.selected_source(),
608 };
609 if !block_text.is_empty() {
610 if matches!(kind, BlockTextKind::SelectedSource) {
613 text.push_str(&"#".repeat(*level as usize));
614 text.push(' ');
615 }
616 text.push_str(&block_text);
617 text.push('\n');
618 }
619 }
620 BlockNode::List {
621 children,
622 ordered,
623 start,
624 ..
625 } => {
626 if matches!(kind, BlockTextKind::SelectedSource) {
627 text.push_str(&list_selected_source(children, *ordered, *start, ""));
630 } else {
631 text.push_str(&Self::children_text(children, kind));
632 }
633 }
634 BlockNode::ListItem { children, .. } => {
635 text.push_str(&Self::children_text(children, kind));
636 }
637 BlockNode::Blockquote { children, .. } => {
638 let block_text = Self::children_text(children, kind);
639
640 if !block_text.is_empty() {
641 if matches!(kind, BlockTextKind::SelectedSource) {
642 text.push_str("ed_source(None, &block_text));
643 } else {
644 text.push_str(&block_text);
645 }
646 text.push('\n');
647 }
648 }
649 BlockNode::Surface { name, children, .. } => {
650 let block_text = Self::children_text(children, kind);
651 if matches!(kind, BlockTextKind::SelectedSource) {
652 if !block_text.is_empty() {
655 text.push_str("ed_source(Some(name), &block_text));
656 text.push('\n');
657 }
658 } else {
659 text.push_str(&block_text);
660 }
661 }
662 BlockNode::Table(table) => {
663 if matches!(kind, BlockTextKind::SelectedSource) {
664 let block_text = table_selected_source(table);
665 if !block_text.is_empty() {
666 text.push_str(&block_text);
667 text.push('\n');
668 }
669 } else {
670 let mut block_text = String::new();
671 for row in table.children.iter() {
672 let mut row_texts = vec![];
673 for cell in row.children.iter() {
674 match kind {
675 BlockTextKind::All => row_texts.push(cell.children.text()),
676 _ => {
680 let selected = cell.children.selected_text();
681 if !selected.is_empty() {
682 row_texts.push(selected);
683 }
684 }
685 }
686 }
687 if !row_texts.is_empty() {
688 block_text.push_str(&row_texts.join(" "));
689 block_text.push('\n');
690 }
691 }
692
693 if !block_text.is_empty() {
694 text.push_str(&block_text);
695 text.push('\n');
696 }
697 }
698 }
699 BlockNode::CodeBlock(code_block) => {
700 let block_text = match kind {
701 BlockTextKind::All => code_block.text(),
702 BlockTextKind::Selected => code_block.selected_text(),
703 BlockTextKind::SelectedSource => code_block.selected_source(),
704 };
705 if !block_text.is_empty() {
706 text.push_str(&block_text);
707 text.push('\n');
708 }
709 }
710 BlockNode::Custom { node, state } => {
711 if matches!(kind, BlockTextKind::All) || state.is_selected() {
712 let content = match kind {
713 BlockTextKind::SelectedSource => Cow::Owned(node.to_markdown()),
714 _ => Cow::Borrowed(node.as_text()),
715 };
716 if !content.is_empty() {
717 text.push_str(&content);
718 text.push('\n');
719 }
720 }
721 }
722 BlockNode::Definition { .. }
723 | BlockNode::Break { .. }
724 | BlockNode::HorizontalRule { .. }
725 | BlockNode::Unknown { .. } => {}
726 }
727
728 text
729 }
730
731 fn children_text(children: &[BlockNode], kind: BlockTextKind) -> String {
732 let mut text = String::new();
733 for child in children.iter() {
734 text.push_str(&child.text_by_kind(kind));
735 }
736
737 text
738 }
739
740 pub(super) fn has_selection(&self) -> bool {
751 match self {
752 BlockNode::Root { children, .. }
753 | BlockNode::Blockquote { children, .. }
754 | BlockNode::Surface { children, .. }
755 | BlockNode::List { children, .. }
756 | BlockNode::ListItem { children, .. } => {
757 children.iter().any(|child| child.has_selection())
758 }
759 BlockNode::Paragraph(paragraph) => paragraph.has_selection(),
760 BlockNode::Heading { children, .. } => children.has_selection(),
761 BlockNode::Table(table) => table.children.iter().any(|row| {
762 row.children
763 .iter()
764 .any(|cell| cell.children.has_selection())
765 }),
766 BlockNode::CodeBlock(code_block) => code_block.has_selection(),
767 BlockNode::Custom { state, .. } => {
768 state.has_selection_observation()
770 }
771 BlockNode::Definition { .. }
772 | BlockNode::Break { .. }
773 | BlockNode::HorizontalRule { .. }
774 | BlockNode::Unknown { .. } => false,
775 }
776 }
777
778 pub(super) fn clear_selection(&self) {
779 match self {
780 BlockNode::Root { children, .. }
781 | BlockNode::Blockquote { children, .. }
782 | BlockNode::Surface { children, .. }
783 | BlockNode::List { children, .. }
784 | BlockNode::ListItem { children, .. } => {
785 for child in children.iter() {
786 child.clear_selection();
787 }
788 }
789 BlockNode::Paragraph(paragraph) => paragraph.clear_selection(),
790 BlockNode::Heading { children, .. } => children.clear_selection(),
791 BlockNode::Table(table) => {
792 for row in table.children.iter() {
793 for cell in row.children.iter() {
794 cell.children.clear_selection();
795 }
796 }
797 }
798 BlockNode::CodeBlock(code_block) => code_block.clear_selection(),
799 BlockNode::Custom { state, .. } => {
800 state.clear_selection();
801 }
802 BlockNode::Definition { .. }
803 | BlockNode::Break { .. }
804 | BlockNode::HorizontalRule { .. }
805 | BlockNode::Unknown { .. } => {}
806 }
807 }
808}
809
810#[allow(unused)]
811#[derive(Debug, Default, Clone, PartialEq)]
812pub struct LinkMark {
813 pub url: SharedString,
814 pub identifier: Option<SharedString>,
816 pub title: Option<SharedString>,
817}
818
819#[derive(Debug, Default, Clone, PartialEq)]
820pub struct TextMark {
821 pub bold: bool,
822 pub italic: bool,
823 pub strikethrough: bool,
824 pub underline: bool,
825 pub code: bool,
826 pub highlight: Option<Hsla>,
830 pub link: Option<LinkMark>,
831}
832
833impl TextMark {
834 pub fn bold(mut self) -> Self {
835 self.bold = true;
836 self
837 }
838
839 pub fn italic(mut self) -> Self {
840 self.italic = true;
841 self
842 }
843
844 pub fn strikethrough(mut self) -> Self {
845 self.strikethrough = true;
846 self
847 }
848
849 pub fn underline(mut self) -> Self {
850 self.underline = true;
851 self
852 }
853
854 pub fn code(mut self) -> Self {
855 self.code = true;
856 self
857 }
858
859 pub fn highlight(mut self, color: Hsla) -> Self {
861 self.highlight = Some(color);
862 self
863 }
864
865 pub fn link(mut self, link: impl Into<LinkMark>) -> Self {
866 self.link = Some(link.into());
867 self
868 }
869
870 pub fn merge(&mut self, other: TextMark) {
871 self.bold |= other.bold;
872 self.italic |= other.italic;
873 self.strikethrough |= other.strikethrough;
874 self.underline |= other.underline;
875 self.code |= other.code;
876 if other.highlight.is_some() {
877 self.highlight = other.highlight;
878 }
879 if let Some(link) = other.link {
880 self.link = Some(link);
881 }
882 }
883}
884
885#[derive(Debug, Default, Copy, Clone, PartialEq)]
887pub struct Span {
888 pub start: usize,
889 pub end: usize,
890}
891
892#[allow(unused)]
893#[derive(Default, Clone)]
894pub struct ImageNode {
895 pub url: SharedUri,
896 pub link: Option<LinkMark>,
897 pub title: Option<SharedString>,
898 pub alt: Option<SharedString>,
899 pub width: Option<DefiniteLength>,
900 pub height: Option<DefiniteLength>,
901 pub(crate) span: Option<Span>,
902 pub(super) embedded: OnceLock<Option<Arc<Image>>>,
905}
906
907impl ImageNode {
908 pub fn title(&self) -> String {
909 self.title
910 .clone()
911 .unwrap_or_else(|| self.alt.clone().unwrap_or_default())
912 .to_string()
913 }
914
915 pub(super) fn source(&self) -> ImageSource {
923 match self.embedded.get_or_init(|| data_url_image(&self.url)) {
924 Some(image) => ImageSource::Image(image.clone()),
925 None => self.url.clone().into(),
926 }
927 }
928}
929
930impl std::fmt::Debug for ImageNode {
931 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
932 f.debug_struct("ImageNode")
933 .field("url", &self.url)
934 .field("link", &self.link)
935 .field("title", &self.title)
936 .field("alt", &self.alt)
937 .field("width", &self.width)
938 .field("height", &self.height)
939 .field("span", &self.span)
940 .finish()
941 }
942}
943
944impl PartialEq for ImageNode {
945 fn eq(&self, other: &Self) -> bool {
946 self.url == other.url
947 && self.link == other.link
948 && self.title == other.title
949 && self.alt == other.alt
950 && self.width == other.width
951 && self.height == other.height
952 && self.span == other.span
953 }
954}
955
956#[derive(Debug, Clone, PartialEq)]
957pub(crate) struct SourceSegment {
958 pub(crate) rendered: Range<usize>,
959 pub(crate) source: Range<usize>,
960 pub(crate) linear: bool,
965}
966
967pub(crate) enum SourceRangeSelection {
968 Unselected,
969 Mapped(Range<usize>),
970 Unmapped,
971}
972
973impl SourceRangeSelection {
974 pub(crate) fn merge(&mut self, other: Self) {
975 match (&mut *self, other) {
976 (_, Self::Unselected) => {}
977 (_, Self::Unmapped) => *self = Self::Unmapped,
978 (Self::Unselected, mapped @ Self::Mapped(_)) => *self = mapped,
979 (Self::Mapped(selected), Self::Mapped(range)) => {
980 selected.start = selected.start.min(range.start);
981 selected.end = selected.end.max(range.end);
982 }
983 (Self::Unmapped, Self::Mapped(_)) => {}
984 }
985 }
986
987 pub(crate) fn into_range(self) -> Option<Range<usize>> {
988 match self {
989 Self::Mapped(range) => Some(range),
990 Self::Unselected | Self::Unmapped => None,
991 }
992 }
993}
994
995fn source_range_for_segments(
996 segments: &[SourceSegment],
997 selection: Range<usize>,
998) -> Option<Range<usize>> {
999 fn mapped_source_start(segment: &SourceSegment, rendered_start: usize) -> usize {
1000 if segment.linear {
1001 segment.source.start + rendered_start.saturating_sub(segment.rendered.start)
1002 } else {
1003 segment.source.start
1004 }
1005 }
1006
1007 fn mapped_source_end(segment: &SourceSegment, rendered_end: usize) -> usize {
1008 if segment.linear {
1009 segment.source.start
1010 + rendered_end
1011 .min(segment.rendered.end)
1012 .saturating_sub(segment.rendered.start)
1013 } else {
1014 segment.source.end
1015 }
1016 }
1017
1018 if selection.start >= selection.end {
1019 return None;
1020 }
1021
1022 let mut overlapping = segments.iter().filter(|segment| {
1023 segment.rendered.start < selection.end && segment.rendered.end > selection.start
1024 });
1025 let first = overlapping.next()?;
1026 if first.rendered.start > selection.start {
1027 return None;
1028 }
1029 let mut rendered_end = first.rendered.end;
1030 let source_start = mapped_source_start(first, selection.start);
1031 let mut source_end = mapped_source_end(first, selection.end);
1032 for segment in overlapping {
1033 if segment.rendered.start > rendered_end {
1034 return None;
1035 }
1036 rendered_end = rendered_end.max(segment.rendered.end);
1037 source_end = mapped_source_end(segment, selection.end);
1038 }
1039 (rendered_end >= selection.end).then_some(source_start..source_end)
1040}
1041
1042#[derive(Default, Clone, Debug)]
1045pub struct InlineNode {
1046 pub(crate) text: SharedString,
1048 pub(crate) image: Option<ImageNode>,
1049 pub(crate) custom: Option<MarkdownNode>,
1050 custom_selection: Arc<Mutex<bool>>,
1051 pub(crate) marks: Vec<(Range<usize>, TextMark)>,
1053 pub(crate) source_segments: Vec<SourceSegment>,
1055
1056 pub(super) state: Arc<Mutex<InlineState>>,
1057}
1058
1059impl PartialEq for InlineNode {
1060 fn eq(&self, other: &Self) -> bool {
1061 self.text == other.text
1062 && self.image == other.image
1063 && self.custom == other.custom
1064 && self.marks == other.marks
1065 && self.source_segments == other.source_segments
1066 }
1067}
1068
1069fn set_leaf_key(state: &mut Arc<Mutex<InlineState>>, key: u64) {
1070 let text = state
1071 .lock()
1072 .map(|state| state.text.clone())
1073 .unwrap_or_default();
1074 *state = Arc::new(Mutex::new(InlineState {
1077 text,
1078 editor_key: Some(key),
1079 selection_rows: None,
1080 cleanup_senders: Vec::new(),
1081 hovered_link: None,
1082 ..Default::default()
1083 }));
1084}
1085
1086pub(crate) fn wrap_with_mark(text: &str, mark: &TextMark) -> String {
1093 if text.is_empty() {
1094 return String::new();
1095 }
1096
1097 let mut out = text.to_string();
1098 if mark.code {
1099 out = format!("`{}`", out);
1100 }
1101 if mark.italic {
1102 out = format!("*{}*", out);
1103 }
1104 if mark.bold {
1105 out = format!("**{}**", out);
1106 }
1107 if mark.strikethrough {
1108 out = format!("~~{}~~", out);
1109 }
1110 if mark.underline {
1111 out = format!("<u>{}</u>", out);
1114 }
1115 if mark.highlight.is_some() {
1116 out = format!("=={}==", out);
1117 }
1118 if let Some(link) = &mark.link {
1119 out = match &link.title {
1120 Some(title) => format!("[{}]({} \"{}\")", out, link.url, title),
1121 None => format!("[{}]({})", out, link.url),
1122 };
1123 }
1124 out
1125}
1126
1127#[derive(Default)]
1131struct MarkdownSource {
1132 pieces: Vec<(String, Vec<TextMark>)>,
1133 has_objects: bool,
1136}
1137
1138impl MarkdownSource {
1139 fn push_str(&mut self, source: &str) {
1140 self.push_marked(source, &TextMark::default());
1141 }
1142
1143 fn push_marked(&mut self, source: &str, mark: &TextMark) {
1144 if source.is_empty() {
1145 return;
1146 }
1147 let mut layers = Vec::new();
1150 if let Some(link) = &mark.link {
1151 layers.push(TextMark {
1152 link: Some(link.clone()),
1153 ..Default::default()
1154 });
1155 }
1156 if let Some(highlight) = mark.highlight {
1157 layers.push(TextMark {
1158 highlight: Some(highlight),
1159 ..Default::default()
1160 });
1161 }
1162 if mark.underline {
1163 layers.push(TextMark::default().underline());
1164 }
1165 if mark.strikethrough {
1166 layers.push(TextMark::default().strikethrough());
1167 }
1168 if mark.bold {
1169 layers.push(TextMark::default().bold());
1170 }
1171 if mark.italic {
1172 layers.push(TextMark::default().italic());
1173 }
1174 if mark.code {
1175 layers.push(TextMark::default().code());
1176 }
1177 self.pieces.push((source.to_string(), layers));
1178 }
1179
1180 fn push_text(
1181 &mut self,
1182 text: &str,
1183 marks: &[(Range<usize>, TextMark)],
1184 selection: Range<usize>,
1185 ) {
1186 let start = selection.start.min(text.len());
1187 let end = selection.end.min(text.len());
1188 if start >= end {
1189 return;
1190 }
1191 let mut cursor = start;
1192 for (range, mark) in marks {
1193 let lo = range.start.max(start);
1194 let hi = range.end.min(end);
1195 if lo >= hi {
1196 continue;
1197 }
1198 if cursor < lo {
1199 self.push_str(&text[cursor..lo]);
1200 }
1201 self.push_marked(&text[lo..hi], mark);
1202 cursor = hi;
1203 }
1204 if cursor < end {
1205 self.push_str(&text[cursor..end]);
1206 }
1207 }
1208
1209 fn push_images(&mut self, images: &[String]) {
1210 if images.is_empty() {
1211 return;
1212 }
1213 self.has_objects = true;
1214 self.push_str(&images.join(""));
1215 }
1216
1217 fn push_object(&mut self, node: &InlineNode) {
1218 self.has_objects = true;
1219 let mut mark = TextMark::default();
1220 for (_, layer) in &node.marks {
1221 mark.merge(layer.clone());
1222 }
1223 self.push_marked(&node.custom.as_ref().unwrap().to_markdown(), &mark);
1224 }
1225
1226 fn is_empty(&self) -> bool {
1227 self.pieces.is_empty()
1228 }
1229
1230 fn styles(&self) -> SelectionStyles {
1231 if self.is_empty() {
1232 SelectionStyles::None
1233 } else if !self.has_objects && self.pieces.windows(2).all(|pair| pair[0].1 == pair[1].1) {
1234 SelectionStyles::One
1235 } else {
1236 SelectionStyles::Mixed
1237 }
1238 }
1239
1240 fn finish(mut self) -> String {
1241 fn write(pieces: &mut [(String, Vec<TextMark>)]) -> String {
1242 let mut out = String::new();
1243 let mut offset = 0;
1244 while offset < pieces.len() {
1245 let Some((mark, count)) = pieces[offset]
1246 .1
1247 .iter()
1248 .map(|mark| {
1249 let count = pieces[offset..]
1250 .iter()
1251 .take_while(|(_, layers)| layers.contains(mark))
1252 .count();
1253 (mark.clone(), count)
1254 })
1255 .reduce(|best, candidate| {
1256 if candidate.1 > best.1 {
1257 candidate
1258 } else {
1259 best
1260 }
1261 })
1262 else {
1263 out.push_str(&pieces[offset].0);
1264 offset += 1;
1265 continue;
1266 };
1267 let group = &mut pieces[offset..offset + count];
1268 for (_, layers) in group.iter_mut() {
1269 layers.retain(|layer| layer != &mark);
1270 }
1271 let content = write(group);
1272 out.push_str(&wrap_with_mark(&content, &mark));
1273 offset += count;
1274 }
1275 out
1276 }
1277 write(&mut self.pieces)
1278 }
1279}
1280
1281#[derive(Default)]
1284struct RunSelection {
1285 emitted: bool,
1286 at_start: bool,
1287 at_end: bool,
1288}
1289
1290fn emit_run(
1294 state: &Arc<Mutex<InlineState>>,
1295 run: &[(usize, &InlineNode)],
1296 pending_images: &mut Vec<String>,
1297 out: &mut MarkdownSource,
1298) -> RunSelection {
1299 let mut selected = RunSelection::default();
1300 let Ok(state) = state.lock() else {
1301 return selected;
1302 };
1303 let Some(selection) = &state.selection else {
1304 return selected;
1305 };
1306 if selection.start >= selection.end {
1307 return selected;
1308 }
1309
1310 selected.at_start = selection.start == 0;
1311 selected.at_end = selection.end >= state.text.len();
1312
1313 for (start, child) in run {
1314 let end = start + child.text.len();
1315 let lo = selection.start.max(*start);
1316 let hi = selection.end.min(end);
1317 if lo >= hi {
1318 continue;
1319 }
1320
1321 if !selected.emitted {
1322 if selected.at_start {
1323 out.push_images(pending_images);
1324 }
1325 pending_images.clear();
1326 }
1327 selected.emitted = true;
1328
1329 out.push_text(&child.text, &child.marks, (lo - start)..(hi - start));
1330 }
1331
1332 selected
1333}
1334
1335fn image_markdown(image: &ImageNode) -> String {
1337 let alt = image.alt.clone().unwrap_or_default();
1338 let title = image
1339 .title
1340 .clone()
1341 .map_or(String::new(), |title| format!(" \"{}\"", title));
1342 format!("", alt, image.url, title)
1343}
1344
1345#[cfg(test)]
1354pub(crate) fn reconstruct_markdown(
1355 text: &str,
1356 marks: &[(Range<usize>, TextMark)],
1357 selection: Range<usize>,
1358) -> String {
1359 let mut source = MarkdownSource::default();
1360 source.push_text(text, marks, selection);
1361 source.finish()
1362}
1363
1364fn table_selected_source(table: &Table) -> String {
1372 let cell_source = |cell: &TableCell| cell.children.selected_source().replace('\n', " ");
1373
1374 let mut selected = table
1375 .children
1376 .iter()
1377 .flat_map(|row| row.children.iter())
1378 .map(cell_source)
1379 .filter(|source| !source.trim().is_empty());
1380 match (selected.next(), selected.next()) {
1381 (None, _) => return String::new(),
1382 (Some(only), None) => return only.trim().to_string(),
1383 _ => {}
1384 }
1385
1386 let mut lines: Vec<String> = Vec::new();
1387 for (row_ix, row) in table.children.iter().enumerate() {
1388 let cells: Vec<String> = row
1389 .children
1390 .iter()
1391 .map(|cell| cell_source(cell).trim().to_string())
1392 .collect();
1393 lines.push(format!("| {} |", cells.join(" | ")));
1394
1395 if row_ix == 0 {
1398 let aligns: Vec<String> = (0..row.children.len())
1399 .map(|ix| {
1400 match table.column_align(ix) {
1401 ColumnumnAlign::None | ColumnumnAlign::Left => ":--",
1402 ColumnumnAlign::Center => ":-:",
1403 ColumnumnAlign::Right => "--:",
1404 }
1405 .to_string()
1406 })
1407 .collect();
1408 lines.push(format!("| {} |", aligns.join(" | ")));
1409 }
1410 }
1411
1412 lines.join("\n")
1413}
1414
1415fn quoted_source(marker: Option<&SharedString>, text: &str) -> String {
1419 marker
1420 .map(|name| format!("[!{name}]"))
1421 .into_iter()
1422 .chain(text.trim_end_matches('\n').lines().map(str::to_string))
1423 .map(|line| {
1424 if line.is_empty() {
1425 ">".to_string()
1426 } else {
1427 format!("> {line}")
1428 }
1429 })
1430 .collect::<Vec<_>>()
1431 .join("\n")
1432}
1433
1434fn list_selected_source(
1444 children: &[BlockNode],
1445 ordered: bool,
1446 start: Option<u32>,
1447 indent: &str,
1448) -> String {
1449 let mut out = String::new();
1450 let mut item_ix = 0usize;
1451
1452 for child in children {
1453 let BlockNode::ListItem {
1454 children: item_children,
1455 checked,
1456 ..
1457 } = child
1458 else {
1459 continue;
1460 };
1461
1462 let marker = if ordered {
1463 format!("{}. ", ordered_list_ordinal(start, item_ix))
1464 } else {
1465 "- ".to_string()
1466 };
1467 let checkbox = match checked {
1468 Some(true) => "[x] ",
1469 Some(false) => "[ ] ",
1470 None => "",
1471 };
1472 let child_indent = format!("{}{}", indent, " ".repeat(marker.len()));
1473
1474 let mut content = String::new();
1477 let mut nested = String::new();
1478 for sub in item_children {
1479 if let BlockNode::List {
1480 children: sub_children,
1481 ordered: sub_ordered,
1482 start: sub_start,
1483 ..
1484 } = sub
1485 {
1486 nested.push_str(&list_selected_source(
1487 sub_children,
1488 *sub_ordered,
1489 *sub_start,
1490 &child_indent,
1491 ));
1492 } else {
1493 content.push_str(&sub.text_by_kind(BlockTextKind::SelectedSource));
1494 }
1495 }
1496 let content = content.trim_end_matches('\n');
1497
1498 if content.is_empty() && nested.is_empty() {
1499 item_ix += 1;
1500 continue;
1501 }
1502
1503 if content.is_empty() {
1504 out.push_str(indent);
1506 out.push_str(&marker);
1507 out.push_str(checkbox.trim_end());
1508 out.push('\n');
1509 } else {
1510 let mut lines = content.lines();
1513 if let Some(first) = lines.next() {
1514 out.push_str(indent);
1515 out.push_str(&marker);
1516 out.push_str(checkbox);
1517 out.push_str(first);
1518 out.push('\n');
1519 }
1520 for line in lines {
1521 out.push_str(&child_indent);
1522 out.push_str(line);
1523 out.push('\n');
1524 }
1525 }
1526 out.push_str(&nested);
1527 item_ix += 1;
1528 }
1529
1530 out
1531}
1532
1533impl InlineNode {
1534 pub fn new(text: impl Into<SharedString>) -> Self {
1536 Self {
1537 text: text.into(),
1538 image: None,
1539 custom: None,
1540 custom_selection: Arc::default(),
1541 marks: vec![],
1542 source_segments: vec![],
1543 state: Arc::new(Mutex::new(InlineState::default())),
1544 }
1545 }
1546
1547 pub fn custom(node: MarkdownNode) -> Self {
1549 let mut this = Self::new(node.as_text().to_string());
1550 this.custom = Some(node);
1551 this
1552 }
1553
1554 pub fn image(image: ImageNode) -> Self {
1556 let mut this = Self::new("");
1557 this.image = Some(image);
1558 this
1559 }
1560
1561 pub fn marks(mut self, marks: Vec<(Range<usize>, TextMark)>) -> Self {
1563 self.marks = marks;
1564 self
1565 }
1566
1567 pub fn text(&self) -> &str {
1569 &self.text
1570 }
1571
1572 pub fn as_image(&self) -> Option<&ImageNode> {
1574 self.image.as_ref()
1575 }
1576
1577 pub fn as_custom(&self) -> Option<&MarkdownNode> {
1579 self.custom.as_ref()
1580 }
1581
1582 pub fn mark_runs(&self) -> &[(Range<usize>, TextMark)] {
1584 &self.marks
1585 }
1586
1587 pub(crate) fn source_segments(mut self, source_segments: Vec<SourceSegment>) -> Self {
1588 self.source_segments = source_segments;
1589 self
1590 }
1591
1592 fn selected_source_range(&self, selection: Range<usize>) -> Option<Range<usize>> {
1593 source_range_for_segments(&self.source_segments, selection)
1594 }
1595}
1596
1597#[derive(Debug, Clone, Default)]
1602pub struct Paragraph {
1603 pub(super) span: Option<Span>,
1604 pub(super) children: Vec<InlineNode>,
1605 pub(super) link_refs: HashMap<SharedString, SharedString>,
1609
1610 pub(crate) state: Arc<Mutex<InlineState>>,
1611 pub(super) render_cache: ParagraphRenderCache,
1614}
1615
1616#[derive(Default)]
1624pub(super) struct ParagraphRenderCache {
1625 plain: Mutex<Option<Arc<ParagraphRender>>>,
1627 flow: Mutex<Option<Arc<FlowRender>>>,
1629}
1630
1631impl Clone for ParagraphRenderCache {
1632 fn clone(&self) -> Self {
1633 Self {
1634 plain: Mutex::new(self.plain.lock().ok().and_then(|cache| cache.clone())),
1635 flow: Mutex::new(self.flow.lock().ok().and_then(|cache| cache.clone())),
1636 }
1637 }
1638}
1639
1640impl std::fmt::Debug for ParagraphRenderCache {
1641 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1642 f.write_str("ParagraphRenderCache")
1643 }
1644}
1645
1646struct ParagraphRender {
1656 style: RenderStyle,
1657 text: SharedString,
1658 highlights: Vec<(Range<usize>, InlineHighlight)>,
1659 links: Vec<(Range<usize>, LinkMark)>,
1661 replaced: Vec<Option<LinkMark>>,
1665}
1666
1667impl ParagraphRender {
1668 fn drawn_links(&self) -> Vec<(Range<usize>, LinkMark)> {
1670 self.links
1671 .iter()
1672 .zip(&self.replaced)
1673 .filter_map(|((range, _), link)| Some((range.clone(), link.clone()?)))
1674 .collect()
1675 }
1676}
1677
1678struct FlowRender {
1688 style: RenderStyle,
1689 texts: Vec<FlowText>,
1691 links: Vec<(LinkMark, Option<LinkMark>)>,
1694}
1695
1696impl FlowRender {
1697 fn is_current(&self, node_cx: &NodeContext, cx: &App) -> bool {
1698 self.style.is_current(node_cx, cx)
1699 && self
1700 .links
1701 .iter()
1702 .all(|(link, replaced)| node_cx.link(link, cx) == *replaced)
1703 }
1704}
1705
1706#[derive(Default)]
1712struct FlowText {
1713 end: Option<usize>,
1717 text: SharedString,
1718 highlights: Arc<[(Range<usize>, InlineHighlight)]>,
1719 links: Arc<[(Range<usize>, LinkMark)]>,
1721}
1722
1723struct RenderStyle {
1727 style: Arc<TextViewStyle>,
1728 mono_font: SharedString,
1729 background: Hsla,
1730}
1731
1732impl RenderStyle {
1733 fn new(node_cx: &NodeContext, cx: &App) -> Self {
1734 let theme = cx.theme();
1735 Self {
1736 style: node_cx.style.clone(),
1737 mono_font: theme.tokens.typography.mono,
1738 background: theme.tokens.colors.background,
1739 }
1740 }
1741
1742 fn is_current(&self, node_cx: &NodeContext, cx: &App) -> bool {
1745 let theme = cx.theme();
1746 (Arc::ptr_eq(&self.style, &node_cx.style) || *self.style == *node_cx.style)
1747 && self.mono_font == theme.tokens.typography.mono
1748 && self.background == theme.tokens.colors.background
1749 }
1750}
1751
1752impl PartialEq for Paragraph {
1753 fn eq(&self, other: &Self) -> bool {
1754 self.span == other.span
1755 && self.children == other.children
1756 && self.link_refs == other.link_refs
1757 }
1758}
1759
1760impl Paragraph {
1761 pub(crate) fn new(text: String) -> Self {
1762 Self {
1763 span: None,
1764 children: vec![InlineNode::new(&text)],
1765 link_refs: HashMap::new(),
1766 state: Arc::new(Mutex::new(InlineState::default())),
1767 render_cache: ParagraphRenderCache::default(),
1768 }
1769 }
1770
1771 fn plain_render(
1774 &self,
1775 node_cx: &NodeContext,
1776 cx: &App,
1777 ) -> (
1778 SharedString,
1779 Vec<(Range<usize>, InlineHighlight)>,
1780 Vec<(Range<usize>, LinkMark)>,
1781 ) {
1782 if let Ok(cache) = self.render_cache.plain.lock()
1783 && let Some(cached) = cache.as_ref()
1784 && cached.style.is_current(node_cx, cx)
1785 && cached
1786 .links
1787 .iter()
1788 .zip(&cached.replaced)
1789 .all(|((_, link), replaced)| node_cx.link(link, cx) == *replaced)
1790 {
1791 return (
1792 cached.text.clone(),
1793 foreground_highlights(
1794 cached.highlights.clone(),
1795 &cached.text,
1796 0,
1797 node_cx.foregrounds(self.leaf_key()),
1798 ),
1799 cached.drawn_links(),
1800 );
1801 }
1802
1803 let mut text = String::new();
1804 let mut highlights: Vec<(Range<usize>, InlineHighlight)> = vec![];
1805 let mut links: Vec<(Range<usize>, LinkMark)> = vec![];
1806 let mut replaced = vec![];
1807 let mut offset = 0;
1808 for inline_node in &self.children {
1809 let text_len = inline_node.text.len();
1810 text.push_str(&inline_node.text);
1811 let mut node_highlights = vec![];
1812 for (range, style) in &inline_node.marks {
1813 let inner_range = (offset + range.start)..(offset + range.end);
1814 let mut highlight = mark_highlight(style, node_cx, cx);
1815 if let Some(link_mark) = style.link.clone() {
1816 let link = node_cx.link(&link_mark, cx);
1817 if link.is_some() {
1818 highlight.style.color = Some(node_cx.style.link());
1819 highlight.style.underline = Some(link_underline(&node_cx.style));
1820 }
1821 links.push((inner_range.clone(), link_mark));
1822 replaced.push(link);
1823 }
1824 node_highlights.push((inner_range, highlight));
1825 }
1826 append_node_highlights(&mut highlights, node_highlights);
1827 offset += text_len;
1828 }
1829 let text = SharedString::from(text);
1830 let render = Arc::new(ParagraphRender {
1831 style: RenderStyle::new(node_cx, cx),
1832 text: text.clone(),
1833 highlights: highlights.clone(),
1834 links,
1835 replaced,
1836 });
1837 let links = render.drawn_links();
1838 if let Ok(mut cache) = self.render_cache.plain.lock() {
1839 *cache = Some(render);
1840 }
1841 let highlights =
1842 foreground_highlights(highlights, &text, 0, node_cx.foregrounds(self.leaf_key()));
1843 (text, highlights, links)
1844 }
1845
1846 pub(super) fn selected_text(&self) -> String {
1847 let mut text = String::new();
1848
1849 for c in self.children.iter() {
1850 let Ok(state) = c.state.lock() else {
1851 continue;
1852 };
1853 if let Some(selection) = &state.selection {
1854 text.push_str(&state.text[selection.start..selection.end]);
1855 }
1856 if let Some(custom) = &c.custom
1857 && c.custom_selection.lock().is_ok_and(|selected| *selected)
1858 {
1859 text.push_str(custom.as_text());
1860 }
1861 }
1862
1863 if let Ok(state) = self.state.lock()
1864 && let Some(selection) = &state.selection
1865 {
1866 text.push_str(&state.text[selection.start..selection.end]);
1867 }
1868
1869 text
1870 }
1871
1872 pub(super) fn selected_source_range(&self) -> SourceRangeSelection {
1874 let mut selected = SourceRangeSelection::Unselected;
1875 let mut run: Vec<(usize, &InlineNode)> = Vec::new();
1876 let mut offset = 0;
1877 let mut pending_images: Vec<Option<Span>> = Vec::new();
1878 let mut enters_image = true;
1879
1880 let include_run = |state: &Arc<Mutex<InlineState>>,
1881 run: &[(usize, &InlineNode)]|
1882 -> (SourceRangeSelection, RunSelection) {
1883 let Ok(state) = state.lock() else {
1884 return (SourceRangeSelection::Unmapped, RunSelection::default());
1885 };
1886 let Some(selection) = state.selection else {
1887 return (SourceRangeSelection::Unselected, RunSelection::default());
1888 };
1889 if selection.start >= selection.end {
1890 return (SourceRangeSelection::Unselected, RunSelection::default());
1891 }
1892
1893 let mut run_selection = RunSelection {
1894 at_start: selection.start == 0,
1895 at_end: selection.end >= state.text.len(),
1896 ..Default::default()
1897 };
1898 let mut mapped = SourceRangeSelection::Unselected;
1899 let mut rendered_end = selection.start;
1900 for (start, child) in run {
1901 let end = start + child.text.len();
1902 let lo = selection.start.max(*start);
1903 let hi = selection.end.min(end);
1904 if lo >= hi {
1905 continue;
1906 }
1907 run_selection.emitted = true;
1908 if lo > rendered_end {
1909 return (SourceRangeSelection::Unmapped, run_selection);
1910 }
1911 let Some(range) = child.selected_source_range((lo - start)..(hi - start)) else {
1912 return (SourceRangeSelection::Unmapped, run_selection);
1913 };
1914 mapped.merge(SourceRangeSelection::Mapped(range));
1915 rendered_end = rendered_end.max(hi);
1916 }
1917 if rendered_end < selection.end {
1918 (SourceRangeSelection::Unmapped, run_selection)
1919 } else {
1920 (mapped, run_selection)
1921 }
1922 };
1923
1924 let merge_images = |selected: &mut SourceRangeSelection, images: &mut Vec<Option<Span>>| {
1925 for span in images.drain(..) {
1926 selected.merge(
1927 span.map(|span| SourceRangeSelection::Mapped(span.start..span.end))
1928 .unwrap_or(SourceRangeSelection::Unmapped),
1929 );
1930 }
1931 };
1932
1933 for child in &self.children {
1934 if child.custom.is_some() {
1935 let (run_range, run_selection) = include_run(&child.state, &run);
1936 if run_selection.emitted && run_selection.at_start {
1937 merge_images(&mut selected, &mut pending_images);
1938 }
1939 selected.merge(run_range);
1940
1941 match child.custom_selection.lock() {
1942 Ok(value) if *value => {
1943 if run.is_empty() || (run_selection.emitted && run_selection.at_end) {
1944 merge_images(&mut selected, &mut pending_images);
1945 }
1946 selected.merge(
1947 child
1948 .custom
1949 .as_ref()
1950 .and_then(MarkdownNode::source_range)
1951 .map(SourceRangeSelection::Mapped)
1952 .unwrap_or(SourceRangeSelection::Unmapped),
1953 );
1954 enters_image = true;
1955 }
1956 Ok(_) => enters_image = false,
1957 Err(_) => {
1958 selected.merge(SourceRangeSelection::Unmapped);
1959 enters_image = false;
1960 }
1961 }
1962 pending_images.clear();
1963 run.clear();
1964 offset = 0;
1965 continue;
1966 }
1967 if let Some(image) = &child.image {
1968 let run_before = !run.is_empty();
1969 let (run_range, run_selection) = include_run(&child.state, &run);
1970 if run_selection.emitted && run_selection.at_start {
1971 merge_images(&mut selected, &mut pending_images);
1972 }
1973 selected.merge(run_range);
1974 if run_before {
1975 enters_image = run_selection.emitted && run_selection.at_end;
1976 }
1977 if enters_image {
1978 pending_images.push(image.span);
1979 } else {
1980 pending_images.clear();
1981 }
1982 run.clear();
1983 offset = 0;
1984 continue;
1985 }
1986 run.push((offset, child));
1987 offset += child.text.len();
1988 }
1989
1990 let (trailing_range, trailing) = include_run(&self.state, &run);
1991 if trailing.emitted && trailing.at_start {
1992 merge_images(&mut selected, &mut pending_images);
1993 }
1994 selected.merge(trailing_range);
1995 if !trailing.emitted
1996 && enters_image
1997 && !matches!(selected, SourceRangeSelection::Unselected)
1998 {
1999 merge_images(&mut selected, &mut pending_images);
2000 }
2001 selected
2002 }
2003
2004 pub(super) fn selected_source(&self) -> String {
2024 self.selected_markdown().finish()
2025 }
2026
2027 pub(super) fn selection_styles(&self) -> SelectionStyles {
2029 self.selected_markdown().styles()
2030 }
2031
2032 fn selected_markdown(&self) -> MarkdownSource {
2035 let mut source = MarkdownSource::default();
2036 let mut pending_images: Vec<String> = Vec::new();
2037 let mut run: Vec<(usize, &InlineNode)> = Vec::new();
2038 let mut offset = 0;
2039 let mut enters_image = true;
2040
2041 for child in self.children.iter() {
2042 if child.custom.is_some() {
2043 let selected = emit_run(&child.state, &run, &mut pending_images, &mut source);
2044 let object_selected = child
2045 .custom_selection
2046 .lock()
2047 .is_ok_and(|selected| *selected);
2048 if object_selected {
2049 if run.is_empty() || (selected.emitted && selected.at_end) {
2050 source.push_images(&pending_images);
2051 }
2052 source.push_object(child);
2053 }
2054 pending_images.clear();
2055 enters_image = object_selected;
2056 run.clear();
2057 offset = 0;
2058 continue;
2059 }
2060 let Some(image) = &child.image else {
2061 run.push((offset, child));
2062 offset += child.text.len();
2063 continue;
2064 };
2065
2066 let run_before = !run.is_empty();
2068 let selected = emit_run(&child.state, &run, &mut pending_images, &mut source);
2069 if run_before {
2070 enters_image = selected.emitted && selected.at_end;
2071 }
2072 if enters_image {
2073 pending_images.push(image_markdown(image));
2074 } else {
2075 pending_images.clear();
2076 }
2077
2078 run.clear();
2079 offset = 0;
2080 }
2081
2082 let trailing = emit_run(&self.state, &run, &mut pending_images, &mut source);
2083 if !trailing.emitted && enters_image && !source.is_empty() {
2085 source.push_images(&pending_images);
2086 }
2087
2088 source
2089 }
2090
2091 pub(super) fn text(&self) -> String {
2092 let mut text = String::new();
2093 for node in self.children.iter() {
2094 text.push_str(&node.text);
2095 }
2096 text
2097 }
2098
2099 pub(super) fn has_selection(&self) -> bool {
2103 self.children.iter().any(|c| {
2104 c.state.lock().is_ok_and(|state| state.selection.is_some())
2105 || c.custom_selection.lock().is_ok_and(|selected| *selected)
2106 }) || self
2107 .state
2108 .lock()
2109 .is_ok_and(|state| state.selection.is_some())
2110 }
2111
2112 pub(super) fn clear_selection(&self) {
2113 for c in self.children.iter() {
2114 if let Ok(mut selected) = c.custom_selection.lock() {
2115 *selected = false;
2116 }
2117 if let Ok(mut state) = c.state.lock() {
2118 state.selection = None;
2119 }
2120 }
2121
2122 if let Ok(mut state) = self.state.lock() {
2123 state.selection = None;
2124 }
2125 }
2126}
2127
2128#[derive(Debug, Clone, Default, PartialEq)]
2130pub struct Table {
2131 pub(crate) children: Vec<TableRow>,
2132 pub(crate) column_aligns: Vec<ColumnumnAlign>,
2133 pub(crate) span: Option<Span>,
2134 pub(crate) table_data_cache: TableDataCache,
2137 pub(crate) column_widths_cache: TableColumnWidthsCache,
2138}
2139
2140#[derive(Default)]
2148pub(crate) struct TableDataCache(Mutex<Option<Arc<TableData>>>);
2149
2150impl Clone for TableDataCache {
2151 fn clone(&self) -> Self {
2152 let cached = self.0.lock().ok().and_then(|cache| cache.clone());
2153 Self(Mutex::new(cached))
2154 }
2155}
2156
2157impl PartialEq for TableDataCache {
2158 fn eq(&self, _: &Self) -> bool {
2159 true
2160 }
2161}
2162
2163impl std::fmt::Debug for TableDataCache {
2164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2165 f.write_str("TableDataCache")
2166 }
2167}
2168
2169#[derive(Default)]
2172pub(crate) struct TableColumnWidthsCache(Mutex<Option<Arc<TableColumnWidths>>>);
2173
2174impl Clone for TableColumnWidthsCache {
2175 fn clone(&self) -> Self {
2176 let cached = self.0.lock().ok().and_then(|cache| cache.clone());
2177 Self(Mutex::new(cached))
2178 }
2179}
2180
2181impl PartialEq for TableColumnWidthsCache {
2182 fn eq(&self, _: &Self) -> bool {
2183 true
2184 }
2185}
2186
2187impl std::fmt::Debug for TableColumnWidthsCache {
2188 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2189 f.write_str("TableColumnWidthsCache")
2190 }
2191}
2192
2193fn text_system_id(window: &Window) -> usize {
2194 std::rc::Rc::as_ptr(window.text_system()) as usize
2195}
2196
2197struct TableColumnWidths {
2198 text_system: usize,
2202 text_styles: TableTextStyles,
2204 rem_size: Pixels,
2205 mono_family: SharedString,
2206 inline_code: HighlightStyle,
2207 widths: Vec<f32>,
2209 custom_cells: Vec<(usize, usize)>,
2210}
2211
2212#[derive(Clone, PartialEq)]
2216struct TableTextStyles {
2217 head: gpui::TextStyle,
2218 body: gpui::TextStyle,
2219 head_refinement: TextStyleRefinement,
2220 body_refinement: TextStyleRefinement,
2221}
2222
2223impl TableTextStyles {
2224 fn new(style: &TextViewStyle, window: &Window) -> Self {
2225 let mut body_refinement = style.table().text.clone();
2226 let mut head_refinement = body_refinement.clone();
2227 head_refinement.refine(&style.table_head().text);
2228 head_refinement.refine(&style.table_cell().text);
2229 body_refinement.refine(&style.table_cell().text);
2230 let mut head = window.text_style();
2231 let mut body = head.clone();
2232 head.refine(&head_refinement);
2233 body.refine(&body_refinement);
2234 Self {
2235 head,
2236 body,
2237 head_refinement,
2238 body_refinement,
2239 }
2240 }
2241
2242 fn row(&self, row_ix: usize) -> &gpui::TextStyle {
2243 if row_ix == 0 { &self.head } else { &self.body }
2244 }
2245
2246 fn row_refinement(&self, row_ix: usize) -> &TextStyleRefinement {
2247 if row_ix == 0 {
2248 &self.head_refinement
2249 } else {
2250 &self.body_refinement
2251 }
2252 }
2253}
2254
2255#[derive(Debug, Clone, Default, PartialEq)]
2258pub struct TableData {
2259 pub headers: Vec<String>,
2261 pub rows: Vec<Vec<String>>,
2264 pub markdown: String,
2266 pub span: Option<Range<usize>>,
2273}
2274
2275impl Table {
2276 pub fn new(rows: Vec<Vec<Paragraph>>, column_aligns: Vec<ColumnumnAlign>) -> Self {
2278 Self {
2279 children: rows
2280 .into_iter()
2281 .map(|row| TableRow {
2282 children: row
2283 .into_iter()
2284 .map(|children| TableCell {
2285 children,
2286 width: None,
2287 })
2288 .collect(),
2289 })
2290 .collect(),
2291 column_aligns,
2292 ..Default::default()
2293 }
2294 }
2295
2296 pub fn rows(&self) -> impl Iterator<Item = impl Iterator<Item = &Paragraph>> {
2298 self.children
2299 .iter()
2300 .map(|row| row.children.iter().map(|cell| &cell.children))
2301 }
2302
2303 pub fn column_aligns(&self) -> &[ColumnumnAlign] {
2305 &self.column_aligns
2306 }
2307
2308 pub(crate) fn column_align(&self, index: usize) -> ColumnumnAlign {
2309 self.column_aligns.get(index).copied().unwrap_or_default()
2310 }
2311
2312 pub(crate) fn to_markdown(&self) -> String {
2319 let mut lines: Vec<String> = Vec::with_capacity(self.children.len() + 1);
2320
2321 for (row_ix, row) in self.children.iter().enumerate() {
2322 let cells: Vec<String> = row
2323 .children
2324 .iter()
2325 .map(|cell| {
2326 cell.children
2327 .to_markdown()
2328 .trim()
2329 .replace('\n', " ")
2330 .replace('|', "\\|")
2331 })
2332 .collect();
2333 lines.push(format!("| {} |", cells.join(" | ")));
2334
2335 if row_ix == 0 {
2338 let aligns: Vec<String> = (0..row.children.len())
2339 .map(|ix| {
2340 match self.column_align(ix) {
2341 ColumnumnAlign::None | ColumnumnAlign::Left => ":--",
2342 ColumnumnAlign::Center => ":-:",
2343 ColumnumnAlign::Right => "--:",
2344 }
2345 .to_string()
2346 })
2347 .collect();
2348 lines.push(format!("| {} |", aligns.join(" | ")));
2349 }
2350 }
2351
2352 lines.join("\n")
2353 }
2354
2355 pub(crate) fn table_data(&self) -> TableData {
2358 let row_text = |row: &TableRow| {
2359 row.children
2360 .iter()
2361 .map(|cell| cell.children.text().trim().to_string())
2362 .collect::<Vec<_>>()
2363 };
2364
2365 TableData {
2366 headers: self.children.first().map(row_text).unwrap_or_default(),
2367 rows: self.children.iter().skip(1).map(row_text).collect(),
2368 markdown: self.to_markdown(),
2369 span: self.span.map(|span| span.start..span.end),
2370 }
2371 }
2372
2373 fn cached_table_data(&self) -> Arc<TableData> {
2378 if let Ok(cache) = self.table_data_cache.0.lock()
2379 && let Some(cached) = cache.as_ref()
2380 {
2381 return cached.clone();
2382 }
2383
2384 let data = Arc::new(self.table_data());
2385 if let Ok(mut cache) = self.table_data_cache.0.lock() {
2386 *cache = Some(data.clone());
2387 }
2388 data
2389 }
2390}
2391
2392#[derive(Debug, Default, Copy, Clone, PartialEq)]
2394pub enum ColumnumnAlign {
2395 #[default]
2397 None,
2398 Left,
2399 Center,
2400 Right,
2401}
2402
2403impl From<mdast::AlignKind> for ColumnumnAlign {
2404 fn from(value: mdast::AlignKind) -> Self {
2405 match value {
2406 mdast::AlignKind::None => ColumnumnAlign::None,
2407 mdast::AlignKind::Left => ColumnumnAlign::Left,
2408 mdast::AlignKind::Center => ColumnumnAlign::Center,
2409 mdast::AlignKind::Right => ColumnumnAlign::Right,
2410 }
2411 }
2412}
2413
2414#[derive(Debug, Clone, Default, PartialEq)]
2415pub(crate) struct TableRow {
2416 pub children: Vec<TableCell>,
2417}
2418
2419#[derive(Debug, Clone, Default, PartialEq)]
2420pub(crate) struct TableCell {
2421 pub children: Paragraph,
2422 pub width: Option<DefiniteLength>,
2423}
2424
2425impl Paragraph {
2426 pub(crate) fn take(&mut self) -> Paragraph {
2427 std::mem::replace(
2428 self,
2429 Paragraph {
2430 span: None,
2431 children: vec![],
2432 link_refs: Default::default(),
2433 state: Arc::new(Mutex::new(InlineState::default())),
2434 render_cache: ParagraphRenderCache::default(),
2435 },
2436 )
2437 }
2438
2439 pub(crate) fn is_image(&self) -> bool {
2440 false
2441 }
2442
2443 pub(crate) fn set_span(&mut self, span: Span) {
2444 self.span = Some(span);
2445 }
2446
2447 pub(crate) fn push_str(&mut self, text: &str) {
2448 self.children.push(
2449 InlineNode::new(text.to_string()).marks(vec![(0..text.len(), TextMark::default())]),
2450 );
2451 self.invalidate_render_cache();
2452 }
2453
2454 pub fn push(&mut self, text: InlineNode) {
2456 self.children.push(text);
2457 self.invalidate_render_cache();
2458 }
2459
2460 pub fn children(&self) -> &[InlineNode] {
2462 &self.children
2463 }
2464
2465 pub fn with_leaf_key(mut self, key: u64) -> Self {
2470 set_leaf_key(&mut self.state, key);
2471 self
2472 }
2473
2474 pub(crate) fn push_image(&mut self, image: ImageNode) {
2475 self.children.push(InlineNode::image(image));
2476 self.invalidate_render_cache();
2477 }
2478
2479 fn invalidate_render_cache(&mut self) {
2481 self.render_cache = ParagraphRenderCache::default();
2482 }
2483
2484 pub(crate) fn is_empty(&self) -> bool {
2485 self.children.is_empty()
2486 || self
2487 .children
2488 .iter()
2489 .all(|node| node.text.is_empty() && node.image.is_none())
2490 }
2491
2492 pub(crate) fn text_len(&self) -> usize {
2494 self.children
2495 .iter()
2496 .map(|node| node.text.len())
2497 .sum::<usize>()
2498 }
2499
2500 pub(crate) fn merge(&mut self, other: Self) {
2501 self.children.extend(other.children);
2502 self.invalidate_render_cache();
2503 }
2504}
2505
2506#[derive(Debug, Clone)]
2507pub struct CodeBlock {
2508 lang: Option<SharedString>,
2509 meta: Option<SharedString>,
2510 state: Arc<Mutex<InlineState>>,
2511 highlight_cache: Arc<Mutex<Option<CachedCodeBlockHighlights>>>,
2512 pub(crate) source_segments: Vec<SourceSegment>,
2515 pub span: Option<Span>,
2516}
2517
2518struct CachedCodeBlockHighlights {
2519 highlighter: Arc<CodeBlockHighlighterFn>,
2520 styles: Vec<(Range<usize>, HighlightStyle)>,
2521}
2522
2523impl std::fmt::Debug for CachedCodeBlockHighlights {
2524 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2525 f.debug_struct("CachedCodeBlockHighlights")
2526 .field("styles", &self.styles)
2527 .finish_non_exhaustive()
2528 }
2529}
2530
2531impl PartialEq for CodeBlock {
2532 fn eq(&self, other: &Self) -> bool {
2533 self.lang == other.lang
2534 && self.meta == other.meta
2535 && self.code() == other.code()
2536 && self.span == other.span
2537 }
2538}
2539
2540impl CodeBlock {
2541 pub fn lang(&self) -> Option<SharedString> {
2543 self.lang.clone()
2544 }
2545
2546 pub fn meta(&self) -> Option<SharedString> {
2548 self.meta.clone()
2549 }
2550
2551 pub fn with_meta(mut self, meta: Option<SharedString>) -> Self {
2554 self.meta = meta;
2555 self
2556 }
2557
2558 pub fn with_leaf_key(mut self, key: u64) -> Self {
2561 set_leaf_key(&mut self.state, key);
2562 self
2563 }
2564
2565 pub fn code(&self) -> SharedString {
2567 self.state
2568 .lock()
2569 .map(|state| state.text.clone())
2570 .unwrap_or_default()
2571 }
2572
2573 pub fn from_code(code: impl Into<SharedString>, lang: Option<impl Into<SharedString>>) -> Self {
2579 Self::new(code.into(), lang.map(Into::into), None::<Span>)
2580 }
2581
2582 pub fn new(
2584 code: SharedString,
2585 lang: Option<SharedString>,
2586 span: Option<impl Into<Span>>,
2587 ) -> Self {
2588 let state = Arc::new(Mutex::new(InlineState::default()));
2589 if let Ok(mut state) = state.lock() {
2590 state.set_text(code);
2591 }
2592
2593 Self {
2594 lang,
2595 meta: None,
2596 state,
2597 highlight_cache: Arc::new(Mutex::new(None)),
2598 source_segments: vec![],
2599 span: span.map(|s| s.into()),
2600 }
2601 }
2602
2603 pub(crate) fn source_segments(mut self, source_segments: Vec<SourceSegment>) -> Self {
2604 self.source_segments = source_segments;
2605 self
2606 }
2607
2608 #[cfg(test)]
2609 pub(crate) fn set_selection(&self, selection: Range<usize>) {
2610 if let Ok(mut state) = self.state.lock() {
2611 state.selection = Some(selection.into());
2612 }
2613 }
2614
2615 pub(super) fn selected_source_range(&self) -> SourceRangeSelection {
2616 let Ok(state) = self.state.lock() else {
2617 return SourceRangeSelection::Unmapped;
2618 };
2619 let Some(selection) = state.selection else {
2620 return SourceRangeSelection::Unselected;
2621 };
2622 if selection.start >= selection.end {
2623 return SourceRangeSelection::Unselected;
2624 }
2625 source_range_for_segments(&self.source_segments, selection.start..selection.end)
2626 .map(SourceRangeSelection::Mapped)
2627 .unwrap_or(SourceRangeSelection::Unmapped)
2628 }
2629
2630 fn highlighted_styles(
2631 &self,
2632 highlighter: &Arc<CodeBlockHighlighterFn>,
2633 ) -> Vec<(Range<usize>, HighlightStyle)> {
2634 if let Ok(cache) = self.highlight_cache.lock()
2635 && let Some(cache) = cache.as_ref()
2636 && Arc::ptr_eq(&cache.highlighter, highlighter)
2637 {
2638 return cache.styles.clone();
2639 }
2640
2641 let code_len = self.code().len();
2642 let styles = highlighter(self)
2643 .into_iter()
2644 .filter(|(range, _)| range.start <= range.end && range.end <= code_len)
2645 .collect::<Vec<_>>();
2646 if let Ok(mut cache) = self.highlight_cache.lock() {
2647 *cache = Some(CachedCodeBlockHighlights {
2648 highlighter: highlighter.clone(),
2649 styles: styles.clone(),
2650 });
2651 }
2652 styles
2653 }
2654
2655 pub(super) fn selected_text(&self) -> String {
2656 let mut text = String::new();
2657 if let Ok(state) = self.state.lock()
2658 && let Some(selection) = &state.selection
2659 {
2660 text.push_str(&state.text[selection.start..selection.end]);
2661 }
2662 text
2663 }
2664
2665 pub(super) fn selected_source(&self) -> String {
2672 let code = self.selected_text();
2673 if code.is_empty() {
2674 return String::new();
2675 }
2676 let lang = self.lang.clone().unwrap_or_default();
2677 let code = code.trim_end_matches('\n');
2680 format!("```{}\n{}\n```", lang, code)
2681 }
2682
2683 pub(super) fn text(&self) -> String {
2684 self.state
2685 .lock()
2686 .map(|state| state.text.to_string())
2687 .unwrap_or_default()
2688 }
2689
2690 pub(super) fn has_selection(&self) -> bool {
2694 self.state
2695 .lock()
2696 .is_ok_and(|state| state.selection.is_some())
2697 }
2698
2699 pub(super) fn clear_selection(&self) {
2700 if let Ok(mut state) = self.state.lock() {
2701 state.selection = None;
2702 }
2703 }
2704
2705 fn render(
2706 &self,
2707 options: &NodeRenderOptions,
2708 node_cx: &NodeContext,
2709 window: &mut Window,
2710 cx: &mut App,
2711 ) -> AnyElement {
2712 let style = &node_cx.style;
2713 let leaf_key = self.span.map(|span| TextLeafKey::block(span.start));
2714 let lang_label = self
2719 .lang()
2720 .filter(|lang| !lang.is_empty() && node_cx.code_block_actions.is_none())
2721 .map(|lang| {
2722 div()
2723 .absolute()
2724 .top(px(7.))
2725 .right_3()
2726 .font_family(cx.theme().tokens.typography.sans)
2727 .text_size(cx.theme().tokens.typography.xs.size)
2728 .line_height(px(16.))
2729 .text_color(style.muted_foreground())
2730 .child(lang)
2731 });
2732
2733 let block = div()
2734 .w_full()
2735 .min_w_0()
2736 .px_4()
2737 .pt(if lang_label.is_some() {
2738 px(28.)
2739 } else {
2740 px(14.)
2741 })
2742 .pb(px(14.))
2743 .bg(style.code_background())
2744 .border_1()
2745 .border_color(style.border())
2746 .font_family(cx.theme().tokens.typography.mono)
2747 .text_size(cx.theme().tokens.typography.mono_md.size)
2748 .line_height(relative(1.6))
2749 .relative()
2750 .refine_style(&style.code_block())
2751 .child(
2752 Inline::new(
2753 self.state.clone(),
2754 vec![],
2755 fade_highlights(
2756 node_cx
2757 .code_block_highlighter
2758 .as_ref()
2759 .map(|highlighter| self.highlighted_styles(highlighter))
2760 .unwrap_or_default()
2761 .into_iter()
2762 .map(|(range, style)| (range, InlineHighlight::from(style)))
2763 .collect(),
2764 node_cx.stream_fades(leaf_key),
2765 ),
2766 node_cx.link_click_handler.clone(),
2767 )
2768 .range_backgrounds(node_cx.range_backgrounds(leaf_key).to_vec())
2769 .reveal(node_cx.reveal_at(leaf_key, 0, self.code().len())),
2770 );
2771 let actions = node_cx.code_block_actions.clone().map(|actions| {
2772 div()
2773 .id("actions")
2774 .absolute()
2775 .top_2()
2776 .right_2()
2777 .bg(style.code_background())
2778 .rounded(cx.theme().tokens.radius.md)
2779 .child(actions(&self, window, cx))
2780 });
2781 let id = block_element_id("codeblock", self.span, options.ix);
2784 let block = if matches!(style.code_block().overflow.y, Some(Overflow::Scroll)) {
2785 let scroll_handle = window
2786 .use_keyed_state(
2787 block_element_id("codeblock-scroll", self.span, options.ix),
2788 cx,
2789 |_, _| ScrollHandle::default(),
2790 )
2791 .read(cx)
2792 .clone();
2793 div()
2800 .id(id.clone())
2801 .w_full()
2802 .min_w_0()
2803 .relative()
2804 .child(block.id("scroll").track_scroll(&scroll_handle))
2805 .child(ScrollableMask::new(Axis::Vertical, &scroll_handle).id(id))
2806 .child(
2807 div()
2808 .absolute()
2809 .inset_0()
2810 .child(Scrollbar::vertical(&scroll_handle)),
2811 )
2812 .children(actions)
2813 .children(lang_label)
2814 .into_any_element()
2815 } else {
2816 match actions {
2818 Some(actions) => block.id(id).child(actions).into_any_element(),
2819 None => block.children(lang_label).into_any_element(),
2820 }
2821 };
2822
2823 gapped(
2824 block,
2825 if options.is_last {
2826 rems(0.)
2827 } else {
2828 style.paragraph_gap()
2829 },
2830 )
2831 }
2832}
2833
2834#[derive(Default, Clone)]
2836pub(crate) struct NodeContext {
2837 pub(crate) offset: usize,
2840 pub(crate) link_refs: HashMap<SharedString, LinkMark>,
2841 pub(crate) style: Arc<TextViewStyle>,
2842 pub(crate) code_block_actions: Option<Arc<CodeBlockActionsFn>>,
2843 pub(crate) code_block_highlighter: Option<Arc<CodeBlockHighlighterFn>>,
2844 pub(crate) table_actions: Option<Arc<TableActionsFn>>,
2845 pub(crate) image_source: Option<Arc<super::text_view::ImageSourceFn>>,
2846 pub(crate) link_click_handler: Option<Arc<LinkClickHandlerFn>>,
2847 pub(crate) link_hook: Option<Arc<LinkFn>>,
2850 pub(crate) task_toggle_handler: Option<Arc<TaskToggleHandlerFn>>,
2851 pub(crate) markdown_extensions: Arc<MarkdownExtensions>,
2852 pub(crate) stream_fade: Option<Arc<StreamFadeFrame>>,
2854 pub(crate) range_highlights: Option<Arc<RangeHighlightFrame>>,
2856 pub(crate) foregrounds: Option<Arc<HashMap<u64, Vec<(Range<usize>, Hsla)>>>>,
2858 pub(crate) reveal: Option<RevealRequest>,
2860 pub(crate) body_font_size: Pixels,
2863}
2864
2865impl NodeContext {
2866 pub(crate) fn link(&self, link: &LinkMark, cx: &App) -> Option<LinkMark> {
2870 let resolved = link
2871 .identifier
2872 .as_ref()
2873 .and_then(|identifier| self.link_refs.get(identifier))
2874 .unwrap_or(link);
2875 let Some(hook) = &self.link_hook else {
2876 return Some(resolved.clone());
2877 };
2878 let replaced = hook(
2879 &Link {
2880 url: resolved.url.clone(),
2881 title: resolved.title.clone(),
2882 },
2883 cx,
2884 )?;
2885 Some(LinkMark {
2886 url: replaced.url,
2887 identifier: None,
2888 title: replaced.title,
2889 })
2890 }
2891
2892 fn foregrounds(&self, key: Option<u64>) -> &[(Range<usize>, Hsla)] {
2893 key.and_then(|key| self.foregrounds.as_ref()?.get(&key))
2894 .map_or(&[], Vec::as_slice)
2895 }
2896
2897 fn image_source(&self, image: &ImageNode) -> ImageSource {
2898 match &self.image_source {
2899 Some(resolve) => resolve(&image.url),
2900 None => image.source(),
2901 }
2902 }
2903
2904 pub(super) fn add_ref(&mut self, identifier: SharedString, link: LinkMark) {
2905 self.link_refs.insert(identifier, link);
2906 }
2907
2908 fn stream_fades(&self, key: Option<TextLeafKey>) -> &[(Range<usize>, f32)] {
2910 match (&self.stream_fade, key) {
2911 (Some(frame), Some(key)) => frame.fades(key).unwrap_or_default(),
2912 _ => &[],
2913 }
2914 }
2915
2916 fn range_backgrounds(&self, key: Option<TextLeafKey>) -> &[(Range<usize>, Hsla)] {
2919 match (&self.range_highlights, key) {
2920 (Some(frame), Some(key)) => frame.backgrounds(key),
2921 _ => &[],
2922 }
2923 }
2924
2925 fn reveal_at(&self, key: Option<TextLeafKey>, start: usize, end: usize) -> Option<RevealAt> {
2928 self.reveal.as_ref()?.at(key, start, end)
2929 }
2930}
2931
2932impl PartialEq for NodeContext {
2933 fn eq(&self, other: &Self) -> bool {
2934 self.link_refs == other.link_refs && self.style == other.style
2935 }
2938}
2939
2940fn mark_text_color(highlight: Hsla, background: Hsla) -> Hsla {
2943 fn channel(value: f32) -> f32 {
2944 if value <= 0.04045 {
2945 value / 12.92
2946 } else {
2947 ((value + 0.055) / 1.055).powf(2.4)
2948 }
2949 }
2950 let rgb = background.to_rgb().blend(highlight.to_rgb());
2951 let luminance = 0.2126 * channel(rgb.r) + 0.7152 * channel(rgb.g) + 0.0722 * channel(rgb.b);
2952 if (luminance + 0.05) * (luminance + 0.05) > 0.0525 {
2955 gpui::black()
2956 } else {
2957 gpui::white()
2958 }
2959}
2960
2961fn mark_highlight(mark: &TextMark, node_cx: &NodeContext, cx: &App) -> InlineHighlight {
2964 let mut highlight = HighlightStyle::default();
2965 if mark.bold {
2966 highlight.font_weight = Some(FontWeight::BOLD);
2967 }
2968 if mark.italic {
2969 highlight.font_style = Some(FontStyle::Italic);
2970 }
2971 if mark.strikethrough {
2972 highlight.strikethrough = Some(gpui::StrikethroughStyle {
2973 thickness: gpui::px(1.),
2974 ..Default::default()
2975 });
2976 }
2977 if mark.underline {
2978 highlight.underline = Some(gpui::UnderlineStyle {
2979 thickness: gpui::px(1.),
2980 ..Default::default()
2981 });
2982 }
2983 let mut font_family = None;
2984 if mark.code {
2985 highlight = highlight.highlight(node_cx.style.inline_code_highlight());
2986 let style = node_cx.style.inline_code_style();
2987 highlight = highlight.highlight(HighlightStyle {
2988 color: style.text.color,
2989 font_weight: style.text.font_weight,
2990 font_style: style.text.font_style,
2991 underline: style.text.underline,
2992 strikethrough: style.text.strikethrough,
2993 ..Default::default()
2994 });
2995 font_family = Some(
2996 style
2997 .text
2998 .font_family
2999 .clone()
3000 .unwrap_or_else(|| cx.theme().tokens.typography.mono),
3001 );
3002 }
3003 if let Some(color) = mark.highlight {
3004 highlight.background_color = Some(color);
3005 if color.a > 0.0 {
3011 highlight.color = Some(mark_text_color(color, cx.theme().tokens.colors.background));
3012 }
3013 }
3014 InlineHighlight {
3015 style: highlight,
3016 font_family,
3017 font_size_scale: mark.code.then_some(0.875),
3018 code_style: mark.code.then(|| node_cx.style.inline_code_style().clone()),
3019 }
3020}
3021
3022fn append_node_highlights(
3023 highlights: &mut Vec<(Range<usize>, InlineHighlight)>,
3024 node_highlights: Vec<(Range<usize>, InlineHighlight)>,
3025) {
3026 if highlights.last().is_some_and(|(last, _)| {
3029 node_highlights
3030 .iter()
3031 .any(|(range, _)| !range.is_empty() && range.start < last.end)
3032 }) {
3033 *highlights = combine_highlights(std::mem::take(highlights), node_highlights);
3034 } else {
3035 highlights.extend(combine_highlights([], node_highlights));
3036 }
3037}
3038
3039impl Paragraph {
3040 fn inline_highlights(
3044 &self,
3045 node_cx: &NodeContext,
3046 cx: &App,
3047 ) -> Vec<(Range<usize>, InlineHighlight)> {
3048 let mut highlights = vec![];
3049 let mut offset = 0;
3050 for inline_node in &self.children {
3051 let node_highlights = inline_node
3052 .marks
3053 .iter()
3054 .map(|(range, mark)| {
3055 (
3056 (offset + range.start)..(offset + range.end),
3057 mark_highlight(mark, node_cx, cx),
3058 )
3059 })
3060 .collect::<Vec<_>>();
3061 append_node_highlights(&mut highlights, node_highlights);
3062 offset += inline_node.text.len();
3063 }
3064 highlights
3065 }
3066
3067 fn render(
3071 &self,
3072 fade_key: Option<TextLeafKey>,
3073 node_cx: &NodeContext,
3074 _window: &mut Window,
3075 cx: &mut App,
3076 ) -> AnyElement {
3077 let children = &self.children;
3078 let fades = node_cx.stream_fades(fade_key);
3079 let backgrounds = node_cx.range_backgrounds(fade_key);
3080
3081 if self.should_render_inline_flow() {
3082 return InlineFlow::new(
3083 self.element_id(fade_key),
3084 self.inline_flow_items(fade_key, fades, backgrounds, node_cx, cx),
3085 node_cx.link_click_handler.clone(),
3086 )
3087 .editor_key(self.leaf_key())
3088 .into_any_element();
3089 }
3090
3091 let has_image = children.iter().any(|child| child.image.is_some());
3092 if !has_image {
3095 let (text, highlights, links) = self.plain_render(node_cx, cx);
3096 if text.is_empty() && self.leaf_key().is_none() {
3099 return div().into_any_element();
3100 }
3101 let highlights = fade_highlights(highlights, &slice_fades(fades, 0, text.len()));
3102 let backgrounds = slice_backgrounds(backgrounds, 0, text.len());
3103 let reveal = node_cx.reveal_at(fade_key, 0, text.len());
3104 if let Ok(mut state) = self.state.lock() {
3105 state.set_text(text);
3106 }
3107 return Inline::new(
3108 self.state.clone(),
3109 links,
3110 highlights,
3111 node_cx.link_click_handler.clone(),
3112 )
3113 .range_backgrounds(backgrounds)
3114 .reveal(reveal)
3115 .into_any_element();
3116 }
3117
3118 let mut child_nodes: Vec<AnyElement> = vec![];
3119
3120 let mut text = String::new();
3121 let mut highlights: Vec<(Range<usize>, InlineHighlight)> = vec![];
3122 let mut links: Vec<(Range<usize>, LinkMark)> = vec![];
3123 let mut offset = 0;
3124 let mut consumed = 0;
3127
3128 for (ix, inline_node) in children.iter().enumerate() {
3129 let text_len = inline_node.text.len();
3130 text.push_str(&inline_node.text);
3131
3132 if let Some(image) = &inline_node.image {
3133 if text.len() > 0 {
3134 if let Ok(mut state) = inline_node.state.lock() {
3135 state.set_text(text.clone().into());
3136 }
3137 child_nodes.push(
3138 Inline::new(
3139 inline_node.state.clone(),
3140 links.clone(),
3141 fade_highlights(
3142 highlights.clone(),
3143 &slice_fades(fades, consumed, consumed + text.len()),
3144 ),
3145 node_cx.link_click_handler.clone(),
3146 )
3147 .range_backgrounds(slice_backgrounds(
3148 backgrounds,
3149 consumed,
3150 consumed + text.len(),
3151 ))
3152 .reveal(node_cx.reveal_at(fade_key, consumed, consumed + text.len()))
3153 .into_any_element(),
3154 );
3155 }
3156 let link_click_handler = node_cx.link_click_handler.clone();
3157 let image_link = image.link.as_ref().and_then(|link| node_cx.link(link, cx));
3158 child_nodes.push(
3159 img(node_cx.image_source(image))
3160 .id(ix)
3161 .object_fit(ObjectFit::Contain)
3162 .max_w(relative(1.))
3163 .when_some(image.width, |this, width| this.w(width))
3164 .when_some(image_link, |this, link| {
3165 linked_image(this, link.url, link_click_handler.clone())
3166 })
3167 .into_any_element(),
3168 );
3169
3170 consumed += text.len();
3171 text.clear();
3172 links.clear();
3173 highlights.clear();
3174 offset = 0;
3175 } else {
3176 let mut node_highlights = vec![];
3177 for (range, style) in &inline_node.marks {
3178 let inner_range = (offset + range.start)..(offset + range.end);
3179 let mut highlight = mark_highlight(style, node_cx, cx);
3180
3181 if let Some(link_mark) = style.link.as_ref()
3182 && let Some(link) = node_cx.link(link_mark, cx)
3183 {
3184 highlight.style.color = Some(node_cx.style.link());
3185 highlight.style.underline = Some(link_underline(&node_cx.style));
3186 links.push((inner_range.clone(), link));
3187 }
3188
3189 node_highlights.push((inner_range, highlight));
3190 }
3191
3192 append_node_highlights(&mut highlights, node_highlights);
3193 offset += text_len;
3194 }
3195 }
3196
3197 if text.len() > 0 {
3199 let text_end = consumed + text.len();
3200 let highlights = fade_highlights(highlights, &slice_fades(fades, consumed, text_end));
3201 if let Ok(mut state) = self.state.lock() {
3202 state.set_text(text.into());
3203 }
3204 child_nodes.push(
3205 Inline::new(
3206 self.state.clone(),
3207 links,
3208 highlights,
3209 node_cx.link_click_handler.clone(),
3210 )
3211 .range_backgrounds(slice_backgrounds(backgrounds, consumed, text_end))
3212 .reveal(node_cx.reveal_at(fade_key, consumed, text_end))
3213 .into_any_element(),
3214 );
3215 }
3216
3217 if !has_image {
3221 return child_nodes
3222 .pop()
3223 .unwrap_or_else(|| div().into_any_element());
3224 }
3225
3226 div()
3227 .id(self.element_id(fade_key))
3228 .children(child_nodes)
3229 .into_any_element()
3230 }
3231
3232 fn element_id(&self, fade_key: Option<TextLeafKey>) -> ElementId {
3240 match fade_key {
3241 Some(key) => ElementId::from(key),
3242 None => ElementId::NamedInteger(
3243 "p".into(),
3244 Arc::as_ptr(&self.state) as *const () as usize as u64,
3245 ),
3246 }
3247 }
3248
3249 fn leaf_key(&self) -> Option<u64> {
3251 self.state.lock().ok().and_then(|state| state.editor_key)
3252 }
3253
3254 fn should_render_inline_flow(&self) -> bool {
3255 let images = self
3256 .children
3257 .iter()
3258 .filter(|child| child.image.is_some())
3259 .count();
3260 let has_text = self.children.iter().any(|child| !child.text.is_empty());
3261 if images > 0 && self.leaf_key().is_some() {
3265 return true;
3266 }
3267 self.children.iter().any(|child| child.custom.is_some())
3270 || images > 1
3271 || (images > 0 && has_text)
3272 || self
3273 .children
3274 .iter()
3275 .any(|child| child.marks.iter().any(|(_, mark)| mark.code))
3276 }
3277
3278 fn inline_flow_items(
3283 &self,
3284 leaf_key: Option<TextLeafKey>,
3285 fades: &[(Range<usize>, f32)],
3286 backgrounds: &[(Range<usize>, Hsla)],
3287 node_cx: &NodeContext,
3288 cx: &mut App,
3289 ) -> Vec<InlineFlowItem> {
3290 let render = self.flow_render(node_cx, cx);
3291 let mut items = Vec::new();
3292 let mut consumed = 0;
3295
3296 for flow_text in &render.texts {
3297 let ending = flow_text.end.map(|ix| &self.children[ix]);
3298 let state = ending.map_or(&self.state, |child| &child.state);
3299 if (!flow_text.text.is_empty() || ending.is_some_and(|child| child.custom.is_some()))
3302 && let Ok(mut state) = state.lock()
3303 {
3304 state.set_text(flow_text.text.clone());
3305 }
3306 if !flow_text.text.is_empty() {
3307 let text_end = consumed + flow_text.text.len();
3308 items.push(InlineFlowItem::Text {
3309 state: state.clone(),
3310 text: flow_text.text.clone(),
3311 links: flow_text.links.clone(),
3312 highlights: fade_highlights(
3313 flow_text.highlights.clone(),
3314 &slice_fades(fades, consumed, text_end),
3315 ),
3316 backgrounds: slice_backgrounds(backgrounds, consumed, text_end),
3317 reveal: node_cx.reveal_at(leaf_key, consumed, text_end),
3318 });
3319 consumed = text_end;
3320 }
3321
3322 let Some(child) = ending else {
3323 continue;
3324 };
3325 if let Some(node) = &child.custom {
3326 let mut object_style = HighlightStyle::default();
3327 let mut object_link = None;
3328 for (_, mark) in &child.marks {
3329 object_style = object_style.highlight(mark_highlight(mark, node_cx, cx).style);
3330 if let Some(link) = mark.link.as_ref().and_then(|link| node_cx.link(link, cx)) {
3331 object_link = Some(link);
3332 object_style.color = Some(node_cx.style.link());
3333 object_style.underline = Some(link_underline(&node_cx.style));
3334 }
3335 }
3336 let rendered_node = node.clone();
3337 let extensions = node_cx.markdown_extensions.clone();
3338 items.push(InlineFlowItem::Object {
3339 text: node.shared_text(),
3340 accessibility_label: node.shared_accessibility_name(),
3341 id: node.source_range().map_or(items.len(), |range| range.start),
3342 renderer: Arc::new(move |context, window, cx| {
3343 extensions.render_inline(&rendered_node, context, window, cx)
3344 }),
3345 selected: child.custom_selection.clone(),
3346 style: object_style,
3347 link: object_link,
3348 });
3349 consumed += child.text.len();
3350 } else if let Some(image) = &child.image {
3351 items.push(InlineFlowItem::Image {
3352 source: node_cx.image_source(image),
3353 link: image.link.as_ref().and_then(|link| node_cx.link(link, cx)),
3354 title: image.title(),
3355 width: image.width,
3356 height: image.height,
3357 });
3358 }
3359 }
3360
3361 let foregrounds = node_cx.foregrounds(self.leaf_key());
3362 if !foregrounds.is_empty() {
3363 let mut offset = 0;
3364 for item in &mut items {
3365 match item {
3366 InlineFlowItem::Text {
3367 text, highlights, ..
3368 } => {
3369 *highlights =
3370 foreground_highlights(highlights.clone(), text, offset, foregrounds);
3371 offset += text.len();
3372 }
3373 InlineFlowItem::Object { style, .. } => {
3374 let end = offset + '\u{FFFC}'.len_utf8();
3375 if let Some((_, color)) = foregrounds
3376 .iter()
3377 .rev()
3378 .find(|(range, _)| range.start <= offset && end <= range.end)
3379 {
3380 style.color = Some(*color);
3381 }
3382 offset = end;
3383 }
3384 InlineFlowItem::Image { .. } => offset += '\u{FFFC}'.len_utf8(),
3385 }
3386 }
3387 }
3388 items
3389 }
3390
3391 fn flow_render(&self, node_cx: &NodeContext, cx: &App) -> Arc<FlowRender> {
3394 let cached = self
3395 .render_cache
3396 .flow
3397 .lock()
3398 .ok()
3399 .and_then(|cache| cache.clone());
3400 if let Some(cached) = cached
3401 && cached.is_current(node_cx, cx)
3402 {
3403 return cached;
3404 }
3405
3406 let mut texts = Vec::new();
3407 let mut written = Vec::new();
3408 let mut text = String::new();
3409 let mut highlights: Vec<(Range<usize>, InlineHighlight)> = vec![];
3410 let mut links: Vec<(Range<usize>, LinkMark)> = vec![];
3411 let mut offset = 0;
3412 for (ix, inline_node) in self.children.iter().enumerate() {
3413 if inline_node.custom.is_some() {
3414 texts.push(if text.is_empty() {
3417 FlowText {
3418 end: Some(ix),
3419 ..Default::default()
3420 }
3421 } else {
3422 FlowText {
3423 end: Some(ix),
3424 text: std::mem::take(&mut text).into(),
3425 highlights: std::mem::take(&mut highlights).into(),
3426 links: std::mem::take(&mut links).into(),
3427 }
3428 });
3429 offset = 0;
3430 continue;
3431 }
3432 text.push_str(&inline_node.text);
3433 if inline_node.image.is_some() {
3434 texts.push(FlowText {
3435 end: Some(ix),
3436 text: std::mem::take(&mut text).into(),
3437 highlights: std::mem::take(&mut highlights).into(),
3438 links: std::mem::take(&mut links).into(),
3439 });
3440 offset = 0;
3441 continue;
3442 }
3443
3444 let mut node_highlights = vec![];
3445 for (range, style) in &inline_node.marks {
3446 let inner_range = (offset + range.start)..(offset + range.end);
3447 let mut highlight = mark_highlight(style, node_cx, cx);
3448 if let Some(link_mark) = &style.link {
3449 let link = node_cx.link(link_mark, cx);
3450 if let Some(link) = &link {
3451 highlight.style.color = Some(node_cx.style.link());
3452 highlight.style.underline = Some(link_underline(&node_cx.style));
3453 links.push((inner_range.clone(), link.clone()));
3454 }
3455 written.push((link_mark.clone(), link));
3456 }
3457 node_highlights.push((inner_range, highlight));
3458 }
3459 append_node_highlights(&mut highlights, node_highlights);
3460 offset += inline_node.text.len();
3461 }
3462 texts.push(FlowText {
3463 end: None,
3464 text: text.into(),
3465 highlights: highlights.into(),
3466 links: links.into(),
3467 });
3468
3469 let render = Arc::new(FlowRender {
3470 style: RenderStyle::new(node_cx, cx),
3471 texts,
3472 links: written,
3473 });
3474 if let Ok(mut cache) = self.render_cache.flow.lock() {
3475 *cache = Some(render.clone());
3476 }
3477 render
3478 }
3479}
3480
3481fn block_element_id(kind: &'static str, span: Option<Span>, ix: usize) -> ElementId {
3486 (kind, span.map_or(ix, |span| span.start)).into()
3487}
3488
3489fn link_underline(style: &TextViewStyle) -> gpui::UnderlineStyle {
3492 gpui::UnderlineStyle {
3493 thickness: px(1.),
3494 color: Some(style.link().opacity(0.4)),
3495 ..Default::default()
3496 }
3497}
3498
3499fn body_font_size(node_cx: &NodeContext, window: &Window) -> Pixels {
3506 if node_cx.body_font_size > Pixels::ZERO {
3507 node_cx.body_font_size
3508 } else {
3509 window.text_style().font_size.to_pixels(window.rem_size())
3510 }
3511}
3512
3513fn heading_metrics(level: u8) -> (f32, f32, f32) {
3518 match level {
3519 1 => (1.8, 1.25, 1.1),
3520 2 => (4. / 3., 1.35, 1.6),
3521 3 => (17. / 15., 1.35, 1.4),
3522 4 => (1., 1.35, 1.4),
3523 5 => (14. / 15., 1.35, 1.4),
3524 _ => (13. / 15., 1.35, 1.4),
3525 }
3526}
3527
3528const HEADING_BOTTOM_GAP: f32 = 0.35;
3530
3531fn heading_size(level: u8, node_cx: &NodeContext, window: &Window) -> Pixels {
3534 node_cx.style.heading(level).text.font_size.map_or_else(
3535 || body_font_size(node_cx, window) * heading_metrics(level).0,
3536 |size| size.to_pixels(window.rem_size()),
3537 )
3538}
3539
3540fn rule_space(body_font_size: Pixels) -> Pixels {
3542 body_font_size * 1.6
3543}
3544
3545fn block_gap(options: &NodeRenderOptions, style: &TextViewStyle) -> Rems {
3547 if options.in_list || options.is_last {
3548 rems(0.)
3549 } else {
3550 style.paragraph_gap()
3551 }
3552}
3553
3554fn gapped(block: AnyElement, gap: Rems) -> AnyElement {
3557 if gap.is_zero() {
3558 block
3559 } else {
3560 div().pb(gap).child(block).into_any_element()
3561 }
3562}
3563
3564fn slice_fades(
3566 fades: &[(Range<usize>, f32)],
3567 start: usize,
3568 end: usize,
3569) -> Vec<(Range<usize>, f32)> {
3570 slice_ranges(fades, start, end, |range, fade_out| (range, *fade_out))
3571}
3572
3573fn slice_backgrounds(
3576 backgrounds: &[(Range<usize>, Hsla)],
3577 start: usize,
3578 end: usize,
3579) -> Vec<(Range<usize>, Hsla)> {
3580 slice_ranges(backgrounds, start, end, |range, color| (range, *color))
3581}
3582
3583struct TableColumn {
3585 max: f32,
3587 min: f32,
3589 divider: f32,
3590}
3591
3592fn table_cell_padding_x(style: &TextViewStyle, rem_size: Pixels) -> f32 {
3595 let padding = &style.table_cell().padding;
3596 let side = |length: Option<DefiniteLength>| match length {
3597 Some(DefiniteLength::Absolute(length)) => f32::from(length.to_pixels(rem_size)),
3598 _ => CELL_PAD_PX / 2.,
3599 };
3600 side(padding.left) + side(padding.right)
3601}
3602
3603const CELL_PAD_PX: f32 = 24.0; const CELL_MIN_PX: f32 = 48.0;
3605const CELL_BORDER_PX: f32 = 1.0; fn measure_table_columns(
3612 table: &Table,
3613 col_count: usize,
3614 node_cx: &NodeContext,
3615 window: &mut Window,
3616 cx: &mut App,
3617) -> Vec<f32> {
3618 let text_styles = TableTextStyles::new(&node_cx.style, window);
3619 let rem_size = window.rem_size();
3620 let mono_family = cx.theme().tokens.typography.mono;
3621 let inline_code = node_cx.style.inline_code_highlight();
3622 let cached = table.column_widths_cache.0.lock().ok().and_then(|cache| {
3623 cache
3624 .as_ref()
3625 .filter(|cached| {
3626 cached.widths.len() == col_count
3627 && cached.text_styles == text_styles
3628 && cached.rem_size == rem_size
3629 && cached.mono_family == mono_family
3630 && cached.inline_code == inline_code
3631 && cached.text_system == text_system_id(window)
3632 })
3633 .cloned()
3634 });
3635 let measured = cached.unwrap_or_else(|| {
3636 let (widths, custom_cells) =
3637 measure_table_text_columns(table, col_count, &text_styles, node_cx, window, cx);
3638 let measured = Arc::new(TableColumnWidths {
3639 text_system: text_system_id(window),
3640 text_styles: text_styles.clone(),
3641 rem_size,
3642 mono_family,
3643 inline_code,
3644 widths,
3645 custom_cells,
3646 });
3647 if let Ok(mut cache) = table.column_widths_cache.0.lock() {
3648 *cache = Some(measured.clone());
3649 }
3650 measured
3651 });
3652
3653 let mut col_w = measured.widths.clone();
3657 for &(row_ix, ix) in &measured.custom_cells {
3658 let cell = &table.children[row_ix].children[ix];
3659 let items = cell.children.inline_flow_items(None, &[], &[], node_cx, cx);
3660 let style = text_styles.row_refinement(row_ix).clone();
3661 let width = window.with_text_style(Some(style), |window| {
3662 super::inline_flow::intrinsic_width(&items, window, cx)
3663 });
3664 let border = if ix + 1 < col_count {
3665 CELL_BORDER_PX
3666 } else {
3667 0.
3668 };
3669 col_w[ix] = col_w[ix].max(f32::from(width) + CELL_PAD_PX + border);
3670 }
3671 col_w
3672}
3673
3674fn measure_table_text_columns(
3677 table: &Table,
3678 col_count: usize,
3679 text_styles: &TableTextStyles,
3680 node_cx: &NodeContext,
3681 window: &mut Window,
3682 cx: &mut App,
3683) -> (Vec<f32>, Vec<(usize, usize)>) {
3684 let mut col_w = vec![CELL_MIN_PX; col_count];
3685 let mut custom_cells = Vec::new();
3686 for (row_ix, row) in table.children.iter().enumerate() {
3687 let text_style = text_styles.row(row_ix);
3688 let font_size = text_style.font_size.to_pixels(window.rem_size());
3689 for (ix, cell) in row.children.iter().enumerate() {
3690 let Some(slot) = col_w.get_mut(ix) else {
3691 continue;
3692 };
3693 if cell
3694 .children
3695 .children
3696 .iter()
3697 .any(|node| node.custom.is_some() || node.image.is_some())
3698 {
3699 custom_cells.push((row_ix, ix));
3700 continue;
3701 }
3702 let text = cell.children.text();
3703 let highlights = cell.children.inline_highlights(node_cx, cx);
3704 let mut w = 0.0_f32;
3705 let mut line_start = 0;
3706 for line in text.split('\n') {
3707 let start = line_start + (line.len() - line.trim_start().len());
3708 let line_end = line_start + line.len();
3709 line_start = line_end + 1;
3710 let line = line.trim();
3711 if line.is_empty() {
3712 continue;
3713 }
3714 let end = start + line.len();
3715 let line_highlights = highlights
3716 .iter()
3717 .filter_map(|(range, highlight)| {
3718 let clipped = range.start.max(start)..range.end.min(end);
3719 (clipped.start < clipped.end).then(|| {
3720 (
3721 clipped.start - start..clipped.end - start,
3722 highlight.clone(),
3723 )
3724 })
3725 })
3726 .collect::<Vec<_>>();
3727 let mut line_w = gpui::Pixels::ZERO;
3728 for (range, scale) in
3729 text_size_ranges(line.len(), &line_highlights, font_size, window.rem_size())
3730 {
3731 let highlights = slice_ranges(
3732 &line_highlights,
3733 range.start,
3734 range.end,
3735 |range, highlight| (range, highlight.clone()),
3736 );
3737 let insets = code_insets(&highlights, font_size * scale, window.rem_size());
3738 line_w += insets.left + insets.right;
3739 let runs = text_runs(range.len(), text_style, &highlights);
3740 line_w += window
3741 .text_system()
3742 .layout_line(&line[range], font_size * scale, &runs, None)
3743 .width;
3744 }
3745 w = w.max(f32::from(line_w));
3746 }
3747 let border = if ix + 1 < col_count {
3750 CELL_BORDER_PX
3751 } else {
3752 0.
3753 };
3754 *slot = slot.max(w + CELL_PAD_PX + border);
3755 }
3756 }
3757 (col_w, custom_cells)
3758}
3759
3760impl Paragraph {
3761 fn to_markdown(&self) -> String {
3762 if self.children.iter().any(|node| node.custom.is_some()) {
3763 let mut source = MarkdownSource::default();
3764 for node in &self.children {
3765 if node.custom.is_some() {
3766 source.push_object(node);
3767 } else {
3768 source.push_text(&node.text, &node.marks, 0..node.text.len());
3769 if let Some(image) = &node.image {
3770 source.push_str(&image_markdown(image));
3771 }
3772 }
3773 }
3774 let mut text = source.finish();
3775 text.push_str("\n\n");
3776 return text;
3777 }
3778 let mut text = self
3779 .children
3780 .iter()
3781 .map(|text_node| {
3782 let mut text = text_node.text.to_string();
3783 for (range, style) in &text_node.marks {
3784 if style.bold {
3785 text = format!("**{}**", &text_node.text[range.clone()]);
3786 }
3787 if style.italic {
3788 text = format!("*{}*", &text_node.text[range.clone()]);
3789 }
3790 if style.strikethrough {
3791 text = format!("~~{}~~", &text_node.text[range.clone()]);
3792 }
3793 if style.code {
3794 text = format!("`{}`", &text_node.text[range.clone()]);
3795 }
3796 if style.highlight.is_some() {
3797 text = format!("=={}==", &text_node.text[range.clone()]);
3798 }
3799 if let Some(link) = &style.link {
3800 text = format!("[{}]({})", &text_node.text[range.clone()], link.url);
3801 }
3802 }
3803
3804 if let Some(image) = &text_node.image {
3805 let alt = image.alt.clone().unwrap_or_default();
3806 let title = image
3807 .title
3808 .clone()
3809 .map_or(String::new(), |t| format!(" \"{}\"", t));
3810 text.push_str(&format!("", alt, image.url, title))
3811 }
3812
3813 text
3814 })
3815 .collect::<Vec<_>>()
3816 .join("");
3817
3818 text.push_str("\n\n");
3819 text
3820 }
3821}
3822
3823impl BlockNode {
3824 #[allow(dead_code)]
3828 pub(crate) fn to_markdown(&self) -> String {
3829 match self {
3830 BlockNode::Root { children, .. } => children
3831 .iter()
3832 .map(|child| child.to_markdown())
3833 .collect::<Vec<_>>()
3834 .join("\n\n"),
3835 BlockNode::Paragraph(paragraph) => paragraph.to_markdown(),
3836 BlockNode::Heading {
3837 level, children, ..
3838 } => {
3839 let hashes = "#".repeat(*level as usize);
3840 format!("{} {}", hashes, children.to_markdown())
3841 }
3842 BlockNode::Blockquote { children, .. } => {
3843 let content = children
3844 .iter()
3845 .map(|child| child.to_markdown())
3846 .collect::<Vec<_>>()
3847 .join("\n\n");
3848
3849 content
3850 .lines()
3851 .map(|line| format!("> {}", line))
3852 .collect::<Vec<_>>()
3853 .join("\n")
3854 }
3855 BlockNode::Surface { name, children, .. } => {
3856 let content = children
3857 .iter()
3858 .map(|child| child.to_markdown())
3859 .collect::<Vec<_>>()
3860 .join("\n\n");
3861 quoted_source(Some(name), &content)
3862 }
3863 BlockNode::List {
3864 children,
3865 ordered,
3866 start,
3867 ..
3868 } => children
3869 .iter()
3870 .enumerate()
3871 .map(|(i, child)| {
3872 let prefix = if *ordered {
3873 format!("{}. ", ordered_list_ordinal(*start, i))
3874 } else {
3875 "- ".to_string()
3876 };
3877 format!("{}{}", prefix, child.to_markdown())
3878 })
3879 .collect::<Vec<_>>()
3880 .join("\n"),
3881 BlockNode::ListItem {
3882 children, checked, ..
3883 } => {
3884 let checkbox = if let Some(checked) = checked {
3885 if *checked { "[x] " } else { "[ ] " }
3886 } else {
3887 ""
3888 };
3889 format!(
3890 "{}{}",
3891 checkbox,
3892 children
3893 .iter()
3894 .map(|child| child.to_markdown())
3895 .collect::<Vec<_>>()
3896 .join("\n")
3897 )
3898 }
3899 BlockNode::CodeBlock(code_block) => {
3900 format!(
3901 "```{}\n{}\n```",
3902 code_block.lang.clone().unwrap_or_default(),
3903 code_block.code()
3904 )
3905 }
3906 BlockNode::Table(table) => table.to_markdown(),
3907 BlockNode::Break { html, .. } => {
3908 if *html {
3909 "<br>".to_string()
3910 } else {
3911 "\n".to_string()
3912 }
3913 }
3914 BlockNode::HorizontalRule { .. } => "---".to_string(),
3915 BlockNode::Custom { node, .. } => node.to_markdown(),
3916 BlockNode::Definition {
3917 identifier,
3918 url,
3919 title,
3920 ..
3921 } => {
3922 if let Some(title) = title {
3923 format!("[{}]: {} \"{}\"", identifier, url, title)
3924 } else {
3925 format!("[{}]: {}", identifier, url)
3926 }
3927 }
3928 BlockNode::Unknown { .. } => "".to_string(),
3929 }
3930 .trim()
3931 .to_string()
3932 }
3933}
3934
3935impl BlockNode {
3936 #[allow(clippy::too_many_arguments)]
3939 fn render_list_item_row(
3940 content: AnyElement,
3941 ix: usize,
3942 options: NodeRenderOptions,
3943 checked: Option<bool>,
3944 task_toggle: Option<(Arc<TaskToggleHandlerFn>, TaskToggleEvent)>,
3945 style: &TextViewStyle,
3946 line_height: Pixels,
3947 indent: Pixels,
3948 ) -> Div {
3949 h_flex()
3950 .w_full()
3951 .min_w_0()
3952 .relative()
3953 .items_start()
3954 .content_start()
3955 .when(!options.todo && checked.is_none(), |this| {
3956 this.child(
3960 div()
3961 .flex_none()
3962 .min_w(indent)
3963 .pr(indent * 0.3)
3964 .text_right()
3965 .text_color(style.muted_foreground())
3966 .refine_style(style.list_style())
3967 .child(
3968 list_item_prefix(
3969 ix,
3970 options.list_start,
3971 options.ordered,
3972 options.depth,
3973 )
3974 .trim_end()
3975 .to_string(),
3976 ),
3977 )
3978 })
3979 .when_some(checked, |this, checked| {
3980 let check_svg = if style.is_dark() {
3982 CHECK_SVG_DARK
3983 } else {
3984 CHECK_SVG_LIGHT
3985 };
3986 this.child(
3987 div()
3988 .flex()
3989 .mr_2()
3990 .h(line_height)
3991 .flex_none()
3992 .items_center()
3993 .justify_center()
3994 .child(
3995 div()
3996 .flex()
3997 .size(rems(0.9375))
3998 .items_center()
3999 .justify_center()
4000 .rounded(px(4.))
4001 .border(px(1.5))
4002 .border_color(
4003 style
4004 .list_style()
4005 .text
4006 .color
4007 .unwrap_or(style.muted_foreground()),
4008 )
4009 .when(checked, |this| {
4010 this.bg(style.link()).border_color(style.link()).child(
4011 img(Arc::new(Image::from_bytes(
4012 ImageFormat::Svg,
4013 check_svg.to_vec(),
4014 )))
4015 .size(rems(0.75)),
4016 )
4017 }),
4018 )
4019 .map(|checkbox| match task_toggle {
4020 Some((handler, event)) => checkbox
4021 .id(("task-toggle", event.item_range().start))
4022 .on_click(move |_, window, cx| {
4023 crate::TextSelection::end(window, cx);
4024 cx.stop_propagation();
4025 handler(&event, window, cx);
4026 })
4027 .into_any_element(),
4028 None => checkbox.into_any_element(),
4029 }),
4030 )
4031 })
4032 .child(
4033 div()
4034 .flex_auto()
4037 .min_w_0()
4038 .overflow_hidden()
4039 .when(checked == Some(true), |this| {
4041 this.text_color(style.muted_foreground())
4042 })
4043 .child(content),
4044 )
4045 }
4046
4047 fn render_list_item(
4048 item: &BlockNode,
4049 ix: usize,
4050 options: NodeRenderOptions,
4051 node_cx: &NodeContext,
4052 window: &mut Window,
4053 cx: &mut App,
4054 ) -> AnyElement {
4055 match item {
4056 BlockNode::ListItem {
4057 children,
4058 spread,
4059 checked,
4060 task_marker,
4061 span,
4062 } => {
4063 let body = body_font_size(node_cx, window);
4064 let indent = body * 1.4;
4065 let task_toggle = match (&node_cx.task_toggle_handler, checked, span, task_marker) {
4066 (Some(handler), Some(checked), Some(item), Some(marker)) => Some((
4067 handler.clone(),
4068 TaskToggleEvent::new(
4069 !checked,
4070 item.start..item.end,
4071 marker.start..marker.end,
4072 ),
4073 )),
4074 _ => None,
4075 };
4076 div()
4077 .w_full()
4078 .min_w_0()
4079 .when(ix > 0, |this| this.pt(body * 0.25))
4081 .when(*spread, |this| this.child(div()))
4082 .children({
4083 let mut items: Vec<Div> = Vec::with_capacity(children.len());
4084
4085 for (child_ix, child) in children.iter().enumerate() {
4086 match child {
4087 BlockNode::Paragraph { .. } => {
4088 let continuation = child_ix > 0;
4089 let last_not_list = continuation
4090 && !matches!(
4091 children[child_ix - 1],
4092 BlockNode::List { .. }
4093 );
4094
4095 let text = child.render_block(
4096 NodeRenderOptions {
4097 depth: options.depth + 1,
4098 todo: checked.is_some(),
4099 is_last: true,
4100 ..options
4101 },
4102 node_cx,
4103 window,
4104 cx,
4105 );
4106
4107 if last_not_list {
4111 if let Some(preceding_row) = items.pop() {
4112 items.push(
4113 div().child(preceding_row).child(
4114 div()
4115 .w_full()
4116 .pl(indent)
4117 .overflow_hidden()
4118 .child(text),
4119 ),
4120 );
4121 continue;
4122 }
4123 }
4124
4125 if continuation {
4129 items.push(
4130 div()
4131 .w_full()
4132 .min_w_0()
4133 .pl(indent)
4134 .overflow_hidden()
4135 .child(text),
4136 );
4137 continue;
4138 }
4139
4140 items.push(Self::render_list_item_row(
4141 text,
4142 ix,
4143 options,
4144 *checked,
4145 task_toggle.clone(),
4146 &node_cx.style,
4147 window.line_height(),
4148 indent,
4149 ));
4150 }
4151 BlockNode::List { .. } => {
4152 items.push(div().ml(indent).child(child.render_block(
4153 NodeRenderOptions {
4154 depth: options.depth + 1,
4155 todo: checked.is_some(),
4156 is_last: true,
4157 ..options
4158 },
4159 node_cx,
4160 window,
4161 cx,
4162 )));
4163 }
4164 BlockNode::Root { .. }
4165 | BlockNode::Heading { .. }
4166 | BlockNode::Blockquote { .. }
4167 | BlockNode::Surface { .. }
4168 | BlockNode::CodeBlock(_)
4169 | BlockNode::Custom { .. }
4170 | BlockNode::Table(_)
4171 | BlockNode::HorizontalRule { .. } => {
4172 let block = child.render_block(
4173 NodeRenderOptions {
4174 depth: options.depth + 1,
4175 todo: checked.is_some(),
4176 is_last: true,
4177 ..options
4178 },
4179 node_cx,
4180 window,
4181 cx,
4182 );
4183
4184 if child_ix == 0 {
4185 items.push(Self::render_list_item_row(
4186 block,
4187 ix,
4188 options,
4189 *checked,
4190 task_toggle.clone(),
4191 &node_cx.style,
4192 window.line_height(),
4193 indent,
4194 ));
4195 } else {
4196 items.push(
4200 div()
4201 .w_full()
4202 .min_w_0()
4203 .pl(indent)
4204 .overflow_hidden()
4205 .child(block),
4206 );
4207 }
4208 }
4209 BlockNode::ListItem { .. }
4210 | BlockNode::Break { .. }
4211 | BlockNode::Definition { .. }
4212 | BlockNode::Unknown => {}
4213 }
4214 }
4215 items
4216 })
4217 .into_any_element()
4218 }
4219 _ => div().into_any_element(),
4220 }
4221 }
4222
4223 fn render_table(
4245 item: &BlockNode,
4246 options: &NodeRenderOptions,
4247 node_cx: &NodeContext,
4248 text_size: Pixels,
4249 window: &mut Window,
4250 cx: &mut App,
4251 ) -> impl IntoElement {
4252 const CELL_WRAP_MAX_LINES: f32 = 2.0;
4258 const CELL_WRAP_MIN_PX: f32 = 160.0;
4259 const CELL_WRAP_MAX_PX: f32 = 480.0;
4260 const TABLE_BORDER_PX: f32 = 2.0; let table = match item {
4263 BlockNode::Table(table) => table,
4264 _ => return div().into_any_element(),
4265 };
4266
4267 let style = &node_cx.style;
4268 let col_count = table
4269 .children
4270 .iter()
4271 .map(|row| row.children.len())
4272 .max()
4273 .unwrap_or(0);
4274 let col_w = measure_table_columns(table, col_count, node_cx, window, cx);
4275 let scroll = matches!(style.table().overflow.x, Some(Overflow::Scroll));
4276 let nowrap = style.table_cell().text.white_space == Some(WhiteSpace::Nowrap);
4277 let rem_size = window.rem_size();
4278 let wrap_min_px = f32::from(rems(4.).to_pixels(rem_size));
4279 let padding_delta = table_cell_padding_x(style, rem_size) - CELL_PAD_PX;
4281 let scale_factor = window.scale_factor();
4285 let device_ceil = |width: f32| (width * scale_factor).ceil() / scale_factor;
4286 let columns: Vec<TableColumn> = col_w
4287 .iter()
4288 .enumerate()
4289 .map(|(ix, &w)| {
4290 let w = w + padding_delta;
4291 let floor = if scroll && nowrap {
4292 w
4293 } else if scroll {
4294 (w / CELL_WRAP_MAX_LINES)
4295 .clamp(CELL_WRAP_MIN_PX, CELL_WRAP_MAX_PX)
4296 .min(w)
4297 } else {
4298 w.min(wrap_min_px)
4299 };
4300 let divider = if ix + 1 < col_count {
4301 CELL_BORDER_PX
4302 } else {
4303 0.
4304 };
4305 let max = device_ceil(w - divider);
4306 TableColumn {
4307 min: device_ceil(floor - divider).min(max),
4308 max,
4309 divider,
4310 }
4311 })
4312 .collect();
4313
4314 let rows = Self::render_table_rows(table, &columns, node_cx, window, cx);
4315 let frame = StyleRefinement::default()
4316 .text_size(text_size)
4317 .bg(style
4318 .table_background()
4319 .unwrap_or(cx.theme().tokens.colors.surface))
4320 .border_1()
4321 .border_color(style.border())
4322 .refine_style(style.table());
4323 let body = if scroll {
4324 let scroll_handle = window
4325 .use_keyed_state(
4326 block_element_id("table-scroll", table.span, options.ix),
4327 cx,
4328 |_, _| ScrollHandle::default(),
4329 )
4330 .read(cx)
4331 .clone();
4332 let min_total_w = columns
4333 .iter()
4334 .map(|column| column.min + column.divider)
4335 .sum::<f32>()
4336 + TABLE_BORDER_PX;
4337 horizontal_scroll_area(
4347 block_element_id("table", table.span, options.ix),
4348 &scroll_handle,
4349 &frame,
4350 div().min_w_full().w(px(min_total_w)).children(rows),
4356 )
4357 .into_any_element()
4358 } else {
4359 div()
4360 .id(block_element_id("table", table.span, options.ix))
4363 .w_full()
4364 .overflow_hidden()
4365 .refine_style(&frame)
4366 .children(rows)
4367 .into_any_element()
4368 };
4369
4370 div()
4371 .pb(block_gap(options, style))
4372 .w_full()
4373 .child(body)
4374 .children(node_cx.table_actions.clone().map(|f| {
4381 div()
4382 .id(block_element_id("table-actions", table.span, options.ix))
4383 .mt_1()
4384 .child(f(&table.cached_table_data(), window, cx))
4385 }))
4386 .into_any_element()
4387 }
4388
4389 fn table_row_corner_radii(style: &TextViewStyle, window: &Window) -> [Option<Pixels>; 4] {
4401 let rem_size = window.rem_size();
4402 let inset = |radius: Option<gpui::AbsoluteLength>| {
4403 radius.map(|radius| (radius.to_pixels(rem_size) - px(1.)).max(px(0.)))
4404 };
4405 let radii = &style.table().corner_radii;
4406 [
4407 inset(radii.top_left),
4408 inset(radii.top_right),
4409 inset(radii.bottom_left),
4410 inset(radii.bottom_right),
4411 ]
4412 }
4413
4414 fn render_table_rows(
4428 table: &Table,
4429 columns: &[TableColumn],
4430 node_cx: &NodeContext,
4431 window: &mut Window,
4432 cx: &mut App,
4433 ) -> Vec<AnyElement> {
4434 const CELL_GROW: f32 = 1e6;
4440 const SLACK_GROW: f32 = 1.0;
4441
4442 let style = &node_cx.style;
4443 let col_count = columns.len();
4444 let total_w = columns.iter().map(|column| column.max).sum::<f32>().max(1.);
4445 let mut slack_style = StyleRefinement::default();
4448 slack_style.background = style.table_cell().background.clone();
4449 slack_style.border_color = style.table_cell().border_color;
4450 let slack = |grow: f32| {
4451 div()
4452 .flex_basis(px(0.))
4453 .flex_grow(grow)
4454 .flex_shrink(0.)
4455 .border_color(style.border())
4456 .refine_style(&slack_style)
4457 };
4458
4459 let row_count = table.children.len();
4460 let [top_left, top_right, bottom_left, bottom_right] =
4461 Self::table_row_corner_radii(style, window);
4462 let mut rows = Vec::with_capacity(row_count);
4463 let mut cell_ordinal = 0;
4464 for (row_ix, row) in table.children.iter().enumerate() {
4465 let mut cells = Vec::with_capacity(col_count * 2);
4466 for (ix, column) in columns.iter().enumerate() {
4467 let is_last_col = ix + 1 == col_count;
4468 let align = table.column_align(ix);
4469 let content = row.children.get(ix).map(|cell| {
4470 let fade_key = table
4471 .span
4472 .map(|span| TextLeafKey::table_cell(span.start, cell_ordinal));
4473 cell_ordinal += 1;
4474 cell.children.render(fade_key, node_cx, window, cx)
4475 });
4476
4477 let grow = SLACK_GROW * column.max / total_w;
4478 let (lead, trail) = match align {
4479 ColumnumnAlign::None | ColumnumnAlign::Left => (0., grow),
4480 ColumnumnAlign::Center => (grow / 2., grow / 2.),
4481 ColumnumnAlign::Right => (grow, 0.),
4482 };
4483 if lead > 0. {
4484 cells.push(slack(lead).into_any_element());
4485 }
4486 cells.push(
4487 TableCellElement(
4488 div()
4489 .flex_basis(px(0.))
4490 .flex_grow(CELL_GROW)
4491 .min_w(px(column.min))
4492 .max_w(px(column.max))
4493 .overflow_hidden()
4494 .when(align == ColumnumnAlign::Center, |this| {
4500 this.flex().flex_col().items_center()
4501 })
4502 .when(align == ColumnumnAlign::Right, |this| {
4503 this.flex().flex_col().items_end()
4504 })
4505 .px_3()
4506 .py(px(7.))
4507 .refine_style(&style.table_cell())
4508 .children(content)
4509 .into_any_element(),
4510 )
4511 .into_any_element(),
4512 );
4513 if trail > 0. || !is_last_col {
4514 cells.push(
4515 slack(trail)
4516 .when(!is_last_col, |this| this.border_r_1())
4517 .into_any_element(),
4518 );
4519 }
4520 }
4521 rows.push(
4522 div()
4523 .id(("row", row_ix))
4526 .w_full()
4527 .when(row_ix < row_count - 1, |this| this.border_b_1())
4528 .border_color(style.border())
4529 .flex()
4530 .flex_row()
4531 .when(row_ix == 0, |this| {
4535 this.bg(style.code_background())
4536 .text_color(style.foreground())
4537 .when_some(top_left, |this, radius| this.rounded_tl(radius))
4538 .when_some(top_right, |this, radius| this.rounded_tr(radius))
4539 .refine_style(&style.table_head())
4540 })
4541 .when(row_ix + 1 == row_count, |this| {
4542 this.when_some(bottom_left, |this, radius| this.rounded_bl(radius))
4543 .when_some(bottom_right, |this, radius| this.rounded_br(radius))
4544 })
4545 .when_some(
4547 style.table_row_hover().filter(|_| row_ix > 0),
4548 |this, color| this.hover(|this| this.bg(color)),
4549 )
4550 .children(cells)
4551 .into_any_element(),
4552 );
4553 }
4554 rows
4555 }
4556
4557 pub(crate) fn render_block(
4558 &self,
4559 options: NodeRenderOptions,
4560 node_cx: &NodeContext,
4561 window: &mut Window,
4562 cx: &mut App,
4563 ) -> AnyElement {
4564 let mb = block_gap(&options, &node_cx.style);
4565
4566 match self {
4567 BlockNode::Root { children, .. } => div()
4568 .children(children.into_iter().enumerate().map(move |(ix, node)| {
4569 let (is_first, prev) = match flow_position(children, ix) {
4573 (true, _) => (options.is_first, options.prev),
4574 (false, prev) => (false, prev),
4575 };
4576 node.render_block(
4577 NodeRenderOptions {
4578 ix,
4579 is_first,
4580 prev,
4581 is_last: options.is_last && ix + 1 == children.len(),
4582 ..options
4583 },
4584 node_cx,
4585 window,
4586 cx,
4587 )
4588 }))
4589 .into_any_element(),
4590 BlockNode::Paragraph(paragraph) => gapped(
4591 paragraph.render(
4592 paragraph.span.map(|span| TextLeafKey::block(span.start)),
4593 node_cx,
4594 window,
4595 cx,
4596 ),
4597 mb,
4598 ),
4599 BlockNode::Heading {
4600 level,
4601 children,
4602 span,
4603 } => {
4604 let (_, line_height, section_gap) = heading_metrics(*level);
4605 let refinement = node_cx.style.heading(*level);
4606 let text_size = heading_size(*level, node_cx, window);
4607 let top = if options.is_first || options.depth > 0 {
4613 px(0.)
4614 } else {
4615 match options.prev {
4616 PrevBlock::Heading(_) => text_size * 0.25,
4617 PrevBlock::Rule => (text_size * section_gap
4618 - rule_space(body_font_size(node_cx, window)))
4619 .max(px(0.)),
4620 PrevBlock::Other => (text_size * section_gap
4621 - node_cx.style.paragraph_gap().to_pixels(window.rem_size()))
4622 .max(px(0.)),
4623 }
4624 };
4625 let bottom = if options.is_last {
4626 px(0.)
4627 } else {
4628 text_size * HEADING_BOTTOM_GAP
4629 };
4630
4631 div()
4632 .pt(top)
4633 .pb(bottom)
4634 .whitespace_normal()
4635 .text_size(text_size)
4636 .line_height(relative(line_height))
4637 .font_weight(FontWeight::SEMIBOLD)
4638 .when(*level >= 6, |this| {
4639 this.text_color(node_cx.style.muted_foreground())
4640 })
4641 .refine_style(&refinement)
4642 .child(children.render(
4643 span.map(|span| TextLeafKey::block(span.start)),
4644 node_cx,
4645 window,
4646 cx,
4647 ))
4648 .into_any_element()
4649 }
4650 BlockNode::Blockquote { children, .. } => gapped(
4651 div()
4652 .w_full()
4653 .text_color(node_cx.style.muted_foreground())
4654 .border_l_2()
4655 .border_color(node_cx.style.border())
4656 .pl(body_font_size(node_cx, window) * 0.9)
4657 .refine_style(node_cx.style.blockquote_style())
4658 .children({
4660 let children_len = children.len();
4661 children.into_iter().enumerate().map(move |(index, c)| {
4662 let is_last = index == children_len - 1;
4663 let (is_first, prev) = flow_position(children, index);
4664 window.with_text_style(
4665 Some(node_cx.style.blockquote_style().text.clone()),
4666 |window| {
4667 c.render_block(
4668 NodeRenderOptions {
4669 is_first,
4670 prev,
4671 ..options.is_last(is_last)
4672 },
4673 node_cx,
4674 window,
4675 cx,
4676 )
4677 },
4678 )
4679 })
4680 })
4681 .into_any_element(),
4682 mb,
4683 ),
4684 BlockNode::Surface { name, children, .. } => {
4685 if children.iter().all(Self::draws_nothing) {
4686 return div().into_any_element();
4688 }
4689 let mut container = node_cx
4693 .markdown_extensions
4694 .render_block_surface(name, window, cx)
4695 .unwrap_or_else(div)
4696 .map(|mut this| {
4697 let style = this.style();
4698 let unset_width = style.size.width.is_none();
4699 let unset_min_width = style.min_size.width.is_none();
4700 this.when(unset_width, |this| this.w_full())
4701 .when(unset_min_width, |this| this.min_w_0())
4702 });
4703 let text_style = container.style().text.clone();
4706 let blocks = window.with_text_style(Some(text_style), |window| {
4707 children
4708 .iter()
4709 .enumerate()
4710 .map(|(ix, child)| {
4711 let (is_first, prev) = flow_position(children, ix);
4712 child.render_block(
4713 NodeRenderOptions {
4714 is_first,
4715 prev,
4716 ..options
4717 .is_last(children[ix + 1..].iter().all(Self::draws_nothing))
4718 },
4719 node_cx,
4720 window,
4721 cx,
4722 )
4723 })
4724 .collect::<Vec<_>>()
4725 });
4726 gapped(container.children(blocks).into_any_element(), mb)
4727 }
4728 BlockNode::List {
4729 children,
4730 ordered,
4731 start,
4732 ..
4733 } => div()
4734 .w_full()
4735 .min_w_0()
4736 .pb(mb)
4737 .children({
4738 let mut items = Vec::with_capacity(children.len());
4739 let mut item_index = 0;
4740 for (ix, item) in children.into_iter().enumerate() {
4741 let is_item = item.is_list_item();
4742
4743 items.push(Self::render_list_item(
4744 item,
4745 item_index,
4746 NodeRenderOptions {
4747 ix,
4748 ordered: *ordered,
4749 list_start: *start,
4750 ..options
4751 },
4752 node_cx,
4753 window,
4754 cx,
4755 ));
4756
4757 if is_item {
4758 item_index += 1;
4759 }
4760 }
4761 items
4762 })
4763 .into_any_element(),
4764 BlockNode::CodeBlock(code_block) => code_block.render(&options, node_cx, window, cx),
4765 BlockNode::Custom { node, state } => {
4766 let inner = match node_cx.markdown_extensions.render_block(node, window, cx) {
4767 Some(rendered) => rendered,
4768 None => div().child(node.as_text().to_string()).into_any_element(),
4769 };
4770
4771 div()
4772 .pb(mb)
4773 .child(CustomBlockElement {
4774 content: inner,
4775 state: state.clone(),
4776 reveal: node_cx.reveal_at(
4777 node.span.map(|span| TextLeafKey::block(span.start)),
4778 0,
4779 1,
4780 ),
4781 })
4782 .into_any_element()
4783 }
4784 BlockNode::Table { .. } => {
4785 let text_size = body_font_size(node_cx, window) * (14. / 15.);
4790 window.with_text_style(
4791 Some(TextStyleRefinement {
4792 font_size: Some(text_size.into()),
4793 ..Default::default()
4794 }),
4795 |window| {
4796 Self::render_table(self, &options, node_cx, text_size, window, cx)
4797 .into_any_element()
4798 },
4799 )
4800 }
4801 BlockNode::HorizontalRule { .. } => {
4802 let space = rule_space(body_font_size(node_cx, window));
4806 let top = if options.is_first || options.depth > 0 {
4807 px(0.)
4808 } else {
4809 let above = match options.prev {
4810 PrevBlock::Rule => space,
4811 PrevBlock::Heading(level) => {
4812 heading_size(level, node_cx, window) * HEADING_BOTTOM_GAP
4813 }
4814 PrevBlock::Other => {
4815 node_cx.style.paragraph_gap().to_pixels(window.rem_size())
4816 }
4817 };
4818 (space - above).max(px(0.))
4819 };
4820 div()
4821 .pt(top)
4822 .when(!options.is_last, |this| this.pb(space))
4823 .child(div().bg(node_cx.style.border()).h(px(1.)))
4824 .into_any_element()
4825 }
4826 BlockNode::Break { .. } => div().into_any_element(),
4827 BlockNode::Unknown { .. } | BlockNode::Definition { .. } => div().into_any_element(),
4828 _ => {
4829 if cfg!(debug_assertions) {
4830 tracing::warn!("unknown implementation: {:?}", self);
4831 }
4832
4833 div().into_any_element()
4834 }
4835 }
4836 }
4837}
4838
4839#[cfg(test)]
4840mod tests {
4841 use super::*;
4842
4843 #[test]
4844 fn paragraph_highlights_preserve_overlaps_and_utf8_boundaries() {
4845 let mut app = gpui::TestApp::new();
4846 let mut window = app.open_window(|_, _| gpui::Empty);
4847 window.update(|_, _, cx| {
4848 cx.set_global(crate::Theme::default());
4849 let context = NodeContext::default();
4850 let link = LinkMark {
4851 url: "https://example.com".into(),
4852 ..Default::default()
4853 };
4854 let paragraph = Paragraph {
4855 children: vec![
4856 InlineNode::new("a中😀").marks(vec![
4857 (0..8, TextMark::default().bold()),
4858 (1..8, TextMark::default().italic()),
4859 (4..8, TextMark::default().code()),
4860 ]),
4861 InlineNode::new("文b").marks(vec![
4862 (0..4, TextMark::default().link(link.clone())),
4863 (0..3, TextMark::default().bold()),
4864 ]),
4865 ],
4866 ..Default::default()
4867 };
4868 let measured = paragraph.inline_highlights(&context, cx);
4869 let (text, highlights, links) = paragraph.plain_render(&context, cx);
4870 assert_eq!(text.as_ref(), "a中😀文b");
4871 assert_eq!(links, vec![(8..12, link)]);
4872 for spans in [&measured, &highlights] {
4873 assert_eq!(
4874 spans
4875 .iter()
4876 .map(|(range, _)| range.clone())
4877 .collect::<Vec<_>>(),
4878 vec![0..1, 1..4, 4..8, 8..11, 11..12]
4879 );
4880 for ix in [1, 2] {
4881 assert_eq!(spans[ix].1.style.font_weight, Some(FontWeight::BOLD));
4882 assert_eq!(spans[ix].1.style.font_style, Some(FontStyle::Italic));
4883 }
4884 assert!(spans[2].1.code_style.is_some());
4885 assert_eq!(spans[2].1.font_size_scale, Some(0.875));
4886 assert_eq!(spans[3].1.style.font_weight, Some(FontWeight::BOLD));
4887 assert_eq!(spans[3].1.style.font_style, None);
4888 assert!(spans[3].1.code_style.is_none());
4889 assert_eq!(spans[4].1.style.font_weight, None);
4890 }
4891 assert!(highlights[3..].iter().all(|(_, highlight)| {
4892 highlight.style.color == Some(context.style.link())
4893 && highlight.style.underline.is_some()
4894 }));
4895 let items = paragraph.inline_flow_items(None, &[], &[], &context, cx);
4896 let [
4897 InlineFlowItem::Text {
4898 text: flow_text,
4899 highlights: flow_highlights,
4900 links: flow_links,
4901 ..
4902 },
4903 ] = items.as_slice()
4904 else {
4905 panic!("one text item");
4906 };
4907 assert_eq!(flow_text, &text);
4908 assert_eq!(**flow_highlights, *highlights);
4909 assert_eq!(**flow_links, *links);
4910
4911 let paragraph = Paragraph {
4913 children: vec![
4914 InlineNode::new("a").marks(vec![(0..2, TextMark::default().bold())]),
4915 InlineNode::new("bc").marks(vec![(0..2, TextMark::default().italic())]),
4916 ],
4917 ..Default::default()
4918 };
4919 let highlights = paragraph.inline_highlights(&context, cx);
4920 assert_eq!(
4921 highlights
4922 .iter()
4923 .map(|(range, _)| range.clone())
4924 .collect::<Vec<_>>(),
4925 vec![0..1, 1..2, 2..3]
4926 );
4927 assert_eq!(highlights[1].1.style.font_weight, Some(FontWeight::BOLD));
4928 assert_eq!(highlights[1].1.style.font_style, Some(FontStyle::Italic));
4929 assert_eq!(highlights[2].1.style.font_weight, None);
4930 });
4931 }
4932
4933 #[test]
4934 fn paragraph_highlight_builders_merge_each_mark_once() {
4935 use super::super::inline::COMBINED_HIGHLIGHT_INPUTS;
4936
4937 let mut app = gpui::TestApp::new();
4938 let mut window = app.open_window(|_, _| gpui::Empty);
4939 window.update(|_, _, cx| {
4940 cx.set_global(crate::Theme::default());
4941 let context = NodeContext::default();
4942 let inputs = || COMBINED_HIGHLIGHT_INPUTS.with(|inputs| inputs.get());
4943 for node_count in [64, 128] {
4944 let paragraph = Paragraph {
4945 children: (0..node_count)
4946 .map(|_| {
4947 InlineNode::new("a中😀").marks(vec![
4948 (0..8, TextMark::default().bold()),
4949 (1..8, TextMark::default().italic()),
4950 (4..8, TextMark::default().code()),
4951 ])
4952 })
4953 .collect(),
4954 ..Default::default()
4955 };
4956 let before = inputs();
4957 paragraph.inline_highlights(&context, cx);
4958 assert_eq!(inputs() - before, 3 * node_count);
4959 let before = inputs();
4960 paragraph.plain_render(&context, cx);
4961 assert_eq!(inputs() - before, 3 * node_count);
4962 let before = inputs();
4963 paragraph.inline_flow_items(None, &[], &[], &context, cx);
4964 assert_eq!(inputs() - before, 3 * node_count);
4965 }
4966 });
4967 }
4968
4969 #[test]
4970 fn host_foregrounds_follow_the_render_context_without_entering_the_paragraph_cache() {
4971 let mut app = gpui::TestApp::new();
4972 let mut window = app.open_window(|_, _| gpui::Empty);
4973 window.update(|_, _, cx| {
4974 cx.set_global(crate::Theme::default());
4975 let link = LinkMark {
4976 url: "https://example.com".into(),
4977 ..Default::default()
4978 };
4979 let mut paragraph = Paragraph::default().with_leaf_key(7);
4980 paragraph.push(InlineNode::new("a中😀link").marks(vec![
4981 (0..12, TextMark::default().bold()),
4982 (1..12, TextMark::default().italic().link(link.clone())),
4983 ]));
4984 let original = paragraph.clone();
4985 let base = NodeContext::default();
4986 let (_, inherited, _) = paragraph.plain_render(&base, cx);
4987 let cached = paragraph
4988 .render_cache
4989 .plain
4990 .lock()
4991 .unwrap()
4992 .clone()
4993 .unwrap();
4994 for color in [gpui::red(), gpui::blue()] {
4995 let context = NodeContext {
4996 foregrounds: Some(Arc::new(HashMap::from([(7, vec![(0..12, color)])]))),
4997 ..base.clone()
4998 };
4999 let (text, highlights, links) = paragraph.plain_render(&context, cx);
5000 assert_eq!(text.as_ref(), "a中😀link");
5001 assert_eq!(links, vec![(1..12, link.clone())]);
5002 assert!(highlights.iter().all(|(_, h)| h.style.color == Some(color)));
5003 assert!(
5004 highlights
5005 .iter()
5006 .all(|(_, h)| h.style.font_weight == Some(FontWeight::BOLD))
5007 );
5008 assert!(
5009 highlights
5010 .iter()
5011 .filter(|(r, _)| r.start >= 1)
5012 .all(|(_, h)| h.style.font_style == Some(FontStyle::Italic)
5013 && h.style.underline.is_some())
5014 );
5015 assert!(Arc::ptr_eq(
5016 &cached,
5017 paragraph
5018 .render_cache
5019 .plain
5020 .lock()
5021 .unwrap()
5022 .as_ref()
5023 .unwrap()
5024 ));
5025 }
5026 let context = NodeContext {
5029 foregrounds: Some(Arc::new(HashMap::from([(7, vec![])]))),
5030 ..base.clone()
5031 };
5032 assert_eq!(paragraph.plain_render(&context, cx).1, inherited);
5033 let invalid = NodeContext {
5034 foregrounds: Some(Arc::new(HashMap::from([(7, vec![(2..3, gpui::red())])]))),
5035 ..base.clone()
5036 };
5037 assert_eq!(paragraph.plain_render(&invalid, cx).1, inherited);
5038 let other_leaf = NodeContext {
5039 foregrounds: Some(Arc::new(HashMap::from([(8, vec![(0..12, gpui::red())])]))),
5040 ..base
5041 };
5042 assert_eq!(paragraph.plain_render(&other_leaf, cx).1, inherited);
5043 assert_eq!(paragraph, original);
5044 });
5045 }
5046
5047 #[test]
5048 fn host_foregrounds_override_mixed_links_and_preserve_atom_byte_coordinates() {
5049 let mut app = gpui::TestApp::new();
5050 let mut window = app.open_window(|_, _| gpui::Empty);
5051 window.update(|_, _, cx| {
5052 cx.set_global(crate::Theme::default());
5053 let link = LinkMark {
5054 url: "https://example.com".into(),
5055 ..Default::default()
5056 };
5057 let mut paragraph = Paragraph::default().with_leaf_key(7);
5058 paragraph.push(InlineNode::new("a中😀link").marks(vec![
5059 (0..12, TextMark::default().bold()),
5060 (1..12, TextMark::default().link(link.clone())),
5061 (4..8, TextMark::default().code()),
5062 ]));
5063 paragraph.push(
5064 InlineNode::custom(MarkdownNode::new("atom", ()).text("long fallback"))
5065 .marks(vec![(0..13, TextMark::default().link(link.clone()))]),
5066 );
5067 paragraph.push(InlineNode::new("尾"));
5068 paragraph.push(InlineNode::image(ImageNode::default()));
5069 paragraph.push(InlineNode::new("z"));
5070 let context = NodeContext {
5071 foregrounds: Some(Arc::new(HashMap::from([(
5072 7,
5073 vec![
5074 (0..22, gpui::red()),
5075 (15..18, gpui::blue()),
5076 (21..22, gpui::blue()),
5077 ],
5078 )]))),
5079 ..Default::default()
5080 };
5081 let items = paragraph.inline_flow_items(None, &[], &[], &context, cx);
5082 assert_eq!(items.len(), 5);
5083 let InlineFlowItem::Text {
5084 text,
5085 highlights,
5086 links,
5087 ..
5088 } = &items[0]
5089 else {
5090 panic!("text");
5091 };
5092 assert_eq!(text.as_ref(), "a中😀link");
5093 assert_eq!(**links, [(1..12, link.clone())]);
5094 assert!(
5095 highlights
5096 .iter()
5097 .all(|(_, h)| h.style.color == Some(gpui::red()))
5098 );
5099 assert!(
5100 highlights
5101 .iter()
5102 .any(|(r, h)| r.start == 4 && h.code_style.is_some())
5103 );
5104 let InlineFlowItem::Object {
5105 style,
5106 link: actual_link,
5107 ..
5108 } = &items[1]
5109 else {
5110 panic!("object");
5111 };
5112 assert_eq!(style.color, Some(gpui::red()));
5113 assert_eq!(actual_link.as_ref(), Some(&link));
5114 assert!(style.underline.is_some());
5115 for ix in [2, 4] {
5116 let InlineFlowItem::Text { highlights, .. } = &items[ix] else {
5117 panic!("trailing text");
5118 };
5119 assert!(
5120 highlights
5121 .iter()
5122 .all(|(_, h)| h.style.color == Some(gpui::blue()))
5123 );
5124 assert!(!highlights.is_empty());
5125 }
5126 });
5127 }
5128
5129 #[test]
5130 fn block_plugin_selection_copies_both_formats_and_clears_synchronously() {
5131 let source = "$$\nx\n$$";
5132 let mut node = MarkdownNode::new("math", ()).text("x").markdown(source);
5133 node.set_span(Some(Span {
5134 start: 0,
5135 end: source.len(),
5136 }));
5137 let state = BlockState::default();
5138 let same_content = BlockNode::Custom {
5139 node: node.clone(),
5140 state: BlockState::default(),
5141 };
5142 let block = BlockNode::Custom {
5143 node,
5144 state: state.clone(),
5145 };
5146 let document = crate::text::document::ParsedDocument {
5147 source: source.into(),
5148 blocks: Arc::new(vec![block.clone()]),
5149 };
5150 assert!(!block.has_selection());
5151 state.set_selection(Some(BlockSelection::Full));
5152 assert_eq!(block, same_content);
5154 for blocks in [None, Some(0..=0)] {
5155 assert_eq!(
5156 document.selected_text(SelectionFormat::Plain, blocks.clone()),
5157 "x\n"
5158 );
5159 assert_eq!(
5160 document.selected_text(SelectionFormat::Source, blocks),
5161 source
5162 );
5163 }
5164 assert_eq!(document.selected_source_range(), Some(0..source.len()));
5165
5166 block.clear_selection();
5168 assert!(!document.blocks[0].has_selection());
5169 assert_eq!(
5170 document.selected_text(SelectionFormat::Plain, Some(0..=0)),
5171 ""
5172 );
5173 assert_eq!(document.selected_source_range(), None);
5174 }
5175
5176 #[test]
5177 fn block_plugin_empty_endpoint_suppresses_virtualized_copy_fallback() {
5178 let state = BlockState::default();
5179 let block = BlockNode::Custom {
5180 node: MarkdownNode::new("math", ())
5181 .text("formula")
5182 .markdown("$$formula$$"),
5183 state: state.clone(),
5184 };
5185 let after = CodeBlock::from_code("after", None::<SharedString>);
5186 after.set_selection(0..5);
5187 let document = crate::text::document::ParsedDocument {
5188 blocks: Arc::new(vec![block, BlockNode::CodeBlock(after)]),
5189 ..Default::default()
5190 };
5191 assert!(
5192 document
5193 .selected_text(SelectionFormat::Plain, Some(0..=1))
5194 .contains("formula")
5195 );
5196 state.set_selection(Some(BlockSelection::Empty));
5197 assert!(document.blocks[0].has_selection());
5198 for format in [SelectionFormat::Plain, SelectionFormat::Source] {
5199 let text = document.selected_text(format, Some(0..=1));
5200 assert!(text.contains("after"));
5201 assert!(!text.contains("formula"));
5202 }
5203 }
5204
5205 #[test]
5206 fn block_plugin_geometry_selects_whole_blocks_in_both_drag_directions() {
5207 let bounds = Bounds::new(gpui::point(px(10.), px(20.)), gpui::size(px(100.), px(40.)));
5208 let inside = bounds.center();
5209 let above = gpui::point(px(0.), px(0.));
5210 let below = gpui::point(px(0.), px(80.));
5211 for (start, end) in [(above, inside), (inside, below), (above, below)] {
5212 assert!(custom_block_is_selected(bounds, start, end));
5213 assert!(custom_block_is_selected(bounds, end, start));
5214 }
5215 assert!(!custom_block_is_selected(bounds, inside, inside));
5216 for (start, end) in [
5219 (inside, inside + gpui::point(px(1.), px(0.))),
5220 (
5221 bounds.origin,
5222 bounds.bottom_right() - gpui::point(px(1.), px(1.)),
5223 ),
5224 ] {
5225 assert!(!custom_block_is_selected(bounds, start, end));
5226 assert!(!custom_block_is_selected(bounds, end, start));
5227 }
5228 assert!(!custom_block_is_selected(
5229 bounds,
5230 gpui::point(px(150.), px(30.)),
5231 gpui::point(px(160.), px(40.))
5232 ));
5233 }
5234
5235 #[test]
5236 fn selected_inline_objects_coalesce_surrounding_emphasis() {
5237 for (object_mark, expected) in [
5238 (TextMark::default().italic(), "*fore $x$ aft*"),
5239 (TextMark::default().italic().bold(), "*fore **$x$** aft*"),
5240 ] {
5241 let italic = TextMark::default().italic();
5242 let before = InlineNode::new("before ").marks(vec![(0..7, italic.clone())]);
5243 let formula =
5244 InlineNode::custom(MarkdownNode::new("math", ()).text("x").markdown("$x$"))
5245 .marks(vec![(0..1, object_mark)]);
5246 let after = InlineNode::new(" after").marks(vec![(0..6, italic)]);
5247 {
5248 let mut state = formula.state.lock().unwrap();
5249 state.text = "before ".into();
5250 state.selection = Some((2..7).into());
5251 }
5252 *formula.custom_selection.lock().unwrap() = true;
5253 let paragraph = Paragraph {
5254 children: vec![before, formula, after],
5255 ..Default::default()
5256 };
5257 {
5258 let mut state = paragraph.state.lock().unwrap();
5259 state.text = " after".into();
5260 state.selection = Some((0..4).into());
5261 }
5262 assert_eq!(paragraph.selected_source(), expected);
5263 }
5264 }
5265
5266 #[test]
5267 fn consecutive_inline_objects_copy_atomically_without_neighboring_text() {
5268 let first =
5269 InlineNode::custom(MarkdownNode::new("math", ()).text("甲²").markdown("$甲^2$"));
5270 let second = InlineNode::custom(MarkdownNode::new("math", ()).text("b").markdown("$b$"));
5271 *first.custom_selection.lock().unwrap() = true;
5272 *second.custom_selection.lock().unwrap() = true;
5273 let paragraph = Paragraph {
5274 children: vec![first, second],
5275 ..Default::default()
5276 };
5277 assert_eq!(paragraph.selected_text(), "甲²b");
5278 assert_eq!(paragraph.selected_source(), "$甲^2$$b$");
5279 assert!(paragraph.has_selection());
5280 paragraph.clear_selection();
5281 assert_eq!(paragraph.selected_text(), "");
5282 assert_eq!(paragraph.selected_source(), "");
5283 assert!(!paragraph.has_selection());
5284 }
5285
5286 #[test]
5287 fn selected_inline_object_interleaves_runs_and_preserves_enclosing_mark() {
5288 let before = InlineNode::new("中文 ");
5289 let formula =
5290 InlineNode::custom(MarkdownNode::new("math", ()).text("x²").markdown("$x^2$"))
5291 .marks(vec![(0..3, TextMark::default().bold())]);
5292 let after = InlineNode::new(" English");
5293 {
5294 let mut preceding = formula.state.lock().unwrap();
5295 preceding.text = "中文 ".into();
5296 preceding.selection = Some((3..7).into());
5297 }
5298 *formula.custom_selection.lock().unwrap() = true;
5299 let paragraph = Paragraph {
5300 children: vec![before, formula, after],
5301 ..Default::default()
5302 };
5303 {
5304 let mut trailing = paragraph.state.lock().unwrap();
5305 trailing.text = " English".into();
5306 trailing.selection = Some((0..4).into());
5307 }
5308 assert_eq!(paragraph.selected_text(), "文 x² Eng");
5309 assert_eq!(paragraph.selected_source(), "文 **$x^2$** Eng");
5310 }
5311
5312 #[test]
5313 fn mark_sets_a_readable_text_color_with_its_background() {
5314 use gpui::{Empty, TestApp};
5315 let mut app = TestApp::new();
5316 let mut window = app.open_window(|_, _| Empty);
5317 window.update(|_, _, cx| {
5318 cx.set_global(crate::Theme::default());
5319 let node_cx = NodeContext::default();
5320
5321 let yellow: Hsla = gpui::rgb(0xfef08a).into();
5324 let style = mark_highlight(&TextMark::default().highlight(yellow), &node_cx, cx).style;
5325 assert_eq!(style.background_color, Some(yellow));
5326 assert_eq!(style.color, Some(gpui::black()));
5327
5328 let navy: Hsla = gpui::rgb(0x1e3a8a).into();
5330 let style = mark_highlight(&TextMark::default().highlight(navy), &node_cx, cx).style;
5331 assert_eq!(style.color, Some(gpui::white()));
5332
5333 let translucent_black: Hsla = gpui::rgba(0x00000080).into();
5336 let translucent_white: Hsla = gpui::rgba(0xffffff4d).into();
5337 assert_eq!(
5338 mark_text_color(translucent_black, gpui::white()),
5339 gpui::black()
5340 );
5341 assert_eq!(
5342 mark_text_color(translucent_white, gpui::black()),
5343 gpui::white()
5344 );
5345 let transparent: Hsla = gpui::rgba(0x00000000).into();
5346 let style =
5347 mark_highlight(&TextMark::default().highlight(transparent), &node_cx, cx).style;
5348 assert_eq!(style.color, None);
5349
5350 let style = mark_highlight(&TextMark::default().bold(), &node_cx, cx).style;
5352 assert_eq!(style.color, None);
5353 });
5354 }
5355
5356 #[test]
5357 fn translucent_mark_cache_tracks_theme_background() {
5358 use gpui::{Empty, TestApp};
5359 let mut app = TestApp::new();
5360 let mut window = app.open_window(|_, _| Empty);
5361 window.update(|_, _, cx| {
5362 cx.set_global(crate::Theme::default());
5363 let paragraph = Paragraph {
5364 children: vec![InlineNode::new("mark").marks(vec![(
5365 0..4,
5366 TextMark::default().highlight(gpui::rgba(0x00000033).into()),
5367 )])],
5368 ..Default::default()
5369 };
5370 let context = NodeContext::default();
5371 crate::Theme::global_mut(cx).tokens.colors.background = gpui::white();
5372 let (_, light, _) = paragraph.plain_render(&context, cx);
5373 assert_eq!(light[0].1.style.color, Some(gpui::black()));
5374 crate::Theme::global_mut(cx).tokens.colors.background = gpui::black();
5375 let (_, dark, _) = paragraph.plain_render(&context, cx);
5376 assert_eq!(dark[0].1.style.color, Some(gpui::white()));
5377 });
5378 }
5379
5380 #[test]
5381 fn link_hook_replaces_or_drops_links_and_the_cache_follows_it() {
5382 use gpui::{Empty, TestApp};
5383 let mut app = TestApp::new();
5384 let mut window = app.open_window(|_, _| Empty);
5385 window.update(|_, _, cx| {
5386 cx.set_global(crate::Theme::default());
5387 let link = |url: &str| {
5388 TextMark::default().link(LinkMark {
5389 url: url.to_string().into(),
5390 ..Default::default()
5391 })
5392 };
5393 let mut by_reference = TextMark::default();
5394 by_reference.link = Some(LinkMark {
5395 identifier: Some("ref".into()),
5396 ..Default::default()
5397 });
5398 let paragraph = Paragraph {
5400 children: vec![InlineNode::new("live dead cited").marks(vec![
5401 (0..4, link("https://live.example")),
5402 (5..9, link("app://dead")),
5403 (10..15, by_reference.clone()),
5404 ])],
5405 ..Default::default()
5406 };
5407 let mut node_cx = NodeContext::default();
5408 node_cx.link_refs.insert(
5409 "ref".into(),
5410 LinkMark {
5411 url: "https://cited.example".into(),
5412 ..Default::default()
5413 },
5414 );
5415 let underlined = |highlights: &[(Range<usize>, InlineHighlight)], at: usize| {
5416 highlights.iter().any(|(range, highlight)| {
5417 range.contains(&at) && highlight.style.underline.is_some()
5418 })
5419 };
5420
5421 let (_, highlights, links) = paragraph.plain_render(&node_cx, cx);
5422 assert_eq!(links.len(), 3, "without a hook every link is drawn");
5423 assert_eq!(links[2].1.url.as_ref(), "https://cited.example");
5424 assert!(underlined(&highlights, 5));
5425
5426 let seen = Arc::new(Mutex::new(Vec::<String>::new()));
5429 let recorded = seen.clone();
5430 node_cx.link_hook = Some(Arc::new(move |link: &Link, _: &App| {
5431 recorded.lock().unwrap().push(link.url.to_string());
5432 if link.url.starts_with("app://") {
5433 None
5434 } else if link.url.contains("cited") {
5435 Some(link.clone().url("https://moved.example"))
5436 } else {
5437 Some(link.clone())
5438 }
5439 }));
5440 let (_, highlights, links) = paragraph.plain_render(&node_cx, cx);
5441 let drawn: Vec<_> = links
5442 .iter()
5443 .map(|(range, link)| (range.clone(), link.url.to_string()))
5444 .collect();
5445 assert_eq!(
5446 drawn,
5447 [
5448 (0..4, "https://live.example".to_string()),
5449 (10..15, "https://moved.example".to_string()),
5450 ],
5451 "the cached render must follow the hook"
5452 );
5453 assert!(underlined(&highlights, 0) && underlined(&highlights, 10));
5454 assert!(!underlined(&highlights, 5), "a dropped link is plain text");
5455 assert!(
5456 seen.lock()
5457 .unwrap()
5458 .contains(&"https://cited.example".to_string())
5459 );
5460
5461 let flow = Paragraph {
5464 children: vec![
5465 InlineNode::new("dead").marks(vec![(0..4, link("app://dead"))]),
5466 InlineNode::new("code").marks(vec![(0..4, TextMark::default().code())]),
5467 InlineNode::custom(MarkdownNode::new("test", ()).text("x"))
5468 .marks(vec![(0..1, link("app://dead"))]),
5469 InlineNode::custom(MarkdownNode::new("test", ()).text("y"))
5470 .marks(vec![(0..1, by_reference)]),
5471 ],
5472 ..Default::default()
5473 };
5474 let items = flow.inline_flow_items(None, &[], &[], &node_cx, cx);
5475 for item in &items {
5476 if let InlineFlowItem::Text { links, .. } = item {
5477 assert!(links.is_empty(), "dropped link survived in the inline flow");
5478 }
5479 }
5480 let objects: Vec<_> = items
5481 .iter()
5482 .filter_map(|item| match item {
5483 InlineFlowItem::Object { link, .. } => {
5484 Some(link.as_ref().map(|l| l.url.to_string()))
5485 }
5486 _ => None,
5487 })
5488 .collect();
5489 assert_eq!(objects, [None, Some("https://moved.example".to_string())]);
5490 });
5491 }
5492
5493 fn flow_texts(
5495 items: &[InlineFlowItem],
5496 ) -> Vec<(
5497 SharedString,
5498 Arc<[(Range<usize>, InlineHighlight)]>,
5499 Arc<[(Range<usize>, LinkMark)]>,
5500 )> {
5501 items
5502 .iter()
5503 .filter_map(|item| match item {
5504 InlineFlowItem::Text {
5505 text,
5506 highlights,
5507 links,
5508 ..
5509 } => Some((text.clone(), highlights.clone(), links.clone())),
5510 _ => None,
5511 })
5512 .collect()
5513 }
5514
5515 #[test]
5516 fn inline_flow_text_is_kept_between_frames_and_layered_per_frame() {
5517 use super::super::inline::COMBINED_HIGHLIGHT_INPUTS;
5518
5519 let mut app = gpui::TestApp::new();
5520 let mut window = app.open_window(|_, _| gpui::Empty);
5521 window.update(|_, _, cx| {
5522 cx.set_global(crate::Theme::default());
5523 let context = NodeContext::default();
5524 let inputs = || COMBINED_HIGHLIGHT_INPUTS.with(|inputs| inputs.get());
5525 let cached =
5526 |paragraph: &Paragraph| paragraph.render_cache.flow.lock().unwrap().clone();
5527 let mut paragraph = Paragraph::default();
5528 paragraph
5529 .push(InlineNode::new("call ").marks(vec![(0..5, TextMark::default().bold())]));
5530 paragraph
5531 .push(InlineNode::new("run()").marks(vec![(0..5, TextMark::default().code())]));
5532 paragraph.push(InlineNode::image(ImageNode::default()));
5533 paragraph.push(InlineNode::new("after"));
5534
5535 let first = paragraph.inline_flow_items(None, &[], &[], &context, cx);
5536 assert_eq!(first.len(), 3);
5537 let built = cached(¶graph).expect("the first frame fills the cache");
5538
5539 let before = inputs();
5541 let again = paragraph.inline_flow_items(None, &[], &[], &context, cx);
5542 assert_eq!(inputs(), before);
5543 assert!(Arc::ptr_eq(&built, &cached(¶graph).unwrap()));
5544 assert_eq!(flow_texts(&again), flow_texts(&first));
5545 assert!(matches!(again[1], InlineFlowItem::Image { .. }));
5546
5547 let faded = paragraph.inline_flow_items(None, &[(0..10, 0.5)], &[], &context, cx);
5549 let (_, highlights, _) = &flow_texts(&faded)[0];
5550 assert!(
5551 highlights
5552 .iter()
5553 .all(|(_, highlight)| highlight.style.fade_out == Some(0.5))
5554 );
5555 assert!(Arc::ptr_eq(&built, &cached(¶graph).unwrap()));
5556 let settled = paragraph.inline_flow_items(None, &[], &[], &context, cx);
5557 assert_eq!(flow_texts(&settled), flow_texts(&first));
5558
5559 let mut clone = paragraph.clone();
5561 assert!(Arc::ptr_eq(&built, &cached(&clone).unwrap()));
5562 clone.push(InlineNode::new(" more"));
5563 assert!(cached(&clone).is_none());
5564 let items = clone.inline_flow_items(None, &[], &[], &context, cx);
5565 assert_eq!(flow_texts(&items)[1].0.as_ref(), "after more");
5566 assert!(Arc::ptr_eq(&built, &cached(¶graph).unwrap()));
5567 });
5568 }
5569
5570 #[test]
5574 fn inline_flow_items_share_the_cached_highlights_and_links() {
5575 let mut app = gpui::TestApp::new();
5576 let mut window = app.open_window(|_, _| gpui::Empty);
5577 window.update(|_, _, cx| {
5578 cx.set_global(crate::Theme::default());
5579 let link = TextMark::default().link(LinkMark {
5580 url: "https://example.com".into(),
5581 ..Default::default()
5582 });
5583 let mut paragraph = Paragraph::default().with_leaf_key(7);
5584 paragraph.push(InlineNode::new("see ").marks(vec![(0..3, link)]));
5585 paragraph
5586 .push(InlineNode::new("run()").marks(vec![(0..5, TextMark::default().code())]));
5587 let shares_cache = |context: &NodeContext, cx: &mut gpui::App| {
5588 let items = paragraph.inline_flow_items(None, &[], &[], context, cx);
5589 let [
5590 InlineFlowItem::Text {
5591 highlights, links, ..
5592 },
5593 ] = &items[..]
5594 else {
5595 panic!("one text item");
5596 };
5597 let flow = paragraph.render_cache.flow.lock().unwrap().clone().unwrap();
5598 Arc::ptr_eq(highlights, &flow.texts[0].highlights)
5599 && Arc::ptr_eq(links, &flow.texts[0].links)
5600 };
5601
5602 let foreground_elsewhere = NodeContext {
5605 foregrounds: Some(Arc::new(HashMap::from([(7, vec![(20..30, gpui::red())])]))),
5606 ..Default::default()
5607 };
5608 assert!(shares_cache(&NodeContext::default(), cx));
5609 assert!(shares_cache(&NodeContext::default(), cx));
5610 assert!(shares_cache(&foreground_elsewhere, cx));
5611 });
5612 }
5613
5614 #[test]
5615 fn inline_flow_cache_follows_style_theme_and_links() {
5616 use gpui::{Empty, TestApp};
5617 let mut app = TestApp::new();
5618 let mut window = app.open_window(|_, _| Empty);
5619 window.update(|_, _, cx| {
5620 cx.set_global(crate::Theme::default());
5621 let link = |url: &str| {
5622 TextMark::default().link(LinkMark {
5623 url: url.to_string().into(),
5624 ..Default::default()
5625 })
5626 };
5627 let mut by_reference = TextMark::default();
5628 by_reference.link = Some(LinkMark {
5629 identifier: Some("ref".into()),
5630 ..Default::default()
5631 });
5632 let mut paragraph = Paragraph::default();
5634 paragraph.push(InlineNode::new("code").marks(vec![(0..4, TextMark::default().code())]));
5635 paragraph.push(InlineNode::new(" live dead cited mark").marks(vec![
5636 (1..5, link("https://live.example")),
5637 (6..10, link("app://dead")),
5638 (11..16, by_reference),
5639 (
5640 17..21,
5641 TextMark::default().highlight(gpui::rgba(0x00000033).into()),
5642 ),
5643 ]));
5644 let render = |node_cx: &NodeContext, cx: &mut App| {
5645 let items = paragraph.inline_flow_items(None, &[], &[], node_cx, cx);
5646 let [(_, highlights, links)] = flow_texts(&items).try_into().unwrap();
5647 let urls: Vec<_> = links
5648 .iter()
5649 .map(|(range, link)| (range.clone(), link.url.to_string()))
5650 .collect();
5651 (highlights, urls)
5652 };
5653 let at = |highlights: &[(Range<usize>, InlineHighlight)], ix: usize| {
5654 highlights
5655 .iter()
5656 .find(|(range, _)| range.contains(&ix))
5657 .map(|(_, highlight)| highlight.style)
5658 .unwrap_or_default()
5659 };
5660
5661 crate::Theme::global_mut(cx).tokens.colors.background = gpui::white();
5662 let mut node_cx = NodeContext::default();
5663 let (highlights, urls) = render(&node_cx, cx);
5664 assert_eq!(urls[2], (15..20, String::new()), "no definition yet");
5665 assert_eq!(at(&highlights, 21).color, Some(gpui::black()));
5666
5667 node_cx.link_refs.insert(
5669 "ref".into(),
5670 LinkMark {
5671 url: "https://cited.example".into(),
5672 ..Default::default()
5673 },
5674 );
5675 let (_, urls) = render(&node_cx, cx);
5676 assert_eq!(urls[2], (15..20, "https://cited.example".to_string()));
5677
5678 crate::Theme::global_mut(cx).tokens.colors.background = gpui::black();
5680 let (highlights, _) = render(&node_cx, cx);
5681 assert_eq!(at(&highlights, 21).color, Some(gpui::white()));
5682
5683 node_cx.style = Arc::new(TextViewStyle::default().with_link(gpui::red()));
5685 let (highlights, _) = render(&node_cx, cx);
5686 assert_eq!(at(&highlights, 5).color, Some(gpui::red()));
5687
5688 node_cx.link_hook = Some(Arc::new(|link: &Link, _: &App| {
5690 (!link.url.starts_with("app://")).then(|| link.clone())
5691 }));
5692 let (highlights, urls) = render(&node_cx, cx);
5693 assert_eq!(
5694 urls,
5695 [
5696 (5..9, "https://live.example".to_string()),
5697 (15..20, "https://cited.example".to_string()),
5698 ]
5699 );
5700 assert!(at(&highlights, 10).underline.is_none());
5701 assert!(at(&highlights, 5).underline.is_some());
5702 });
5703 }
5704
5705 #[test]
5706 fn custom_inline_inherits_marks_and_resolves_link_references() {
5707 use gpui::{Empty, TestApp};
5708 let mut app = TestApp::new();
5709 let mut window = app.open_window(|_, _| Empty);
5710 window.update(|_, _, cx| {
5711 cx.set_global(crate::Theme::default());
5712 let mut node_cx = NodeContext::default();
5713 let mut mark = TextMark::default().bold();
5714 mark.italic = true;
5715 mark.strikethrough = true;
5716 mark.link = Some(LinkMark {
5717 identifier: Some("ref".into()),
5718 ..Default::default()
5719 });
5720 node_cx.link_refs.insert(
5721 "ref".into(),
5722 LinkMark {
5723 url: "https://example.com".into(),
5724 ..Default::default()
5725 },
5726 );
5727 let paragraph = Paragraph {
5728 children: vec![
5729 InlineNode::custom(MarkdownNode::new("test", ()).text("x"))
5730 .marks(vec![(0..1, mark)]),
5731 ],
5732 ..Default::default()
5733 };
5734 let items = paragraph.inline_flow_items(None, &[], &[], &node_cx, cx);
5735 let InlineFlowItem::Object { style, link, .. } = &items[0] else {
5736 panic!()
5737 };
5738 assert_eq!(style.font_weight, Some(FontWeight::BOLD));
5739 assert_eq!(style.font_style, Some(FontStyle::Italic));
5740 assert!(style.strikethrough.is_some());
5741 assert_eq!(link.as_ref().unwrap().url.as_ref(), "https://example.com");
5742 });
5743 }
5744
5745 #[test]
5746 fn table_column_uses_prepared_inline_metrics_after_resource_update() {
5747 use crate::text::InlineElement;
5748 use crate::text::inline::test_draw::in_prepaint;
5749 use gpui::{Image, ImageFormat, TestApp};
5750 let mut app = TestApp::new();
5751 let width = Arc::new(std::sync::atomic::AtomicUsize::new(400));
5752 let render_width = width.clone();
5753 let mut node_cx = NodeContext::default();
5754 node_cx.markdown_extensions = Arc::new(MarkdownExtensions::default().plugin(
5755 crate::text::markdown_ext::TestInlinePlugin::new("test").render_with(
5756 move |_, _, _, _| {
5757 Some(
5758 InlineElement::new(
5759 gpui::img(Arc::new(Image::from_bytes(
5760 ImageFormat::Svg,
5761 b"<svg/>".to_vec(),
5762 )))
5763 .w(px(
5764 render_width.load(std::sync::atomic::Ordering::Relaxed) as f32
5765 ))
5766 .h(px(20.)),
5767 )
5768 .with_baseline(px(15.)),
5769 )
5770 },
5771 ),
5772 ));
5773 let table = table_of(
5774 vec![
5775 vec![plain_cell("ordinary text")],
5776 vec![TableCell {
5777 children: Paragraph {
5778 children: vec![InlineNode::custom(MarkdownNode::new("test", ()).text("x"))],
5779 ..Default::default()
5780 },
5781 width: None,
5782 }],
5783 ],
5784 vec![],
5785 );
5786 in_prepaint(&mut app, move |window, cx| {
5787 let mut cached = None;
5788 for expected in [400, 600, 10, 400] {
5789 width.store(expected, std::sync::atomic::Ordering::Relaxed);
5790 let measured = measure_table_columns(&table, 1, &node_cx, window, cx)[0];
5791 let current = cached_column_widths(&table);
5792 assert_eq!(
5793 measured,
5794 current.widths[0].max(expected as f32 + CELL_PAD_PX)
5795 );
5796 assert_eq!(current.custom_cells, vec![(1, 0)]);
5797 if let Some(cached) = cached.replace(current.clone()) {
5798 assert!(Arc::ptr_eq(&cached, ¤t));
5799 }
5800 }
5801 });
5802 }
5803
5804 fn cached_column_widths(table: &Table) -> Arc<TableColumnWidths> {
5805 table.column_widths_cache.0.lock().unwrap().clone().unwrap()
5806 }
5807
5808 #[test]
5809 fn blockquote_typography_reaches_nested_table_measurement() {
5810 use crate::text::inline::test_draw::in_prepaint;
5811 use crate::text::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
5812 use gpui::TestApp;
5813
5814 let quote = BlockNode::Blockquote {
5815 children: vec![BlockNode::Table(table_of(
5816 vec![vec![plain_cell("0123456789")]],
5817 vec![],
5818 ))],
5819 span: None,
5820 };
5821 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5822 in_prepaint(&mut app, move |window, cx| {
5823 cx.set_global(crate::Theme::default());
5824 window.with_text_style(
5825 Some(
5826 StyleRefinement::default()
5827 .font_family(BODY)
5828 .text_size(px(15.))
5829 .text,
5830 ),
5831 |window| {
5832 for (refinement, expected_width) in [
5833 (StyleRefinement::default(), 94.),
5834 (
5835 StyleRefinement::default()
5836 .font_family(MONO)
5837 .text_size(px(30.))
5838 .font_weight(FontWeight::BOLD),
5839 199.,
5840 ),
5841 ] {
5842 let node_cx = NodeContext {
5843 style: Arc::new(
5844 TextViewStyle::default().with_blockquote_style(refinement),
5845 ),
5846 body_font_size: px(15.),
5847 ..Default::default()
5848 };
5849 quote.render_block(NodeRenderOptions::default(), &node_cx, window, cx);
5850 let BlockNode::Blockquote { children, .. } = "e else {
5851 unreachable!()
5852 };
5853 let BlockNode::Table(table) = &children[0] else {
5854 unreachable!()
5855 };
5856 assert_eq!(cached_column_widths(table).widths, vec![expected_width]);
5858 }
5859 },
5860 );
5861 });
5862 }
5863
5864 #[test]
5865 fn block_surface_typography_reaches_nested_table_measurement() {
5866 use crate::text::MarkdownExtensions;
5867 use crate::text::inline::test_draw::in_prepaint;
5868 use crate::text::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
5869 use gpui::TestApp;
5870
5871 let surface = BlockNode::Surface {
5872 name: "large".into(),
5873 children: vec![BlockNode::Table(table_of(
5874 vec![vec![plain_cell("0123456789")]],
5875 vec![],
5876 ))],
5877 span: None,
5878 };
5879 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5880 in_prepaint(&mut app, move |window, cx| {
5881 cx.set_global(crate::Theme::default());
5882 window.with_text_style(
5883 Some(
5884 StyleRefinement::default()
5885 .font_family(BODY)
5886 .text_size(px(15.))
5887 .text,
5888 ),
5889 |window| {
5890 let node_cx = NodeContext {
5891 body_font_size: px(15.),
5892 markdown_extensions: Arc::new(MarkdownExtensions::default().block_surface(
5893 "large",
5894 |_, _| {
5895 div()
5896 .font_family(MONO)
5897 .text_size(px(30.))
5898 .font_weight(FontWeight::BOLD)
5899 },
5900 )),
5901 ..Default::default()
5902 };
5903 surface.render_block(NodeRenderOptions::default(), &node_cx, window, cx);
5904 let BlockNode::Surface { children, .. } = &surface else {
5905 unreachable!()
5906 };
5907 let BlockNode::Table(table) = &children[0] else {
5908 unreachable!()
5909 };
5910 assert_eq!(cached_column_widths(table).widths, vec![199.]);
5912 },
5913 );
5914 });
5915 }
5916
5917 #[test]
5918 fn table_columns_cache_preserves_plain_widths_and_clones() {
5919 use crate::text::inline::test_draw::in_prepaint;
5920 use crate::text::inline::test_fonts::{BODY, WideMonoTextSystem, record_shaped_lines};
5921 use gpui::{Refineable as _, TestApp, TextStyle};
5922
5923 let long = "é界".repeat(2048);
5924 let table = table_of(
5925 vec![
5926 vec![plain_cell(&format!(" \t{long} \nshort\n ")), plain_cell("")],
5927 vec![plain_cell("short")],
5928 vec![],
5929 vec![plain_cell(""), plain_cell("a\nabcdefghijklmnop")],
5930 ],
5931 vec![],
5932 );
5933 let uncached = table.clone();
5934 let node_cx = NodeContext::default();
5935 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
5936 let (table, node_cx, cached) = in_prepaint(&mut app, move |window, cx| {
5937 window.set_rem_size(px(20.));
5938 let style = TextStyle {
5939 font_family: BODY.into(),
5940 font_size: rems(1.).into(),
5941 ..Default::default()
5942 };
5943 let cached =
5944 window.with_text_style(Some(style.subtract(&Default::default())), |window| {
5945 let (widths, shaped) = record_shaped_lines(|| {
5946 measure_table_columns(&table, 2, &node_cx, window, cx)
5947 });
5948 assert_eq!(widths, vec![40960. + CELL_PAD_PX + CELL_BORDER_PX, 184.]);
5949 assert!(shaped.iter().any(|line| line == &long));
5950 assert_eq!(
5951 table, uncached,
5952 "derived widths do not change table equality"
5953 );
5954 assert!(uncached.column_widths_cache.0.lock().unwrap().is_none());
5955
5956 let cached = cached_column_widths(&table);
5957 let cloned = table.clone();
5958 for same in [&table, &cloned] {
5959 let (again, shaped) = record_shaped_lines(|| {
5960 measure_table_columns(same, 2, &node_cx, window, cx)
5961 });
5962 assert_eq!(again, widths);
5963 assert!(shaped.is_empty());
5964 assert!(Arc::ptr_eq(&cached, &cached_column_widths(same)));
5965 }
5966
5967 assert_eq!(
5969 measure_table_columns(&cloned, 3, &node_cx, window, cx),
5970 vec![widths[0], widths[1] + CELL_BORDER_PX, CELL_MIN_PX]
5971 );
5972 assert!(!Arc::ptr_eq(&cached, &cached_column_widths(&cloned)));
5973 assert!(Arc::ptr_eq(&cached, &cached_column_widths(&table)));
5974 assert!(
5975 measure_table_columns(&Table::default(), 0, &node_cx, window, cx)
5976 .is_empty()
5977 );
5978 cached
5979 });
5980 (table, node_cx, cached)
5981 });
5982 in_prepaint(&mut app, move |window, cx| {
5985 window.set_rem_size(cached.rem_size);
5986 window.with_text_style(
5987 Some(cached.text_styles.body.subtract(&Default::default())),
5988 |window| {
5989 measure_table_columns(&table, 2, &node_cx, window, cx);
5990 assert!(!Arc::ptr_eq(&cached, &cached_column_widths(&table)));
5991 },
5992 );
5993 });
5994 }
5995
5996 #[test]
5997 fn table_columns_cache_tracks_typography() {
5998 use crate::text::inline::test_draw::in_prepaint;
5999 use crate::text::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
6000 use gpui::{Refineable as _, TestApp, TextStyle};
6001
6002 let code = "0123456789";
6003 let mut paragraph = Paragraph::default();
6004 paragraph
6005 .push(InlineNode::new(code).marks(vec![(0..code.len(), TextMark::default().code())]));
6006 let table = table_of(
6007 vec![vec![
6008 plain_cell(code),
6009 TableCell {
6010 children: paragraph,
6011 width: None,
6012 },
6013 ]],
6014 vec![],
6015 );
6016 let base = TextStyle {
6017 font_family: BODY.into(),
6018 font_size: rems(1.).into(),
6019 ..Default::default()
6020 };
6021 let mut larger = base.clone();
6022 larger.font_size = rems(2.).into();
6023 let mut bold = base.clone();
6024 bold.font_weight = FontWeight::BOLD;
6025 let mut mono = base.clone();
6026 mono.font_family = MONO.into();
6027 let normal_code = HighlightStyle::default();
6028 let bold_code = HighlightStyle {
6029 font_weight: Some(FontWeight::BOLD),
6030 ..Default::default()
6031 };
6032 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
6033 in_prepaint(&mut app, move |window, cx| {
6034 let mut previous = None;
6035 for (style, rem_size, family, inline_code, expected) in [
6036 (base.clone(), 20., MONO, normal_code, [125., 207.]),
6037 (base.clone(), 30., MONO, normal_code, [175., 294.5]),
6038 (larger, 20., MONO, normal_code, [225., 382.]),
6039 (bold, 20., MONO, normal_code, [175., 250.75]),
6040 (mono, 20., MONO, normal_code, [225., 207.]),
6041 (base.clone(), 20., MONO, normal_code, [125., 207.]),
6042 (base.clone(), 20., BODY, normal_code, [125., 119.5]),
6043 (base.clone(), 20., MONO, normal_code, [125., 207.]),
6044 (base, 20., MONO, bold_code, [125., 250.75]),
6045 ] {
6046 let mut theme = crate::Theme::default();
6047 theme.tokens.typography.mono = family.into();
6048 cx.set_global(theme);
6049 window.set_rem_size(px(rem_size));
6050 let node_cx = NodeContext {
6051 style: Arc::new(TextViewStyle::default().with_inline_code(inline_code)),
6052 ..Default::default()
6053 };
6054 window.with_text_style(Some(style.subtract(&Default::default())), |window| {
6055 let widths = measure_table_columns(&table, 2, &node_cx, window, cx);
6056 for (width, expected) in widths.iter().zip(expected) {
6057 assert!((width - expected).abs() < 0.01, "{width} != {expected}");
6058 }
6059 let cached = cached_column_widths(&table);
6060 if let Some(previous) = previous.replace(cached.clone()) {
6061 assert!(!Arc::ptr_eq(&previous, &cached));
6062 }
6063 assert_eq!(
6064 measure_table_columns(&table, 2, &node_cx, window, cx),
6065 widths
6066 );
6067 assert!(Arc::ptr_eq(&cached, &cached_column_widths(&table)));
6068 });
6069 }
6070 });
6071 }
6072
6073 #[test]
6074 fn table_columns_cache_is_rebuilt_for_reparsed_tables() {
6075 use crate::text::format::markdown;
6076 use crate::text::inline::test_draw::in_prepaint;
6077 use crate::text::inline::test_fonts::{BODY, WideMonoTextSystem};
6078 use gpui::{Refineable as _, TestApp, TextStyle};
6079
6080 let mut node_cx = NodeContext::default();
6081 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
6082 in_prepaint(&mut app, move |window, cx| {
6083 let style = TextStyle {
6084 font_family: BODY.into(),
6085 font_size: px(20.).into(),
6086 ..Default::default()
6087 };
6088 window.with_text_style(Some(style.subtract(&Default::default())), |window| {
6089 let mut previous = None;
6090 for (text, expected) in [("longer cell", 134.), ("x", CELL_MIN_PX)] {
6091 let source = format!("| h |\n| - |\n| {text} |\n");
6092 let document = markdown::parse(&source, &mut node_cx).unwrap();
6093 let BlockNode::Table(table) = &document.blocks[0] else {
6094 panic!("expected a parsed table");
6095 };
6096 assert!(table.column_widths_cache.0.lock().unwrap().is_none());
6097 assert_eq!(
6098 measure_table_columns(table, 1, &node_cx, window, cx),
6099 vec![expected]
6100 );
6101 let cached = cached_column_widths(table);
6102 if let Some(previous) = previous.replace(cached.clone()) {
6103 assert!(!Arc::ptr_eq(&previous, &cached));
6104 }
6105 assert_eq!(document.source.as_ref(), source);
6106 }
6107 });
6108 });
6109 }
6110
6111 #[test]
6115 fn table_column_of_inline_code_cells_fits_the_mono_width() {
6116 use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
6117 use gpui::{Empty, TestApp};
6118
6119 let code = "method_name()";
6120 let mut paragraph = Paragraph::default();
6121 paragraph
6122 .push(InlineNode::new(code).marks(vec![(0..code.len(), TextMark::default().code())]));
6123 let table = Table {
6124 children: vec![TableRow {
6125 children: vec![TableCell {
6126 children: paragraph,
6127 width: None,
6128 }],
6129 }],
6130 column_aligns: vec![],
6131 span: None,
6132 table_data_cache: TableDataCache::default(),
6133 column_widths_cache: TableColumnWidthsCache::default(),
6134 };
6135 let node_cx = NodeContext::default();
6136
6137 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
6138 let mut window = app.open_window(|_, _| Empty);
6139 let (col_w, font_size) = window.update(|_, window, cx| {
6140 let mut theme = crate::Theme::default();
6141 theme.tokens.typography.mono = MONO.into();
6142 cx.set_global(theme);
6143 let font_size = window.text_style().font_size.to_pixels(window.rem_size());
6144 (
6145 measure_table_columns(&table, 1, &node_cx, window, cx),
6146 font_size,
6147 )
6148 });
6149
6150 let mono_w = f32::from(WideMonoTextSystem::width_of(code, MONO, font_size * 0.875));
6151 assert!(
6152 (col_w[0]
6153 - (mono_w + CELL_PAD_PX + crate::text::inline_flow::INLINE_CODE_PADDING * 2.))
6154 .abs()
6155 < 0.01,
6156 "col_w {} must fit the mono width {} plus padding {}",
6157 col_w[0],
6158 mono_w,
6159 CELL_PAD_PX
6160 );
6161 }
6162
6163 #[test]
6168 fn table_column_of_an_image_cell_fits_the_image_width() {
6169 use crate::text::inline::test_draw::in_prepaint;
6170 use crate::text::inline::test_fonts::{BODY, WideMonoTextSystem};
6171 use gpui::{Refineable as _, TestApp, TextStyle};
6172
6173 let mut paragraph = Paragraph::default();
6174 paragraph.push(InlineNode::image(ImageNode {
6175 url: "https://example.com/photo.png".into(),
6176 width: Some(px(100.).into()),
6177 height: Some(px(50.).into()),
6178 ..Default::default()
6179 }));
6180 let table = Table {
6181 children: vec![TableRow {
6182 children: vec![TableCell {
6183 children: paragraph,
6184 width: None,
6185 }],
6186 }],
6187 column_aligns: vec![],
6188 span: None,
6189 table_data_cache: TableDataCache::default(),
6190 column_widths_cache: TableColumnWidthsCache::default(),
6191 };
6192 let node_cx = NodeContext::default();
6193
6194 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
6195 in_prepaint(&mut app, move |window, cx| {
6196 let style = TextStyle {
6197 font_family: BODY.into(),
6198 font_size: px(20.).into(),
6199 ..Default::default()
6200 };
6201 window.with_text_style(Some(style.subtract(&Default::default())), |window| {
6202 assert_eq!(
6203 measure_table_columns(&table, 1, &node_cx, window, cx),
6204 vec![100. + CELL_PAD_PX]
6205 );
6206 });
6207 });
6208 }
6209
6210 #[test]
6211 fn code_block_highlights_are_cached_by_highlighter_identity() {
6212 use std::sync::atomic::{AtomicUsize, Ordering};
6213
6214 let calls = Arc::new(AtomicUsize::new(0));
6215 let calls_for_highlighter = calls.clone();
6216 let highlighter: Arc<CodeBlockHighlighterFn> = Arc::new(move |_| {
6217 calls_for_highlighter.fetch_add(1, Ordering::Relaxed);
6218 Vec::new()
6219 });
6220 let block = CodeBlock::new("fn main() {}".into(), Some("rust".into()), None::<Span>);
6221
6222 block.highlighted_styles(&highlighter);
6223 block.highlighted_styles(&highlighter);
6224 assert_eq!(calls.load(Ordering::Relaxed), 1);
6225
6226 let replacement: Arc<CodeBlockHighlighterFn> = Arc::new(|_| Vec::new());
6227 block.highlighted_styles(&replacement);
6228 assert!(Arc::ptr_eq(
6229 &block
6230 .highlight_cache
6231 .lock()
6232 .unwrap()
6233 .as_ref()
6234 .unwrap()
6235 .highlighter,
6236 &replacement
6237 ));
6238 }
6239
6240 #[test]
6241 fn a_new_highlighter_replaces_styles_instead_of_reusing_the_cache() {
6242 let light: Arc<CodeBlockHighlighterFn> = Arc::new(|_| {
6246 vec![(
6247 0..2,
6248 HighlightStyle {
6249 color: Some(gpui::rgb(0x0000ff).into()),
6250 ..Default::default()
6251 },
6252 )]
6253 });
6254 let dark: Arc<CodeBlockHighlighterFn> = Arc::new(|_| {
6255 vec![(
6256 0..2,
6257 HighlightStyle {
6258 color: Some(gpui::rgb(0xffff00).into()),
6259 ..Default::default()
6260 },
6261 )]
6262 });
6263 let block = CodeBlock::from_code("42", Some("json"));
6264
6265 let light_styles = block.highlighted_styles(&light);
6266 let dark_styles = block.highlighted_styles(&dark);
6267
6268 assert_eq!(light_styles[0].1.color, Some(gpui::rgb(0x0000ff).into()));
6269 assert_eq!(dark_styles[0].1.color, Some(gpui::rgb(0xffff00).into()));
6270 assert_eq!(block.code(), "42", "the document must survive the swap");
6271 }
6272
6273 #[test]
6274 fn reconstruct_markdown_wraps_marked_runs() {
6275 let marks = vec![(0..4, TextMark::default().bold())];
6277 assert_eq!(reconstruct_markdown("bold", &marks, 0..4), "**bold**");
6278 assert_eq!(reconstruct_markdown("bold", &marks, 1..3), "**ol**");
6280 }
6281
6282 #[test]
6283 fn reconstruct_markdown_emits_unmarked_text_verbatim() {
6284 let text = "a b c";
6286 let marks = vec![(2..3, TextMark::default().code())];
6287 assert_eq!(reconstruct_markdown(text, &marks, 0..5), "a `b` c");
6288 assert_eq!(reconstruct_markdown(text, &marks, 3..5), " c");
6290 }
6291
6292 #[test]
6293 fn reconstruct_markdown_handles_code_italic_strike_link() {
6294 assert_eq!(
6295 reconstruct_markdown("x", &[(0..1, TextMark::default().code())], 0..1),
6296 "`x`"
6297 );
6298 assert_eq!(
6299 reconstruct_markdown("x", &[(0..1, TextMark::default().italic())], 0..1),
6300 "*x*"
6301 );
6302 assert_eq!(
6303 reconstruct_markdown("x", &[(0..1, TextMark::default().strikethrough())], 0..1),
6304 "~~x~~"
6305 );
6306 let link = TextMark::default().link(LinkMark {
6307 url: "https://example.com".into(),
6308 ..Default::default()
6309 });
6310 assert_eq!(
6311 reconstruct_markdown("x", &[(0..1, link)], 0..1),
6312 "[x](https://example.com)"
6313 );
6314 }
6315
6316 #[test]
6317 fn reconstruct_markdown_nested_bold_italic() {
6318 let mark = TextMark::default().bold().italic();
6320 assert_eq!(reconstruct_markdown("x", &[(0..1, mark)], 0..1), "***x***");
6322 }
6323
6324 fn paragraph_with_children(children: Vec<InlineNode>) -> Paragraph {
6328 let combined: String = children.iter().map(|c| c.text.to_string()).collect();
6329 let paragraph = Paragraph {
6330 span: None,
6331 children,
6332 link_refs: HashMap::new(),
6333 state: Arc::new(Mutex::new(InlineState::default())),
6334 render_cache: ParagraphRenderCache::default(),
6335 };
6336 if let Ok(mut state) = paragraph.state.lock() {
6337 state.set_text(combined.into());
6338 }
6339 paragraph
6340 }
6341
6342 fn set_paragraph_selection(paragraph: &Paragraph, range: Range<usize>) {
6343 if let Ok(mut state) = paragraph.state.lock() {
6344 state.selection = Some(range.into());
6345 }
6346 }
6347
6348 #[test]
6349 fn paragraph_selected_source_maps_partial_selection_across_runs() {
6350 let children = vec![
6352 InlineNode::new("This has ").marks(vec![(0..9, TextMark::default())]),
6353 InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
6354 InlineNode::new(" text.").marks(vec![(0..6, TextMark::default())]),
6355 ];
6356 let paragraph = paragraph_with_children(children);
6357
6358 set_paragraph_selection(¶graph, 0..(9 + 4 + 6));
6360 assert_eq!(paragraph.selected_source(), "This has **bold** text.");
6361
6362 set_paragraph_selection(¶graph, 5..16);
6365 assert_eq!(paragraph.selected_source(), "has **bold** te");
6366
6367 set_paragraph_selection(¶graph, 10..12);
6369 assert_eq!(paragraph.selected_source(), "**ol**");
6370 }
6371
6372 #[test]
6373 fn paragraph_selected_source_matches_text_when_no_marks() {
6374 let children =
6375 vec![InlineNode::new("plain words").marks(vec![(0..11, TextMark::default())])];
6376 let paragraph = paragraph_with_children(children);
6377 set_paragraph_selection(¶graph, 0..11);
6378 assert_eq!(paragraph.selected_source(), "plain words");
6379 assert_eq!(paragraph.selected_text(), "plain words");
6380 }
6381
6382 fn copy_across_styles(blocks: Vec<BlockNode>) -> String {
6385 let document = crate::text::document::ParsedDocument {
6386 blocks: blocks.into(),
6387 ..Default::default()
6388 };
6389 document.selected_text(SelectionFormat::SourceAcrossStyles, None)
6390 }
6391
6392 #[test]
6393 fn source_across_styles_copies_plain_text_within_one_style() {
6394 let paragraph = || {
6396 paragraph_with_children(vec![
6397 InlineNode::new("This has ").marks(vec![(0..9, TextMark::default())]),
6398 InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
6399 InlineNode::new(" text.").marks(vec![(0..6, TextMark::default())]),
6400 ])
6401 };
6402 let copy = |range: Range<usize>| {
6403 let paragraph = paragraph();
6404 set_paragraph_selection(¶graph, range);
6405 copy_across_styles(vec![BlockNode::Paragraph(paragraph)])
6406 };
6407
6408 assert_eq!(copy(10..12), "ol\n");
6410 assert_eq!(copy(9..13), "bold\n");
6411 assert_eq!(copy(0..9), "This has \n");
6413 assert_eq!(copy(5..16), "has **bold** te");
6415 assert_eq!(copy(8..10), " **b**");
6416 }
6417
6418 #[test]
6419 fn source_across_styles_drops_the_url_of_a_link_selected_alone() {
6420 let link = TextMark::default().link(LinkMark {
6421 url: "https://example.com".into(),
6422 ..Default::default()
6423 });
6424 let paragraph = paragraph_with_children(vec![
6425 InlineNode::new("see ").marks(vec![(0..4, TextMark::default())]),
6426 InlineNode::new("the docs").marks(vec![(0..8, link)]),
6427 ]);
6428
6429 set_paragraph_selection(¶graph, 4..12);
6430 assert_eq!(
6431 copy_across_styles(vec![BlockNode::Paragraph(paragraph.clone())]),
6432 "the docs\n"
6433 );
6434
6435 set_paragraph_selection(¶graph, 0..12);
6436 assert_eq!(
6437 copy_across_styles(vec![BlockNode::Paragraph(paragraph)]),
6438 "see [the docs](https://example.com)"
6439 );
6440 }
6441
6442 #[test]
6443 fn source_across_styles_drops_the_markup_of_a_single_block() {
6444 let heading = BlockNode::Heading {
6445 level: 2,
6446 children: selected_paragraph("Title"),
6447 span: None,
6448 };
6449 assert_eq!(copy_across_styles(vec![heading]), "Title\n");
6450
6451 let code = CodeBlock::from_code("let a = 1;\nlet b = 2;", Some("rust"));
6452 code.set_selection(0..10);
6453 assert_eq!(
6454 copy_across_styles(vec![BlockNode::CodeBlock(code)]),
6455 "let a = 1;\n"
6456 );
6457
6458 let item = |text: &str| BlockNode::ListItem {
6459 children: vec![BlockNode::Paragraph(selected_paragraph(text))],
6460 spread: false,
6461 checked: None,
6462 task_marker: None,
6463 span: None,
6464 };
6465 let unselected_item = BlockNode::ListItem {
6466 children: vec![BlockNode::Paragraph(paragraph_with_children(vec![
6467 InlineNode::new("two"),
6468 ]))],
6469 spread: false,
6470 checked: None,
6471 task_marker: None,
6472 span: None,
6473 };
6474 let list = BlockNode::List {
6475 ordered: false,
6476 start: None,
6477 span: None,
6478 children: vec![item("one"), unselected_item],
6479 };
6480 assert_eq!(copy_across_styles(vec![list]), "one\n");
6481 }
6482
6483 #[test]
6484 fn source_across_styles_keeps_the_source_across_blocks() {
6485 let item = |text: &str| BlockNode::ListItem {
6486 children: vec![BlockNode::Paragraph(selected_paragraph(text))],
6487 spread: false,
6488 checked: None,
6489 task_marker: None,
6490 span: None,
6491 };
6492 let list = BlockNode::List {
6493 ordered: false,
6494 start: None,
6495 span: None,
6496 children: vec![item("one"), item("two")],
6497 };
6498 assert_eq!(copy_across_styles(vec![list]), "- one\n- two");
6499
6500 assert_eq!(
6501 copy_across_styles(vec![
6502 BlockNode::Paragraph(selected_paragraph("start")),
6503 BlockNode::Paragraph(selected_paragraph("end")),
6504 ]),
6505 "start\n\nend"
6506 );
6507 }
6508
6509 #[test]
6510 fn source_across_styles_keeps_the_source_of_an_inline_object() {
6511 let formula = InlineNode::custom(MarkdownNode::new("math", ()).text("x").markdown("$x$"));
6512 *formula.custom_selection.lock().unwrap() = true;
6513 let paragraph = Paragraph {
6514 children: vec![formula],
6515 ..Default::default()
6516 };
6517 assert_eq!(
6518 copy_across_styles(vec![BlockNode::Paragraph(paragraph)]),
6519 "$x$"
6520 );
6521 }
6522
6523 fn selected_paragraph(text: &str) -> Paragraph {
6524 let len = text.len();
6525 let paragraph = paragraph_with_children(vec![
6526 InlineNode::new(text).marks(vec![(0..len, TextMark::default())]),
6527 ]);
6528 set_paragraph_selection(¶graph, 0..len);
6529 paragraph
6530 }
6531
6532 #[test]
6533 fn heading_selected_source_prefixes_hashes() {
6534 let heading = BlockNode::Heading {
6535 level: 2,
6536 children: selected_paragraph("Title"),
6537 span: None,
6538 };
6539 assert_eq!(heading.selected_text(SelectionFormat::Source), "## Title\n");
6540 assert_eq!(heading.selected_text(SelectionFormat::Plain), "Title\n");
6542 }
6543
6544 #[test]
6545 fn unordered_list_selected_source_prefixes_dash() {
6546 let list = BlockNode::List {
6547 ordered: false,
6548 start: None,
6549 span: None,
6550 children: vec![
6551 BlockNode::ListItem {
6552 children: vec![BlockNode::Paragraph(selected_paragraph("one"))],
6553 spread: false,
6554 checked: None,
6555 task_marker: None,
6556 span: None,
6557 },
6558 BlockNode::ListItem {
6559 children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
6560 spread: false,
6561 checked: None,
6562 task_marker: None,
6563 span: None,
6564 },
6565 ],
6566 };
6567 assert_eq!(
6568 list.selected_text(SelectionFormat::Source),
6569 "- one\n- two\n"
6570 );
6571 }
6572
6573 #[test]
6574 fn ordered_list_selected_source_preserves_start() {
6575 let list = BlockNode::List {
6576 ordered: true,
6577 start: Some(3),
6578 span: None,
6579 children: vec![
6580 BlockNode::ListItem {
6581 children: vec![BlockNode::Paragraph(selected_paragraph("three"))],
6582 spread: false,
6583 checked: None,
6584 task_marker: None,
6585 span: None,
6586 },
6587 BlockNode::ListItem {
6588 children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
6589 spread: false,
6590 checked: None,
6591 task_marker: None,
6592 span: None,
6593 },
6594 ],
6595 };
6596 assert_eq!(list.to_markdown(), "3. three\n4. four");
6597 assert_eq!(
6598 list.selected_text(SelectionFormat::Source),
6599 "3. three\n4. four\n"
6600 );
6601 }
6602
6603 #[test]
6604 fn ordered_list_selected_source_preserves_nested_starts_and_continuations() {
6605 let nested = BlockNode::List {
6606 ordered: true,
6607 start: Some(4),
6608 span: None,
6609 children: vec![
6610 BlockNode::ListItem {
6611 children: vec![BlockNode::Paragraph(selected_paragraph("nested"))],
6612 spread: false,
6613 checked: None,
6614 task_marker: None,
6615 span: None,
6616 },
6617 BlockNode::ListItem {
6618 children: vec![BlockNode::Paragraph(selected_paragraph("again"))],
6619 spread: false,
6620 checked: None,
6621 task_marker: None,
6622 span: None,
6623 },
6624 ],
6625 };
6626 let nested_list = BlockNode::List {
6627 ordered: true,
6628 start: Some(3),
6629 span: None,
6630 children: vec![
6631 BlockNode::ListItem {
6632 children: vec![BlockNode::Paragraph(selected_paragraph("three")), nested],
6633 spread: false,
6634 checked: None,
6635 task_marker: None,
6636 span: None,
6637 },
6638 BlockNode::ListItem {
6639 children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
6640 spread: false,
6641 checked: None,
6642 task_marker: None,
6643 span: None,
6644 },
6645 ],
6646 };
6647 assert_eq!(
6648 nested_list.selected_text(SelectionFormat::Source),
6649 "3. three\n 4. nested\n 5. again\n4. four\n"
6650 );
6651
6652 let loose_list = BlockNode::List {
6653 ordered: true,
6654 start: Some(3),
6655 span: None,
6656 children: vec![
6657 BlockNode::ListItem {
6658 children: vec![
6659 BlockNode::Paragraph(selected_paragraph("loose")),
6660 BlockNode::Paragraph(selected_paragraph("continuation")),
6661 ],
6662 spread: true,
6663 checked: None,
6664 task_marker: None,
6665 span: None,
6666 },
6667 BlockNode::ListItem {
6668 children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
6669 spread: false,
6670 checked: None,
6671 task_marker: None,
6672 span: None,
6673 },
6674 ],
6675 };
6676 assert_eq!(
6677 loose_list.selected_text(SelectionFormat::Source),
6678 "3. loose\n continuation\n4. four\n"
6679 );
6680 }
6681
6682 #[test]
6683 fn nested_list_selected_source_indents_sublists() {
6684 let nested = BlockNode::List {
6688 ordered: false,
6689 start: None,
6690 span: None,
6691 children: vec![BlockNode::ListItem {
6692 children: vec![BlockNode::Paragraph(selected_paragraph("nested"))],
6693 spread: false,
6694 checked: None,
6695 task_marker: None,
6696 span: None,
6697 }],
6698 };
6699 let list = BlockNode::List {
6700 ordered: false,
6701 start: None,
6702 span: None,
6703 children: vec![
6704 BlockNode::ListItem {
6705 children: vec![BlockNode::Paragraph(selected_paragraph("one")), nested],
6706 spread: false,
6707 checked: None,
6708 task_marker: None,
6709 span: None,
6710 },
6711 BlockNode::ListItem {
6712 children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
6713 spread: false,
6714 checked: None,
6715 task_marker: None,
6716 span: None,
6717 },
6718 ],
6719 };
6720 assert_eq!(
6721 list.selected_text(SelectionFormat::Source),
6722 "- one\n - nested\n- two\n"
6723 );
6724 }
6725
6726 #[test]
6727 fn task_list_selected_source_restores_checkboxes() {
6728 let list = BlockNode::List {
6729 ordered: false,
6730 start: None,
6731 span: None,
6732 children: vec![
6733 BlockNode::ListItem {
6734 children: vec![BlockNode::Paragraph(selected_paragraph("done"))],
6735 spread: false,
6736 checked: Some(true),
6737 task_marker: None,
6738 span: None,
6739 },
6740 BlockNode::ListItem {
6741 children: vec![BlockNode::Paragraph(selected_paragraph("todo"))],
6742 spread: false,
6743 checked: Some(false),
6744 task_marker: None,
6745 span: None,
6746 },
6747 ],
6748 };
6749 assert_eq!(
6750 list.selected_text(SelectionFormat::Source),
6751 "- [x] done\n- [ ] todo\n"
6752 );
6753 }
6754
6755 #[test]
6756 fn blockquote_selected_source_prefixes_gt() {
6757 let quote = BlockNode::Blockquote {
6758 span: None,
6759 children: vec![BlockNode::Paragraph(selected_paragraph("quoted text"))],
6760 };
6761 assert_eq!(
6762 quote.selected_text(SelectionFormat::Source),
6763 "> quoted text\n"
6764 );
6765 }
6766
6767 #[test]
6768 fn table_selected_source_pipes_cells_with_alignment_row() {
6769 let cell = |text: &str| TableCell {
6770 children: selected_paragraph(text),
6771 width: None,
6772 };
6773 let table = Table {
6774 children: vec![
6775 TableRow {
6776 children: vec![cell("Name"), cell("Age")],
6777 },
6778 TableRow {
6779 children: vec![cell("Alice"), cell("30")],
6780 },
6781 ],
6782 column_aligns: vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
6783 span: None,
6784 table_data_cache: TableDataCache::default(),
6785 column_widths_cache: TableColumnWidthsCache::default(),
6786 };
6787 let block = BlockNode::Table(table);
6788 assert_eq!(
6789 block.selected_text(SelectionFormat::Source),
6790 "| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n"
6791 );
6792 }
6793
6794 #[test]
6797 fn a_selection_in_one_table_cell_copies_only_that_cell() {
6798 let table = table_of(
6799 vec![
6800 vec![plain_cell("Name"), plain_cell("Age")],
6801 vec![
6802 TableCell {
6803 children: selected_paragraph("Alice"),
6804 width: None,
6805 },
6806 plain_cell("30"),
6807 ],
6808 ],
6809 vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
6810 );
6811 let block = BlockNode::Table(table);
6812 assert_eq!(block.selected_text(SelectionFormat::Plain).trim(), "Alice");
6813 assert_eq!(block.selected_text(SelectionFormat::Source), "Alice\n");
6814 }
6815
6816 fn plain_cell(text: &str) -> TableCell {
6819 TableCell {
6820 children: Paragraph::new(text.to_string()),
6821 width: None,
6822 }
6823 }
6824
6825 fn table_of(rows: Vec<Vec<TableCell>>, column_aligns: Vec<ColumnumnAlign>) -> Table {
6826 Table {
6827 children: rows
6828 .into_iter()
6829 .map(|children| TableRow { children })
6830 .collect(),
6831 column_aligns,
6832 span: None,
6833 table_data_cache: TableDataCache::default(),
6834 column_widths_cache: TableColumnWidthsCache::default(),
6835 }
6836 }
6837
6838 #[test]
6839 fn table_to_markdown_pipes_cells_with_alignment_row() {
6840 let table = table_of(
6841 vec![
6842 vec![plain_cell("Name"), plain_cell("Age"), plain_cell("Score")],
6843 vec![plain_cell("Alice"), plain_cell("30"), plain_cell("9.5")],
6844 ],
6845 vec![
6846 ColumnumnAlign::Left,
6847 ColumnumnAlign::Center,
6848 ColumnumnAlign::Right,
6849 ],
6850 );
6851
6852 assert_eq!(
6853 table.to_markdown(),
6854 "| Name | Age | Score |\n| :-- | :-: | --: |\n| Alice | 30 | 9.5 |"
6855 );
6856 assert_eq!(
6858 BlockNode::Table(table.clone()).to_markdown(),
6859 table.to_markdown()
6860 );
6861 }
6862
6863 #[test]
6864 fn table_to_markdown_keeps_outer_pipes_for_a_single_column() {
6865 let table = table_of(
6866 vec![vec![plain_cell("Symbol")], vec![plain_cell("TSLA.US")]],
6867 vec![ColumnumnAlign::Left],
6868 );
6869
6870 assert_eq!(table.to_markdown(), "| Symbol |\n| :-- |\n| TSLA.US |");
6871 }
6872
6873 #[test]
6874 fn table_to_markdown_escapes_pipes_and_keeps_inline_marks() {
6875 let bold = TableCell {
6876 children: paragraph_with_children(vec![
6877 InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
6878 ]),
6879 width: None,
6880 };
6881 let table = table_of(
6882 vec![
6883 vec![plain_cell("a | b"), plain_cell("plain")],
6884 vec![plain_cell("c"), bold],
6885 ],
6886 vec![ColumnumnAlign::Left, ColumnumnAlign::Left],
6887 );
6888
6889 assert_eq!(
6890 table.to_markdown(),
6891 "| a \\| b | plain |\n| :-- | :-- |\n| c | **bold** |"
6892 );
6893 }
6894
6895 #[test]
6896 fn table_data_snapshots_plain_cells_and_markdown() {
6897 let mut table = table_of(
6898 vec![
6899 vec![plain_cell(" Name "), plain_cell("Age")],
6900 vec![plain_cell("Alice"), plain_cell("30")],
6901 ],
6902 vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
6903 );
6904 table.span = Some(Span { start: 4, end: 42 });
6905
6906 let data = table.table_data();
6907 assert_eq!(data.headers, vec!["Name", "Age"]);
6908 assert_eq!(data.rows, vec![vec!["Alice", "30"]]);
6909 assert_eq!(data.markdown, table.to_markdown());
6910 assert_eq!(data.span, Some(4..42));
6911 }
6912
6913 #[test]
6914 fn cloned_table_keeps_cached_table_data() {
6915 let table = table_of(
6918 vec![vec![plain_cell("Name")], vec![plain_cell("Alice")]],
6919 vec![ColumnumnAlign::Left],
6920 );
6921 let data = table.cached_table_data();
6922
6923 #[expect(
6924 clippy::redundant_clone,
6925 reason = "This test verifies that cloning a table shares its cached snapshot"
6926 )]
6927 let cloned = table.clone();
6928 assert!(Arc::ptr_eq(&data, &cloned.cached_table_data()));
6929 }
6930
6931 #[test]
6932 fn table_data_handles_tables_without_rows() {
6933 let header_only = table_of(
6935 vec![vec![plain_cell("Name"), plain_cell("Age")]],
6936 vec![ColumnumnAlign::Left, ColumnumnAlign::Left],
6937 );
6938 let data = header_only.table_data();
6939 assert_eq!(data.headers, vec!["Name", "Age"]);
6940 assert!(data.rows.is_empty());
6941 assert_eq!(data.markdown, "| Name | Age |\n| :-- | :-- |");
6942
6943 assert_eq!(Table::default().table_data(), TableData::default());
6945 }
6946
6947 #[test]
6948 fn test_image_node_source() {
6949 use gpui::{ImageFormat, ImageSource, Resource};
6950
6951 fn image_node(url: &str) -> ImageNode {
6952 ImageNode {
6953 url: url.into(),
6954 ..Default::default()
6955 }
6956 }
6957
6958 fn assert_uri(url: &str) {
6962 match image_node(url).source() {
6963 ImageSource::Resource(Resource::Uri(uri)) => assert_eq!(uri.as_ref(), url),
6964 _ => panic!("expected Uri for {url:?}"),
6965 }
6966 }
6967 assert_uri("https://example.com/logo.png");
6968 assert_uri("http://example.com/logo.png");
6969 assert_uri("website/public/logo.svg");
6970 assert_uri("./images/a.png");
6971 assert_uri("../images/a.png");
6972 assert_uri("/absolute/path/logo.svg");
6973 assert_uri("file:///absolute/path/logo.svg");
6974 assert_uri(r"C:\images\logo.png");
6975 assert_uri("docs/a:b.png");
6976 assert_uri("data:text/plain;base64,aGVsbG8=");
6977
6978 let node = image_node("data:image/png;base64,iVBORw0KGgo=");
6981 let ImageSource::Image(first) = node.source() else {
6982 panic!("expected an embedded image");
6983 };
6984 assert_eq!(first.format(), ImageFormat::Png);
6985 assert_eq!(first.bytes(), b"\x89PNG\r\n\x1a\n");
6986 let ImageSource::Image(second) = node.source() else {
6987 panic!("expected an embedded image");
6988 };
6989 assert!(Arc::ptr_eq(&first, &second));
6990 }
6991
6992 #[test]
6995 fn a_paragraph_of_several_images_is_an_inline_flow() {
6996 use crate::text::format::markdown;
6997
6998 let mut node_cx = NodeContext::default();
6999 for (source, expected) in [
7000 ("", false),
7001 ("", true),
7002 (
7003 "[](https://a.com)[](https://b.com)",
7004 true,
7005 ),
7006 (" ", true),
7007 ] {
7008 let document = markdown::parse(source, &mut node_cx).unwrap();
7009 let BlockNode::Paragraph(paragraph) = &document.blocks[0] else {
7010 panic!("expected a paragraph for {source}");
7011 };
7012 assert_eq!(paragraph.should_render_inline_flow(), expected, "{source}");
7013 }
7014 }
7015
7016 fn image_paragraph(alt: &str, url: &str) -> Paragraph {
7017 let image = ImageNode {
7018 url: url.into(),
7019 alt: Some(alt.into()),
7020 ..Default::default()
7021 };
7022 Paragraph {
7023 span: None,
7024 children: vec![InlineNode::image(image)],
7025 link_refs: HashMap::new(),
7026 state: Arc::new(Mutex::new(InlineState::default())),
7027 render_cache: ParagraphRenderCache::default(),
7028 }
7029 }
7030
7031 #[test]
7034 fn marks_round_trip_through_reconstruction() {
7035 let wrap = |mark: TextMark| reconstruct_markdown("x", &[(0..1, mark)], 0..1);
7036
7037 assert_eq!(wrap(TextMark::default().bold()), "**x**");
7038 assert_eq!(wrap(TextMark::default().italic()), "*x*");
7039 assert_eq!(wrap(TextMark::default().code()), "`x`");
7040 assert_eq!(wrap(TextMark::default().strikethrough()), "~~x~~");
7041 assert_eq!(
7042 wrap(TextMark::default().highlight(gpui::rgb(0xfef08a).into())),
7043 "==x=="
7044 );
7045 assert_eq!(wrap(TextMark::default().underline()), "<u>x</u>");
7047
7048 assert_eq!(
7050 wrap(TextMark::default().link(LinkMark {
7051 url: "https://example.com".into(),
7052 title: Some("Tip".into()),
7053 ..Default::default()
7054 })),
7055 "[x](https://example.com \"Tip\")"
7056 );
7057 }
7058
7059 #[test]
7062 fn document_selected_source_slices_covered_blocks_from_the_source() {
7063 use crate::text::document::ParsedDocument;
7064
7065 let source = "start\n\n3. _one_\n4. two\n\n---\n\nend";
7068 let list = "3. _one_\n4. two";
7069 let list_start = source.find(list).unwrap();
7070 let rule_start = source.find("---").unwrap();
7071
7072 let document = ParsedDocument {
7073 source: source.into(),
7074 blocks: vec![
7075 BlockNode::Paragraph(selected_paragraph("start")),
7076 BlockNode::List {
7077 ordered: true,
7078 start: Some(3),
7079 children: vec![],
7080 span: Some(Span {
7081 start: list_start,
7082 end: list_start + list.len(),
7083 }),
7084 },
7085 BlockNode::HorizontalRule {
7086 span: Some(Span {
7087 start: rule_start,
7088 end: rule_start + 3,
7089 }),
7090 },
7091 BlockNode::Paragraph(selected_paragraph("end")),
7092 ]
7093 .into(),
7094 };
7095
7096 assert_eq!(
7097 document.selected_text(SelectionFormat::Source, None),
7098 "start\n\n3. _one_\n4. two\n\n---\n\nend"
7099 );
7100 }
7101
7102 #[test]
7103 fn document_selected_source_includes_enclosed_image() {
7104 use crate::text::document::ParsedDocument;
7105
7106 let source = "before\n\n\n\nafter";
7110 let image_markdown = "";
7111 let start = source.find(image_markdown).unwrap();
7112 let mut image = image_paragraph("alt", "https://example.com/i.png");
7113 image.span = Some(Span {
7114 start,
7115 end: start + image_markdown.len(),
7116 });
7117
7118 let document = ParsedDocument {
7119 source: source.into(),
7120 blocks: vec![
7121 BlockNode::Paragraph(selected_paragraph("before")),
7122 BlockNode::Paragraph(image),
7123 BlockNode::Paragraph(selected_paragraph("after")),
7124 ]
7125 .into(),
7126 };
7127 assert_eq!(
7128 document.selected_text(SelectionFormat::Source, None),
7129 "before\n\n\n\nafter"
7130 );
7131 }
7132
7133 #[test]
7134 fn document_selected_source_drops_unenclosed_image() {
7135 use crate::text::document::ParsedDocument;
7136
7137 let document = ParsedDocument {
7140 source: String::new().into(),
7141 blocks: vec![
7142 BlockNode::Paragraph(selected_paragraph("before")),
7143 BlockNode::Paragraph(image_paragraph("alt", "u")),
7144 ]
7145 .into(),
7146 };
7147 assert_eq!(
7148 document.selected_text(SelectionFormat::Source, None),
7149 "before"
7150 );
7151 }
7152
7153 fn selected_code_block(code: &str, lang: Option<&str>) -> BlockNode {
7154 let block = CodeBlock::new(
7155 code.to_string().into(),
7156 lang.map(|l| l.to_string().into()),
7157 None::<Span>,
7158 );
7159 if let Ok(mut state) = block.state.lock() {
7160 let len = state.text.len();
7161 state.selection = Some((0..len).into());
7162 }
7163 BlockNode::CodeBlock(block)
7164 }
7165
7166 #[test]
7167 fn code_block_selected_source_wraps_in_fence_with_lang() {
7168 let block = selected_code_block("let x = 1;\n", Some("rust"));
7169 let code = block.selected_text(SelectionFormat::Plain);
7170 let code_trimmed = code.trim_end_matches('\n');
7171 assert_eq!(
7175 block.selected_text(SelectionFormat::Source),
7176 format!("```rust\n{}\n```\n", code_trimmed)
7177 );
7178 assert!(
7179 block
7180 .selected_text(SelectionFormat::Source)
7181 .starts_with("```rust\n")
7182 );
7183 assert!(
7184 block
7185 .selected_text(SelectionFormat::Source)
7186 .trim_end()
7187 .ends_with("\n```")
7188 );
7189 }
7190
7191 #[test]
7192 fn code_block_selected_source_without_lang() {
7193 let block = selected_code_block("plain\n", None);
7194 let code_trimmed = block.selected_text(SelectionFormat::Plain);
7195 let code_trimmed = code_trimmed.trim_end_matches('\n');
7196 assert_eq!(
7197 block.selected_text(SelectionFormat::Source),
7198 format!("```\n{}\n```\n", code_trimmed)
7199 );
7200 }
7201
7202 #[test]
7203 fn document_selected_source_joins_blocks_with_blank_line() {
7204 use crate::text::document::ParsedDocument;
7205
7206 let document = ParsedDocument {
7210 source: String::new().into(),
7211 blocks: vec![
7212 BlockNode::Heading {
7213 level: 1,
7214 children: selected_paragraph("Title"),
7215 span: None,
7216 },
7217 BlockNode::Paragraph(selected_paragraph("A paragraph.")),
7218 selected_code_block("let x = 1;\n", Some("rust")),
7219 BlockNode::List {
7220 ordered: true,
7221 start: Some(1),
7222 span: None,
7223 children: vec![
7224 BlockNode::ListItem {
7225 children: vec![BlockNode::Paragraph(selected_paragraph("one"))],
7226 spread: false,
7227 checked: None,
7228 task_marker: None,
7229 span: None,
7230 },
7231 BlockNode::ListItem {
7232 children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
7233 spread: false,
7234 checked: None,
7235 task_marker: None,
7236 span: None,
7237 },
7238 ],
7239 },
7240 ]
7241 .into(),
7242 };
7243
7244 assert_eq!(
7245 document.selected_text(SelectionFormat::Source, None),
7246 "# Title\n\nA paragraph.\n\n```rust\nlet x = 1;\n```\n\n1. one\n2. two"
7247 );
7248 }
7249
7250 #[test]
7251 fn code_block_equality_includes_code_content() {
7252 let first = CodeBlock::new("let value = 1;".into(), Some("rust".into()), None::<Span>);
7253 let second = CodeBlock::new("let value = 2;".into(), Some("rust".into()), None::<Span>);
7254
7255 assert_ne!(first, second);
7256 }
7257}