use std::cell::RefCell;
use std::ops::Range;
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, ElementId, Font, FontFeatures, FontStyle, FontWeight, Hsla,
InteractiveElement, InteractiveText, IntoElement, ParentElement, Pixels, RenderOnce,
SharedString, StatefulInteractiveElement, StrikethroughStyle, Styled, StyledText, TextRun,
Window, canvas, div, px, relative,
};
use pulldown_cmark::{Alignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
use super::{CodeBlock, Icon, Selection, group_for, selectable_block, selection_root};
use crate::cache::{Lru, content_key};
use crate::motion::key;
use crate::theme::{MONO_FONT_FAMILY, Scheme, Theme, alpha, font_family, text};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct InlineStyle {
pub bold: bool,
pub italic: bool,
pub strike: bool,
pub code: bool,
pub link: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RichText {
pub text: String,
pub spans: Vec<(Range<usize>, InlineStyle)>,
pub links: Vec<(Range<usize>, String)>,
}
impl RichText {
pub fn code_ranges(&self) -> impl Iterator<Item = Range<usize>> + '_ {
self.spans
.iter()
.filter(|(_, s)| s.code)
.map(|(r, _)| r.clone())
}
pub fn as_str(&self) -> &str {
&self.text
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MarkdownImage {
pub url: String,
pub alt: String,
pub title: String,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ColumnAlign {
#[default]
None,
Left,
Center,
Right,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MarkdownItem {
pub task: Option<bool>,
pub blocks: Vec<MarkdownBlock>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MarkdownBlock {
Paragraph(RichText),
Heading {
level: u8,
text: RichText,
},
Code {
language: String,
code: String,
},
Quote(Vec<MarkdownBlock>),
List {
start: Option<u64>,
items: Vec<MarkdownItem>,
},
Table {
align: Vec<ColumnAlign>,
head: Vec<RichText>,
rows: Vec<Vec<RichText>>,
},
Rule,
Image(MarkdownImage),
}
#[derive(Default)]
struct Inline {
rich: RichText,
bold: u32,
italic: u32,
strike: u32,
links: Vec<(usize, String)>,
images: Vec<MarkdownImage>,
}
impl Inline {
fn style(&self, code: bool) -> InlineStyle {
InlineStyle {
bold: self.bold > 0,
italic: self.italic > 0,
strike: self.strike > 0,
code,
link: !self.links.is_empty(),
}
}
fn push(&mut self, text: &str, style: InlineStyle) {
if text.is_empty() {
return;
}
let start = self.rich.text.len();
self.rich.text.push_str(text);
let end = self.rich.text.len();
match self.rich.spans.last_mut() {
Some((range, last)) if *last == style && range.end == start => range.end = end,
_ => self.rich.spans.push((start..end, style)),
}
}
fn text(&mut self, text: &str) {
let style = self.style(false);
if style.link {
self.push(text, style);
return;
}
let mut at = 0;
for url in find_urls(text) {
self.push(&text[at..url.start], style);
let start = self.rich.text.len();
self.push(
&text[url.clone()],
InlineStyle {
link: true,
..style
},
);
self.rich
.links
.push((start..self.rich.text.len(), text[url.clone()].to_string()));
at = url.end;
}
self.push(&text[at..], style);
}
}
enum Frame {
Blocks(Vec<MarkdownBlock>),
Quote(Vec<MarkdownBlock>),
List {
start: Option<u64>,
items: Vec<MarkdownItem>,
},
Item(MarkdownItem),
Table {
align: Vec<ColumnAlign>,
head: Vec<RichText>,
rows: Vec<Vec<RichText>>,
row: Vec<RichText>,
},
}
struct Builder {
frames: Vec<Frame>,
inline: Option<Inline>,
heading: Option<u8>,
code: Option<(String, String)>,
html: Option<String>,
image: Option<MarkdownImage>,
in_cell: bool,
}
impl Builder {
fn push_block(&mut self, block: MarkdownBlock) {
match self.frames.last_mut() {
Some(Frame::Blocks(blocks) | Frame::Quote(blocks)) => blocks.push(block),
Some(Frame::Item(item)) => item.blocks.push(block),
Some(Frame::List { .. } | Frame::Table { .. }) | None => {}
}
}
fn inline(&mut self) -> &mut Inline {
self.inline.get_or_insert_with(Inline::default)
}
fn flush(&mut self) {
let Some(inline) = self.inline.take() else {
return;
};
let images = inline.images;
let mut rich = inline.rich;
trim_rich(&mut rich);
if !rich.text.is_empty() {
match self.heading.take() {
Some(level) => self.push_block(MarkdownBlock::Heading { level, text: rich }),
None => self.push_block(MarkdownBlock::Paragraph(rich)),
}
}
for image in images {
self.push_block(MarkdownBlock::Image(image));
}
}
fn start(&mut self, tag: Tag) {
match tag {
Tag::Paragraph => self.flush(),
Tag::Heading { level, .. } => {
self.flush();
self.heading = Some(level as u8);
}
Tag::BlockQuote(_) => {
self.flush();
self.frames.push(Frame::Quote(Vec::new()));
}
Tag::CodeBlock(kind) => {
self.flush();
let language = match kind {
CodeBlockKind::Fenced(info) => info.trim().to_string(),
CodeBlockKind::Indented => String::new(),
};
self.code = Some((language, String::new()));
}
Tag::HtmlBlock => {
self.flush();
self.html = Some(String::new());
}
Tag::List(start) => {
self.flush();
self.frames.push(Frame::List {
start,
items: Vec::new(),
});
}
Tag::Item => {
self.flush();
self.frames.push(Frame::Item(MarkdownItem::default()));
}
Tag::Table(align) => {
self.flush();
self.frames.push(Frame::Table {
align: align
.into_iter()
.map(|a| match a {
Alignment::None => ColumnAlign::None,
Alignment::Left => ColumnAlign::Left,
Alignment::Center => ColumnAlign::Center,
Alignment::Right => ColumnAlign::Right,
})
.collect(),
head: Vec::new(),
rows: Vec::new(),
row: Vec::new(),
});
}
Tag::TableCell => {
self.in_cell = true;
self.inline = Some(Inline::default());
}
Tag::Emphasis => self.inline().italic += 1,
Tag::Strong => self.inline().bold += 1,
Tag::Strikethrough => self.inline().strike += 1,
Tag::Link { dest_url, .. } => {
let inline = self.inline();
let at = inline.rich.text.len();
inline.links.push((at, dest_url.to_string()));
}
Tag::Image {
dest_url, title, ..
} => {
self.image = Some(MarkdownImage {
url: dest_url.to_string(),
alt: String::new(),
title: title.to_string(),
});
}
_ => {}
}
}
fn end(&mut self, tag: TagEnd) {
match tag {
TagEnd::Paragraph | TagEnd::Heading(_) => self.flush(),
TagEnd::BlockQuote(_) => {
self.flush();
if let Some(Frame::Quote(blocks)) = self.frames.pop() {
self.push_block(MarkdownBlock::Quote(blocks));
}
}
TagEnd::CodeBlock => {
if let Some((language, mut code)) = self.code.take() {
if code.ends_with('\n') {
code.pop();
}
self.push_block(MarkdownBlock::Code { language, code });
}
}
TagEnd::HtmlBlock => {
if let Some(html) = self.html.take() {
let plain = strip_tags(&html);
let plain = plain.trim();
if !plain.is_empty() {
let mut inline = Inline::default();
inline.text(plain);
self.push_block(MarkdownBlock::Paragraph(inline.rich));
}
}
}
TagEnd::Item => {
self.flush();
if let Some(Frame::Item(item)) = self.frames.pop()
&& let Some(Frame::List { items, .. }) = self.frames.last_mut()
{
items.push(item);
}
}
TagEnd::List(_) => {
self.flush();
if let Some(Frame::List { start, items }) = self.frames.pop() {
self.push_block(MarkdownBlock::List { start, items });
}
}
TagEnd::TableCell => {
self.in_cell = false;
let mut rich = self.inline.take().unwrap_or_default().rich;
trim_rich(&mut rich);
if let Some(Frame::Table { row, .. }) = self.frames.last_mut() {
row.push(rich);
}
}
TagEnd::TableHead => {
if let Some(Frame::Table { head, row, .. }) = self.frames.last_mut() {
*head = std::mem::take(row);
}
}
TagEnd::TableRow => {
if let Some(Frame::Table { rows, row, .. }) = self.frames.last_mut() {
rows.push(std::mem::take(row));
}
}
TagEnd::Table => {
if let Some(Frame::Table {
align, head, rows, ..
}) = self.frames.pop()
{
self.push_block(MarkdownBlock::Table { align, head, rows });
}
}
TagEnd::Emphasis => self.inline().italic = self.inline().italic.saturating_sub(1),
TagEnd::Strong => self.inline().bold = self.inline().bold.saturating_sub(1),
TagEnd::Strikethrough => self.inline().strike = self.inline().strike.saturating_sub(1),
TagEnd::Link => {
let inline = self.inline();
if let Some((start, url)) = inline.links.pop() {
let end = inline.rich.text.len();
if end > start {
inline.rich.links.push((start..end, url));
}
}
}
TagEnd::Image => {
if let Some(image) = self.image.take() {
if self.in_cell || self.heading.is_some() {
let alt = image.alt.clone();
self.inline().text(&alt);
} else {
self.inline().images.push(image);
}
}
}
_ => {}
}
}
fn event(&mut self, event: Event) {
match event {
Event::Start(tag) => self.start(tag),
Event::End(tag) => self.end(tag),
Event::Text(text) => {
if let Some((_, code)) = &mut self.code {
code.push_str(&text);
} else if let Some(image) = &mut self.image {
image.alt.push_str(&text);
} else {
self.inline().text(&text);
}
}
Event::Code(code) => {
if let Some(image) = &mut self.image {
image.alt.push_str(&code);
} else {
let inline = self.inline();
let style = inline.style(true);
inline.push(&code, style);
}
}
Event::Html(html) => {
if let Some(buffer) = &mut self.html {
buffer.push_str(&html);
}
}
Event::InlineHtml(html) => {
let tag = html.trim().to_ascii_lowercase();
if matches!(tag.as_str(), "<br>" | "<br/>" | "<br />") {
let inline = self.inline();
let style = inline.style(false);
inline.push("\n", style);
}
}
Event::SoftBreak => {
if self.image.is_none() {
let inline = self.inline();
let style = inline.style(false);
inline.push(" ", style);
}
}
Event::HardBreak => {
let inline = self.inline();
let style = inline.style(false);
inline.push("\n", style);
}
Event::Rule => {
self.flush();
self.push_block(MarkdownBlock::Rule);
}
Event::TaskListMarker(done) => {
if let Some(Frame::Item(item)) = self
.frames
.iter_mut()
.rev()
.find(|f| matches!(f, Frame::Item(_)))
{
item.task = Some(done);
}
}
_ => {}
}
}
}
fn trim_rich(rich: &mut RichText) {
let start = rich.text.len() - rich.text.trim_start().len();
let end = rich.text.trim_end().len();
if start == 0 && end == rich.text.len() {
return;
}
let end = end.max(start);
let clip =
|r: &Range<usize>| r.start.clamp(start, end) - start..r.end.clamp(start, end) - start;
rich.text = rich.text[start..end].to_string();
rich.spans = rich
.spans
.iter()
.map(|(r, s)| (clip(r), *s))
.filter(|(r, _)| !r.is_empty())
.collect();
rich.links = rich
.links
.iter()
.map(|(r, u)| (clip(r), u.clone()))
.filter(|(r, _)| !r.is_empty())
.collect();
}
fn strip_tags(html: &str) -> String {
let mut out = String::with_capacity(html.len());
let mut in_tag = false;
for c in html.chars() {
match c {
'<' => in_tag = true,
'>' if in_tag => in_tag = false,
_ if !in_tag => out.push(c),
_ => {}
}
}
out
}
fn find_urls(text: &str) -> Vec<Range<usize>> {
let mut out = Vec::new();
let mut from = 0;
while let Some(found) = text[from..].find("http") {
let start = from + found;
let rest = &text[start..];
let scheme = if rest.starts_with("https://") {
8
} else if rest.starts_with("http://") {
7
} else {
from = start + 4;
continue;
};
let boundary = text[..start]
.chars()
.next_back()
.is_none_or(|c| !c.is_alphanumeric());
let len = rest
.find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"' | '`'))
.unwrap_or(rest.len());
let mut url = &rest[..len];
loop {
let trimmed = url.trim_end_matches(['.', ',', ';', ':', '!', '?', '\'', '*', '_']);
let trimmed = if trimmed.ends_with(')')
&& trimmed.matches(')').count() > trimmed.matches('(').count()
{
&trimmed[..trimmed.len() - 1]
} else {
trimmed
};
if trimmed.len() == url.len() {
break;
}
url = trimmed;
}
if boundary && url.len() > scheme {
out.push(start..start + url.len());
}
from = start + len.max(1);
}
out
}
pub fn looks_like_path(text: &str) -> bool {
let (path, _) = split_path_line(text.trim());
let path = match path.as_bytes() {
[drive, b':', b'\\' | b'/', ..] if drive.is_ascii_alphabetic() => &path[2..],
_ => path,
};
let Some((stem, ext)) = path.rsplit_once('.') else {
return false;
};
!stem.is_empty()
&& stem
.chars()
.all(|c| c.is_ascii_alphanumeric() || "_.-/\\@~".contains(c))
&& (1..=8).contains(&ext.len())
&& ext.chars().all(|c| c.is_ascii_alphanumeric())
&& ext.chars().any(|c| c.is_ascii_alphabetic())
}
pub fn split_path_line(text: &str) -> (&str, Option<(u32, Option<u32>)>) {
if let Some((path, lines)) = text.rsplit_once(':') {
let (start, end) = match lines.split_once('-') {
Some((a, b)) => (a, Some(b)),
None => (lines, None),
};
if let Ok(start) = start.parse::<u32>() {
match end.map(str::parse::<u32>) {
None => return (path, Some((start, None))),
Some(Ok(end)) => return (path, Some((start, Some(end)))),
Some(Err(_)) => {}
}
}
}
(text, None)
}
pub fn parse_markdown(text: &str) -> Vec<MarkdownBlock> {
let options = Options::ENABLE_TABLES
| Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_TASKLISTS
| Options::ENABLE_GFM;
let mut builder = Builder {
frames: vec![Frame::Blocks(Vec::new())],
inline: None,
heading: None,
code: None,
html: None,
image: None,
in_cell: false,
};
for event in Parser::new_ext(text, options) {
builder.event(event);
}
builder.flush();
while builder.frames.len() > 1 {
let end = match builder.frames.last() {
Some(Frame::Quote(_)) => TagEnd::BlockQuote(None),
Some(Frame::List { start, .. }) => TagEnd::List(start.is_some()),
Some(Frame::Item(_)) => TagEnd::Item,
Some(Frame::Table { .. }) => TagEnd::Table,
_ => break,
};
builder.end(end);
}
match builder.frames.pop() {
Some(Frame::Blocks(blocks)) => blocks,
_ => Vec::new(),
}
}
thread_local! {
static PARSED: RefCell<Lru<Rc<Vec<MarkdownBlock>>>> = const { RefCell::new(Lru::new(4096)) };
}
pub fn parse_markdown_cached(text: &str) -> Rc<Vec<MarkdownBlock>> {
let key = content_key(&[text]);
PARSED.with(|c| {
c.borrow_mut()
.get_or_insert_with(key, || Rc::new(parse_markdown(text)))
})
}
fn fence_of(line: &str) -> Option<(char, usize)> {
let t = line.trim_start();
let c = t.chars().next().filter(|c| matches!(c, '`' | '~'))?;
let n = t.chars().take_while(|x| *x == c).count();
(n >= 3).then_some((c, n))
}
fn continues_block(line: &str) -> bool {
let t = line.trim_start();
if t.len() != line.len() || t.starts_with('>') {
return true;
}
let digits = t.chars().take_while(char::is_ascii_digit).count();
matches!(t.as_bytes(), [b'-' | b'*' | b'+', b' ', ..])
|| (digits > 0 && matches!(t.as_bytes().get(digits..), Some([b'.' | b')', b' ', ..])))
}
fn stream_split(text: &str) -> usize {
let mut starts: Vec<usize> = Vec::new();
let mut fence: Option<(char, usize)> = None;
let mut blank_before = false;
let mut in_list = false;
let mut at = 0;
for line in text.split_inclusive('\n') {
let body = line.trim_end_matches(['\n', '\r']);
if let Some((c, n)) = fence {
if fence_of(body).is_some_and(|(c2, n2)| c2 == c && n2 >= n)
&& body.trim().chars().all(|x| x == c)
{
fence = None;
}
} else if body.trim().is_empty() {
blank_before = true;
at += line.len();
continue;
} else {
let continues = continues_block(body);
if blank_before {
if !continues || !in_list {
starts.push(at);
in_list = continues;
}
} else if at == 0 {
in_list = continues;
}
fence = fence_of(body);
}
blank_before = false;
at += line.len();
}
starts.last().copied().unwrap_or(0)
}
fn fence_open(text: &str) -> bool {
text.lines().filter(|l| fence_of(l).is_some()).count() % 2 == 1
}
fn stream_tail(tail: &str) -> String {
if fence_open(tail) {
return tail.to_string();
}
let fences = tail.lines().filter(|l| fence_of(l).is_some()).count();
let mut region_at = 0;
if fences > 0 {
let mut at = 0;
for line in tail.split_inclusive('\n') {
at += line.len();
if fence_of(line).is_some() {
region_at = at;
}
}
}
let (head, region) = tail.split_at(region_at);
let mut region = region.to_string();
let last_start = region.trim_end().rfind('\n').map_or(0, |i| i + 1);
let last = region[last_start..].trim();
let digits = last.chars().take_while(char::is_ascii_digit).count();
if matches!(last, "-" | "*" | "+" | ">")
|| (!last.is_empty() && last.chars().all(|c| c == '#'))
|| (digits > 0 && matches!(&last[digits..], "." | ")"))
{
region.truncate(last_start);
}
format!("{head}{}", close_inline(®ion))
}
fn close_inline(text: &str) -> String {
let mut out = text.trim_end_matches([' ', '\t']).to_string();
if let Some(i) = out.rfind("](")
&& !out[i..].contains(')')
&& let Some(open) = out[..i].rfind('[')
{
let bang = open > 0 && out.as_bytes()[open - 1] == b'!';
let label = out[open + 1..i].to_string();
out.truncate(open - usize::from(bang));
out.push_str(&label);
} else if let Some(open) = out.rfind('[')
&& !out[open..].contains(']')
{
out.remove(open);
}
let bytes = out.as_bytes();
let mut code: Option<usize> = None;
let mut open: Vec<(&'static str, usize)> = Vec::new();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'\\' => i += 1,
b'`' => code = if code.is_some() { None } else { Some(i) },
_ if code.is_some() => {}
b'*' | b'~' if bytes.get(i + 1) == Some(&bytes[i]) => {
let mark = if bytes[i] == b'*' { "**" } else { "~~" };
match open.iter().rposition(|(m, _)| *m == mark) {
Some(at) => open.truncate(at),
None => open.push((mark, i)),
}
i += 1;
}
_ => {}
}
i += 1;
}
if let Some(at) = code.filter(|at| at + 1 == out.len()) {
out.truncate(at);
out.truncate(out.trim_end().len());
} else if code.is_some() {
out.push('`');
}
while let Some((mark, at)) = open.pop() {
if at + 2 == out.len() {
out.truncate(at);
out.truncate(out.trim_end().len());
} else {
out.truncate(out.trim_end().len());
out.push_str(mark);
}
}
out
}
type LinkHandler = Rc<dyn Fn(&str, &mut Window, &mut App)>;
type ImageRenderer = Rc<dyn Fn(&MarkdownImage, &mut Window, &mut App) -> AnyElement>;
#[derive(IntoElement)]
pub struct Markdown {
id: ElementId,
text: SharedString,
size: Pixels,
on_link: Option<LinkHandler>,
on_path: Option<LinkHandler>,
on_image: Option<ImageRenderer>,
#[cfg(feature = "mermaid")]
on_diagram: Option<super::mermaid::DiagramHandler>,
streaming: bool,
fade_tail: Vec<(usize, f32)>,
}
impl Markdown {
pub fn new(id: impl Into<ElementId>, text: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
text: text.into(),
size: text::BODY,
on_link: None,
on_path: None,
on_image: None,
#[cfg(feature = "mermaid")]
on_diagram: None,
streaming: false,
fade_tail: Vec::new(),
}
}
#[cfg(feature = "mermaid")]
pub fn on_diagram(
mut self,
f: impl Fn(&super::mermaid::MermaidDiagram, &mut Window, &mut App) + 'static,
) -> Self {
self.on_diagram = Some(Rc::new(f));
self
}
pub fn text_size(mut self, size: Pixels) -> Self {
self.size = size;
self
}
pub fn streaming(mut self, streaming: bool) -> Self {
self.streaming = streaming;
self
}
pub fn fade_tail(mut self, chunks: Vec<(usize, f32)>) -> Self {
self.fade_tail = chunks;
self
}
pub fn on_link(mut self, f: impl Fn(&str, &mut Window, &mut App) + 'static) -> Self {
self.on_link = Some(Rc::new(f));
self
}
pub fn on_path(mut self, f: impl Fn(&str, &mut Window, &mut App) + 'static) -> Self {
self.on_path = Some(Rc::new(f));
self
}
pub fn on_image(
mut self,
f: impl Fn(&MarkdownImage, &mut Window, &mut App) -> AnyElement + 'static,
) -> Self {
self.on_image = Some(Rc::new(f));
self
}
}
enum Target {
Link(String),
Path(String),
}
struct Render<'a> {
id: &'a ElementId,
counts: Vec<(&'static str, usize)>,
size: f32,
s: Scheme,
on_link: Option<LinkHandler>,
on_path: Option<LinkHandler>,
on_image: Option<ImageRenderer>,
#[cfg(feature = "mermaid")]
on_diagram: Option<super::mermaid::DiagramHandler>,
group: Selection,
diagrams: bool,
whole: SharedString,
joint: Option<String>,
fade: Vec<(usize, f32)>,
}
impl Render<'_> {
fn next_id(&mut self, part: &'static str) -> ElementId {
let n = match self.counts.iter_mut().find(|(p, _)| *p == part) {
Some((_, n)) => {
*n += 1;
*n
}
None => {
self.counts.push((part, 0));
0
}
};
ElementId::NamedChild(Box::new(self.id.clone()), format!("{part}{n}").into())
}
fn rich(&mut self, rich: &RichText, weight: FontWeight) -> AnyElement {
let s = self.s;
let runs: Vec<TextRun> = rich
.spans
.iter()
.map(|(range, style)| {
let color = if style.link { s.primary } else { s.on_surface };
TextRun {
len: range.len(),
font: Font {
family: if style.code {
MONO_FONT_FAMILY.into()
} else {
font_family().into()
},
features: FontFeatures::default(),
fallbacks: None,
weight: if style.bold {
FontWeight(weight.0.max(FontWeight::SEMIBOLD.0))
} else {
weight
},
style: if style.italic {
FontStyle::Italic
} else {
FontStyle::Normal
},
},
color,
background_color: style.code.then_some(s.surface_container_high),
underline: None,
strikethrough: style.strike.then_some(StrikethroughStyle {
thickness: px(1.),
color: Some(color),
}),
}
})
.collect();
let runs = if self.fade.is_empty() {
runs
} else {
fade_runs(runs, &rich.text, &std::mem::take(&mut self.fade))
};
let styled = StyledText::new(rich.text.clone()).with_runs(runs);
let layout = styled.layout().clone();
let joint: SharedString = self.joint.take().unwrap_or_else(|| "\n\n".into()).into();
let select = |inner: AnyElement, this: &Self| {
selectable_block(
&this.group,
layout,
rich.text.clone().into(),
joint,
Some(this.whole.clone()),
inner,
alpha(s.primary, 0.3),
)
};
let mut targets: Vec<(Range<usize>, Target)> = Vec::new();
if self.on_link.is_some() {
targets.extend(
rich.links
.iter()
.map(|(r, url)| (r.clone(), Target::Link(url.clone()))),
);
}
if self.on_path.is_some() {
targets.extend(rich.code_ranges().filter_map(|r| {
let text = &rich.text[r.clone()];
looks_like_path(text).then(|| (r.clone(), Target::Path(text.trim().to_string())))
}));
}
if targets.is_empty() {
return select(styled.into_any_element(), self);
}
targets.sort_by_key(|(r, _)| r.start);
let ranges = targets.iter().map(|(r, _)| r.clone()).collect();
let (on_link, on_path) = (self.on_link.clone(), self.on_path.clone());
let text = InteractiveText::new(self.next_id("text"), styled)
.on_click(ranges, move |ix, window, cx| match &targets[ix].1 {
Target::Link(url) => {
if let Some(f) = &on_link {
f(url, window, cx)
}
}
Target::Path(path) => {
if let Some(f) = &on_path {
f(path, window, cx)
}
}
})
.into_any_element();
select(text, self)
}
fn lead(&mut self, mark: &str) {
let base = self.joint.take().unwrap_or_else(|| "\n\n".into());
self.joint = Some(base + mark);
}
fn blocks(
&mut self,
blocks: &[MarkdownBlock],
depth: usize,
window: &mut Window,
cx: &mut App,
) -> Vec<AnyElement> {
blocks
.iter()
.enumerate()
.map(|(i, block)| self.block(block, i == 0, depth, window, cx))
.collect()
}
fn block(
&mut self,
block: &MarkdownBlock,
first: bool,
depth: usize,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let s = self.s;
let size = self.size;
match block {
MarkdownBlock::Paragraph(rich) => div()
.child(self.rich(rich, FontWeight::NORMAL))
.into_any_element(),
MarkdownBlock::Heading { level, text } => {
let scale = match level {
1 => 1.3,
2 => 1.18,
3 => 1.06,
_ => 1.,
};
let muted = *level >= 4;
self.lead(&format!("{} ", "#".repeat(*level as usize)));
let rich = self.rich(text, FontWeight::SEMIBOLD);
div()
.when(!first, |d| d.pt(px(size * 0.5)))
.text_size(px(size * scale))
.line_height(relative(1.3))
.when(muted, |d| d.text_color(s.on_surface_variant))
.child(rich)
.into_any_element()
}
MarkdownBlock::Code { language, code } => {
#[cfg(feature = "mermaid")]
if self.diagrams
&& language.trim().eq_ignore_ascii_case("mermaid")
&& let Some(diagram) = super::mermaid::diagram(
self.next_id("diagram"),
code,
&s,
self.on_diagram.clone(),
window,
cx,
)
{
self.joint = None;
return diagram;
}
let joint = self.joint.take().unwrap_or_else(|| "\n\n".into());
CodeBlock::new(self.next_id("code"), code.clone())
.language(language.clone())
.selection(self.group.clone(), joint.into(), Some(self.whole.clone()))
.into_any_element()
}
MarkdownBlock::Quote(blocks) => {
let children = self.blocks(blocks, depth, window, cx);
div()
.flex()
.gap(px(size * 0.9 - 3.))
.text_color(s.on_surface_variant)
.child(
div()
.flex_none()
.w(px(3.))
.rounded(px(1.5))
.bg(s.outline_variant),
)
.child(
div()
.flex()
.flex_col()
.gap(px(size * 0.75))
.flex_1()
.min_w_0()
.children(children),
)
.into_any_element()
}
MarkdownBlock::List { start, items } => {
let mut list = div().flex().flex_col().gap(px(size * 0.2));
for (i, item) in items.iter().enumerate() {
let marker = match (item.task, start) {
(Some(done), _) => task_box(done, size, &s).into_any_element(),
(None, Some(n)) => div()
.text_color(s.on_surface_variant)
.child(format!("{}.", n + i as u64))
.into_any_element(),
(None, None) => div()
.text_color(s.on_surface_variant)
.child(["•", "◦", "▪"][depth % 3])
.into_any_element(),
};
let mark = match (item.task, start) {
(Some(true), _) => "- [x] ".to_string(),
(Some(false), _) => "- [ ] ".to_string(),
(None, Some(n)) => format!("{}. ", n + i as u64),
(None, None) => "- ".to_string(),
};
self.joint = Some(format!("\n{}{mark}", " ".repeat(depth)));
let children = self.blocks(&item.blocks, depth + 1, window, cx);
list = list.child(
div()
.flex()
.child(
div()
.flex_none()
.w(px(size * 1.5))
.pr(px(size * 0.4))
.flex()
.justify_end()
.child(marker),
)
.child(
div()
.flex()
.flex_col()
.gap(px(size * 0.2))
.flex_1()
.min_w_0()
.when(item.task == Some(true), |d| {
d.text_color(s.on_surface_variant)
})
.children(children),
),
);
}
list.into_any_element()
}
MarkdownBlock::Table { align, head, rows } => {
self.table(align, head, rows, window, cx)
}
MarkdownBlock::Rule => div()
.my(px(size * 0.35))
.h(px(1.))
.bg(s.outline_variant)
.into_any_element(),
MarkdownBlock::Image(image) => match self.on_image.clone() {
Some(f) => f(image, window, cx),
None => self.image_placeholder(image),
},
}
}
fn table(
&mut self,
align: &[ColumnAlign],
head: &[RichText],
rows: &[Vec<RichText>],
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let s = self.s;
let columns = head.len().max(rows.iter().map(Vec::len).max().unwrap_or(0));
if columns == 0 {
return div().into_any_element();
}
let mut weights = vec![3f32; columns];
for row in std::iter::once(head).chain(rows.iter().map(Vec::as_slice)) {
for (c, cell) in row.iter().enumerate() {
weights[c] = weights[c].max(cell.text.chars().count().min(40) as f32);
}
}
let total: f32 = weights.iter().sum();
let id = self.next_id("table");
let measured = window.use_keyed_state(key(&id, "width"), cx, |_, _| px(0.));
let min_width = px(columns as f32 * 72.);
let last = *measured.read(cx);
let width = (last > px(0.)).then(|| last.max(min_width));
let inner = width.map(|w| w - px(2.));
let row_el = |cells: &[RichText], header: bool, last: bool, this: &mut Self| {
let mut row = div()
.flex()
.w_full()
.when(!last, |d| d.border_b_1().border_color(s.outline_variant));
if header {
row = row.bg(s.surface_container).rounded_tl(px(7.)).rounded_tr(px(7.));
if last {
row = row.rounded_bl(px(7.)).rounded_br(px(7.));
}
}
for (c, weight) in weights.iter().enumerate() {
let content = cells.get(c).map(|cell| {
if c > 0 {
this.joint = Some("\t".into());
} else if !header {
this.joint = Some("\n".into());
}
this.rich(
cell,
if header {
FontWeight::SEMIBOLD
} else {
FontWeight::NORMAL
},
)
});
let cell = div()
.map(|d| match inner {
Some(inner) => d.flex_none().w(inner * (weight / total)),
None => d.w(relative(weight / total)),
})
.min_w(px(48.))
.px(px(10.))
.py(px(4.))
.when(c + 1 < columns, |d| {
d.border_r_1().border_color(s.outline_variant)
})
.map(|d| match align.get(c).copied().unwrap_or_default() {
ColumnAlign::Center => d.text_center(),
ColumnAlign::Right => d.text_right(),
_ => d,
})
.children(content);
row = row.child(cell);
}
row
};
let mut table = div()
.flex()
.flex_col()
.map(|d| match width {
Some(width) => d.flex_none().w(width),
None => d.w_full(),
})
.min_w(min_width)
.border_1()
.border_color(s.outline_variant)
.rounded(px(8.))
.overflow_hidden()
.text_size(px(self.size * 0.95));
if !head.is_empty() {
table = table.child(row_el(head, true, rows.is_empty(), self));
}
for (i, row) in rows.iter().enumerate() {
table = table.child(row_el(row, false, i + 1 == rows.len(), self));
}
let measure = canvas(
move |bounds, window, cx| {
let changed = measured.update(cx, |w, _| {
let changed = (*w - bounds.size.width).abs() > px(0.5);
if changed {
*w = bounds.size.width;
}
changed
});
if changed {
window.refresh();
}
},
|_, _, _, _| {},
)
.absolute()
.top_0()
.left_0()
.size_full();
div()
.id(id)
.relative()
.overflow_x_scroll()
.child(table)
.child(measure)
.into_any_element()
}
fn image_placeholder(&mut self, image: &MarkdownImage) -> AnyElement {
let s = self.s;
let label = if !image.alt.is_empty() {
image.alt.clone()
} else if !image.title.is_empty() {
image.title.clone()
} else {
image.url.clone()
};
let url = image.url.clone();
let on_link = self.on_link.clone();
div()
.id(self.next_id("image"))
.flex()
.items_center()
.gap(px(8.))
.max_w_full()
.px(px(12.))
.py(px(8.))
.rounded(px(12.))
.bg(s.surface_container_high)
.text_color(s.on_surface_variant)
.child(Icon::new("file").size(px(16.)).color(s.on_surface_variant))
.child(
div()
.min_w_0()
.overflow_hidden()
.whitespace_nowrap()
.text_ellipsis()
.child(label),
)
.when_some(on_link, |d, f| {
d.cursor_pointer()
.hover(|d| d.bg(s.surface_container_highest))
.on_click(move |_, window, cx| f(&url, window, cx))
})
.into_any_element()
}
}
fn task_box(done: bool, size: f32, s: &Scheme) -> impl IntoElement {
let side = (size * 1.05).round();
let color: Hsla = if done { s.primary } else { s.outline };
div()
.mt(px((size * 1.6 - side) / 2.))
.size(px(side))
.flex()
.items_center()
.justify_center()
.rounded(px(4.))
.when(done, |d| d.bg(color))
.when(!done, |d| d.border_2().border_color(color))
.when(done, |d| {
d.child(Icon::new("check").size(px(side - 3.)).color(s.on_primary))
})
}
fn fade_runs(runs: Vec<TextRun>, text: &str, fades: &[(usize, f32)]) -> Vec<TextRun> {
let len = text.len();
let mut cuts: Vec<(usize, f32)> = fades
.iter()
.filter(|(_, opacity)| *opacity < 1.)
.map(|&(back, opacity)| {
let mut at = len.saturating_sub(back);
while at < len && !text.is_char_boundary(at) {
at += 1;
}
(at, opacity.clamp(0., 1.))
})
.filter(|(at, _)| *at < len)
.collect();
if cuts.is_empty() {
return runs;
}
cuts.sort_by_key(|(at, _)| *at);
let opacity_at = |byte: usize| {
cuts.iter()
.filter(|(at, _)| *at <= byte)
.map(|(_, o)| *o)
.fold(1f32, f32::min)
};
let mut out = Vec::with_capacity(runs.len() + cuts.len());
let mut start = 0;
for run in runs {
let end = start + run.len;
let mut from = start;
let edges = cuts
.iter()
.map(|(at, _)| *at)
.filter(|at| *at > start && *at < end)
.chain(std::iter::once(end));
for to in edges {
if to <= from {
continue;
}
let mut piece = run.clone();
piece.len = to - from;
let opacity = opacity_at(from);
if opacity < 1. {
piece.color = piece.color.opacity(opacity);
if let Some(bg) = piece.background_color.as_mut() {
*bg = bg.opacity(opacity);
}
}
out.push(piece);
from = to;
}
start = end;
}
out
}
impl RenderOnce for Markdown {
fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let s = *Theme::of(cx);
let mut tail_fence_open = false;
let (blocks, tail) = if self.streaming {
let at = stream_split(&self.text);
tail_fence_open = fence_open(&self.text[at..]);
let tail =
(at < self.text.len()).then(|| parse_markdown(&stream_tail(&self.text[at..])));
(parse_markdown_cached(&self.text[..at]), tail)
} else {
(parse_markdown_cached(&self.text), None)
};
let size = f32::from(self.size);
let (group, own) = group_for(self.id.clone(), window, cx);
let mut r = Render {
id: &self.id,
counts: Vec::new(),
size,
s,
on_link: self.on_link,
on_path: self.on_path,
on_image: self.on_image,
#[cfg(feature = "mermaid")]
on_diagram: self.on_diagram,
group: group.clone(),
diagrams: true,
whole: self.text.clone(),
joint: None,
fade: Vec::new(),
};
let mut children = r.blocks(&blocks, 0, window, cx);
if let Some(tail) = &tail {
let first = blocks.is_empty();
for (i, block) in tail.iter().enumerate() {
r.diagrams = !(tail_fence_open && i + 1 == tail.len());
let fades = i + 1 == tail.len()
&& matches!(block, MarkdownBlock::Paragraph(_) | MarkdownBlock::Heading { .. });
if fades && !self.fade_tail.is_empty() {
r.fade = std::mem::take(&mut self.fade_tail);
}
children.push(r.block(block, first && i == 0, 0, window, cx));
r.fade.clear();
}
}
let root = if own {
selection_root(&group.state, div(), cx)
} else {
div()
};
root.flex()
.flex_col()
.gap(px(size * 0.75))
.min_w_0()
.font_family(font_family())
.text_size(self.size)
.line_height(relative(1.6))
.text_color(s.on_surface)
.children(children)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn para(blocks: &[MarkdownBlock], i: usize) -> &RichText {
match &blocks[i] {
MarkdownBlock::Paragraph(rich) => rich,
other => panic!("not a paragraph: {other:?}"),
}
}
fn styled(rich: &RichText, f: impl Fn(&InlineStyle) -> bool) -> Vec<&str> {
rich.spans
.iter()
.filter(|(_, s)| f(s))
.map(|(r, _)| &rich.text[r.clone()])
.collect()
}
fn run(len: usize) -> TextRun {
TextRun {
len,
font: gpui::font("Inter"),
color: gpui::black(),
background_color: None,
underline: None,
strikethrough: None,
}
}
#[test]
fn fade_tail_splits_runs_at_the_chunks() {
let text = "hello brave world";
let out = fade_runs(vec![run(text.len())], text, &[(12, 0.6), (6, 0.2)]);
let lens: Vec<usize> = out.iter().map(|r| r.len).collect();
assert_eq!(lens, vec![5, 6, 6]);
assert_eq!(out[0].color.a, 1.);
assert!((out[1].color.a - 0.6).abs() < 1e-6);
assert!((out[2].color.a - 0.2).abs() < 1e-6);
assert_eq!(fade_runs(vec![run(text.len())], text, &[(6, 1.)]).len(), 1);
let accented = "añá";
let out = fade_runs(vec![run(accented.len())], accented, &[(3, 0.5)]);
let lens: Vec<usize> = out.iter().map(|r| r.len).collect();
assert_eq!(lens, vec![3, 2]);
}
#[test]
fn streaming_splits_at_the_last_finished_block() {
let text = "One.\n\nTwo **bo";
assert_eq!(&text[stream_split(text)..], "Two **bo");
let list = "Intro\n\n- a\n\n- b\n\n- c";
assert_eq!(&list[stream_split(list)..], "- a\n\n- b\n\n- c");
let code = "Intro\n\n```rust\nlet a;\n\nlet b;";
assert_eq!(&code[stream_split(code)..], "```rust\nlet a;\n\nlet b;");
assert!(fence_open(&code[stream_split(code)..]));
assert_eq!(stream_split("only one block"), 0);
}
#[test]
fn streaming_tail_closes_or_hides_unfinished_marks() {
assert_eq!(stream_tail("a **bol"), "a **bol**");
assert_eq!(stream_tail("a **bold** and **"), "a **bold** and");
assert_eq!(stream_tail("use `cod"), "use `cod`");
assert_eq!(stream_tail("use `"), "use");
assert_eq!(stream_tail("see [the do"), "see the do");
assert_eq!(stream_tail("see [the doc](http://exa"), "see the doc");
assert_eq!(
stream_tail("see [the doc](http://x.y) ok"),
"see [the doc](http://x.y) ok"
);
assert_eq!(stream_tail("text\n-"), "text\n");
assert_eq!(stream_tail("```rs\nlet a = **;"), "```rs\nlet a = **;");
let done = "Hello **world** and `code`";
assert_eq!(
parse_markdown(&stream_tail(&done[..done.len() - 1])),
parse_markdown(done)
);
assert_eq!(
parse_markdown(&stream_tail("Hello **wor")),
parse_markdown("Hello **wor**")
);
}
#[test]
fn paragraphs_and_inline_styles() {
let blocks = parse_markdown(
"Some **bold**, *italic*, ~~gone~~ and `code`.\nSame paragraph.\n\nSecond.",
);
assert_eq!(blocks.len(), 2);
let p = para(&blocks, 0);
assert_eq!(p.text, "Some bold, italic, gone and code. Same paragraph.");
assert_eq!(styled(p, |s| s.bold), ["bold"]);
assert_eq!(styled(p, |s| s.italic), ["italic"]);
assert_eq!(styled(p, |s| s.strike), ["gone"]);
assert_eq!(styled(p, |s| s.code), ["code"]);
assert_eq!(
p.spans.iter().map(|(r, _)| r.len()).sum::<usize>(),
p.text.len()
);
assert_eq!(para(&blocks, 1).text, "Second.");
}
#[test]
fn headings_keep_their_level() {
let blocks = parse_markdown("# One\n### Three *x*\n###### Six");
let levels: Vec<(u8, &str)> = blocks
.iter()
.map(|b| match b {
MarkdownBlock::Heading { level, text } => (*level, text.as_str()),
_ => panic!(),
})
.collect();
assert_eq!(levels, [(1, "One"), (3, "Three x"), (6, "Six")]);
}
#[test]
fn nested_numbered_and_task_lists() {
let blocks = parse_markdown(
"3. three\n4. four\n - nested\n - deeper\n\n- [x] done\n- [ ] todo",
);
let MarkdownBlock::List { start, items } = &blocks[0] else {
panic!("{blocks:?}")
};
assert_eq!(*start, Some(3));
assert_eq!(items.len(), 2);
assert_eq!(para(&items[0].blocks, 0).text, "three");
let MarkdownBlock::List {
start: None,
items: nested,
} = &items[1].blocks[1]
else {
panic!("{:?}", items[1].blocks)
};
assert!(matches!(&nested[0].blocks[1], MarkdownBlock::List { .. }));
let MarkdownBlock::List { items: tasks, .. } = &blocks[1] else {
panic!()
};
assert_eq!(tasks[0].task, Some(true));
assert_eq!(tasks[1].task, Some(false));
assert_eq!(para(&tasks[1].blocks, 0).text, "todo");
}
#[test]
fn quotes_rules_and_code() {
let blocks =
parse_markdown("> quoted\n> > inner\n\n---\n\n```rust title=x\nfn x() {}\n```\n");
let MarkdownBlock::Quote(inner) = &blocks[0] else {
panic!()
};
assert_eq!(para(inner, 0).text, "quoted");
assert!(matches!(inner[1], MarkdownBlock::Quote(_)));
assert_eq!(blocks[1], MarkdownBlock::Rule);
assert_eq!(
blocks[2],
MarkdownBlock::Code {
language: "rust title=x".into(),
code: "fn x() {}".into()
}
);
}
#[test]
fn an_unclosed_fence_streams_as_code() {
let blocks = parse_markdown("Look:\n\n```ts\nconst a = 1;\nconst b");
assert_eq!(
blocks[1],
MarkdownBlock::Code {
language: "ts".into(),
code: "const a = 1;\nconst b".into()
}
);
}
#[test]
fn tables_with_alignment() {
let blocks = parse_markdown("| A | B |\n|:--|--:|\n| `x` | **2** |\n| y | 3 |");
let MarkdownBlock::Table { align, head, rows } = &blocks[0] else {
panic!("{blocks:?}")
};
assert_eq!(align, &[ColumnAlign::Left, ColumnAlign::Right]);
assert_eq!(
head.iter().map(RichText::as_str).collect::<Vec<_>>(),
["A", "B"]
);
assert_eq!(rows.len(), 2);
assert_eq!(styled(&rows[0][0], |s| s.code), ["x"]);
assert_eq!(styled(&rows[0][1], |s| s.bold), ["2"]);
}
#[test]
fn links_and_bare_urls() {
let blocks = parse_markdown(
"See [the docs](https://a.dev/x) or https://b.dev/y. (Also https://c.dev/(z)).",
);
let p = para(&blocks, 0);
let links: Vec<(&str, &str)> = p
.links
.iter()
.map(|(r, url)| (&p.text[r.clone()], url.as_str()))
.collect();
assert_eq!(
links,
[
("the docs", "https://a.dev/x"),
("https://b.dev/y", "https://b.dev/y"),
("https://c.dev/(z)", "https://c.dev/(z)"),
]
);
assert_eq!(
styled(p, |s| s.link),
["the docs", "https://b.dev/y", "https://c.dev/(z)"]
);
}
#[test]
fn images_become_blocks_after_their_text() {
let blocks = parse_markdown("Before  after\n\n");
assert_eq!(para(&blocks, 0).text, "Before after");
assert_eq!(
blocks[1],
MarkdownBlock::Image(MarkdownImage {
url: "cat.png".into(),
alt: "a cat".into(),
title: "Cat".into()
})
);
assert!(matches!(&blocks[2], MarkdownBlock::Image(i) if i.alt == "only"));
assert_eq!(blocks.len(), 3);
}
#[test]
fn hard_breaks_and_html() {
let blocks = parse_markdown("one \ntwo<br>three\n\n<div>\nraw <b>html</b>\n</div>");
assert_eq!(para(&blocks, 0).text, "one\ntwo\nthree");
assert_eq!(para(&blocks, 1).text, "raw html");
}
#[test]
fn path_detection() {
for yes in [
"src/x.ts",
"x.ts:42",
"a/b-c.rs:3-9",
"C:\\x\\y.rs",
"Cargo.toml",
"./m.mjs",
] {
assert!(looks_like_path(yes), "{yes}");
}
for no in ["hello", "1.5", "e.g.", "a b.rs", "x.toolongext", "fn()"] {
assert!(!looks_like_path(no), "{no}");
}
assert_eq!(split_path_line("x.ts:42"), ("x.ts", Some((42, None))));
assert_eq!(split_path_line("x.ts:3-9"), ("x.ts", Some((3, Some(9)))));
assert_eq!(split_path_line("x.ts"), ("x.ts", None));
}
#[test]
fn cached_parse_is_shared() {
let a = parse_markdown_cached("# same");
let b = parse_markdown_cached("# same");
assert!(Rc::ptr_eq(&a, &b));
}
}