A framed monospace code block with syntax highlighting, an optional filename header, line numbers and a copy button.
use gpui::{div, prelude::*, px};
use crate::ui::code_block::CodeBlock;
const CODE: &str = r#"#[derive(IntoElement)]
pub struct Greeting {
name: SharedString,
}
impl RenderOnce for Greeting {
fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
div().child(format!("Hello, {}!", self.name))
}
}"#;
pub fn code_block_demo() -> impl IntoElement {
div().w(px(620.0)).child(
CodeBlock::new("greeting", CODE)
.filename("src/greeting.rs")
.line_numbers(true),
)
}Installation
Copies src/ui/code_block.rs into your project, along with any components it depends on, and registers the module in src/ui/mod.rs.
Install the theme
Every component reads colors from
crate::theme. Follow the installation guide if you have not added it yet.Install the icons
This component draws icons from
crate::icons. Copy src/icons.rs into your project and declaremod icons;next tomod theme;.Copy the source
Paste the code below into
src/ui/code_block.rs.src/ui/code_block.rs use std::{ops::Range, time::Duration}; use gpui::{ div, hsla, prelude::*, px, svg, App, ClipboardItem, Context, ElementId, HighlightStyle, Hsla, Pixels, SharedString, StyledText, Task, TextRun, Window, }; use crate::theme::{ActiveTheme, Theme}; use crate::icons::{CHECK, COPY, FILE}; const MONO: &str = "Geist Mono"; /// Every row gets the same height so blank lines keep their place next to the line numbers. const LINE_HEIGHT: Pixels = px(20.0); const COPIED_FOR: Duration = Duration::from_secs(2); const TAB: &str = " "; /// The copy button's "copied" check is a few seconds of feedback the app has no reason to own, /// and it needs a timer to reset, so it lives here. #[derive(Default)] struct CopyState { copied: bool, reset: Option<Task<()>>, } impl CopyState { fn copied(&mut self, cx: &mut Context<Self>) { self.copied = true; cx.notify(); // Replacing the task drops, and so cancels, the reset from an earlier click. self.reset = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(COPIED_FOR).await; this.update(cx, |state, cx| { state.copied = false; cx.notify(); }) .ok(); })); } } /// How much room the block takes. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum CodeBlockSize { /// A bordered card with 13px code. #[default] Default, /// shadcn's `size="sm"`, for tool output inside a trace: a borderless muted panel with 12px /// code on 19.5px lines. Sm, } /// A framed block of monospace code with an optional filename header, line numbers and a copy /// button, syntax highlighted for its language. #[derive(IntoElement)] pub struct CodeBlock { id: ElementId, code: SharedString, filename: Option<SharedString>, language: Option<Language>, line_numbers: bool, copy_button: bool, size: CodeBlockSize, wrap: bool, } impl CodeBlock { pub fn new(id: impl Into<ElementId>, code: impl Into<SharedString>) -> Self { Self { id: id.into(), code: code.into(), filename: None, language: None, line_numbers: false, copy_button: true, size: CodeBlockSize::default(), wrap: false, } } pub fn filename(mut self, filename: impl Into<SharedString>) -> Self { self.filename = Some(filename.into()); self } /// The language to highlight. Without it, the language is picked from the filename's /// extension, and code with neither is shown as plain text. pub fn language(mut self, language: Language) -> Self { self.language = Some(language); self } pub fn line_numbers(mut self, line_numbers: bool) -> Self { self.line_numbers = line_numbers; self } pub fn copy_button(mut self, copy_button: bool) -> Self { self.copy_button = copy_button; self } pub fn size(mut self, size: CodeBlockSize) -> Self { self.size = size; self } /// Wraps long lines instead of scrolling them sideways. pub fn wrap(mut self, wrap: bool) -> Self { self.wrap = wrap; self } } impl RenderOnce for CodeBlock { fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { let state = window.use_keyed_state(self.id.clone(), cx, |_, _| CopyState::default()); let copied = state.read(cx).copied; let theme = cx.theme(); let small = self.size == CodeBlockSize::Sm; let line_height = if small { px(19.5) } else { LINE_HEIGHT }; let wrap = self.wrap; let copy_button = self.copy_button.then(|| { let code = self.code.clone(); div() .id("copy") .flex() .flex_none() .items_center() .justify_center() .size(px(28.0)) .rounded(theme.radius) .cursor_pointer() .hover(|style| style.bg(theme.accent)) .on_click(move |_, _, cx| { cx.write_to_clipboard(ClipboardItem::new_string(code.to_string())); state.update(cx, |state, cx| state.copied(cx)); }) .child( svg() .data(if copied { CHECK } else { COPY }) .flex_none() .size(px(14.0)) .text_color(theme.muted_foreground), ) }); let language = self .language .or_else(|| self.filename.as_deref().and_then(Language::from_filename)) .unwrap_or_default(); let palette = Palette::for_theme(theme); // Tabs are expanded before lexing so token ranges index the text that is drawn. let source = self.code.replace('\t', TAB); let tokens = highlight(&source, language); let mut lines: Vec<StyledText> = Vec::new(); let mut start = 0; let mut next_token = 0; for raw in source.split_inclusive('\n') { let line = raw.strip_suffix('\n').unwrap_or(raw); let line = line.strip_suffix('\r').unwrap_or(line); let end = start + line.len(); // A token can span lines (block comments, multi-line strings), so clip it to each. while next_token < tokens.len() && tokens[next_token].0.end <= start { next_token += 1; } let highlights: Vec<(Range<usize>, HighlightStyle)> = tokens[next_token..] .iter() .take_while(|(range, _)| range.start < end) .filter_map(|(range, token)| { let clipped = range.start.max(start)..range.end.min(end); (!clipped.is_empty()).then(|| { let style = HighlightStyle { color: Some(palette.color(*token)), ..Default::default() }; (clipped.start - start..clipped.end - start, style) }) }) .collect(); lines.push(StyledText::new(SharedString::from(line.to_string())).with_highlights(highlights)); start += raw.len(); } // Each line number shares a row with its line, so a wrapped line pushes the numbers // below it down with it. Every number gets the widest one's width, right-aligned. let font_size = px(if small { 12.0 } else { 13.0 }); let number_width = self.line_numbers.then(|| { let widest = SharedString::from(lines.len().to_string()); let run = TextRun { len: widest.len(), font: gpui::font(MONO), color: theme.muted_foreground, background_color: None, underline: None, strikethrough: None, }; window.text_system().shape_line(widest, font_size, &[run], None).width }); let muted_fg = theme.muted_foreground; let text = div() .flex() .flex_col() .map(|this| if wrap { this.flex_1().min_w_0() } else { this.flex_none() }) .children(lines.into_iter().enumerate().map(|(ix, line)| { // A wrapped line grows to fit; otherwise each row is one line high. let code = div().min_h(line_height); let code = if wrap { code.flex_1().min_w_0().child(line) } else { code.h(line_height).whitespace_nowrap().child(line) }; div() .flex() .children(number_width.map(|width| { div() .flex_none() .w(width) .mr_4() .flex() .justify_end() .text_color(muted_fg) .child(SharedString::from((ix + 1).to_string())) })) .child(code) })); let body = div() .id("code") .flex() .map(|this| if small { this.p_3() } else { this.p_4() }) .when(!wrap, |this| this.overflow_x_scroll()) .font_family(MONO) .text_size(font_size) .line_height(line_height) .text_color(if small { theme.foreground } else { theme.card_foreground }) .child(text); // Without a header the copy button floats over the code's top-right corner. let (header, floating_copy) = match self.filename { Some(filename) => ( Some( div() .flex() .items_center() .gap_2() .h(px(40.0)) .pl_4() .pr(px(6.0)) .border_b_1() .border_color(theme.border) .text_sm() .text_color(theme.muted_foreground) .child(svg().data(FILE).flex_none().size(px(14.0)).text_color(theme.muted_foreground)) .child(div().flex_1().child(filename)) .children(copy_button), ), None, ), None => (None, copy_button), }; div() .id(self.id) .relative() .w_full() .flex() .flex_col() .overflow_hidden() .map(|this| { if small { this.rounded(px(14.0)).bg(theme.muted) } else { this.rounded(theme.radius).border_1().border_color(theme.border).bg(theme.card) } }) .children(header) .child(body) .children(floating_copy.map(|button| div().absolute().top(px(6.0)).right(px(6.0)).child(button))) } } /// The languages a [`CodeBlock`] can highlight. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Language { /// No highlighting. #[default] PlainText, Rust, /// Also used for TSX. TypeScript, /// Also used for JSX. JavaScript, Python, Go, /// Shell scripts and terminal commands. Bash, Json, Toml, Yaml, Css, /// Also used for XML and SVG. Html, } impl Language { /// Picks a language from a name or file extension such as `"rust"`, `"rs"` or `"tsx"`. pub fn from_name(name: &str) -> Option<Self> { Some(match name.to_ascii_lowercase().as_str() { "rust" | "rs" => Self::Rust, "typescript" | "ts" | "tsx" | "mts" | "cts" => Self::TypeScript, "javascript" | "js" | "jsx" | "mjs" | "cjs" => Self::JavaScript, "python" | "py" => Self::Python, "go" | "golang" => Self::Go, "bash" | "sh" | "shell" | "zsh" | "console" => Self::Bash, "json" | "jsonc" => Self::Json, "toml" => Self::Toml, "yaml" | "yml" => Self::Yaml, "css" => Self::Css, "html" | "htm" | "xml" | "svg" => Self::Html, "text" | "txt" | "plaintext" => Self::PlainText, _ => return None, }) } /// Picks a language from a path's extension, like `src/main.rs`. pub fn from_filename(filename: &str) -> Option<Self> { let name = filename.rsplit(['/', '\\']).next().unwrap_or(filename); match name { "Cargo.lock" => Some(Self::Toml), "Dockerfile" | ".bashrc" | ".zshrc" => Some(Self::Bash), _ => Self::from_name(name.rsplit_once('.')?.1), } } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Token { Comment, Keyword, String, /// Numbers, literals like `true`, constants, attributes and object keys. Constant, Function, Type, /// HTML tags and CSS selectors. Tag, } /// The token colors of GitHub's light and dark themes, the ones the docs site's code uses. struct Palette { comment: Hsla, keyword: Hsla, string: Hsla, constant: Hsla, function: Hsla, ty: Hsla, tag: Hsla, } impl Palette { fn for_theme(theme: &Theme) -> Self { if theme.background.l < 0.5 { Self { comment: rgb(0x8b949e), keyword: rgb(0xff7b72), string: rgb(0xa5d6ff), constant: rgb(0x79c0ff), function: rgb(0xd2a8ff), ty: rgb(0xffa657), tag: rgb(0x7ee787), } } else { Self { comment: rgb(0x6e7781), keyword: rgb(0xcf222e), string: rgb(0x0a3069), constant: rgb(0x0550ae), function: rgb(0x8250df), ty: rgb(0x953800), tag: rgb(0x116329), } } } fn color(&self, token: Token) -> Hsla { match token { Token::Comment => self.comment, Token::Keyword => self.keyword, Token::String => self.string, Token::Constant => self.constant, Token::Function => self.function, Token::Type => self.ty, Token::Tag => self.tag, } } } fn rgb(hex: u32) -> Hsla { let channel = |shift: u32| ((hex >> shift) & 0xff) as f32 / 255.0; let (r, g, b) = (channel(16), channel(8), channel(0)); let max = r.max(g).max(b); let min = r.min(g).min(b); let l = (max + min) / 2.0; if max == min { return hsla(0.0, 0.0, l, 1.0); } let d = max - min; let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) }; let h = if max == r { (g - b) / d + if g < b { 6.0 } else { 0.0 } } else if max == g { (b - r) / d + 2.0 } else { (r - g) / d + 4.0 }; hsla(h / 6.0, s, l, 1.0) } /// What a language's lexer needs to know. Highlighting is lexical, like a TextMate grammar /// without the nesting: good for showing code, not for checking it. struct Syntax { keywords: &'static [&'static str], /// Words shown as constants: `true`, `null`, `self`. literals: &'static [&'static str], /// Built-in types in lowercase, like `u32` or `string`. Capitalized names are types anyway. types: &'static [&'static str], line_comments: &'static [&'static str], block_comment: Option<(&'static str, &'static str)>, /// Quote characters that open a string. quotes: &'static [char], /// Characters allowed in identifiers besides letters, digits and `_`. ident_extra: &'static [char], /// Capitalized names are types (Rust, TypeScript); otherwise only when declared as one. capitalized_types: bool, } const RUST: Syntax = Syntax { keywords: &[ "as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "static", "struct", "super", "trait", "type", "unsafe", "use", "where", "while", "yield", ], literals: &["true", "false", "self"], types: &[ "bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", ], line_comments: &["//"], block_comment: Some(("/*", "*/")), quotes: &['"'], ident_extra: &[], capitalized_types: true, }; const TYPESCRIPT: Syntax = Syntax { keywords: &[ "abstract", "as", "async", "await", "break", "case", "catch", "class", "const", "continue", "debugger", "declare", "default", "delete", "do", "else", "enum", "export", "extends", "finally", "for", "from", "function", "get", "if", "implements", "import", "in", "instanceof", "interface", "keyof", "let", "namespace", "new", "of", "private", "protected", "public", "readonly", "return", "satisfies", "set", "static", "switch", "throw", "try", "type", "typeof", "var", "void", "while", "with", "yield", ], literals: &["true", "false", "null", "undefined", "this", "super", "NaN", "Infinity"], types: &["string", "number", "boolean", "any", "unknown", "never", "object", "symbol", "bigint"], line_comments: &["//"], block_comment: Some(("/*", "*/")), quotes: &['"', '\'', '`'], ident_extra: &['$'], capitalized_types: true, }; const PYTHON: Syntax = Syntax { keywords: &[ "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "match", "case", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", ], literals: &["True", "False", "None", "self", "cls"], types: &["int", "float", "str", "bool", "bytes", "list", "dict", "set", "tuple", "object"], line_comments: &["#"], block_comment: None, quotes: &['"', '\''], ident_extra: &[], capitalized_types: true, }; const GO: Syntax = Syntax { keywords: &[ "break", "case", "chan", "const", "continue", "default", "defer", "else", "fallthrough", "for", "func", "go", "goto", "if", "import", "interface", "map", "package", "range", "return", "select", "struct", "switch", "type", "var", ], literals: &["true", "false", "nil", "iota"], types: &[ "bool", "byte", "complex64", "complex128", "error", "float32", "float64", "int", "int8", "int16", "int32", "int64", "rune", "string", "uint", "uint8", "uint16", "uint32", "uint64", "uintptr", "any", ], line_comments: &["//"], block_comment: Some(("/*", "*/")), quotes: &['"', '\'', '`'], ident_extra: &[], capitalized_types: false, }; const BASH: Syntax = Syntax { keywords: &[ "if", "then", "else", "elif", "fi", "for", "in", "do", "done", "while", "until", "case", "esac", "function", "return", "export", "local", "readonly", "unset", "source", "sudo", ], literals: &["true", "false"], types: &[], line_comments: &["#"], block_comment: None, quotes: &['"', '\''], ident_extra: &['-', '.', '/'], capitalized_types: false, }; const JSON: Syntax = Syntax { keywords: &[], literals: &["true", "false", "null"], types: &[], line_comments: &["//"], block_comment: Some(("/*", "*/")), quotes: &['"'], ident_extra: &[], capitalized_types: false, }; const TOML: Syntax = Syntax { keywords: &[], literals: &["true", "false"], types: &[], line_comments: &["#"], block_comment: None, quotes: &['"', '\''], ident_extra: &['-'], capitalized_types: false, }; const YAML: Syntax = Syntax { keywords: &[], literals: &["true", "false", "null", "yes", "no", "on", "off"], types: &[], line_comments: &["#"], block_comment: None, quotes: &['"', '\''], ident_extra: &['-', '.'], capitalized_types: false, }; const CSS: Syntax = Syntax { keywords: &["important"], literals: &[], types: &[], line_comments: &[], block_comment: Some(("/*", "*/")), quotes: &['"', '\''], ident_extra: &['-'], capitalized_types: false, }; /// Splits `source` into colored ranges, in order and never overlapping. Text outside them /// keeps the block's foreground color. fn highlight(source: &str, language: Language) -> Vec<(Range<usize>, Token)> { let syntax = match language { Language::PlainText => return Vec::new(), Language::Html => return highlight_html(source), Language::Rust => &RUST, Language::TypeScript | Language::JavaScript => &TYPESCRIPT, Language::Python => &PYTHON, Language::Go => &GO, Language::Bash => &BASH, Language::Json => &JSON, Language::Toml => &TOML, Language::Yaml => &YAML, Language::Css => &CSS, }; Lexer { source, pos: 0, tokens: Vec::new() }.run(syntax, language) } struct Lexer<'a> { source: &'a str, pos: usize, tokens: Vec<(Range<usize>, Token)>, } impl<'a> Lexer<'a> { fn rest(&self) -> &'a str { &self.source[self.pos..] } fn peek(&self) -> Option<char> { self.rest().chars().next() } fn char_at(&self, offset: usize) -> Option<char> { self.source.get(offset..).and_then(|s| s.chars().next()) } fn push(&mut self, start: usize, token: Token) { if self.pos > start { self.tokens.push((start..self.pos, token)); } } /// The next character that isn't a space or tab, from `offset`. fn next_visible(&self, offset: usize) -> Option<char> { self.source[offset..].chars().find(|c| *c != ' ' && *c != '\t') } /// The last character before `offset` that isn't a space or tab, on the same line. fn previous_visible(&self, offset: usize) -> Option<char> { self.source[..offset].chars().rev().find(|c| *c != ' ' && *c != '\t') } fn at_line_start(&self, offset: usize) -> bool { matches!(self.previous_visible(offset), None | Some('\n')) } fn skip_to_line_end(&mut self) { self.pos = self.rest().find('\n').map_or(self.source.len(), |i| self.pos + i); } /// Past the closing `quote`, honoring backslash escapes unless `raw`. fn skip_string(&mut self, quote: &str, raw: bool, multiline: bool) { while self.pos < self.source.len() { let rest = self.rest(); if rest.starts_with(quote) { self.pos += quote.len(); return; } let c = rest.chars().next().unwrap(); if c == '\n' && !multiline { return; } if c == '\\' && !raw { self.pos += 1; if let Some(escaped) = self.peek() { self.pos += escaped.len_utf8(); } continue; } self.pos += c.len_utf8(); } } fn skip_ident(&mut self, syntax: &Syntax) { while let Some(c) = self.peek() { if c.is_alphanumeric() || c == '_' || syntax.ident_extra.contains(&c) { self.pos += c.len_utf8(); } else { break; } } } fn run(mut self, syntax: &Syntax, language: Language) -> Vec<(Range<usize>, Token)> { // Bash colors the command word of each pipeline step; this tracks whether we are on one. let mut command_position = true; // CSS: between an `@rule` and its `{` or `;`, nothing is a selector. let mut in_at_rule = false; // TypeScript and Python: the word after `class`/`interface`/`type` names a type. let mut declares_type = false; // Rust: the name after `fn`, Python after `def`, Go after `func`. let mut declares_function = false; while let Some(c) = self.peek() { let start = self.pos; let rest = self.rest(); if c == '\n' { command_position = true; self.pos += 1; continue; } if c.is_whitespace() { self.pos += c.len_utf8(); continue; } if let Some(prefix) = syntax.line_comments.iter().find(|p| rest.starts_with(**p)) { // `#` only starts a comment at a word boundary: `${#array}` and `a#b` are not. let boundary = *prefix != "#" || start == 0 || self.source[..start].ends_with(char::is_whitespace); if boundary { self.skip_to_line_end(); self.push(start, Token::Comment); continue; } } if let Some((open, close)) = syntax.block_comment { if rest.starts_with(open) { self.pos += open.len(); self.pos = self.rest().find(close).map_or(self.source.len(), |i| self.pos + i + close.len()); self.push(start, Token::Comment); continue; } } match language { Language::Rust => { if rest.starts_with("#[") || rest.starts_with("#![") { let mut depth = 0; for (i, ch) in rest.char_indices() { match ch { '[' => depth += 1, ']' => { depth -= 1; if depth == 0 { self.pos = start + i + 1; break; } } '\n' => { self.pos = start + i; break; } _ => {} } } if self.pos == start { self.pos = self.source.len(); } self.push(start, Token::Constant); continue; } // Raw strings: r"…", r#"…"#, br"…". let after_prefix = rest.strip_prefix("br").or_else(|| rest.strip_prefix('r')); if let Some(after) = after_prefix { let hashes = after.len() - after.trim_start_matches('#').len(); if after[hashes..].starts_with('"') { self.pos += rest.len() - after.len() + hashes + 1; let close = format!("\"{}", "#".repeat(hashes)); self.skip_string(&close, true, true); self.push(start, Token::String); continue; } } if rest.starts_with("b\"") || rest.starts_with("b'") { let quote = &rest[1..2]; self.pos += 2; self.skip_string(quote, false, quote == "\""); self.push(start, Token::String); continue; } if c == '\'' { // 'a' and '\n' are chars; 'a without a closing quote is a lifetime. let mut chars = rest[1..].chars(); let first = chars.next(); let is_char = match first { Some('\\') => true, Some(_) => chars.next() == Some('\''), None => false, }; self.pos += 1; if is_char { self.skip_string("'", false, false); self.push(start, Token::String); } else { self.skip_ident(syntax); self.push(start, Token::Keyword); } continue; } } Language::Python => { // String prefixes: f"", r'', b"", rb"", and triple quotes. let prefix_len = rest .char_indices() .take_while(|(_, ch)| matches!(ch.to_ascii_lowercase(), 'f' | 'r' | 'b' | 'u')) .count() .min(2); let after = &rest[prefix_len..]; if (prefix_len == 0 || !self.prev_is_ident(start, syntax)) && (after.starts_with('"') || after.starts_with('\'')) { let raw = rest[..prefix_len].to_ascii_lowercase().contains('r'); let triple = if after.starts_with("\"\"\"") { Some("\"\"\"") } else if after.starts_with("'''") { Some("'''") } else { None }; match triple { Some(quote) => { self.pos += prefix_len + 3; self.skip_string(quote, raw, true); } None => { self.pos += prefix_len + 1; self.skip_string(&after[..1], raw, false); } } self.push(start, Token::String); continue; } if c == '@' && self.at_line_start(start) { self.pos += 1; self.skip_ident(syntax); while self.peek() == Some('.') { self.pos += 1; self.skip_ident(syntax); } self.push(start, Token::Function); continue; } } Language::TypeScript | Language::JavaScript => { // JSX tags. After a name or `)` a `<` is a comparison or type arguments instead. let name_start = start + if rest.starts_with("</") { 2 } else { 1 }; let opens_tag = c == '<' && self.char_at(name_start).is_some_and(char::is_alphabetic); let before = self.source[..start].trim_end(); let after_value = before.ends_with(|p: char| p.is_alphanumeric() || matches!(p, '_' | '$' | ')' | ']')) && !before.ends_with("return"); if opens_tag && !after_value { self.pos = name_start; self.skip_ident(syntax); while self.peek() == Some('.') { self.pos += 1; self.skip_ident(syntax); } let name = &self.source[name_start..self.pos]; let component = name.starts_with(char::is_uppercase); self.tokens.push((name_start..self.pos, if component { Token::Type } else { Token::Tag })); continue; } if c == '@' { self.pos += 1; self.skip_ident(syntax); self.push(start, Token::Function); continue; } } Language::Bash => { if c == '$' { self.pos += 1; match self.peek() { Some('{') => self.skip_string("}", true, false), Some('(') => { // Command substitution: color the `$(` and let the inside lex normally. self.pos += 1; self.push(start, Token::Constant); command_position = true; continue; } Some(ch) if ch.is_alphanumeric() || ch == '_' => { while let Some(ch) = self.peek() { if ch.is_alphanumeric() || ch == '_' { self.pos += ch.len_utf8(); } else { break; } } } Some(ch) if "@#?*!$-".contains(ch) => self.pos += 1, _ => {} } self.push(start, Token::Constant); continue; } if matches!(c, '|' | ';' | '&' | '(' | '`') { self.pos += 1; command_position = true; continue; } if c == '-' && !command_position && self.source[..start].ends_with(char::is_whitespace) { self.skip_ident(syntax); while self.peek() == Some('=') { self.pos += 1; self.skip_ident(syntax); } self.push(start, Token::Constant); continue; } } Language::Toml => { if c == '[' && self.at_line_start(start) { self.skip_to_line_end(); let line = &self.source[start..self.pos]; self.pos = start + line.rfind(']').map_or(line.len(), |i| i + 1); self.push(start, Token::Type); continue; } if self.at_line_start(start) && (c.is_alphanumeric() || c == '_' || c == '"') { // A key, possibly dotted or quoted, up to the `=`. let line_end = rest.find('\n').unwrap_or(rest.len()); if let Some(eq) = rest[..line_end].find('=') { self.pos = start + rest[..eq].trim_end().len(); self.push(start, Token::Constant); continue; } } } Language::Yaml => { if c != '-' && (self.at_line_start(start) || self.previous_visible(start) == Some('-')) { let line_end = rest.find('\n').unwrap_or(rest.len()); let line = &rest[..line_end]; if let Some(colon) = line.find(':') { let key = &line[..colon]; if !key.is_empty() && !key.contains(['"', '\'', '#', '{', '[']) && line[colon + 1..].chars().next().is_none_or(|ch| ch.is_whitespace()) { self.pos = start + key.trim_end().len(); self.push(start, Token::Tag); continue; } } } } Language::Css => { if c == '@' { self.pos += 1; self.skip_ident(syntax); self.push(start, Token::Keyword); in_at_rule = true; continue; } if matches!(c, '{' | ';') { in_at_rule = false; } // A selector is whatever runs up to a `{` before any `;` or `}`. let structural = rest.find(['{', ';', '}']); let selector = !in_at_rule && (c.is_alphabetic() || matches!(c, '.' | '#' | ':' | '*' | '[' | '&')) && structural.is_some_and(|i| rest[i..].starts_with('{')); if selector { self.pos = start + rest[..structural.unwrap()].trim_end().len(); self.push(start, Token::Tag); continue; } if c == '#' || (c == '-' && rest[1..].starts_with('-')) { // Hex colors and custom properties. self.pos += 1; self.skip_ident(syntax); self.push(start, Token::Constant); continue; } } _ => {} } if let Some(quote) = syntax.quotes.iter().find(|q| **q == c) { self.pos += 1; let raw = language == Language::Bash && *quote == '\'' || language == Language::Go && *quote == '`'; let multiline = *quote == '`' || matches!(language, Language::Bash); self.skip_string("e.to_string(), raw, multiline); // A JSON key: a string followed by `:`. let key = language == Language::Json && self.next_visible(self.pos) == Some(':'); self.push(start, if key { Token::Constant } else { Token::String }); command_position = false; continue; } let leading_dot = c == '.' && self.char_at(start + 1).is_some_and(|d| d.is_ascii_digit()) && !self.source[..start].ends_with(|p: char| p == '.' || p.is_alphanumeric()); if c.is_ascii_digit() || leading_dot { // Digits, hex, `_` separators, exponents, suffixes like `u32` or CSS units like `px`. self.pos += c.len_utf8(); while let Some(ch) = self.peek() { let next_is_digit = self.char_at(self.pos + 1).is_some_and(|d| d.is_ascii_digit()); if ch.is_alphanumeric() || ch == '_' || (ch == '.' && next_is_digit) || ch == '%' { self.pos += ch.len_utf8(); } else { break; } } if language != Language::Bash || !command_position { self.push(start, Token::Constant); } command_position = false; continue; } if c.is_alphabetic() || c == '_' || (syntax.ident_extra.contains(&c) && c == '$') { self.skip_ident(syntax); let word = &self.source[start..self.pos]; let next = self.peek(); let token = self.classify(word, next, syntax, language, command_position); let declarable = token != Some(Token::Keyword); let token = match token { _ if declares_type && declarable => Some(Token::Type), _ if declares_function && declarable => Some(Token::Function), _ => token, }; declares_type = matches!( (language, word), (Language::TypeScript | Language::JavaScript, "class" | "interface" | "type" | "enum") | (Language::Python, "class") | (Language::Go, "type") ); declares_function = matches!( (language, word), (Language::Rust, "fn") | (Language::Python, "def") | (Language::Go, "func") | (Language::TypeScript | Language::JavaScript, "function") ); if let Some(token) = token { // Rust macros include their `!`. if token == Token::Function && language == Language::Rust && next == Some('!') { self.pos += 1; } self.push(start, token); } if language == Language::Bash { // `VAR=value` and keywords like `if` leave the next word in command position. command_position = syntax.keywords.contains(&word) && word != "in"; } continue; } self.pos += c.len_utf8(); } self.tokens } fn prev_is_ident(&self, offset: usize, syntax: &Syntax) -> bool { self.source[..offset] .chars() .next_back() .is_some_and(|c| c.is_alphanumeric() || c == '_' || syntax.ident_extra.contains(&c)) } fn classify( &self, word: &str, next: Option<char>, syntax: &Syntax, language: Language, command_position: bool, ) -> Option<Token> { if syntax.keywords.contains(&word) { return Some(Token::Keyword); } if syntax.literals.contains(&word) { return Some(Token::Constant); } if syntax.types.contains(&word) { return Some(Token::Type); } match language { Language::Bash => { let assignment = next == Some('='); return match () { _ if assignment => Some(Token::Constant), _ if command_position => Some(Token::Function), _ => None, }; } // Properties and keyword values alike. Language::Css => return Some(if next == Some('(') { Token::Function } else { Token::Constant }), Language::Json | Language::Toml | Language::Yaml => return None, _ => {} } let first = word.chars().next()?; let all_caps = word.len() > 1 && word.chars().all(|c| c.is_uppercase() || c.is_ascii_digit() || c == '_') && word.chars().any(char::is_uppercase); if next == Some('(') || (language == Language::Rust && next == Some('!') && self.char_at(self.pos + 1) != Some('=')) { // `Some(x)` and `Foo(…)` are constructors: color them as types. if first.is_uppercase() && syntax.capitalized_types && !all_caps { return Some(Token::Type); } return Some(Token::Function); } // Rust turbofish and generic calls: `collect::<Vec<_>>()`, `foo::<T>()`. if language == Language::Rust && self.rest().starts_with("::<") { return Some(Token::Function); } if language == Language::TypeScript || language == Language::JavaScript { // Generic calls like `useState<string>(…)` are hard to tell from comparisons; skip them. if next == Some('`') { return Some(Token::Function); } } if all_caps { return Some(Token::Constant); } if first.is_uppercase() && syntax.capitalized_types { return Some(Token::Type); } None } } /// HTML, XML and SVG: tags, attribute names, attribute values and comments. fn highlight_html(source: &str) -> Vec<(Range<usize>, Token)> { let mut tokens = Vec::new(); let mut pos = 0; while let Some(offset) = source[pos..].find('<') { let start = pos + offset; let rest = &source[start..]; if rest.starts_with("<!--") { let end = rest.find("-->").map_or(source.len(), |i| start + i + 3); tokens.push((start..end, Token::Comment)); pos = end; continue; } let name_start = start + if rest.starts_with("</") { 2 } else { 1 }; let name_len = source[name_start..] .find(|c: char| !(c.is_alphanumeric() || matches!(c, '-' | ':' | '_' | '!' | '?'))) .unwrap_or(source.len() - name_start); if name_len == 0 { pos = start + 1; continue; } let mut i = name_start + name_len; tokens.push((name_start..i, Token::Tag)); // Attributes until `>`. while i < source.len() { let c = source[i..].chars().next().unwrap(); if c == '>' { i += 1; break; } if c == '"' || c == '\'' { let end = source[i + 1..].find(c).map_or(source.len(), |j| i + 1 + j + 1); tokens.push((i..end, Token::String)); i = end; continue; } if c.is_alphabetic() || c == '_' || c == '@' || c == ':' { let len = source[i..] .find(|c: char| !(c.is_alphanumeric() || matches!(c, '-' | ':' | '_' | '.' | '@'))) .unwrap_or(source.len() - i); tokens.push((i..i + len, Token::Constant)); i += len; continue; } i += c.len_utf8(); } pos = i; } tokens }Register the module
// src/ui/mod.rs pub mod code_block;
Usage
use crate::ui::code_block::*;Examples
Language
The language is picked from the filename's extension. Without a filename, or to override it, pass .language(Language::TypeScript).
use gpui::{div, prelude::*, px};
use crate::ui::code_block::{CodeBlock, Language};
const CODE: &str = r#"import { useState } from "react";
export function Counter({ start = 0 }: { start?: number }) {
const [count, setCount] = useState(start);
// Clicks add one.
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}"#;
pub fn code_block_language() -> impl IntoElement {
div().w(px(620.0)).child(CodeBlock::new("counter", CODE).language(Language::TypeScript))
}Terminal
Language::Bash colors commands, flags, variables and comments.
use gpui::{div, prelude::*, px};
use crate::ui::code_block::{CodeBlock, Language};
const CODE: &str = r#"# Install the CLI, then add a component to your app.
cargo install hyuskui --locked
cargo hyuskui add code-block
echo "Installed in $PWD/src/ui""#;
pub fn code_block_terminal() -> impl IntoElement {
div().w(px(620.0)).child(CodeBlock::new("install", CODE).language(Language::Bash))
}Config
TOML, JSON and YAML color keys, sections and values.
use gpui::{div, prelude::*, px};
use crate::ui::code_block::CodeBlock;
const CODE: &str = r#"[package]
name = "my-app"
version = "0.1.0"
edition = "2024"
[dependencies]
# GPUI is not on crates.io yet.
gpui = { git = "https://github.com/zed-industries/zed" }"#;
pub fn code_block_config() -> impl IntoElement {
div().w(px(620.0)).child(CodeBlock::new("cargo-toml", CODE).filename("Cargo.toml").line_numbers(true))
}API Reference
CodeBlockSize
How much room the block takes.
CodeBlockSize::DefaultA bordered card with 13px code.
CodeBlockSize::Smshadcn's size="sm", for tool output inside a trace: a borderless muted panel with 12px code on 19.5px lines.
CodeBlock
A framed block of monospace code with an optional filename header, line numbers and a copy button, syntax highlighted for its language.
CodeBlock::new(id: impl Into<ElementId>, code: impl Into<SharedString>) -> Self.filename(filename: impl Into<SharedString>).language(language: Language)The language to highlight. Without it, the language is picked from the filename's extension, and code with neither is shown as plain text.
.line_numbers(line_numbers: bool).copy_button(copy_button: bool).size(size: CodeBlockSize).wrap(wrap: bool)Wraps long lines instead of scrolling them sideways.
Language
The languages a [CodeBlock] can highlight.
Language::PlainTextNo highlighting.
Language::RustLanguage::TypeScriptAlso used for TSX.
Language::JavaScriptAlso used for JSX.
Language::PythonLanguage::GoLanguage::BashShell scripts and terminal commands.
Language::JsonLanguage::TomlLanguage::YamlLanguage::CssLanguage::HtmlAlso used for XML and SVG.