Visual Studio Code, rebuilt in Rust
Rust
//! workbench/contrib/markdown markdownDocumentRenderer.ts `renderMarkdownDocument`: GitHub markdown as the
//! document HTML of the extension editor and the walkthroughs, with heading ids (markedGfmHeadingIdPlugin.ts) and
//! the sanitizer's link and media rules (domSanitize.ts `hookDomPurifyHrefAndSrcSanitizer`) and code blocks
//! highlighted as `MarkedHighlight` does. pulldown-cmark stands in for marked.
use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd, html};
use crate::languages::Languages;
use crate::theme::Theme;
/// `MarkdownDocumentSanitizerConfig`: the protocols links and images may use, `None` for any (`override: '*'`).
pub struct Sanitizer {
pub link_protocols: Option<&'static [&'static str]>,
pub media_protocols: &'static [&'static str],
pub allow_relative_media: bool,
}
impl Default for Sanitizer {
/// `defaultAllowedLinkProtocols` and the sanitizer's media default, both http and https.
fn default() -> Self {
Sanitizer { link_protocols: Some(&["http", "https"]), media_protocols: &["http", "https"], allow_relative_media: false }
}
}
/// Raw HTML that would act before or outside the webview's CSP (`<meta http-equiv="refresh">`, `<base>`, frames)
/// is shown as text, as DOMPurify removes it. `highlight` is `tokenizeToString` of a fenced block's code in the
/// language its info string names.
pub fn render_markdown_document(text: &str, sanitizer: &Sanitizer, highlight: impl Fn(&str, &str) -> String) -> String {
let options = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS | Options::ENABLE_GFM;
let mut events: Vec<Event> = Vec::new();
let mut parser = Parser::new_ext(text, options);
while let Some(event) = parser.next() {
match event {
Event::Html(raw) | Event::InlineHtml(raw) if is_unsafe_html(&raw) => events.push(Event::Text(raw)),
Event::Start(Tag::Image { dest_url, title, .. }) => {
// The alt text is the image's inline content, as text.
let mut alt = String::new();
for inner in parser.by_ref() {
match inner {
Event::End(TagEnd::Image) => break,
Event::Text(text) | Event::Code(text) => alt.push_str(&text),
_ => {}
}
}
let src = allowed(&dest_url, Some(sanitizer.media_protocols), sanitizer.allow_relative_media).then(|| format!(" src=\"{}\"", escape(&dest_url))).unwrap_or_default();
let title = if title.is_empty() { String::new() } else { format!(" title=\"{}\"", escape(&title)) };
events.push(Event::InlineHtml(CowStr::from(format!("<img{src} alt=\"{}\"{title}>", escape(&alt)))));
}
Event::Start(Tag::CodeBlock(kind)) => {
let mut code = String::new();
for inner in parser.by_ref() {
match inner {
Event::End(TagEnd::CodeBlock) => break,
Event::Text(text) => code.push_str(&text),
_ => {}
}
}
// marked's code token text has no final newline.
let code = code.strip_suffix('\n').unwrap_or(&code);
let (html, class) = match &kind {
CodeBlockKind::Indented => (escape_without_encoding(code), String::new()),
CodeBlockKind::Fenced(lang) => {
let class = if lang.is_empty() { String::new() } else { format!(" class=\"language-{}\"", escape_without_encoding(lang)) };
(highlight(code, lang), class)
}
};
let html = html.strip_suffix('\n').unwrap_or(&html);
events.push(Event::Html(CowStr::from(format!("<pre><code{class}>{html}\n</code></pre>"))));
}
Event::Start(Tag::Link { .. }) | Event::End(TagEnd::Link) => events.push(sanitize_link(event, sanitizer)),
Event::Start(Tag::Heading { level, .. }) => {
let start = events.len();
let mut raw = String::new();
for inner in parser.by_ref() {
match &inner {
Event::End(TagEnd::Heading(_)) => break,
Event::Text(text) | Event::Code(text) => raw.push_str(text),
_ => {}
}
events.push(sanitize_link(inner, sanitizer));
}
let level = level as usize;
events.insert(start, Event::Html(CowStr::from(format!("<h{level} id=\"{}\">", escape(&slugify(&raw))))));
events.push(Event::Html(CowStr::from(format!("</h{level}>\n"))));
}
other => events.push(other),
}
}
let mut out = String::new();
html::push_html(&mut out, events.into_iter());
out
}
/// A link keeps its `href` only with an allowed protocol or as a fragment; other events pass.
fn sanitize_link<'a>(event: Event<'a>, sanitizer: &Sanitizer) -> Event<'a> {
match event {
Event::Start(Tag::Link { dest_url, title, .. }) => {
let keep = dest_url.starts_with('#') || allowed(&dest_url, sanitizer.link_protocols, false);
let href = if keep { format!(" href=\"{}\"", escape(&dest_url)) } else { String::new() };
let title = if title.is_empty() { String::new() } else { format!(" title=\"{}\"", escape(&title)) };
Event::InlineHtml(CowStr::from(format!("<a{href}{title}>")))
}
Event::End(TagEnd::Link) => Event::InlineHtml(CowStr::Borrowed("</a>")),
other => other,
}
}
/// markedGfmHeadingIdPlugin.ts `slugify`: trimmed, lowercase, each whitespace a `-`.
pub(super) fn slugify(heading: &str) -> String {
heading.trim().to_lowercase().chars().map(|c| if c.is_whitespace() { '-' } else { c }).collect()
}
/// domSanitize.ts `validateLink`: a URL with an allowed scheme, or a relative path when allowed.
fn allowed(url: &str, protocols: Option<&[&str]>, allow_relative: bool) -> bool {
let Some(protocols) = protocols else { return true };
let scheme = url.split_once(':').map(|(scheme, _)| scheme).filter(|scheme| !scheme.is_empty() && scheme.chars().all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)));
match scheme {
Some(scheme) => protocols.iter().any(|protocol| protocol.eq_ignore_ascii_case(scheme)),
None => allow_relative,
}
}
fn is_unsafe_html(raw: &str) -> bool {
let lower = raw.to_ascii_lowercase();
["<meta", "<base", "<iframe", "<frame", "<object", "<embed", "<script", "<form", "<link"].iter().any(|tag| lower.contains(tag))
}
/// marked's `escape(html)` without `encode`: an existing entity keeps its `&`.
fn escape_without_encoding(text: &str) -> String {
let mut out = String::new();
for (index, c) in text.char_indices() {
match c {
'&' if is_entity(&text[index + 1..]) => out.push('&'),
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
c => out.push(c),
}
}
out
}
/// The rest after `&` starts an entity: `#\d{1,7};`, `#[Xx][a-fA-F0-9]{1,6};` or `\w+;`.
fn is_entity(rest: &str) -> bool {
let Some((name, _)) = rest.split_once(';') else { return false };
if let Some(hex) = name.strip_prefix("#x").or_else(|| name.strip_prefix("#X")) {
return (1..=6).contains(&hex.len()) && hex.chars().all(|c| c.is_ascii_hexdigit());
}
if let Some(decimal) = name.strip_prefix('#') {
return (1..=7).contains(&decimal.len()) && decimal.chars().all(|c| c.is_ascii_digit());
}
!name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
/// The `highlight` of markdownDocumentRenderer.ts: the language by its name, else by the info string's first word,
/// then `tokenizeToString` with its grammar; no language tokenizes as one default token.
pub(super) fn highlight_markdown_code(languages: &Languages, theme: &Theme, code: &str, lang: &str) -> String {
let first_word = lang.split(|c: char| c.is_whitespace() || c == ':' || c == ',').next().unwrap_or_default();
let first_word = first_word.char_indices().find(|&(index, c)| (c == '{' && index > 0) || first_word[index..].starts_with("?]")).map_or(first_word, |(index, _)| &first_word[..index]);
let language = languages.id_by_name(lang).or_else(|| languages.id_by_name(first_word));
let tokenization = crate::syntax::Tokenization::new(language.and_then(|language| languages.grammars.grammar(language)));
crate::editor::clipboard::tokenize_to_string(code, |lines, index| tokenization.html_tokens(theme, lines, index))
}
fn escape(text: &str) -> String {
text.replace('&', "&").replace('"', """).replace('<', "<").replace('>', ">")
}
#[cfg(test)]
mod tests {
use super::*;
// markdownDocumentRenderer.test.ts
#[test]
fn removes_relative_images_unless_allowed() {
assert_eq!(render_markdown_document("", &Sanitizer::default(), plain), "<p><img alt=\"alt\"></p>\n");
let relative = Sanitizer { allow_relative_media: true, ..Sanitizer::default() };
assert_eq!(render_markdown_document("", &relative, plain), "<p><img src=\"src/img.png\" alt=\"alt\"></p>\n");
}
#[test]
fn renders_github_markdown_with_heading_ids_and_safe_links() {
let render = |text| render_markdown_document(text, &Sanitizer::default(), plain);
assert_eq!(render("# Big Title\n\n| a |\n|---|\n| b |\n\n~~x~~"), "<h1 id=\"big-title\">Big Title</h1>\n<table><thead><tr><th>a</th></tr></thead><tbody>\n<tr><td>b</td></tr>\n</tbody></table>\n<p><del>x</del></p>\n");
assert_eq!(render("<meta http-equiv=\"refresh\" content=\"0;url=https://x\">\n\n<b>ok</b>"), "<meta http-equiv=\"refresh\" content=\"0;url=https://x\">\n<p><b>ok</b></p>\n");
assert_eq!(render("[a](https://x) [b](command:foo) [c](#top)"), "<p><a href=\"https://x\">a</a> <a>b</a> <a href=\"#top\">c</a></p>\n");
assert_eq!(render_markdown_document("[b](command:foo)", &Sanitizer { link_protocols: None, ..Sanitizer::default() }, plain), "<p><a href=\"command:foo\">b</a></p>\n");
}
fn plain(code: &str, _: &str) -> String {
code.to_owned()
}
/// `MarkedHighlight` with markdownDocumentRenderer.ts `highlight`: a fenced block's language by its name or its
/// info string's first word, tokenized into `mtk` spans; no language is one default token; indented code is escaped.
#[gpui::test]
fn fenced_code_blocks_are_tokenized_in_their_language(cx: &mut gpui::TestAppContext) {
let (workbench, cx, _, _) = crate::workbench::goto_symbol::tests::open(cx, "markdown-code-blocks", "text");
workbench.update(cx, |workbench, _| {
let typescript = exthost::scan::scan_extension(&workbench.app_root.join("extensions/typescript-basics"), true).unwrap();
workbench.languages = crate::languages::Languages::new(&[typescript]);
let render = |text| render_markdown_document(text, &Sanitizer::default(), |code, lang| highlight_markdown_code(&workbench.languages, &workbench.theme, code, lang));
let html = render("```TypeScript {1}\nlet a = 'x';\n```");
assert!(html.starts_with("<pre><code class=\"language-TypeScript {1}\"><div class=\"monaco-tokenized-source\"><span class=\"mtk"), "{html}");
let classes: std::collections::HashSet<&str> = html.split("<span class=\"").skip(1).map(|span| span.split('"').next().unwrap()).collect();
assert!(classes.len() > 2, "keyword, identifier and string colors: {html}");
assert_eq!(render("```\na <b>\n\tc\n```"), "<pre><code><div class=\"monaco-tokenized-source\"><span class=\"mtk1\">a <b></span><br/><span class=\"mtk1\">\tc</span></div>\n</code></pre>");
assert_eq!(render(" x & & <\n"), "<pre><code>x & & <\n</code></pre>");
});
}
}