#![deny(unsafe_code)]
use super::{keys, search, Mode, Pager};
use crate::url::is_external;
use crate::render::{slice_spans, str_width, truncate_width, visible, Line, Span};
use crate::term::{Frame, Style};
use crate::theme;
mod cells;
use cells::Cells;
const CUT_LEFT: char = '\u{2039}';
const CUT_RIGHT: char = '\u{203a}';
const JUMP: &str = "j/k move, Enter jump, Esc close";
const READ: &str = "j/k scroll, Esc close";
pub fn paint(p: &mut Pager, frame: &mut Frame) {
frame.reset();
let body = p.body_rows();
match p.mode {
Mode::Outline => overlay(p, frame, "Outline", JUMP, &outline_rows(p), p.outline_sel),
Mode::Help => overlay(p, frame, "Keys", JUMP, &help_rows(), p.help_top),
Mode::Index => overlay(p, frame, &index_title(p), JUMP, &index_rows(p), p.index_row_pos()),
Mode::Detail => detail(p, frame),
_ => document(p, frame, body),
}
if p.rows > 0 {
frame.move_to(p.rows as u16, 1);
status(p, frame);
}
}
fn document(p: &mut Pager, frame: &mut Frame, body: usize) {
let (top, pin) = (p.top, p.pinned());
let head = p.src.lines(0..pin);
let window = p.src.lines(top..top.saturating_add(body - pin));
for r in 0..body {
frame.move_to(r as u16 + 1, 1);
let (row, line) = match r < pin {
true => (r, head.get(r)),
false => (top + r - pin, window.get(r - pin)),
};
if let Some(line) = line {
let spans = compose(p, row, line);
paint_spans(frame, &spans);
}
frame.reset_style();
frame.clear_to_eol();
}
}
#[cfg(test)]
pub(super) fn row_spans(p: &mut Pager, row: usize) -> Vec<Span> {
match p.src.line(row) {
Some(line) => compose(p, row, &line),
None => Vec::new(),
}
}
fn compose(p: &Pager, row: usize, line: &Line) -> Vec<Span> {
let width = p.cols.max(1);
let scroll = super::scrollable(line, width);
let off = if scroll { p.hoff } else { 0 };
let summary = fold_summary(p, row, line, width, off);
let base: &[Span] = summary.as_deref().unwrap_or(&line.spans);
let full_width = base.iter().map(Span::width).sum::<usize>();
let mut cells = Cells::from_spans(&slice_spans(base, off, width));
focus_link(p, &mut cells, row, line, off);
highlight(p, &mut cells, row, off);
if p.cursor == row || selected(p, row) {
cells.tint(theme::selection());
}
if scroll {
if off > 0 {
cells.set(0, CUT_LEFT, theme::muted());
}
if full_width > off + width {
cells.set(width.saturating_sub(1), CUT_RIGHT, theme::muted());
}
}
cells.into_spans()
}
fn selected(p: &Pager, row: usize) -> bool {
let sel = match p.select {
Some(s) => s,
None => return false,
};
let (lo, hi) = sel.range();
row >= lo && row <= hi.min(p.src.len().saturating_sub(1))
}
fn fold_summary(
p: &Pager,
row: usize,
line: &Line,
width: usize,
off: usize,
) -> Option<Vec<Span>> {
let hidden = p.src.hidden_at(row)?;
let mut spans = line.spans.clone();
if let Some(first) = spans.first_mut() {
if first.text.starts_with(theme::MARKER_OPEN) {
first.text = format!("{} ", theme::MARKER_CLOSED);
}
}
if line.heading.as_ref().is_some_and(|h| h.summarised) {
return Some(spans);
}
let note = match p.src.fold_note(row) {
Some(note) => format!(" \u{b7} {note}"),
None => {
let unit = if hidden == 1 { "line" } else { "lines" };
format!(" ({hidden} {unit})")
}
};
Some(with_count(spans, note, width, off))
}
pub(super) fn with_count(spans: Vec<Span>, note: String, width: usize, off: usize) -> Vec<Span> {
let text: usize = spans.iter().map(Span::width).sum();
let note_width = crate::render::str_width(¬e);
if off > 0 || text + note_width <= width {
let mut out = spans;
out.push(Span::new(note, theme::muted()));
return out;
}
let keep = width.saturating_sub(note_width + 1);
let mut out = crate::render::slice_spans(&spans, 0, keep);
if keep > 0 {
out.push(Span::new(CUT_RIGHT.to_string(), theme::muted()));
}
out.push(Span::new(note, theme::muted()));
out
}
fn link_focus_style(url: &str) -> Style {
Style::new()
.fg(theme::link_fg(is_external(url)))
.bold()
.reverse()
}
fn focus_link(p: &Pager, cells: &mut Cells, row: usize, line: &Line, off: usize) {
let site = match p.focused_link() {
Some(s) if p.src.row_of(s.anchor) == Some(row) => s,
_ => return,
};
let width = link_width(line, &site.url, site.col);
if width == 0 {
return;
}
let start = site.col.saturating_sub(off);
cells.restyle(start, start + width, link_focus_style(&site.url));
}
fn link_width(line: &Line, url: &str, col: usize) -> usize {
let mut x = 0;
let mut w = 0;
for s in &line.spans {
if x >= col && s.link.as_deref() == Some(url) {
w += s.width();
} else if w > 0 {
break;
}
x += s.width();
}
w
}
fn highlight(p: &Pager, cells: &mut Cells, row: usize, off: usize) {
if p.query.is_empty() {
return;
}
for m in p.src.matches_on(row) {
let style = match m.current {
true => theme::search_current(),
false => theme::search(),
};
cells.restyle(m.start.saturating_sub(off), m.end.saturating_sub(off), style);
}
}
pub(super) fn outline_rows(p: &Pager) -> Vec<Vec<Span>> {
p.src
.outline()
.iter()
.map(|e| {
let indent = " ".repeat((e.level as usize).saturating_sub(1));
let marker = match e.folded {
true => theme::MARKER_CLOSED,
false => theme::MARKER_OPEN,
};
let style = theme::heading(e.level);
let mut row = vec![Span::new(format!("{indent}{marker} "), style)];
row.extend(crate::render::tagged(&e.text, style));
row
})
.collect()
}
fn index_title(p: &Pager) -> String {
let total = p.nav.as_ref().map(|n| n.entries().len()).unwrap_or(0);
let shown = p.index_rows().len();
let mut t = match shown == total {
true => format!("Index \u{b7} {total} docs"),
false => format!("Index \u{b7} {shown}/{total} docs"),
};
match p.index_typing || !p.index_filter.is_empty() {
true => {
t.push_str(&format!(" /{}", p.index_filter));
if p.index_typing {
t.push('\u{2588}');
}
}
false => t.push_str(" (/ filters)"),
}
t
}
fn index_rows(p: &Pager) -> Vec<Vec<Span>> {
let nav = match &p.nav {
Some(n) => n,
None => return Vec::new(),
};
p.index_rows()
.into_iter()
.filter_map(|i| nav.entries().get(i))
.map(|e| {
let here = nav.is_current(&e.path);
let style = if here { theme::heading(3) } else { theme::text() };
vec![Span::new(e.row(), style)]
})
.collect()
}
fn help_rows() -> Vec<Vec<Span>> {
let w = keys::help_key_width();
keys::help_rows()
.into_iter()
.map(|(k, d)| {
let pad = w.saturating_sub(str_width(k));
vec![Span::new(format!("{k}{} {d}", " ".repeat(pad)), theme::text())]
})
.collect()
}
fn detail(p: &Pager, frame: &mut Frame) {
let Some(d) = &p.detail else { return };
let label_w = d
.fields
.iter()
.map(|(k, _)| str_width(k))
.max()
.unwrap_or(0);
let rows: Vec<Vec<Span>> = d
.fields
.iter()
.map(|(k, v)| {
let pad = " ".repeat(label_w.saturating_sub(str_width(k)));
let style = match v.is_empty() {
true => theme::muted(),
false => theme::text(),
};
vec![Span::new(format!(" {k}{pad} {}", visible(v)), style)]
})
.collect();
overlay(p, frame, &d.title, READ, &rows, p.detail_sel);
}
fn overlay(
p: &Pager,
frame: &mut Frame,
title: &str,
hint: &str,
rows: &[Vec<Span>],
sel: usize,
) {
let body = p.body_rows();
let width = p.cols.max(1);
if body == 0 {
return;
}
frame.move_to(1, 1);
let head = format!(" {title} \u{2014} {hint}");
frame.span(theme::status(), truncate_width(&head, width));
frame.reset_style();
frame.clear_to_eol();
let list_rows = body.saturating_sub(1);
let top = window_top(sel, rows.len(), list_rows);
for r in 0..list_rows {
frame.move_to(r as u16 + 2, 1);
if let Some(row) = rows.get(top + r) {
let mut row = slice_spans(row, 0, width);
if top + r == sel {
row.iter_mut().for_each(|s| s.style = s.style.reverse());
}
paint_spans(frame, &row);
}
frame.reset_style();
frame.clear_to_eol();
}
}
pub(crate) fn window_top(sel: usize, len: usize, rows: usize) -> usize {
if rows == 0 || len <= rows {
return 0;
}
let half = rows / 2;
sel.saturating_sub(half).min(len - rows)
}
pub(crate) fn status_text(p: &Pager) -> String {
if let Mode::Search(dir) = p.mode {
let lead = if dir == search::Dir::Forward { '/' } else { '?' };
return format!("{lead}{}", p.query);
}
if let Some(m) = &p.message {
return m.clone();
}
if let Some(s) = &p.select {
return s.status();
}
let total = p.src.len();
let cur = if total == 0 { 0 } else { p.cursor + 1 };
let pct = if total <= 1 { 100 } else { p.cursor * 100 / (total - 1) };
let pos = p
.src
.position_text(p.cursor)
.unwrap_or_else(|| format!("{pct}% \u{b7} line {cur}/{total}"));
let mut s = format!("{} \u{b7} {pos}", p.label);
let depth = p.nav.as_ref().map(|n| n.depth()).unwrap_or(0);
if depth > 0 {
s.push_str(&format!(" \u{b7} [{depth} back]"));
}
if let Some(target) = p.link_status() {
s.push_str(" \u{b7} ");
s.push_str(&target);
}
s
}
fn status(p: &Pager, frame: &mut Frame) {
let width = p.cols.max(1);
let text = status_text(p);
let shown = truncate_width(&text, width);
let pad = width.saturating_sub(str_width(shown));
frame.span(theme::status(), shown);
frame.span(theme::status(), &" ".repeat(pad));
frame.reset_style();
}
fn paint_spans(frame: &mut Frame, spans: &[Span]) {
let mut open: Option<String> = None;
for span in spans {
if open.as_deref() != span.link.as_deref() {
if open.is_some() {
frame.link_close();
}
if let Some(url) = &span.link {
frame.link_open(url);
}
open = span.link.clone();
}
frame.span(span.style, &span.text);
}
if open.is_some() {
frame.link_close();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn window_keeps_the_selection_inside() {
assert_eq!(window_top(0, 10, 5), 0);
assert_eq!(window_top(2, 10, 5), 0);
assert_eq!(window_top(5, 10, 5), 3);
assert_eq!(window_top(9, 10, 5), 5);
assert_eq!(window_top(3, 3, 5), 0);
assert_eq!(window_top(3, 10, 0), 0);
}
#[test]
fn help_overlay_lists_every_binding() {
let rows = help_rows();
assert_eq!(rows.len(), keys::BINDINGS.len());
assert!(rows.iter().any(|r| r[0].text.contains("quit")));
assert!(rows.iter().any(|r| r[0].text.contains("collapse every section")));
}
}