mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Support inline code in custom status lines (#63755)
## Why Ordinary status line text collapses spaces and tabs, so it cannot preserve the spacing of commands and other literals. ## What changed Add a `code` element to the terminal UI tree and expose it as `CodeElement` in the status line TypeScript contract. Code spans preserve literal spacing, expand tabs to terminal tab stops, and use theme-aware foreground and background colors. They prefer word breaks and can wrap long tokens at grapheme boundaries in narrow layouts. ## Testing Add renderer coverage for whitespace, wrapping across styled children, clipping, and theme contrast. Extend the TypeScript contract fixture to check that `CodeElement` requires a child list. GitOrigin-RevId: 626d7624829a25e342fc052ab5194ff53b2a7673
This commit is contained in:
+2
-1
@@ -31,7 +31,7 @@ export type Cost = { total_cost_usd?: number, total_credits?: number, };
|
||||
|
||||
export type DisplayMode = "standard" | "raw";
|
||||
|
||||
export type Element = { "type": "text", props?: TextProps, children: Array<Element | null>, } | { "type": "link", props: LinkProps, children: Array<Element | null>, } | { "type": "row", props: RowProps, children: Array<Element | null>, } | { "type": "col", props: ColProps, children: Array<Element | null>, } | { "type": "bold", children: Array<Element | null>, } | { "type": "italic", children: Array<Element | null>, } | { "type": "underline", children: Array<Element | null>, } | string;
|
||||
export type Element = { "type": "text", props?: TextProps, children: Array<Element | null>, } | { "type": "link", props: LinkProps, children: Array<Element | null>, } | { "type": "row", props: RowProps, children: Array<Element | null>, } | { "type": "col", props: ColProps, children: Array<Element | null>, } | { "type": "bold", children: Array<Element | null>, } | { "type": "italic", children: Array<Element | null>, } | { "type": "underline", children: Array<Element | null>, } | { "type": "code", children: Array<Element | null>, } | string;
|
||||
|
||||
export type FileSystem = { "type": "restricted" } | { "type": "unrestricted" };
|
||||
|
||||
@@ -105,6 +105,7 @@ export type UnderlineElement = Extract<Element, { type: "underline" }>;
|
||||
export type LinkElement = Extract<Element, { type: "link" }>;
|
||||
export type RowElement = Extract<Element, { type: "row" }>;
|
||||
export type ColElement = Extract<Element, { type: "col" }>;
|
||||
export type CodeElement = Extract<Element, { type: "code" }>;
|
||||
export type RateLimitWindow = {
|
||||
/**
|
||||
* Percentage of the allowance consumed during the window. Can exceed 100.
|
||||
|
||||
@@ -29,6 +29,7 @@ fn statusline_typescript_contract_matches_the_bundled_reference() -> color_eyre:
|
||||
"UiTree",
|
||||
"RowElement",
|
||||
"ColElement",
|
||||
"CodeElement",
|
||||
"StatuslineItemId",
|
||||
"Color",
|
||||
] {
|
||||
@@ -59,7 +60,16 @@ fn generate_reference(output: &Path) -> color_eyre::Result<String> {
|
||||
"export type StatuslineItemId = {};",
|
||||
items.join(" | ")
|
||||
)?;
|
||||
for name in ["Text", "Bold", "Italic", "Underline", "Link", "Row", "Col"] {
|
||||
for name in [
|
||||
"Text",
|
||||
"Bold",
|
||||
"Italic",
|
||||
"Underline",
|
||||
"Link",
|
||||
"Row",
|
||||
"Col",
|
||||
"Code",
|
||||
] {
|
||||
let tag = name.to_ascii_lowercase();
|
||||
writeln!(
|
||||
generated,
|
||||
|
||||
@@ -182,11 +182,9 @@ impl MarkdownStyles {
|
||||
h4: foreground(&["markup.heading.4.markdown", "markup.heading.markdown"]).italic(),
|
||||
h5: foreground(&["markup.heading.5.markdown", "markup.heading.markdown"]).italic(),
|
||||
h6: foreground(&["markup.heading.6.markdown", "markup.heading.markdown"]).italic(),
|
||||
code: Style::new().fg(color(&[
|
||||
"markup.inline.raw.string.markdown",
|
||||
"markup.raw.inline.markdown",
|
||||
])
|
||||
.unwrap_or_else(accent_color)),
|
||||
code: Style::new()
|
||||
.fg(color(crate::render::highlight::INLINE_CODE_SCOPES)
|
||||
.unwrap_or_else(accent_color)),
|
||||
emphasis: foreground(&["markup.italic.markdown"]).italic(),
|
||||
strong: foreground(&["markup.bold.markdown"]).bold(),
|
||||
strikethrough: Style::new().crossed_out(),
|
||||
|
||||
@@ -360,6 +360,11 @@ fn scope_background(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) const INLINE_CODE_SCOPES: &[&str] = &[
|
||||
"markup.inline.raw.string.markdown",
|
||||
"markup.raw.inline.markdown",
|
||||
];
|
||||
|
||||
/// Query the active syntax theme for the first foreground style provided by the
|
||||
/// supplied TextMate scopes.
|
||||
pub(crate) fn foreground_style_for_scopes(scope_names: &[&str]) -> Option<Style> {
|
||||
|
||||
@@ -60,6 +60,10 @@ pub(crate) enum UiNode {
|
||||
Underline {
|
||||
children: Vec<Option<UiNode>>,
|
||||
},
|
||||
/// An inline span with preserved whitespace and its own theme colors.
|
||||
Code {
|
||||
children: Vec<Option<UiNode>>,
|
||||
},
|
||||
#[serde(untagged)]
|
||||
String(String),
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ impl std::str::FromStr for UiTree {
|
||||
}
|
||||
}
|
||||
UiNode::Text { children, .. }
|
||||
| UiNode::Code { children }
|
||||
| UiNode::Bold { children }
|
||||
| UiNode::Italic { children }
|
||||
| UiNode::Underline { children }
|
||||
|
||||
@@ -101,7 +101,7 @@ impl<'a> Fragment<'a> {
|
||||
|
||||
fn visit(self, limit: usize, mut draw: impl FnMut(usize, &str, usize, &'a Paint)) -> usize {
|
||||
match self {
|
||||
Self::Text(chunks, _) => visit_chunks(chunks, limit, draw),
|
||||
Self::Text(chunks, width) => visit_chunks(chunks, limit.min(width), draw),
|
||||
Self::BlankLine => 0,
|
||||
Self::Padding(width, paint)
|
||||
| Self::Gap(width, paint)
|
||||
|
||||
@@ -102,12 +102,17 @@ impl PreparedNode {
|
||||
let mut widths = Widths::default();
|
||||
for line in &text.lines {
|
||||
let mut width = 0;
|
||||
for chunk in line {
|
||||
let cells = chunk.width_cells as u64;
|
||||
widths.minimum = widths.minimum.max(cells);
|
||||
width += cells + u64::from(chunk.trailing_space.is_some());
|
||||
let mut word = 0;
|
||||
for (i, chunk) in line.iter().enumerate() {
|
||||
let cells = chunk.width_at(width);
|
||||
if chunk.prefers_break_before(i) {
|
||||
word = 0;
|
||||
}
|
||||
word += cells;
|
||||
widths.minimum = widths.minimum.max(word as u64);
|
||||
width += cells + usize::from(chunk.trailing_space.is_some());
|
||||
}
|
||||
widths.preferred = widths.preferred.max(width);
|
||||
widths.preferred = widths.preferred.max(width as u64);
|
||||
}
|
||||
Some(Self {
|
||||
kind: NodeKind::Text(text),
|
||||
@@ -179,11 +184,21 @@ impl PreparedNode {
|
||||
}
|
||||
|
||||
fn collect_inline(flow: &mut Flow, inline: &mut InlineText, node: UiNode, mut paint: Paint) {
|
||||
let parent_preserves_spaces = paint.inline_code;
|
||||
let children = match node {
|
||||
UiNode::String(raw) => {
|
||||
inline.push_leaf(raw, paint);
|
||||
return;
|
||||
}
|
||||
UiNode::Code { children } => {
|
||||
paint.inline_code = true;
|
||||
paint.foreground = None;
|
||||
paint.background = None;
|
||||
paint.modifiers = paint
|
||||
.modifiers
|
||||
.remove_modifier(ratatui::style::Modifier::BOLD);
|
||||
children
|
||||
}
|
||||
UiNode::Col { props, children } => {
|
||||
flow.line.extend(Self::text(std::mem::take(inline)));
|
||||
let line = flow.take_line();
|
||||
@@ -235,6 +250,9 @@ impl PreparedNode {
|
||||
for node in children.into_iter().flatten() {
|
||||
Self::collect_inline(flow, inline, node, paint.clone());
|
||||
}
|
||||
if !parent_preserves_spaces {
|
||||
inline.end_span();
|
||||
}
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
|
||||
@@ -25,6 +25,7 @@ pub(super) struct Paint {
|
||||
pub(super) foreground: Option<Color>,
|
||||
pub(super) background: Option<Color>,
|
||||
pub(super) href: Option<Arc<String>>,
|
||||
pub(super) inline_code: bool,
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
@@ -32,12 +33,17 @@ impl Paint {
|
||||
let mut style = self.modifiers;
|
||||
style.fg = self.foreground.map(|c| theme.resolve(c));
|
||||
style.bg = self.background.map(|c| theme.resolve(c));
|
||||
style
|
||||
if self.inline_code {
|
||||
theme.inline_code_style(style)
|
||||
} else {
|
||||
style
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct Run {
|
||||
break_before: bool,
|
||||
text: RunText,
|
||||
paint: Paint,
|
||||
}
|
||||
@@ -86,8 +92,17 @@ impl PartialEq for RunText {
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub(super) struct Chunk {
|
||||
runs: Vec<Run>,
|
||||
pub(super) width_cells: usize,
|
||||
width_cells: usize,
|
||||
pub(super) trailing_space: Option<Paint>,
|
||||
break_before: BreakBefore,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
enum BreakBefore {
|
||||
#[default]
|
||||
Preferred,
|
||||
AfterHyphenBeforeDigit,
|
||||
Emergency,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
@@ -98,12 +113,18 @@ pub(super) struct PreparedText {
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct InlineText {
|
||||
after_span: bool,
|
||||
text: PreparedText,
|
||||
line: Vec<Run>,
|
||||
space: Option<Paint>,
|
||||
}
|
||||
|
||||
impl InlineText {
|
||||
/// Returning to normal prose allows a break before a sibling’s first literal space.
|
||||
pub(super) fn end_span(&mut self) {
|
||||
self.after_span = true;
|
||||
}
|
||||
|
||||
/// Whitespace-only text nodes join an existing anonymous flex item but cannot start one.
|
||||
pub(super) fn push_flex_leaf(&mut self, raw: String, paint: Paint) {
|
||||
let raw = sanitize_leaf(raw);
|
||||
@@ -118,20 +139,29 @@ impl InlineText {
|
||||
}
|
||||
|
||||
fn push_sanitized(&mut self, raw: String, paint: Paint) {
|
||||
let after_span = !raw.is_empty() && std::mem::take(&mut self.after_span);
|
||||
let break_before = after_span && paint.inline_code && raw.starts_with([' ', '\t']);
|
||||
let separators: &[char] = if paint.inline_code {
|
||||
&['\n']
|
||||
} else {
|
||||
&[' ', '\t', '\n']
|
||||
};
|
||||
let text = RunText::new(raw);
|
||||
let mut start = 0;
|
||||
for (end, ch) in text
|
||||
.match_indices([' ', '\t', '\n'])
|
||||
.match_indices(separators)
|
||||
.chain(std::iter::once((text.len(), "")))
|
||||
{
|
||||
if start < end {
|
||||
if let Some(paint) = self.space.take() {
|
||||
self.line.push(Run {
|
||||
break_before: false,
|
||||
text: RunText::Space,
|
||||
paint,
|
||||
});
|
||||
}
|
||||
self.line.push(Run {
|
||||
break_before: break_before && start == 0,
|
||||
text: text.slice(start..end),
|
||||
paint: paint.clone(),
|
||||
});
|
||||
@@ -191,6 +221,7 @@ fn join_graphemes(runs: Vec<Run>) -> Vec<Run> {
|
||||
let prefix = run.text.len() - split;
|
||||
if prefix > 0 {
|
||||
joined.push(Run {
|
||||
break_before: run.break_before,
|
||||
text: run.text.slice(0..prefix),
|
||||
paint: paint.clone(),
|
||||
});
|
||||
@@ -214,6 +245,7 @@ fn join_graphemes(runs: Vec<Run>) -> Vec<Run> {
|
||||
}
|
||||
if consumed < next.text.len() {
|
||||
if consumed > 0 {
|
||||
next.break_before = false;
|
||||
next.text = next.text.slice(consumed..next.text.len());
|
||||
}
|
||||
break;
|
||||
@@ -221,6 +253,7 @@ fn join_graphemes(runs: Vec<Run>) -> Vec<Run> {
|
||||
runs.next();
|
||||
}
|
||||
joined.push(Run {
|
||||
break_before: prefix == 0 && run.break_before,
|
||||
text: RunText::new(cluster),
|
||||
paint,
|
||||
});
|
||||
@@ -270,6 +303,19 @@ fn break_offsets<'a>(runs: impl Iterator<Item = &'a str>) -> Vec<usize> {
|
||||
breaks
|
||||
}
|
||||
|
||||
/// Preferred breaks between ASCII graphics in Chromium's break-word layout.
|
||||
fn ascii_word_break(previous: char, next: u8, word_hyphen: bool) -> bool {
|
||||
match previous {
|
||||
'-' if next.is_ascii_digit() => word_hyphen,
|
||||
'-' => !b"!$),./:;?]}".contains(&next),
|
||||
'?' => !b"!\"'),./:;?]}".contains(&next),
|
||||
_ if matches!(next, b'(' | b'<' | b'[' | b'{') => {
|
||||
"!\"#%&)*+,.:;=>\\]|}~".contains(previous)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
|
||||
let runs = join_graphemes(runs);
|
||||
let mut breaks = break_offsets(runs.iter().map(|run| run.text.as_ref()))
|
||||
@@ -278,30 +324,73 @@ fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
|
||||
let mut out = Vec::new();
|
||||
let mut chunk = Chunk::default();
|
||||
let mut offset = 0;
|
||||
let mut previous = None;
|
||||
let mut previous: Option<char> = None;
|
||||
let mut word_hyphen = false;
|
||||
let mut previous_code = false;
|
||||
for run in runs {
|
||||
let mut start = 0;
|
||||
for (i, grapheme) in run.text.grapheme_indices(true) {
|
||||
let position = offset + i;
|
||||
while breaks.next_if(|b| *b < position).is_some() {}
|
||||
// Match textwrap's default hyphen splitter, even across style boundaries.
|
||||
// Ordinary text uses textwrap’s word hyphens. In code, Chromium also breaks
|
||||
// at flag hyphens and keeps paths and shell operators within a word.
|
||||
let first = grapheme.as_bytes()[0];
|
||||
let can_break = match previous {
|
||||
_ if i == 0 && run.break_before => true,
|
||||
Some(prev)
|
||||
if (previous_code || run.paint.inline_code)
|
||||
&& prev.is_ascii_graphic()
|
||||
&& first.is_ascii_graphic() =>
|
||||
{
|
||||
ascii_word_break(prev, first, word_hyphen)
|
||||
}
|
||||
Some('-') => word_hyphen && grapheme.starts_with(char::is_alphanumeric),
|
||||
// A collapsed separator can wrap before the first literal space in code.
|
||||
Some(' ' | '\t')
|
||||
if previous_code
|
||||
|| (run.paint.inline_code && matches!(first, b' ' | b'\t')) =>
|
||||
{
|
||||
true
|
||||
}
|
||||
Some('\u{ad}') => false,
|
||||
_ => breaks.peek() == Some(&position),
|
||||
};
|
||||
if can_break {
|
||||
chunk.push(&run, start..i);
|
||||
if chunk.runs.last().is_some_and(|r| &*r.text == " ") {
|
||||
// Preserve normal word breaks first. An overlong code word can also
|
||||
// wrap at a grapheme boundary, as it does under overflow-wrap: break-word.
|
||||
let code_boundary = position > 0
|
||||
&& (run.paint.inline_code
|
||||
|| (previous_code && !matches!(run.text, RunText::Space)));
|
||||
if can_break || code_boundary {
|
||||
// A break after a literal space or tab can precede a collapsed
|
||||
// prose separator. Keep the separator on this chunk, so only
|
||||
// the prose space disappears when the line wraps.
|
||||
let end = if previous_code && matches!(run.text, RunText::Space) {
|
||||
run.text.len()
|
||||
} else {
|
||||
i
|
||||
};
|
||||
chunk.push(&run, start..end);
|
||||
start = end;
|
||||
if chunk
|
||||
.runs
|
||||
.last()
|
||||
.is_some_and(|r| matches!(r.text, RunText::Space))
|
||||
{
|
||||
chunk.trailing_space = chunk.runs.pop().map(|r| r.paint);
|
||||
chunk.width_cells -= 1;
|
||||
}
|
||||
if !chunk.runs.is_empty() {
|
||||
out.push(std::mem::take(&mut chunk));
|
||||
}
|
||||
start = i;
|
||||
chunk.break_before = if !can_break {
|
||||
BreakBefore::Emergency
|
||||
} else if previous_code && word_hyphen && first.is_ascii_digit() {
|
||||
BreakBefore::AfterHyphenBeforeDigit
|
||||
} else {
|
||||
BreakBefore::Preferred
|
||||
};
|
||||
}
|
||||
previous_code = run.paint.inline_code;
|
||||
for ch in grapheme.chars() {
|
||||
word_hyphen = ch == '-' && previous.is_some_and(char::is_alphanumeric);
|
||||
previous = Some(ch);
|
||||
@@ -316,12 +405,40 @@ fn chunks(runs: Vec<Run>) -> Vec<Chunk> {
|
||||
out
|
||||
}
|
||||
|
||||
const TAB_SPACES: &str = " ";
|
||||
|
||||
impl Chunk {
|
||||
pub(super) fn prefers_break_before(&self, index_in_line: usize) -> bool {
|
||||
match self.break_before {
|
||||
BreakBefore::Preferred => true,
|
||||
// A code hyphen occupies its own chunk. When wrapping puts it at the
|
||||
// start of a visual line, keep it with the digits that follow.
|
||||
BreakBefore::AfterHyphenBeforeDigit => index_in_line > 1,
|
||||
BreakBefore::Emergency => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn tab_paint(&self) -> Option<&Paint> {
|
||||
match self.runs.as_slice() {
|
||||
[run] if run.paint.inline_code && &*run.text == "\t" => Some(&run.paint),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn width_at(&self, column: usize) -> usize {
|
||||
if self.tab_paint().is_some() {
|
||||
TAB_SPACES.len() - column % TAB_SPACES.len()
|
||||
} else {
|
||||
self.width_cells
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, run: &Run, range: Range<usize>) {
|
||||
if !range.is_empty() {
|
||||
let text = run.text.slice(range);
|
||||
self.width_cells += span_width(&Span::raw(&*text));
|
||||
self.runs.push(Run {
|
||||
break_before: false,
|
||||
text,
|
||||
paint: run.paint.clone(),
|
||||
});
|
||||
@@ -339,33 +456,49 @@ impl PreparedText {
|
||||
let width = width.cells;
|
||||
let mut y = 0;
|
||||
for line in &self.lines {
|
||||
let mut start = 0;
|
||||
let mut used = 0;
|
||||
let mut space = 0;
|
||||
for (i, chunk) in line.iter().enumerate() {
|
||||
if i > start && used + space + chunk.width_cells > width {
|
||||
visit(y, Fragment::Text(&line[start..i], used));
|
||||
y += 1;
|
||||
if y == limit {
|
||||
return y;
|
||||
}
|
||||
start = i;
|
||||
used = 0;
|
||||
space = 0;
|
||||
let mut remaining = line.as_slice();
|
||||
loop {
|
||||
let (end, cells) = fit_visual_line(remaining, width);
|
||||
let (fitted, rest) = remaining.split_at(end);
|
||||
visit(y, Fragment::Text(fitted, cells));
|
||||
y += 1;
|
||||
if y == limit {
|
||||
return y;
|
||||
}
|
||||
used += space + chunk.width_cells;
|
||||
space = usize::from(chunk.trailing_space.is_some());
|
||||
}
|
||||
visit(y, Fragment::Text(&line[start..], used));
|
||||
y += 1;
|
||||
if y == limit {
|
||||
break;
|
||||
if rest.is_empty() {
|
||||
break;
|
||||
}
|
||||
remaining = rest;
|
||||
}
|
||||
}
|
||||
y
|
||||
}
|
||||
}
|
||||
|
||||
/// Fit one screen row, preferring the last word boundary before splitting a code word.
|
||||
fn fit_visual_line(line: &[Chunk], width: usize) -> (usize, usize) {
|
||||
let mut used = 0;
|
||||
let mut space = 0;
|
||||
let mut last_break = None;
|
||||
for (i, chunk) in line.iter().enumerate() {
|
||||
if i > 0 && chunk.prefers_break_before(i) {
|
||||
last_break = Some((i, used));
|
||||
}
|
||||
let next = used + space + chunk.width_at(used + space);
|
||||
if i > 0 && next > width {
|
||||
return last_break.unwrap_or((i, used));
|
||||
}
|
||||
// A whole tab wider than its line paints only the visible spaces.
|
||||
used = if i == 0 && chunk.tab_paint().is_some() {
|
||||
next.min(width)
|
||||
} else {
|
||||
next
|
||||
};
|
||||
space = usize::from(chunk.trailing_space.is_some());
|
||||
}
|
||||
(line.len(), used)
|
||||
}
|
||||
|
||||
pub(super) fn visit_chunks<'a>(
|
||||
chunks: &'a [Chunk],
|
||||
limit: usize,
|
||||
@@ -374,25 +507,34 @@ pub(super) fn visit_chunks<'a>(
|
||||
let mut used = 0;
|
||||
|
||||
for (index, chunk) in chunks.iter().enumerate() {
|
||||
for run in &chunk.runs {
|
||||
let text = &*run.text;
|
||||
let mut bytes = 0;
|
||||
let mut cells = 0;
|
||||
for g in text.graphemes(true) {
|
||||
let w = usize::from(g.cell_width());
|
||||
if used + cells + w > limit {
|
||||
break;
|
||||
}
|
||||
cells += w;
|
||||
bytes += g.len();
|
||||
}
|
||||
if bytes > 0 && (used < limit || bytes == text.len()) {
|
||||
draw(used, &text[..bytes], cells, &run.paint);
|
||||
}
|
||||
used += cells;
|
||||
if bytes < text.len() {
|
||||
if let Some(paint) = chunk.tab_paint() {
|
||||
let cells = chunk.width_at(used).min(limit.saturating_sub(used));
|
||||
if cells == 0 {
|
||||
return used;
|
||||
}
|
||||
draw(used, &TAB_SPACES[..cells], cells, paint);
|
||||
used += cells;
|
||||
} else {
|
||||
for run in &chunk.runs {
|
||||
let text = &*run.text;
|
||||
let mut bytes = 0;
|
||||
let mut cells = 0;
|
||||
for g in text.graphemes(true) {
|
||||
let w = usize::from(g.cell_width());
|
||||
if used + cells + w > limit {
|
||||
break;
|
||||
}
|
||||
cells += w;
|
||||
bytes += g.len();
|
||||
}
|
||||
if bytes > 0 && (used < limit || bytes == text.len()) {
|
||||
draw(used, &text[..bytes], cells, &run.paint);
|
||||
}
|
||||
used += cells;
|
||||
if bytes < text.len() {
|
||||
return used;
|
||||
}
|
||||
}
|
||||
}
|
||||
if index + 1 < chunks.len()
|
||||
&& let Some(paint) = &chunk.trailing_space
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Resolve typed wire colors against the active theme and terminal palette.
|
||||
|
||||
use ratatui::style::Color as TerminalColor;
|
||||
use ratatui::style::Style;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -17,6 +18,7 @@ use syntect::parsing::Scope;
|
||||
pub(super) struct RenderTheme<'a> {
|
||||
theme: &'a Theme,
|
||||
highlighter: OnceCell<Highlighter<'a>>,
|
||||
inline_code: OnceCell<(TerminalColor, TerminalColor)>,
|
||||
resolved: HashMap<Color, TerminalColor>,
|
||||
}
|
||||
|
||||
@@ -25,6 +27,7 @@ impl<'a> RenderTheme<'a> {
|
||||
Self {
|
||||
theme,
|
||||
highlighter: OnceCell::new(),
|
||||
inline_code: OnceCell::new(),
|
||||
resolved: HashMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -39,6 +42,41 @@ impl<'a> RenderTheme<'a> {
|
||||
resolved
|
||||
}
|
||||
|
||||
pub(super) fn inline_code_style(&self, style: Style) -> Style {
|
||||
let &(fg, bg) = self.inline_code.get_or_init(|| {
|
||||
let fg = terminal_color(
|
||||
highlight::foreground_color_for_scopes(
|
||||
self.highlighter(),
|
||||
highlight::INLINE_CODE_SCOPES,
|
||||
),
|
||||
crate::style::accent_color(),
|
||||
);
|
||||
let bg = terminal_color(
|
||||
self.theme
|
||||
.settings
|
||||
.line_highlight
|
||||
// Use the subdued fallback for translucent overlays, retaining
|
||||
// bat’s alpha-zero ANSI palette encoding.
|
||||
.filter(|c| matches!(c.a, 0 | 255))
|
||||
.and_then(highlight::convert_syntect_color),
|
||||
crate::style::user_message_style()
|
||||
.bg
|
||||
.unwrap_or(TerminalColor::Reset),
|
||||
);
|
||||
(fg, bg)
|
||||
});
|
||||
let bg = style.bg.unwrap_or(bg);
|
||||
if style.fg.is_some() {
|
||||
return style.bg(bg);
|
||||
}
|
||||
let fg = crate::style::readable_color_on(fg, Some(bg));
|
||||
// The terminal owns the ANSI palette. Use its default pair for an exact collision.
|
||||
if fg == bg {
|
||||
return style.fg(TerminalColor::Reset).bg(TerminalColor::Reset);
|
||||
}
|
||||
style.fg(fg).bg(bg)
|
||||
}
|
||||
|
||||
// Plain text and literal colors need no TextMate scope matching.
|
||||
fn highlighter(&self) -> &Highlighter<'a> {
|
||||
self.highlighter
|
||||
|
||||
@@ -38,6 +38,253 @@ fn elements_round_trip_and_require_explicit_row_spacing() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_accepts_inline_children_and_counts_them_toward_tree_limits() {
|
||||
let code = |children: Value| json!({"type":"code","children":children});
|
||||
let literal = code(json!(["cargo test"]));
|
||||
for children in [
|
||||
json!([]),
|
||||
json!(["cargo ", null, {"type":"bold","children":[" test"]}]),
|
||||
] {
|
||||
let element = code(children);
|
||||
assert_eq!(
|
||||
serde_json::to_value(parse(element.clone()).unwrap()).unwrap(),
|
||||
element
|
||||
);
|
||||
}
|
||||
assert!(parse(code(json!("cargo test"))).is_err());
|
||||
assert!(parse(json!({"type":"code","props":{},"children":["x"]})).is_err());
|
||||
assert!(parse(code(json!(["x".repeat(MAX_TEXT_BYTES)]))).is_ok());
|
||||
assert!(parse(code(json!(["x".repeat(MAX_TEXT_BYTES + 1)]))).is_err());
|
||||
|
||||
let mut children = vec![literal.clone(); 127];
|
||||
children.push(json!(""));
|
||||
let group = |items: &[Value]| json!({"type":"text","children":items});
|
||||
assert!(parse(group(&children)).is_ok());
|
||||
children.push(json!(""));
|
||||
assert!(parse(group(&children)).is_err());
|
||||
let nested = (0..15).fold(literal, |child, _| group(&[child]));
|
||||
assert!(parse(nested.clone()).is_ok());
|
||||
assert!(parse(group(&[nested])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_code_preserves_literal_spacing_and_wraps_in_the_text_flow() {
|
||||
let node = tree(json!({"type":"text","children":[
|
||||
"run ", {"type":"code","children":["printf '%s'\t`ok`"]}, " now"
|
||||
]}));
|
||||
insta::assert_snapshot!(painted_rows(&node, Size::new(40, 1)).join("\n"), @"run printf '%s' `ok` now");
|
||||
let narrow = tree(json!({"type":"code","children":["foo bar"]}));
|
||||
assert_eq!(narrow.measure(Size::new(5, 2)), Size::new(5, 2));
|
||||
assert_eq!(painted_rows(&narrow, Size::new(5, 2)), ["foo", "bar"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prose_before_code_can_wrap_before_a_preserved_space() {
|
||||
let node = tree(json!({"type":"text","children":[
|
||||
"last run ", {"type":"code","children":[{"type":"bold","children":[" pending"]}]}
|
||||
]}));
|
||||
assert_eq!(
|
||||
painted_rows(&node, Size::new(8, 2)),
|
||||
["last run", " pending"]
|
||||
);
|
||||
assert_eq!(painted_rows(&node, Size::new(17, 1)), ["last run pending"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn punctuation_can_wrap_at_the_start_of_a_code_span() {
|
||||
let node = tree(json!({"type":"text","children":[
|
||||
{"type":"code","children":["ci-#12"]}, "-", {"type":"code","children":["#34567"]}
|
||||
]}));
|
||||
assert_eq!(painted_rows(&node, Size::new(7, 2)), ["ci-#12-", "#34567"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_space_between_sibling_code_spans_can_start_a_line() {
|
||||
let node = tree(json!({"type":"text","children":[
|
||||
{"type":"code","children":["fix-#123"]},
|
||||
{"type":"code","children":[{"type":"bold","children":[" pending"]}]}
|
||||
]}));
|
||||
assert_eq!(
|
||||
painted_rows(&node, Size::new(8, 2)),
|
||||
["fix-#123", " pending"]
|
||||
);
|
||||
let node = tree(json!({"type":"code","children":[
|
||||
{"type":"bold","children":["fix-#123"]},
|
||||
{"type":"bold","children":[" pending"]}
|
||||
]}));
|
||||
assert_eq!(
|
||||
painted_rows(&node, Size::new(8, 3)),
|
||||
["fix-", "#123", "pending"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prose_after_code_keeps_one_separator_until_the_line_wraps() {
|
||||
for suffix in [" b", " \t b"] {
|
||||
let node = tree(json!({"type":"text","children":[
|
||||
{"type":"code","children":["a "]}, suffix
|
||||
]}));
|
||||
assert_eq!(painted_rows(&node, Size::new(4, 2)), ["a b"]);
|
||||
let bounds = Size::new(3, 2);
|
||||
assert_eq!(painted_rows(&node, bounds), ["a", "b"]);
|
||||
assert_eq!(node.measure(bounds), Size::new(2, 2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_code_keeps_spaces_and_wraps_across_styled_arguments() {
|
||||
use ratatui::style::Modifier;
|
||||
|
||||
let code = |children: Value| tree(json!({"type":"code","children":children}));
|
||||
let joined = code(json!(["cargo test"]));
|
||||
let split = code(json!(["cargo ", " test"]));
|
||||
let styled = code(json!(["cargo ", {"type":"bold","children":[" test"]}]));
|
||||
for width in 1..=11 {
|
||||
let bounds = Size::new(width, 11);
|
||||
let expected = painted_rows(&joined, bounds);
|
||||
for node in [&split, &styled] {
|
||||
assert_eq!(node.measure(bounds), joined.measure(bounds));
|
||||
assert_eq!(painted_rows(node, bounds), expected, "width {width}");
|
||||
}
|
||||
}
|
||||
let area = Rect::new(0, 0, 11, 1);
|
||||
insta::assert_snapshot!(painted_rows(&styled, area.as_size()).join("\n"), @"cargo test");
|
||||
let mut buf = Buffer::empty(area);
|
||||
styled.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
|
||||
for x in 0..area.width {
|
||||
assert_eq!(buf[(x, 0)].modifier.contains(Modifier::BOLD), x >= 6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_code_uses_the_subdued_fallback_for_translucent_highlights() {
|
||||
let node = tree(json!({"type":"code","children":["x"]}));
|
||||
let area = Rect::new(0, 0, 1, 1);
|
||||
let background = |highlight: &str| {
|
||||
let mut theme = Theme::default();
|
||||
theme.settings.line_highlight = Some(highlight.parse().unwrap());
|
||||
let mut buf = Buffer::empty(area);
|
||||
node.render(area, &theme, &mut buf, /*plain_style*/ None);
|
||||
buf[(0, 0)].bg
|
||||
};
|
||||
let palette = crate::terminal_probe::DefaultColors {
|
||||
fg: (255, 255, 255),
|
||||
bg: (0, 0, 0),
|
||||
};
|
||||
crate::terminal_palette::with_test_default_colors(palette, || {
|
||||
assert_eq!(
|
||||
background("#ffffff24"),
|
||||
crate::style::user_message_style().bg.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
background("#ffffff"),
|
||||
crate::terminal_palette::rgb_color((255, 255, 255))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapped_code_keeps_a_leading_hyphen_with_the_hash() {
|
||||
let bounds = Size::new(8, 3);
|
||||
for children in [
|
||||
json!(["detached-123456789abcdef"]),
|
||||
json!(["detached-", "123456789abcdef"]),
|
||||
json!(["detached-", {"type":"bold","children":["123456789abcdef"]}]),
|
||||
] {
|
||||
let node = tree(json!({"type":"code","children":children}));
|
||||
assert_eq!(
|
||||
painted_rows(&node, bounds),
|
||||
["detached", "-1234567", "89abcdef"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_code_wraps_at_spaces_then_graphemes_and_expands_tabs_on_each_line() {
|
||||
for (literal, width, expected) in [
|
||||
("a\tb", 10, vec!["a b"]),
|
||||
("a\tb", 4, vec!["a", "", "b"]),
|
||||
("ab cd\tQ", 5, vec!["ab", "cd", "", "Q"]),
|
||||
("abcdefghij", 5, vec!["abcde", "fghij"]),
|
||||
("git --help", 5, vec!["git -", "-help"]),
|
||||
("job-123", 5, vec!["job-", "123"]),
|
||||
("fix issue-#1234", 10, vec!["fix issue-", "#1234"]),
|
||||
("sum = -(value)", 7, vec!["sum = -", "(value)"]),
|
||||
("tmp-*[0-9]", 5, vec!["tmp-*", "[0-9]"]),
|
||||
("foo?bar", 5, vec!["foo?", "bar"]),
|
||||
("ls|sha256sum", 6, vec!["ls|sha", "256sum"]),
|
||||
(r"\\server\share", 8, vec![r"\\server", r"\share"]),
|
||||
("foo/bar", 5, vec!["foo/b", "ar"]),
|
||||
("/usr/lib/bin", 6, vec!["/usr/l", "ib/bin"]),
|
||||
("--help", 4, vec!["--", "help"]),
|
||||
("foo-bar", 5, vec!["foo-", "bar"]),
|
||||
("e\u{301} x", 3, vec!["e\u{301}", "x"]),
|
||||
] {
|
||||
let node = tree(json!({"type":"code","children":[literal]}));
|
||||
assert_eq!(
|
||||
painted_rows(&node, Size::new(width, 4)),
|
||||
expected,
|
||||
"{literal:?}"
|
||||
);
|
||||
}
|
||||
let clipped = tree(json!({"type":"code","children":["abcdefghij"]}));
|
||||
assert_eq!(painted_rows(&clipped, Size::new(5, 1)), ["abcd…"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_code_uses_its_own_foreground_background_and_weight_inside_styled_links() {
|
||||
use ratatui::style::Color;
|
||||
use ratatui::style::Modifier;
|
||||
use syntect::highlighting::StyleModifier;
|
||||
use syntect::highlighting::ThemeItem;
|
||||
|
||||
let href = "https://example.com/check";
|
||||
let node = tree(
|
||||
json!({"type":"row","props":{"gap":1,"background":"blue"},"children":[
|
||||
{"type":"bold","children":[{"type":"link","props":{"href":href},"children":[
|
||||
{"type":"code","children":["\u{1b}[31ma b\u{1b}[0m"]}
|
||||
]}]},
|
||||
{"type":"text","props":{"color":"red","italic":true},"children":[{"type":"code","children":["X"]}]}
|
||||
]}),
|
||||
);
|
||||
let area = Rect::new(0, 0, 6, 1);
|
||||
assert_eq!(
|
||||
painted_rows(&node, area.as_size()),
|
||||
[linked_columns("a b X", 0..4, href)]
|
||||
);
|
||||
let mut theme = Theme::default();
|
||||
theme.settings.line_highlight = Some(syntect::highlighting::Color {
|
||||
r: 3,
|
||||
g: 0,
|
||||
b: 0,
|
||||
a: 0,
|
||||
});
|
||||
theme.scopes.push(ThemeItem {
|
||||
scope: "markup.raw.inline.markdown".parse().unwrap(),
|
||||
style: StyleModifier {
|
||||
foreground: Some(syntect::highlighting::Color {
|
||||
r: 6,
|
||||
g: 0,
|
||||
b: 0,
|
||||
a: 0,
|
||||
}),
|
||||
..StyleModifier::default()
|
||||
},
|
||||
});
|
||||
let mut buf = Buffer::empty(area);
|
||||
node.render(area, &theme, &mut buf, /*plain_style*/ None);
|
||||
for x in 0..4 {
|
||||
let cell = &buf[(x, 0)];
|
||||
assert_eq!((cell.fg, cell.bg), (Color::Cyan, Color::Yellow));
|
||||
assert_eq!(cell.modifier, Modifier::UNDERLINED);
|
||||
}
|
||||
assert_eq!(buf[(4, 0)].bg, Color::Blue);
|
||||
let last = &buf[(5, 0)];
|
||||
assert_eq!((last.fg, last.bg), (Color::Cyan, Color::Yellow));
|
||||
assert_eq!(last.modifier, Modifier::ITALIC);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_gaps_and_elements() {
|
||||
for gap in ["-1", "1.5", "9007199254740992", r#""1""#, "[1]"] {
|
||||
@@ -1120,3 +1367,55 @@ fn nested_row_background_fills_blank_lines_independently_of_siblings() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_code_checks_theme_contrast_on_its_fill() {
|
||||
use ratatui::style::Color;
|
||||
use syntect::highlighting::StyleModifier;
|
||||
use syntect::highlighting::ThemeItem;
|
||||
|
||||
let node = tree(json!({"type":"code","children":["X"]}));
|
||||
let area = Rect::new(0, 0, 1, 1);
|
||||
let colors = |color: &str| {
|
||||
let color = Some(color.parse().unwrap());
|
||||
let mut theme = Theme::default();
|
||||
theme.settings.line_highlight = color;
|
||||
theme.scopes.push(ThemeItem {
|
||||
scope: "markup.raw.inline.markdown".parse().unwrap(),
|
||||
style: StyleModifier {
|
||||
foreground: color,
|
||||
..Default::default()
|
||||
},
|
||||
});
|
||||
let mut buf = Buffer::empty(area);
|
||||
node.render(area, &theme, &mut buf, /*plain_style*/ None);
|
||||
(buf[(0, 0)].fg, buf[(0, 0)].bg)
|
||||
};
|
||||
let palette = crate::terminal_probe::DefaultColors {
|
||||
fg: (255, 255, 255),
|
||||
bg: (0, 0, 0),
|
||||
};
|
||||
crate::terminal_palette::with_test_default_colors(palette, || {
|
||||
let white = crate::terminal_palette::rgb_color((255, 255, 255));
|
||||
assert_eq!(
|
||||
colors("#ffffff"),
|
||||
(crate::style::readable_color_on(white, Some(white)), white)
|
||||
);
|
||||
assert_eq!(colors("#03000000"), (Color::Reset, Color::Reset));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipped_code_tab_styles_the_marker_only_when_it_paints_cells() {
|
||||
let node = tree(json!({"type":"row","props":{"gap":0},"children":[
|
||||
{"type":"bold","children":["abc"]},{"type":"code","children":["\t"]}
|
||||
]}));
|
||||
for width in [4, 5] {
|
||||
let area = Rect::new(0, 0, width, 1);
|
||||
let mut buf = Buffer::empty(area);
|
||||
node.render(area, &Theme::default(), &mut buf, /*plain_style*/ None);
|
||||
let marker = &buf[(width - 1, 0)];
|
||||
assert_eq!(marker.symbol(), "…");
|
||||
assert_eq!(marker.style(), buf[(width - 2, 0)].style());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type {
|
||||
CodeElement,
|
||||
ColElement,
|
||||
Color,
|
||||
RowElement,
|
||||
@@ -43,6 +44,13 @@ export function render(state: StatuslineState): UiTree {
|
||||
return { type: "row", props: { gap: 1, wrap: "wrap", justify: "between" }, children };
|
||||
}
|
||||
|
||||
const command: CodeElement = {
|
||||
type: "code",
|
||||
children: ["cargo ", null, { type: "bold", children: [" test"] }],
|
||||
};
|
||||
// @ts-expect-error Code requires a child list.
|
||||
const invalidCode: CodeElement = { type: "code", children: "cargo test" };
|
||||
|
||||
// @ts-expect-error The snapshot emits the canonical ID even when config used an alias.
|
||||
const alias: StatuslineItemId = "project-root";
|
||||
// @ts-expect-error Row props require a gap in terminal columns.
|
||||
@@ -50,7 +58,7 @@ const missingGap: RowElement = { type: "row", props: {}, children: [] };
|
||||
const twoLines: ColElement = {
|
||||
type: "col",
|
||||
props: { gap: 0 },
|
||||
children: [{ type: "text", children: ["model main"] }, { type: "text", children: ["75%"] }],
|
||||
children: [command, { type: "text", children: ["75%"] }],
|
||||
};
|
||||
// @ts-expect-error Column props require a gap in terminal rows.
|
||||
const missingColGap: ColElement = { type: "col", props: {}, children: [] };
|
||||
|
||||
Reference in New Issue
Block a user