use nachalnik::{ContextKind, ContextState, Kernel, State, Verdict};
use ratatui::{
Frame,
layout::{Constraint, Layout, Rect},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{
Block, Clear, List, ListItem, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
},
};
use tui_markdown::StyleSheet as _;
use unicode_segmentation::UnicodeSegmentation as _;
use crate::app::{App, Focus, Overlay, Speaker, Tab};
pub const HELP: &str = " THE TABS
ctrl+t the next one
alt+1 / 2 / 3 / 4 chat / context / trace / permissions
tab move between the prompt and the tab, on the last three
ANYWHERE
ctrl+p the exact request that would be sent next
f1 this; also ? on a tab that has the focus
esc close this, or stop what is running
ctrl+c stop what is running; again to leave
ctrl+d leave
THE PROMPT, which is under every tab
enter send
alt+enter a new line
pgup / pgdn scroll the conversation
(a message sent while a turn is running waits for the end of it, and
then gets a turn of its own)
THE CONTEXT TAB, when it has the focus
up / down, j / k pick an item
pgup / pgdn a screenful at a time
g / G the first item / the last
23G the item numbered 23
space cycle how much of it the model gets: all of it, then
a … marker where it was, then nothing, then all of it
p pin it, so that compaction cannot touch it
(on a ▫ archived row, either of those sends the whole
of an output the model was shown a shortened copy of)
e change what it says; the old one stays, marked ~
enter read the whole of what it says
u / U undo / redo the last change to the context
THE TRACE TAB, when it has the focus
up / down, j / k read back through it
pgup / pgdn a screenful at a time
g / G the oldest it still holds / the newest
THE PERMISSIONS TAB, when it has the focus
up / down, j / k pick a capability, or one of the path rules under them
g / G the first / the last
space cycle it: ask, then allow, then deny
a / n / r allow it / never allow it / ask about it again
(backspace does what r does)
(the line along the bottom says what a shell command can reach, and how
many subjects are not listed here because nobody has answered about them)
A TOOL IS WAITING TO RUN
y / n once / no
esc no
a always, for everything the question names - and for
the calls already waiting behind it
i the exact JSON, and the tool's own definition
d drop every call it is waiting on, and tell it why
(a question that arrives while you are typing waits for you to stop:
until then your keys go to the prompt, where you aimed them)
COMMANDS
/help this; also /?
/step [MESSAGE] one transition of the state machine, and stop
/continue run the rest of the turn
/request the request that would go next
/payload the provider's own rendering of it, byte for byte
/raw the provider's own last answer
/prune SELECTOR take items out; with no selector, the whole language
/keep SELECTOR pin them
/restore SELECTOR put them back
/budget the estimate, what the last request really cost, and the
correction the counter has worked out from the difference
/seams what is plugged into each of the runtime's six parts
/tools what the model is offered
/tools drop ID stop offering one of them, from now on
/introspect offer the model the two tools that read and manage its own
context, or stop offering them
/policy open the permissions tab; also /permissions
/model [ID] show or switch the model, and say where it is
/models [FILTER] what this endpoint serves, which is what /model takes
/provider [URL [ID]] show or switch the address the requests go to, and
the model with it; also /endpoint. The key is the one
this started with
/params [KEY JSON] show or set a model parameter
/save [PATH] the session log, and a snapshot to resume from
/quit also /exit, /q";
pub(crate) const SELECTORS: &str = " 17 the item with that number
all every item, whatever state it is in
tool_results every item from that source; also: files, diagnostics,
selections, memories, instructions, system, user, model,
compaction
all:tool_results the same, spelled out
source:helix every item from a source with that name
kind:assistant_message every item of that kind
state:excluded every item in that state
file:src/parser.rs the file with that path
tool:grep every result the `grep` tool produced
tool:grep:latest the most recent one; also: tool:grep:first
tool_result:1842 the tool result with that call id
label:cargo test every item with exactly that label
src/parser.rs anything else is taken as a label
What it matched is reported before anything is sent, and every change is one
`u` away from being undone.";
pub fn wrapped_rows(lines: &[String], width: usize) -> usize {
if width == 0 {
return lines.len().max(1);
}
lines
.iter()
.map(|line| rows_for(line, width))
.sum::<usize>()
.max(1)
}
fn rows_for(line: &str, width: usize) -> usize {
let mut closed = 0;
let mut filled = 0;
let mut started = false;
for (_, text) in line.split_word_bound_indices() {
let mut chunk = text;
while !chunk.is_empty() {
let chunk_width = Span::raw(chunk).width();
if filled + chunk_width <= width {
filled += chunk_width;
started = true;
break;
}
if started {
closed += 1;
filled = 0;
started = false;
continue;
}
let take = prefix_within(chunk, width);
closed += 1;
chunk = &chunk[take..];
filled = 0;
}
}
closed + usize::from(started || closed == 0)
}
fn prefix_within(text: &str, width: usize) -> usize {
let mut end = 0;
let mut filled = 0;
for (offset, grapheme) in text.grapheme_indices(true) {
let next = filled + Span::raw(grapheme).width();
if end != 0 && next > width {
break;
}
end = offset + grapheme.len();
filled = next;
if filled >= width {
break;
}
}
end.max(text.chars().next().map_or(1, char::len_utf8))
.min(text.len())
}
pub fn draw(frame: &mut Frame, app: &mut App) {
let most = match app.editing.is_some() {
true => 16,
false => 8,
};
let inner = frame.area().width.saturating_sub(2) as usize;
let input_height = (wrapped_rows(app.input.lines(), inner) as u16).clamp(1, most) + 2;
let [body, input, status] = Layout::vertical([
Constraint::Min(3),
Constraint::Length(input_height),
Constraint::Length(1),
])
.areas(frame.area());
draw_body(frame, app, body);
draw_input(frame, app, input);
draw_status(frame, app, status);
if let Some(overlay) = &app.overlay {
draw_overlay(frame, overlay, app);
}
}
fn quiet() -> Style {
Style::default().fg(Color::Gray)
}
fn faint() -> Style {
Style::default().fg(Color::DarkGray)
}
fn draw_body(frame: &mut Frame, app: &mut App, area: Rect) {
let focused = app.focus == Focus::Body;
let mut strip = Vec::new();
for tab in Tab::ALL {
if !strip.is_empty() {
strip.push(Span::styled("│", faint()));
}
strip.push(Span::styled(
format!(" {} ", tab.name()),
match tab == app.tab {
true => Style::default().fg(Color::Yellow).bold(),
false => quiet(),
},
));
}
let edge = match focused {
true => Style::default().fg(Color::Yellow),
false => faint(),
};
let block = Block::bordered()
.title(Line::from(strip))
.title_bottom(Line::styled(footer(app), quiet()).right_aligned())
.border_style(edge);
let inner = block.inner(area);
frame.render_widget(block, area);
let scrolled = match app.tab {
Tab::Chat => draw_chat(frame, app, inner),
Tab::Context => draw_context(frame, app, inner),
Tab::Trace => draw_trace(frame, app, inner),
Tab::Permissions => draw_permissions(frame, app, inner),
};
scrollbar(frame, area, edge, scrolled);
}
#[derive(Clone, Copy, Default)]
struct Scrolled {
position: usize,
total: usize,
area: Rect,
}
fn scrollbar(frame: &mut Frame, window: Rect, border: Style, scrolled: Scrolled) {
let viewport = scrolled.area.height as usize;
if viewport == 0 || scrolled.total <= viewport {
return;
}
let bar = Rect {
x: window.right().saturating_sub(1),
y: scrolled.area.y,
width: 1,
height: scrolled.area.height,
};
let mut state = ScrollbarState::new(scrolled.total - viewport + 1)
.position(scrolled.position)
.viewport_content_length(viewport);
frame.render_stateful_widget(
Scrollbar::new(ScrollbarOrientation::VerticalRight)
.begin_symbol(None)
.end_symbol(None)
.track_symbol(Some("│"))
.track_style(border)
.thumb_symbol("█")
.thumb_style(border),
bar,
&mut state,
);
}
fn footer(app: &App) -> String {
match app.tab {
Tab::Chat => match app.busy {
true => " esc stops it ".to_owned(),
false => " alt+1 chat · alt+2 context · alt+3 trace · alt+4 permissions ".to_owned(),
},
Tab::Context => {
let items = app.kernel.items();
let out = items
.iter()
.filter(|item| !item.state.sends_content())
.count();
let elided = items.iter().filter(|item| item.state.is_elided()).count();
match (out, elided) {
(0, _) => format!(" {} items, all of them going ", items.len()),
(n, 0) => format!(" {} items, {n} not going ", items.len()),
(n, e) => format!(" {} items, {n} not going, {e} elided ", items.len()),
}
}
Tab::Trace => format!(" {} events · /save keeps them all ", app.trace.len()),
Tab::Permissions => {
let mut parts = Vec::new();
if let Some(line) = app.confinement() {
parts.push(line);
}
match app.undecided() {
0 => {}
n => parts.push(format!("{n} more it will ask about")),
}
if !app.permissions().is_empty() {
parts.push("space cycles · a allow · n never · r ask again".to_owned());
}
format!(" {} ", parts.join(" · "))
}
}
}
fn draw_chat(frame: &mut Frame, app: &mut App, inner: Rect) -> Scrolled {
let width = inner.width as usize;
let mut lines: Vec<Line> = Vec::new();
for entry in &app.transcript {
if entry.speaker == Speaker::Model {
let split = chunks(&entry.text);
let last = split.len().saturating_sub(1);
for (nth, chunk) in split.into_iter().enumerate() {
let prose = match chunk {
Chunk::Code { language, body } => {
separate(&mut lines);
lines.extend(highlighted(language, body, width));
if nth < last {
separate(&mut lines);
}
continue;
}
Chunk::Prose(prose) => prose,
};
for line in tui_markdown::from_str_with_options(prose, &markdown()).lines {
match line.style == Markdown.code() {
true => lines.extend(gutter(&line, width)),
false => match rule(&line) {
true => lines.push(Line::styled("─".repeat(width), faint())),
false => lines.extend(refit(&line, width)),
},
}
}
}
lines.push(Line::default());
continue;
}
let (prefix, style) = match entry.speaker {
Speaker::User => ("> ", Style::default().fg(Color::White).bold()),
Speaker::Reasoning => ("", quiet().italic()),
Speaker::Call => ("⟩ ", Style::default().fg(Color::Cyan)),
Speaker::Result => ("│ ", quiet()),
Speaker::Note => ("· ", quiet()),
Speaker::Error => ("! ", Style::default().fg(Color::Red)),
Speaker::Model => unreachable!("rendered above"),
};
for text in wrapped(&entry.text, width, prefix) {
lines.push(Line::styled(text, style));
}
lines.push(Line::default());
}
app.rendered = lines.len();
app.viewport = inner.height as usize;
let bottom = lines.len().saturating_sub(inner.height as usize);
if app.follow {
app.scroll = bottom;
}
let at = app.scroll.min(bottom);
let total = lines.len();
frame.render_widget(Paragraph::new(lines).scroll((at as u16, 0)), inner);
Scrolled {
position: at,
total,
area: inner,
}
}
fn draw_context(frame: &mut Frame, app: &mut App, area: Rect) -> Scrolled {
let items = app.kernel.items();
if items.is_empty() {
frame.render_widget(Paragraph::new("nothing here yet").style(quiet()), area);
return Scrolled::default();
}
let [head, inner] = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).areas(area);
let width = inner.width as usize;
let label = 26.min(width / 3);
let kind = if width >= 84 { 18 } else { 0 };
let counted = 4 + 2 + label + 1 + kind + 8 + 2;
let says = width.saturating_sub(counted);
frame.render_widget(
Paragraph::new(Line::styled(
format!(
" {:<4}{:<label$} {:<kind$}{:>8} {}",
"id",
"label",
match kind {
0 => "",
_ => "kind",
},
"tokens",
match says >= 8 {
true => "what it says, or why it is not being sent",
false => "",
}
),
quiet(),
)),
head,
);
let rows: Vec<ListItem> = items
.iter()
.map(|item| {
let (mark, style) = match item.state {
ContextState::Active => ("·", Style::default()),
ContextState::Pinned => ("▪", Style::default().fg(Color::Yellow)),
ContextState::Excluded => ("-", quiet()),
ContextState::Elided => ("…", quiet()),
ContextState::Archived => ("▫", quiet()),
ContextState::Superseded => ("~", quiet()),
_ => ("?", quiet()),
};
let (tail, tail_style) = match item.state.sends_content() {
false => (
match &item.note {
Some(note) => format!("{}: {note}", item.state),
None => item.state.to_string(),
},
quiet().italic(),
),
true => (
match item
.content
.to_text()
.lines()
.find(|line| !line.trim().is_empty())
{
Some(first) => first.trim().to_owned(),
None => match &item.kind {
ContextKind::AssistantMessage { .. } => {
let names: Vec<_> =
item.calls().map(|call| call.tool.as_str()).collect();
match names.is_empty() {
true => String::new(),
false => format!("asked for {}", names.join(", ")),
}
}
_ => String::new(),
},
},
quiet(),
),
};
ListItem::new(Line::from(vec![
Span::styled(
format!(
"{:>3} {mark} {:<label$} ",
item.id.0,
clip(&item.label, label)
),
style,
),
Span::styled(
match kind {
0 => String::new(),
_ => format!("{:<kind$}", clip(item.kind.name(), kind)),
},
quiet(),
),
Span::styled(format!("{:>8} ", thousands(item.tokens)), style),
Span::styled(clip(&tail, says), tail_style),
]))
})
.collect();
app.selected = app.selected.min(items.len() - 1);
app.list.select(Some(app.selected));
let highlight = match app.focus == Focus::Body {
true => Style::default().add_modifier(Modifier::REVERSED),
false => Style::default().add_modifier(Modifier::UNDERLINED),
};
frame.render_stateful_widget(
List::new(rows).highlight_style(highlight),
inner,
&mut app.list,
);
Scrolled {
position: app.list.offset(),
total: items.len(),
area: inner,
}
}
fn draw_permissions(frame: &mut Frame, app: &mut App, area: Rect) -> Scrolled {
let rows = app.permissions();
if rows.is_empty() {
frame.render_widget(
Paragraph::new(
"nothing has been decided yet.\n\nThe policy asks about everything it has not \
been told about; answer a question with `a` or `n` and it will be here, where it \
can be changed.",
)
.style(quiet())
.wrap(ratatui::widgets::Wrap { trim: false }),
area,
);
return Scrolled::default();
}
let [head, inner] = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).areas(area);
let width = inner.width as usize;
let capability = 22.min(width / 3);
let covers = width.saturating_sub(2 + capability + 1 + 10 + 2);
frame.render_widget(
Paragraph::new(Line::styled(
format!(
" {:<capability$} {:<10} {}",
"capability or path",
"answer",
match covers >= 8 {
true => "the tools it covers",
false => "",
}
),
quiet(),
)),
head,
);
let listed: Vec<ListItem> = rows
.iter()
.map(|row| {
let (answer, style) = match row.verdict {
Verdict::Allow => ("allow", Style::default().fg(Color::Green)),
Verdict::Ask => ("ask", Style::default().fg(Color::Yellow)),
Verdict::Deny => ("deny", Style::default().fg(Color::Red)),
};
let tools = match (row.tools.is_empty(), row.sometimes.is_empty()) {
(true, true) => "nothing registered needs it".to_owned(),
(true, false) => format!(
"{}, when the command reaches for it",
row.sometimes.join(", ")
),
(false, true) => row.tools.join(", "),
(false, false) => format!(
"{}; {}, when the command reaches for it",
row.tools.join(", "),
row.sometimes.join(", ")
),
};
ListItem::new(Line::from(vec![
Span::raw(format!(
" {:<capability$} ",
clip(&row.subject.to_string(), capability)
)),
Span::styled(format!("{answer:<10} "), style),
Span::styled(
clip(&tools, covers),
match row.tools.is_empty() && row.sometimes.is_empty() {
true => quiet(),
false => Style::default(),
},
),
]))
})
.collect();
app.chosen = app.chosen.min(rows.len() - 1);
app.grants.select(Some(app.chosen));
let highlight = match app.focus == Focus::Body {
true => Style::default().add_modifier(Modifier::REVERSED),
false => Style::default().add_modifier(Modifier::UNDERLINED),
};
frame.render_stateful_widget(
List::new(listed).highlight_style(highlight),
inner,
&mut app.grants,
);
Scrolled {
position: app.grants.offset(),
total: rows.len(),
area: inner,
}
}
fn draw_trace(frame: &mut Frame, app: &mut App, inner: Rect) -> Scrolled {
const NAMES: usize = 22;
let (width, height) = (inner.width as usize, inner.height as usize);
let column = match width >= NAMES + 20 {
true => NAMES,
false => 0,
};
let mut lines: Vec<Line> = Vec::new();
for event in &app.trace {
let colour = match () {
_ if event.name.ends_with(".failed") => Color::Red,
_ if event.name.starts_with("permission") => Color::Yellow,
_ if event.name.is_empty() => Color::Gray,
_ => Color::White,
};
let named = Style::default().fg(colour);
let said = quiet();
let indent = " ".repeat(column.max(2));
let mut detail = wrapped(&event.detail, width, &indent).into_iter();
match (event.name.is_empty(), event.detail.is_empty()) {
(true, _) => lines.extend(detail.map(|line| Line::styled(line, said))),
(false, true) => lines.push(Line::styled(event.name.clone(), named)),
(false, false) => {
let first = detail.next().unwrap_or_default();
lines.push(Line::from(vec![
Span::styled(format!("{:<column$}", event.name), named),
Span::styled(first.trim_start().to_owned(), said),
]));
lines.extend(detail.map(|line| Line::styled(line, said)));
}
}
}
let bottom = lines.len().saturating_sub(height);
app.trace_scroll = app.trace_scroll.min(bottom);
let at = bottom - app.trace_scroll;
let total = lines.len();
frame.render_widget(Paragraph::new(lines).scroll((at as u16, 0)), inner);
Scrolled {
position: at,
total,
area: inner,
}
}
fn draw_input(frame: &mut Frame, app: &mut App, area: Rect) {
let focused = app.focus == Focus::Input;
let (title, colour) = match app.editing {
Some(id) => (
format!(" editing [{id}] · enter commits · esc cancels "),
Color::Yellow,
),
None => (
match focused {
true => " you ".to_owned(),
false => " you · tab ".to_owned(),
},
match focused {
true => Color::White,
false => Color::Gray,
},
),
};
app.input.set_block(
Block::bordered()
.title(title)
.border_style(Style::default().fg(colour)),
);
app.input.set_cursor_style(match focused {
true => Style::default().add_modifier(Modifier::REVERSED),
false => Style::default(),
});
frame.render_widget(&app.input, area);
}
fn draw_status(frame: &mut Frame, app: &App, area: Rect) {
let dim = quiet();
let mut spans = vec![match app.busy {
true => Span::styled(
format!(" {} ", state_name(&app.kernel)),
Style::default().fg(Color::Yellow),
),
false => Span::styled(format!(" {} ", state_name(&app.kernel)), dim),
}];
let mut add = |text: String, style: Style| {
spans.push(Span::styled("· ", dim));
spans.push(Span::styled(text, style));
spans.push(Span::raw(" "));
};
if let Some(info) = app.kernel.model_info() {
add(format!("{} @ {}", info.model, app.provider.host()), dim);
}
let budget = app.kernel.budget();
let used = thousands(budget.used());
add(
match (budget.fraction_used(), budget.limit) {
(Some(fraction), Some(limit)) => {
format!(
"~{used} tokens, {:.1}% ({})",
fraction * 100.0,
compact(limit)
)
}
_ => format!("~{used} tokens, of an unknown limit"),
},
match budget.fraction_used() {
Some(fraction) if fraction >= 0.9 => Style::default().fg(Color::Red),
Some(fraction) if fraction >= 0.7 => Style::default().fg(Color::Yellow),
Some(_) => Style::default().fg(Color::Green),
None => dim,
},
);
if let Some(reported) = budget.reported.and_then(|usage| usage.input_tokens) {
add(format!("{} really", thousands(reported as usize)), dim);
}
let withheld = app.kernel.with_context(|context| context.tokens_withheld());
if withheld != 0 {
add(format!("{} held back", thousands(withheld)), dim);
}
add(
match app.busy {
true => "esc stops it".to_owned(),
false => "F1 for the keys".to_owned(),
},
dim,
);
let line = Line::from(spans);
let over = line.width().saturating_sub(area.width as usize);
let line = match over {
0 => line,
_ => Line::from(shrink_host(line.spans, over)),
};
frame.render_widget(Paragraph::new(line), area);
}
const HOST_FLOOR: usize = 8;
fn shrink_host(spans: Vec<Span<'static>>, over: usize) -> Vec<Span<'static>> {
spans
.into_iter()
.map(|span| {
let style = span.style;
let Some((model, host)) = span.content.split_once(" @ ") else {
return span;
};
let keep = Span::raw(host).width().saturating_sub(over + 1);
let shortened = match keep >= HOST_FLOOR {
true => format!("{model} @ {}…", &host[..prefix_within(host, keep)]),
false => model.to_owned(),
};
Span::styled(shortened, style)
})
.collect()
}
fn state_name(kernel: &Kernel) -> &'static str {
match kernel.state() {
State::Idle => "idle",
State::Requesting => "asking",
State::Ready { .. } => "ready",
State::Executing { .. } => "running",
State::Deciding { .. } => "waiting on you",
State::Finished { .. } => "done",
_ => "?",
}
}
fn draw_overlay(frame: &mut Frame, overlay: &Overlay, app: &App) {
match overlay {
Overlay::Text {
title,
body,
scroll,
} => panel(frame, &format!(" {title} "), body, *scroll, 100, 90),
Overlay::Permission => draw_permission(frame, app),
}
}
fn draw_permission(frame: &mut Frame, app: &App) {
let Some(request) = app.kernel.pending_permissions().into_iter().next() else {
return;
};
let waiting = app.kernel.pending_permissions().len();
let judged: Vec<String> = app
.policy
.judges(&request)
.iter()
.map(|subject| subject.to_string())
.collect();
let body = format!(
"{} wants: {}\n\n{}\n\
[y] once [a] always, for {} [n] no\n\
[i] the exact JSON [d] {}{}",
request.tool,
judged.join(", "),
readable(&request.args),
judged.join(" and "),
match waiting > 1 {
true => "drop them all",
false => "drop it",
},
match waiting > 1 {
true => format!("\n\n{} more after this one", waiting - 1),
false => String::new(),
}
);
let area = centred(frame.area(), 72, wrapped(&body, 68, "").len() as u16 + 2);
frame.render_widget(Clear, area);
frame.render_widget(
Paragraph::new(wrapped(&body, area.width.saturating_sub(4) as usize, "").join("\n")).block(
Block::bordered()
.title(" a tool wants to run ")
.border_style(Style::default().fg(Color::Yellow))
.padding(ratatui::widgets::Padding::horizontal(1)),
),
area,
);
}
fn readable(args: &serde_json::Value) -> String {
let Some(fields) = args.as_object() else {
return serde_json::to_string_pretty(args).unwrap_or_default();
};
if fields.is_empty() {
return "(no arguments)\n\n".to_owned();
}
let mut out = String::new();
for (name, value) in fields {
match value {
serde_json::Value::String(text) if text.contains('\n') => {
out.push_str(&format!("{name}:\n"));
for line in text.lines() {
out.push_str(&format!(" {line}\n"));
}
}
serde_json::Value::String(text) => out.push_str(&format!("{name}: {text}\n")),
other => out.push_str(&format!("{name}: {other}\n")),
}
out.push('\n');
}
out
}
fn panel(frame: &mut Frame, title: &str, body: &str, scroll: usize, columns: u16, percent: u16) {
let wanted = wrapped(body, columns.saturating_sub(4) as usize, "").len() as u16 + 2;
let area = centred(
frame.area(),
columns,
wanted.min(frame.area().height * percent / 100),
);
frame.render_widget(Clear, area);
let block = Block::bordered()
.title(title)
.border_style(Style::default().fg(Color::Cyan))
.padding(ratatui::widgets::Padding::horizontal(1));
let inner = block.inner(area);
let lines = wrapped(body, inner.width as usize, "");
let at = scroll.min(lines.len().saturating_sub(inner.height as usize));
let footer = format!(
" {}–{} of {} · any key closes ",
at + 1,
(at + inner.height as usize).min(lines.len()),
lines.len()
);
let total = lines.len();
frame.render_widget(
Paragraph::new(lines.join("\n"))
.scroll((at as u16, 0))
.block(block.title_bottom(footer)),
area,
);
scrollbar(
frame,
area,
Style::default().fg(Color::Cyan),
Scrolled {
position: at,
total,
area: inner,
},
);
}
fn separate(lines: &mut Vec<Line<'static>>) {
if lines.last().is_some_and(|line| !line.spans.is_empty()) {
lines.push(Line::default());
}
}
fn extension(language: &str) -> &str {
match language.to_ascii_lowercase().as_str() {
"rust" => "rs",
"python" => "py",
"javascript" | "node" => "js",
"typescript" => "ts",
"shell" | "console" | "zsh" | "fish" => "sh",
"yaml" => "yml",
"c++" => "cpp",
"c#" | "csharp" => "cs",
"golang" => "go",
"rb" | "ruby" => "rb",
"makefile" | "make" => "sh",
_ => language,
}
}
fn token(name: &str) -> Style {
let colour = match name {
"comment" => Color::Gray,
"string" | "character" => Color::Green,
"keyword" | "kw" => Color::Magenta,
"digit" | "boolean" => Color::Yellow,
"function" | "macro" | "tag" => Color::Blue,
"struct" | "namespace" | "type" | "attribute" | "key" => Color::Cyan,
"operator" | "reference" => Color::Reset,
"heading" | "header" | "bold" => return Style::default().bold(),
"italic" | "quote" => return Style::default().italic(),
"insertion" => Color::Green,
"deletion" => Color::Red,
"link" | "list" => Color::Cyan,
_ => Color::Reset,
};
Style::default().fg(colour)
}
fn highlighted(language: &str, body: &str, width: usize) -> Vec<Line<'static>> {
let bar = Span::styled("│ ", faint());
let room = width.saturating_sub(2).max(8);
let source: Vec<String> = body.lines().map(str::to_owned).collect();
let mut highlighter = synoptic::from_extension(extension(language), 4);
if let Some(highlighter) = &mut highlighter {
highlighter.run(&source);
}
let mut drawn = Vec::new();
for (y, line) in source.iter().enumerate() {
let spans: Vec<(String, Style)> = match &highlighter {
Some(highlighter) => highlighter
.line(y, line)
.into_iter()
.map(|piece| match piece {
synoptic::TokOpt::Some(text, name) => (text, token(&name)),
synoptic::TokOpt::None(text) => (text, Style::default()),
})
.collect(),
None => vec![(line.clone(), Style::default().fg(Color::Cyan))],
};
for row in fit(spans, room) {
let mut cells = vec![bar.clone()];
cells.extend(row);
drawn.push(Line::from(cells));
}
}
drawn
}
fn fit(spans: Vec<(String, Style)>, room: usize) -> Vec<Vec<Span<'static>>> {
let mut rows = vec![Vec::new()];
let mut used = 0;
for (text, style) in spans {
let mut rest = text.as_str();
while !rest.is_empty() {
let left = room - used;
let taken: String = rest.chars().take(left).collect();
let bytes = taken.len();
if !taken.is_empty() {
used += taken.chars().count();
rows.last_mut()
.expect("there is always a row")
.push(Span::styled(taken, style));
}
rest = &rest[bytes..];
if used >= room && !rest.is_empty() {
rows.push(Vec::new());
used = 0;
}
}
}
if rows.last().is_some_and(Vec::is_empty) && rows.len() > 1 {
rows.pop();
}
rows
}
#[derive(Debug, PartialEq)]
enum Chunk<'a> {
Prose(&'a str),
Code {
language: &'a str,
body: &'a str,
},
}
fn chunks(text: &str) -> Vec<Chunk<'_>> {
fn fence(line: &str) -> Option<(char, usize)> {
let trimmed = line.trim_start_matches(' ');
if line.len() - trimmed.len() > 3 {
return None;
}
let marker = trimmed.chars().next().filter(|c| *c == '`' || *c == '~')?;
let run = trimmed.chars().take_while(|c| *c == marker).count();
(run >= 3).then_some((marker, run))
}
let mut chunks = Vec::new();
let mut prose = 0;
let mut open: Option<(char, usize, usize)> = None;
let mut at = 0;
for line in text.split_inclusive('\n') {
let start = at;
at += line.len();
let bare = line.trim_end_matches(['\n', '\r']);
match open {
None => {
let Some((marker, run)) = fence(bare) else {
continue;
};
if start > prose {
chunks.push(Chunk::Prose(&text[prose..start]));
}
open = Some((marker, run, at));
}
Some((marker, run, body)) => {
let closes = fence(bare).is_some_and(|(c, n)| c == marker && n >= run)
&& bare.trim().chars().all(|c| c == marker);
if !closes {
continue;
}
let language = text[start_of_line(text, body)..body].trim();
let language = language.trim_start_matches([marker]).trim();
chunks.push(Chunk::Code {
language,
body: &text[body..start],
});
open = None;
prose = at;
}
}
}
match open {
Some((marker, _, body)) => {
let language = text[start_of_line(text, body)..body].trim();
chunks.push(Chunk::Code {
language: language.trim_start_matches([marker]).trim(),
body: &text[body..],
});
}
None if text.len() > prose => chunks.push(Chunk::Prose(&text[prose..])),
None => {}
}
chunks
}
fn start_of_line(text: &str, end: usize) -> usize {
text[..end]
.trim_end_matches('\n')
.rfind('\n')
.map(|at| at + 1)
.unwrap_or(0)
}
fn centred(area: Rect, columns: u16, rows: u16) -> Rect {
let width = columns
.min(area.width.saturating_sub(4))
.max(20)
.min(area.width);
let height = rows
.min(area.height.saturating_sub(2))
.max(4)
.min(area.height);
Rect {
x: area.x + (area.width.saturating_sub(width)) / 2,
y: area.y + (area.height.saturating_sub(height)) / 2,
width,
height,
}
}
#[derive(Clone)]
struct Markdown;
impl tui_markdown::StyleSheet for Markdown {
fn heading(&self, level: u8) -> Style {
match level {
1 => Style::default().fg(Color::Yellow).bold().underlined(),
2 => Style::default().fg(Color::Yellow).bold(),
_ => Style::default().bold(),
}
}
fn heading_marker(&self, _level: u8) -> &str {
""
}
fn code(&self) -> Style {
Style::default().fg(Color::Cyan)
}
fn code_block_fence(&self) -> &str {
""
}
fn blockquote(&self) -> Style {
Style::default().fg(Color::Gray).italic()
}
fn link(&self) -> Style {
Style::default().fg(Color::Blue).underlined()
}
}
fn markdown() -> tui_markdown::Options<Markdown> {
tui_markdown::Options::new(Markdown)
}
fn rule(line: &Line<'_>) -> bool {
let text: String = line
.spans
.iter()
.map(|span| span.content.as_ref())
.collect();
let text = text.trim();
text.len() >= 3
&& (text.chars().all(|c| c == '-')
|| text.chars().all(|c| c == '*')
|| text.chars().all(|c| c == '_'))
}
fn gutter(line: &Line<'_>, width: usize) -> Vec<Line<'static>> {
let bar = Span::styled("│ ", faint());
let code = Style::default().fg(Color::Cyan);
let text: String = line
.spans
.iter()
.map(|span| span.content.as_ref())
.collect();
split_to_fit(&text, width.saturating_sub(2).max(8))
.into_iter()
.map(|piece| Line::from(vec![bar.clone(), Span::styled(piece, code)]))
.collect()
}
fn refit(line: &Line<'_>, width: usize) -> Vec<Line<'static>> {
let width = width.max(8);
let plain: String = line
.spans
.iter()
.map(|span| span.content.as_ref())
.collect();
if plain.chars().count() <= width {
return vec![
Line::from(
line.spans
.iter()
.map(|span| Span::styled(span.content.to_string(), span.style))
.collect::<Vec<_>>(),
)
.style(line.style),
];
}
let spaces = plain.chars().take_while(|c| *c == ' ').count();
let hang = " ".repeat(spaces + bullet(&plain[spaces..]));
let hang = match hang.chars().count() + 8 < width {
true => hang,
false => String::new(),
};
let mut out: Vec<Line<'static>> = Vec::new();
let mut current: Vec<Span<'static>> = Vec::new();
let mut column = 0;
for span in &line.spans {
for word in span.content.split_inclusive(' ') {
for piece in split_to_fit(word, width - hang.chars().count()) {
let length = piece.trim_end().chars().count();
if column != 0 && column + length > width {
out.push(Line::from(std::mem::take(&mut current)).style(line.style));
column = hang.chars().count();
if !hang.is_empty() {
current.push(Span::raw(hang.clone()));
}
}
current.push(Span::styled(piece.clone(), span.style));
column += piece.chars().count();
}
}
}
out.push(Line::from(current).style(line.style));
out
}
fn bullet(text: &str) -> usize {
if let Some(rest) = text.strip_prefix(['-', '*', '+'])
&& rest.starts_with(' ')
{
return 2;
}
let digits = text.chars().take_while(char::is_ascii_digit).count();
match digits != 0 && matches!(text.get(digits..digits + 2), Some(". ") | Some(") ")) {
true => digits + 2,
false => 0,
}
}
fn split_to_fit(word: &str, width: usize) -> Vec<String> {
if word.chars().count() <= width {
return vec![word.to_owned()];
}
let characters: Vec<char> = word.chars().collect();
characters
.chunks(width.max(1))
.map(|piece| piece.iter().collect())
.collect()
}
fn wrapped(text: &str, width: usize, prefix: &str) -> Vec<String> {
let head = prefix.chars().count();
let width = width.max(head + 12);
let hanging = " ".repeat(head);
let mut out: Vec<String> = Vec::new();
for paragraph in text.split('\n') {
let lead: String = paragraph.chars().take_while(|c| *c == ' ').collect();
let room = (width - head).saturating_sub(lead.chars().count()).max(12);
for line in fold(paragraph.trim_start(), room) {
let start = match out.is_empty() {
true => prefix,
false => &hanging,
};
out.push(format!("{start}{lead}{line}"));
}
}
out
}
fn fold(body: &str, room: usize) -> Vec<String> {
if body.chars().count() <= room {
return vec![body.to_owned()];
}
let mut out = Vec::new();
let mut line = String::new();
let mut fresh = true;
for word in body.split(' ') {
if word.chars().count() > room {
if !fresh {
out.push(std::mem::take(&mut line));
}
let characters: Vec<char> = word.chars().collect();
for piece in characters.chunks(room) {
out.push(piece.iter().collect());
}
line = out.pop().unwrap_or_default();
fresh = false;
continue;
}
if !fresh && line.chars().count() + 1 + word.chars().count() > room {
out.push(std::mem::take(&mut line));
fresh = true;
}
if !fresh {
line.push(' ');
}
line.push_str(word);
fresh = false;
}
out.push(line);
out
}
fn clip(text: &str, width: usize) -> String {
match text.chars().count() > width {
true if width > 1 => format!("{}…", text.chars().take(width - 1).collect::<String>()),
true => text.chars().take(width).collect(),
false => text.to_owned(),
}
}
fn compact(n: usize) -> String {
match n {
0..1_000 => n.to_string(),
1_000..10_000 => format!("{:.1}k", n as f64 / 1_000.0),
10_000..1_000_000 => format!("{}k", n / 1_000),
1_000_000..10_000_000 => format!("{:.1}M", n as f64 / 1_000_000.0).replace(".0M", "M"),
_ => format!("{}M", n / 1_000_000),
}
}
pub(crate) fn thousands(n: usize) -> String {
let digits = n.to_string();
let mut out = String::new();
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}