use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use std::process::{Child, Command, Stdio};
use std::time::Instant;
use crossterm::style::Color;
use serde_json::{json, Value};
use crate::highlight::{self, LineState};
use crate::screen::{fit, widen, Decoration, Row, Span, Style, WIDE_PAD};
use crate::snippets::Language;
#[cfg(test)]
mod tests;
const WRITING_TOOLS: &str = "Edit,Write,NotebookEdit,Bash";
const STEP_CHARS: usize = 70;
pub struct Request<'a> {
pub prompt: &'a str,
pub session: Option<&'a str>,
pub can_edit: bool,
pub can_run: bool,
pub context: &'a str,
pub model: Option<&'a str>,
}
pub fn command_line(setting: Option<&str>, request: &Request) -> Option<Vec<String>> {
let program = match setting.map(str::trim) {
Some("off") => return None,
Some(custom) if !custom.is_empty() => custom,
_ => "claude",
};
let mut words: Vec<String> = program.split_whitespace().map(String::from).collect();
let mut add = |extra: &[&str]| words.extend(extra.iter().map(|word| word.to_string()));
add(&["--print", request.prompt]);
add(&["--output-format", "stream-json", "--verbose", "--include-partial-messages"]);
if let Some(session) = request.session {
add(&["--resume", session]);
}
if let Some(model) = request.model {
add(&["--model", model]);
}
if request.can_edit {
add(&["--permission-mode", "acceptEdits"]);
if request.can_run {
add(&["--allowedTools", "Bash"]);
}
} else {
add(&["--disallowedTools", WRITING_TOOLS]);
}
if !request.context.is_empty() {
add(&["--append-system-prompt", request.context]);
}
Some(words)
}
pub fn start(
words: &[String],
dir: &Path,
forward: impl Fn(Option<String>) + Send + Clone + 'static,
) -> std::io::Result<Child> {
let mut child = Command::new(&words[0])
.args(&words[1..])
.current_dir(dir)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
if let Some(errors) = child.stderr.take() {
let forward = forward.clone();
std::thread::spawn(move || {
for line in BufReader::new(errors).lines().map_while(Result::ok) {
forward(Some(json!({"type": "stderr", "text": line}).to_string()));
}
});
}
if let Some(output) = child.stdout.take() {
std::thread::spawn(move || {
for line in BufReader::new(output).lines().map_while(Result::ok) {
forward(Some(line));
}
forward(None);
});
}
Ok(child)
}
#[derive(Debug, PartialEq)]
pub enum Update {
Session(String),
Model(String),
Partial(String),
Text(String),
Step(String),
Problem(String),
Done,
Failed(String),
}
pub fn parse(line: &str) -> Vec<Update> {
let Ok(message) = serde_json::from_str::<Value>(line) else {
return Vec::new();
};
let text = |value: &Value| value.as_str().unwrap_or_default().to_string();
let mut updates = Vec::new();
if let Some(session) = message["session_id"].as_str() {
updates.push(Update::Session(session.to_string()));
}
match message["type"].as_str() {
Some("system") => {
if let Some(model) = message["model"].as_str() {
updates.push(Update::Model(model.to_string()));
}
}
Some("assistant") => {
for block in message["message"]["content"].as_array().into_iter().flatten() {
match block["type"].as_str() {
Some("text") if !text(&block["text"]).trim().is_empty() => {
updates.push(Update::Text(text(&block["text"]).trim().to_string()));
}
Some("tool_use") => updates.push(Update::Step(step(block))),
_ => {}
}
}
}
Some("result") => {
let failed = message["is_error"].as_bool().unwrap_or(false)
|| message["subtype"].as_str().is_some_and(|kind| kind != "success");
updates.push(if failed {
let why = text(&message["result"]);
Update::Failed(if why.is_empty() { text(&message["subtype"]) } else { why })
} else {
Update::Done
});
}
Some("stream_event") => {
let delta = &message["event"]["delta"];
if delta["type"].as_str() == Some("text_delta") {
updates.push(Update::Partial(text(&delta["text"])));
}
}
Some("stderr") => updates.push(Update::Problem(text(&message["text"]))),
_ => {}
}
updates
}
fn step(block: &Value) -> String {
let name = block["name"].as_str().unwrap_or("tool");
let input = &block["input"];
let on = ["file_path", "path", "pattern", "command", "query", "url", "description"]
.iter()
.find_map(|key| input[*key].as_str())
.unwrap_or_default();
let on = on.lines().next().unwrap_or_default();
format!("{name} {on}").trim_end().to_string()
}
pub fn shorten(step: &str, root: &Path) -> String {
let root = format!("{}/", root.display());
step.replace(&root, "").chars().take(STEP_CHARS).collect()
}
const MAX_SESSIONS: usize = 50;
const TITLE_LINES: usize = 400;
#[derive(Debug, PartialEq)]
pub struct SessionInfo {
pub id: String,
pub title: String,
pub modified: SystemTime,
}
pub fn sessions_dir(home: &Path, root: &Path) -> PathBuf {
let name: String = root
.to_string_lossy()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
home.join(".claude").join("projects").join(name)
}
fn transcript_line(line: &str) -> Vec<(Who, String)> {
let Ok(message) = serde_json::from_str::<Value>(line) else {
return Vec::new();
};
if message["isMeta"].as_bool() == Some(true) || message["isSidechain"].as_bool() == Some(true) {
return Vec::new();
}
let content = &message["message"]["content"];
let mut entries = Vec::new();
let mut said = |who: Who, text: &str| {
let text = text.trim();
if !text.is_empty() && !text.starts_with('<') {
entries.push((who, text.to_string()));
}
};
match message["type"].as_str() {
Some("user") => match content.as_str() {
Some(text) => said(Who::You, text),
None => {
for block in content.as_array().into_iter().flatten() {
if block["type"].as_str() == Some("text") {
said(Who::You, block["text"].as_str().unwrap_or_default());
}
}
}
},
Some("assistant") => {
for block in content.as_array().into_iter().flatten() {
match block["type"].as_str() {
Some("text") => said(Who::Claude, block["text"].as_str().unwrap_or_default()),
Some("tool_use") => said(Who::Note, &step(block)),
_ => {}
}
}
}
_ => {}
}
entries
}
pub fn list_sessions(dir: &Path) -> Vec<SessionInfo> {
let mut sessions: Vec<SessionInfo> = std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.filter_map(|item| {
let path = item.path();
let id = path.file_stem()?.to_str()?.to_string();
if path.extension()?.to_str()? != "jsonl" {
return None;
}
let modified = item.metadata().ok()?.modified().ok()?;
let lines = BufReader::new(std::fs::File::open(&path).ok()?).lines();
let title = lines
.map_while(Result::ok)
.take(TITLE_LINES)
.flat_map(|line| transcript_line(&line))
.find(|(who, _)| *who == Who::You)?
.1;
let title = title.lines().next().unwrap_or_default().to_string();
Some(SessionInfo { id, title, modified })
})
.collect();
sessions.sort_by_key(|session| std::cmp::Reverse(session.modified));
sessions.truncate(MAX_SESSIONS);
sessions
}
pub fn load_session(dir: &Path, id: &str) -> Vec<(Who, String)> {
let Ok(file) = std::fs::File::open(dir.join(format!("{id}.jsonl"))) else {
return Vec::new();
};
BufReader::new(file)
.lines()
.map_while(Result::ok)
.flat_map(|line| transcript_line(&line))
.collect()
}
pub fn age(then: SystemTime, now: SystemTime) -> String {
let minutes = now.duration_since(then).map_or(0, |passed| passed.as_secs() / 60);
match minutes {
0 => "now".into(),
1..60 => format!("{minutes}m"),
60..1440 => format!("{}h", minutes / 60),
_ => format!("{}d", minutes / 1440),
}
}
const MAX_KEPT_BYTES: u64 = 512 * 1024;
const MAX_SNAPSHOT_BYTES: u64 = 32 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ChangeKind {
Created,
Modified,
Deleted,
}
#[derive(Debug, PartialEq)]
pub struct Change {
pub file: String,
pub kind: ChangeKind,
}
struct Before {
len: u64,
modified: Option<SystemTime>,
content: Option<Vec<u8>>,
}
pub struct Snapshot {
root: PathBuf,
files: HashMap<String, Before>,
}
impl Snapshot {
pub fn take(root: &Path, files: &[String]) -> Self {
let mut kept = 0;
let mut before = HashMap::new();
for file in files {
let path = root.join(file);
let Ok(data) = std::fs::metadata(&path) else {
continue;
};
let fits = data.len() <= MAX_KEPT_BYTES && kept + data.len() <= MAX_SNAPSHOT_BYTES;
let content = fits.then(|| std::fs::read(&path).ok()).flatten();
kept += content.as_ref().map_or(0, |content| content.len() as u64);
before.insert(
file.clone(),
Before {
len: data.len(),
modified: data.modified().ok(),
content,
},
);
}
Self {
root: root.to_path_buf(),
files: before,
}
}
pub fn changes(&self, files: &[String]) -> Vec<Change> {
let mut changes = Vec::new();
for file in files {
let path = self.root.join(file);
let kind = match self.files.get(file) {
None if !path.exists() => continue,
None => ChangeKind::Created,
Some(before) => {
let same = match (&before.content, std::fs::metadata(&path)) {
(Some(content), Ok(_)) => std::fs::read(&path).is_ok_and(|now| now == *content),
(None, Ok(data)) => {
data.len() == before.len && data.modified().ok() == before.modified
}
(_, Err(_)) => true,
};
if same {
continue;
}
ChangeKind::Modified
}
};
changes.push(Change { file: file.clone(), kind });
}
for file in self.files.keys() {
if !self.root.join(file).exists() {
changes.push(Change { file: file.clone(), kind: ChangeKind::Deleted });
}
}
changes.sort_by(|a, b| a.file.cmp(&b.file));
changes
}
pub fn restore(&self, changes: &[Change]) -> (usize, usize) {
let (mut restored, mut failed) = (0, 0);
for change in changes {
let path = self.root.join(&change.file);
let done = match (change.kind, self.files.get(&change.file)) {
(ChangeKind::Created, _) => std::fs::remove_file(&path).is_ok(),
(_, Some(Before { content: Some(content), .. })) => {
let folder = path.parent().unwrap_or(&self.root);
std::fs::create_dir_all(folder).is_ok() && std::fs::write(&path, content).is_ok()
}
_ => false,
};
if done {
restored += 1;
} else {
failed += 1;
}
}
(restored, failed)
}
}
pub fn describe(changes: &[Change]) -> String {
let names: Vec<String> = changes
.iter()
.map(|change| match change.kind {
ChangeKind::Created => format!("new {}", change.file),
ChangeKind::Modified => change.file.clone(),
ChangeKind::Deleted => format!("deleted {}", change.file),
})
.collect();
let files = if changes.len() == 1 { "file" } else { "files" };
format!("Changed {} {files}: {}", changes.len(), names.join(", "))
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Who {
You,
Claude,
Note,
}
#[derive(Default)]
pub struct Panel {
pub entries: Vec<(Who, String)>,
pub input: String,
cursor: usize,
history: Vec<String>,
history_at: Option<usize>,
pub session: Option<String>,
pub model: Option<String>,
pub answered_by: Option<String>,
pub attached: Vec<String>,
pub can_edit: bool,
pub can_run: bool,
pub running: bool,
started: Option<Instant>,
partial: bool,
scroll: usize,
}
const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
const MAX_INPUT_ROWS: usize = 5;
const HINTS: [&str; 6] = [
"Ask about this project and press Enter. Alt+Enter starts a new line.",
"Type / for commands (model, new conversation, ...) and @ to attach a file.",
"Text selected in the file is sent along with the question.",
"Claude may change files. Alt+M: read only, or also run commands. Alt+U undoes.",
"Ctrl+R lists the earlier conversations. Ctrl+N starts a new one.",
"Esc goes back to the text. Alt+Z makes this panel bigger.",
];
impl Panel {
pub fn new() -> Self {
Self {
can_edit: true,
..Self::default()
}
}
pub fn say(&mut self, who: Who, text: impl Into<String>) {
self.entries.push((who, text.into()));
self.partial = false;
self.scroll = 0;
}
pub fn start(&mut self) {
self.running = true;
self.started = Some(Instant::now());
}
pub fn apply(&mut self, update: Update) -> bool {
match update {
Update::Session(session) => self.session = Some(session),
Update::Model(model) => self.answered_by = Some(model),
Update::Partial(words) => match self.entries.last_mut() {
Some((Who::Claude, text)) if self.partial => text.push_str(&words),
_ => {
self.say(Who::Claude, words);
self.partial = true;
}
},
Update::Text(text) => {
if self.partial {
self.entries.pop();
}
self.say(Who::Claude, text);
}
Update::Step(step) => self.say(Who::Note, step),
Update::Problem(problem) => self.say(Who::Note, problem),
Update::Done => self.running = false,
Update::Failed(why) => {
self.running = false;
self.say(Who::Note, format!("Stopped: {why}"));
}
}
!self.running
}
pub fn next_mode(&mut self) {
(self.can_edit, self.can_run) = match (self.can_edit, self.can_run) {
(true, false) => (false, false),
(false, _) => (true, true),
(true, true) => (true, false),
};
}
pub fn resume(&mut self, id: String, entries: Vec<(Who, String)>) {
self.entries = entries;
self.session = Some(id);
self.partial = false;
self.scroll = 0;
}
pub fn clear(&mut self) {
self.entries.clear();
self.session = None;
self.scroll = 0;
}
pub fn last_answer(&self) -> Option<&str> {
self.entries
.iter()
.rev()
.find(|(who, _)| *who == Who::Claude)
.map(|(_, text)| text.as_str())
}
pub fn scroll_by(&mut self, rows: isize) {
self.scroll = (self.scroll as isize + rows).max(0) as usize;
}
fn byte(&self, at: usize) -> usize {
self.input.char_indices().nth(at).map_or(self.input.len(), |(byte, _)| byte)
}
pub fn type_char(&mut self, c: char) {
let at = self.byte(self.cursor);
self.input.insert(at, c);
self.cursor += 1;
}
pub fn backspace(&mut self) {
if self.cursor > 0 {
self.cursor -= 1;
self.delete();
} else if self.input.is_empty() {
self.attached.pop();
}
}
pub fn attach(&mut self, file: String) {
if !self.attached.contains(&file) {
self.attached.push(file);
}
}
pub fn set_input(&mut self, text: &str) {
self.input = text.to_string();
self.cursor = self.input.chars().count();
}
fn input_rows(&self, room: usize) -> (Vec<String>, (usize, usize)) {
let mut rows = vec![String::new()];
let mut used = 0;
let mut cursor = (0, 0);
for (index, c) in self.input.chars().chain(std::iter::once('\0')).enumerate() {
use unicode_width::UnicodeWidthChar;
let cells = c.width().unwrap_or(0);
if used + cells.max(1) > room && c != '\n' {
rows.push(String::new());
used = 0;
}
if index == self.cursor {
cursor = (rows.len() - 1, used);
}
match c {
'\n' => {
rows.push(String::new());
used = 0;
}
c if cells > 0 => {
let row = rows.last_mut().unwrap();
row.push(c);
if cells == 2 {
row.push(WIDE_PAD);
}
used += cells;
}
_ => {}
}
}
(rows, cursor)
}
pub fn box_rows(&self, width: usize, height: usize) -> usize {
let room = width.saturating_sub(3).max(1);
let most = MAX_INPUT_ROWS.min(height.saturating_sub(3)).max(1);
self.input_rows(room).0.len().min(most) + (height >= 5) as usize
}
fn status(&self) -> String {
let model = match (&self.model, &self.answered_by) {
(Some(model), _) => model.clone(),
(None, Some(answered)) => answered.clone(),
(None, None) => "default model".into(),
};
let files: String = self.attached.iter().map(|file| format!(" @{file}")).collect();
format!(" {model}{files}")
}
pub fn delete(&mut self) {
let at = self.byte(self.cursor);
if at < self.input.len() {
self.input.remove(at);
}
}
pub fn move_cursor(&mut self, step: isize) {
let end = self.input.chars().count() as isize;
self.cursor = (self.cursor as isize).saturating_add(step).clamp(0, end) as usize;
}
pub fn recall(&mut self, step: isize) {
let count = self.history.len() as isize;
let at = self.history_at.map_or(count, |at| at as isize) + step;
if at < 0 || count == 0 {
return;
}
self.history_at = (at < count).then_some(at as usize);
self.input = self.history_at.map(|at| self.history[at].clone()).unwrap_or_default();
self.cursor = self.input.chars().count();
}
pub fn take_input(&mut self) -> Option<String> {
let question = self.input.trim().to_string();
if question.is_empty() {
return None;
}
self.input.clear();
self.cursor = 0;
self.history_at = None;
if self.history.last() != Some(&question) {
self.history.push(question.clone());
}
Some(question)
}
fn lines(&self, width: usize) -> Vec<Row> {
let mut lines: Vec<Row> = Vec::new();
let plain = |style: Style, text: String| vec![Span::new(style, fit(&text, width))];
for (who, text) in &self.entries {
if *who == Who::You && !lines.is_empty() {
lines.push(plain(Style::Plain, String::new()));
}
let (style, first, rest) = match who {
Who::You => (Style::Accent, "> ", " "),
Who::Note => (Style::Dim, "· ", " "),
Who::Claude => {
lines.extend(markdown(text, width));
continue;
}
};
for (index, line) in wrap(&widen(text), width.saturating_sub(2)).into_iter().enumerate() {
let prefix = if index == 0 { first } else { rest };
lines.push(plain(style, format!("{prefix}{line}")));
}
}
lines
}
pub fn render(&mut self, width: usize, height: usize, focused: bool) -> (Vec<Row>, (usize, usize)) {
let state = if self.running {
let waited = self.started.map_or(0, |started| started.elapsed().as_millis());
let spinner = SPINNER[(waited / 120) as usize % SPINNER.len()];
format!("{spinner} working {}s (Esc stops it)", waited / 1000)
} else if self.can_edit && self.can_run {
"may change files and run commands (Alt+M)".into()
} else if self.can_edit {
"may change files (Alt+M: read only)".into()
} else {
"read only (Alt+M: also run commands)".into()
};
let title_style = if focused { Style::Title } else { Style::Menu };
let mut rows = vec![vec![Span::new(title_style, fit(&format!(" Claude · {state}"), width))]];
let room = width.saturating_sub(3).max(1);
let (question, (cursor_row, cursor_x)) = self.input_rows(room);
let most = MAX_INPUT_ROWS.min(height.saturating_sub(3)).max(1);
let from = (cursor_row + 1).saturating_sub(most);
let question: Vec<&String> = question.iter().skip(from).take(most).collect();
let status = (height >= 5) as usize;
let body = height.saturating_sub(1 + status + question.len());
let lines = self.lines(width);
self.scroll = self.scroll.min(lines.len().saturating_sub(body));
let first = lines.len().saturating_sub(body + self.scroll);
let mut shown: Vec<Row> = lines.into_iter().skip(first).take(body).collect();
if shown.is_empty() {
let hints = HINTS.iter().take(body);
shown.extend(hints.map(|hint| vec![Span::new(Style::Dim, fit(hint, width))]));
}
shown.resize(body, vec![Span::new(Style::Plain, fit("", width))]);
rows.extend(shown);
if status > 0 {
rows.push(vec![Span::new(Style::FieldNote, fit(&self.status(), width))]);
}
let first_row = rows.len();
for (index, row) in question.iter().enumerate() {
let mark = if index + from == 0 { "> " } else { " " };
rows.push(vec![Span::new(Style::Field, fit(&format!("{mark}{row}"), width))]);
}
rows.truncate(height);
let cursor = (2 + cursor_x, (first_row + cursor_row - from).min(height.saturating_sub(1)));
(rows, cursor)
}
}
pub fn own_commands(home: &Path, root: &Path) -> Vec<String> {
let mut names = Vec::new();
for base in [root.join(".claude"), home.join(".claude")] {
for (folder, wants_dir) in [("commands", false), ("skills", true)] {
for item in std::fs::read_dir(base.join(folder)).into_iter().flatten().flatten() {
let path = item.path();
let is_command = !wants_dir && path.extension().is_some_and(|ext| ext == "md");
let is_skill = wants_dir && path.is_dir();
if let (true, Some(name)) = (is_command || is_skill, path.file_stem()) {
names.push(name.to_string_lossy().into_owned());
}
}
}
}
names.sort();
names.dedup();
names
}
pub fn wrap(text: &str, width: usize) -> Vec<String> {
let mut lines = Vec::new();
for line in text.split('\n') {
let chars: Vec<(char, Style)> = line.chars().map(|c| (c, Style::Plain)).collect();
let pieces = wrap_chars(&chars, width);
lines.extend(pieces.iter().map(|piece| piece.iter().map(|(c, _)| *c).collect()));
}
lines
}
fn wrap_chars(chars: &[(char, Style)], width: usize) -> Vec<&[(char, Style)]> {
let width = width.max(1);
let mut pieces = Vec::new();
let mut start = 0;
while chars.len() - start > width {
let limit = start + width;
let cut = (start + 1..=limit).rev().find(|at| chars[*at].0 == ' ').unwrap_or(limit);
pieces.push(&chars[start..cut]);
start = cut + (chars[cut].0 == ' ') as usize;
}
pieces.push(&chars[start..]);
pieces
}
fn row_of(prefix: Option<Span>, chars: &[(char, Style)], width: usize) -> Row {
let mut row: Row = prefix.into_iter().collect();
let mut used: usize = row.iter().map(|span| span.text.chars().count()).sum();
for (c, style) in chars {
match row.last_mut() {
Some(last) if last.style == *style => last.text.push(*c),
_ => row.push(Span::new(*style, c.to_string())),
}
}
used += chars.len();
row.push(Span::new(Style::Plain, " ".repeat(width.saturating_sub(used))));
row
}
fn fence_language(tag: &str) -> Option<Language> {
let extension = match tag.trim().to_ascii_lowercase().as_str() {
"rust" => "rs".into(),
"python" => "py".into(),
"javascript" | "typescript" => "js".into(),
"c++" => "cpp".into(),
"golang" => "go".into(),
other => other.to_string(),
};
Language::from_path(&format!("code.{extension}"))
}
fn inline(text: &str, base: Style) -> Vec<(char, Style)> {
let code = Style::Colored(Color::Cyan);
let chars: Vec<char> = text.chars().collect();
let (mut in_code, mut bold) = (false, false);
let mut styled = Vec::new();
let mut i = 0;
while i < chars.len() {
match chars[i] {
'`' => in_code = !in_code,
'*' if !in_code && chars.get(i + 1) == Some(&'*') => {
bold = !bold;
i += 1;
}
c if in_code => styled.push((c, code)),
c if bold => styled.push((c, Style::Bold)),
c => styled.push((c, base)),
}
i += 1;
}
styled
}
pub fn markdown(text: &str, width: usize) -> Vec<Row> {
let mut rows = Vec::new();
let mut code: Option<(Option<Language>, LineState)> = None;
for line in text.split('\n') {
let line = &widen(line);
if let Some(tag) = line.trim_start().strip_prefix("```") {
code = match code {
Some(_) => None,
None => Some((fence_language(tag), LineState::Code)),
};
continue;
}
let Some((language, state)) = &mut code else {
let trimmed = line.trim_start();
let indent = &line[..line.len() - trimmed.len()];
let heading = trimmed.trim_start_matches('#');
let chars = if heading.len() < trimmed.len() && heading.starts_with(' ') {
inline(heading.trim_start(), Style::Bold)
} else if let Some(item) = trimmed.strip_prefix("- ").or(trimmed.strip_prefix("* ")) {
inline(&format!("{indent}• {item}"), Style::Plain)
} else {
inline(line, Style::Plain)
};
for piece in wrap_chars(&chars, width) {
rows.push(row_of(None, piece, width));
}
continue;
};
let mut chars: Vec<(char, Style)> = line.chars().map(|c| (c, Style::Plain)).collect();
if let Some(language) = language {
let mut tokens = Vec::new();
*state = highlight::lex_line(line, *language, *state, &mut tokens);
for token in tokens {
let decoration = Decoration { kind: token.kind, ..Decoration::default() };
let end = token.end.min(chars.len());
for (_, style) in &mut chars[token.start.min(end)..end] {
*style = Style::Code(decoration);
}
}
}
for piece in wrap_chars(&chars, width.saturating_sub(2)) {
rows.push(row_of(Some(Span::new(Style::Dim, "│ ")), piece, width));
}
}
rows
}