Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ All notable changes to `diffs-rs` are recorded here. The forked crates in
has its own column at the right of every row, so rows stay aligned, and a folder shows a
badge when every file under it has the same one. Hosts that never call it, and the `diffs`
viewer, look as before.
- `Engine::set_terminal_background(true)` draws the diff on the terminal's own background
and text color: empty rows, plain context lines, gaps, file headers and the Files sidebar
get no background, and plain text uses the terminal's default foreground. Added and
deleted lines, changed words and hunk headers keep explicit tints from the palette of
`Options::appearance`, adjusted to read on lighter or bluer dark terminals. Off by
default; the `diffs` viewer does not change.

## 0.2.0 - 2026-11-15

Expand Down
14 changes: 14 additions & 0 deletions docs/embedding.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,20 @@ Read the state the footer would have shown from `status()`: `loading`, `coloring
The review label, layout and theme are the host's own inputs and `options()`.
`chrome` is fixed for the engine's lifetime, and `replace()` keeps it.

### Terminal background

By default the engine paints its whole rectangle with the theme's background (#0a0a0a dark, #ffffff light) and its own text color.
A host whose other screens use the terminal's own colors can call `engine.set_terminal_background(true)?`:

- Empty rows, plain context lines, gaps, metadata and "no newline" rows, file headers, the Files sidebar, and with chrome the label row, footer and help draw with `Color::Reset` as background.
- Plain text, including syntax tokens the theme leaves uncolored, uses the terminal's default foreground. Other syntax colors stay.
- Added and deleted lines, changed words, hunk headers, the empty half of a split row, and the Files keyboard cursor row keep explicit colors. They come from the palette of `Options::appearance`, so set the appearance that matches the terminal: `Dark` for a dark terminal, `Light` for a light one.
- The engine cannot know the terminal's exact background, so those colors are mixed for it: hunk headers are stronger than on the theme's own background, and the dark tints start from a slightly lighter base than #0a0a0a, so they read on black, #1e1e1e or a blue-grey alike.
- Gutter markers, the cursor and selection indicators, and the search match keep their own colors and underlines.

It is off by default. It can be set before the first file arrives, stays set across `replace()`, and follows the `t` theme toggle.
It is a method rather than an `Options` field so that adding it does not break hosts that build `Options` without `..Options::default()`.

## Commands and selection

`handle_event(event, focused)` applies the viewer's default bindings.
Expand Down
27 changes: 26 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ pub struct App {
pub(crate) search_match: Option<crate::reading::SearchMatch>,
pub(crate) selection: Option<crate::reading::LineSelection>,
pub(crate) markers: crate::engine::markers::Markers,
/// Draws the base surfaces and plain text in the terminal's own colors.
pub(crate) terminal_background: bool,
/// The theme's text color, which plain syntax tokens carry; drawn as the terminal's own
/// foreground when `terminal_background` is on.
pub(crate) plain: ratatui::style::Color,
reading_anchor: Option<ReadingAnchor>,
}

Expand All @@ -80,6 +85,7 @@ impl App {
wake: std::sync::mpsc::SyncSender<()>,
) -> anyhow::Result<Self> {
let colors = theme::load(appearance)?.0;
let plain = colors.fg;
let worker = crate::highlight::start(wake);
Ok(Self {
view: View::default(),
Expand All @@ -96,6 +102,8 @@ impl App {
search_match: None,
selection: None,
markers: Default::default(),
terminal_background: false,
plain,
top: Position::default(),
cursor: Position::default(),
old_side: false,
Expand Down Expand Up @@ -503,12 +511,29 @@ impl App {

pub fn toggle_theme(&mut self) -> anyhow::Result<()> {
self.appearance = self.appearance.toggle();
self.colors = theme::load(self.appearance)?.0;
self.load_colors()?;
self.epoch += 1;
self.cache = Cache::default();
Ok(())
}

/// Draws the base surfaces and plain text in the terminal's own colors, or in the theme's.
pub(crate) fn set_terminal_background(&mut self, on: bool) -> Result<()> {
self.terminal_background = on;
self.load_colors()
}

fn load_colors(&mut self) -> Result<()> {
let theme = theme::load(self.appearance)?.0;
self.plain = theme.fg;
self.colors = if self.terminal_background {
theme::on_terminal(self.appearance)?
} else {
theme
};
Ok(())
}

pub fn request_highlights(&self) {
let mut ids = Vec::new();
let mut files = Vec::new();
Expand Down
24 changes: 24 additions & 0 deletions src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ pub struct Engine {
markers: markers::Markers,
/// File marks set before the first file arrived, taken like `markers`.
file_marks: file_marks::FileMarks,
/// Draw on the terminal's own background and foreground. Kept across `replace()`.
terminal_background: bool,
}

impl Engine {
Expand Down Expand Up @@ -171,9 +173,26 @@ impl Engine {
area: Rect::default(),
markers: markers::Markers::default(),
file_marks: file_marks::FileMarks::default(),
terminal_background: false,
})
}

/// Draws the base surfaces in the terminal's default colors instead of the theme's:
/// empty rows, plain context lines, gaps, file headers, the Files sidebar, and the label
/// row and footer use `Color::Reset` as background, and plain text uses the terminal's
/// default foreground. Added and deleted lines, changed words, hunk headers and the
/// empty half of a split row keep explicit colors from the palette of
/// `Options::appearance`, so pick the appearance that matches the terminal. Off by
/// default; it stays set across `replace()`.
pub fn set_terminal_background(&mut self, on: bool) -> Result<()> {
self.terminal_background = on;
if let Some(app) = &mut self.app {
app.set_terminal_background(on)?;
}
self.changed(InputEffect::Redraw);
Ok(())
}

pub fn review_id(&self) -> ReviewId {
self.id
}
Expand Down Expand Up @@ -323,6 +342,9 @@ impl Engine {
app.chrome = self.options.chrome;
app.markers = std::mem::take(&mut self.markers);
app.set_file_marks(std::mem::take(&mut self.file_marks));
if self.terminal_background {
app.set_terminal_background(true)?;
}
if self.full_sources {
app.sources = Some(Vec::new());
}
Expand Down Expand Up @@ -596,8 +618,10 @@ impl Engine {
/// Close the previous review before creating fresh channels, identity and workers.
pub fn replace(&mut self, input: Input) -> Result<()> {
let options = self.options();
let terminal_background = self.terminal_background;
self.close()?;
*self = Self::open(input, options, self.wake.clone())?;
self.terminal_background = terminal_background;
Ok(())
}

Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@
//! ```
//!
//! The [embedding guide](https://github.com/plannotator/diffs-rs/blob/main/docs/embedding.md)
//! covers the host loop, focus, source coordinates, chrome, markers, file marks, reading tools,
//! and shutdown.
//! covers the host loop, focus, source coordinates, chrome, the terminal background, markers,
//! file marks, reading tools, and shutdown.

pub mod app;
mod cleanup;
Expand Down
2 changes: 2 additions & 0 deletions src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,8 @@ fn code(buf: &mut Buffer, app: &App, cell: CodeCell) -> anyhow::Result<()> {
.filter(|t| t.range.contains(&glyph.byte))
})
.map(|t| t.color)
// Plain text carries the theme's text color; on the terminal's colors it is `c.fg`.
.filter(|color| !(app.terminal_background && *color == app.plain))
.unwrap_or(c.fg);
let emphasized = style.is_some_and(|s| {
s.changed
Expand Down
9 changes: 8 additions & 1 deletion src/render/sidebar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,14 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) {
let node = state.tree.node(row.node);
let focused = state.focused() && state.cursor == Some(row.node);
let current = node.file().is_some_and(|id| Some(id) == state.current);
let bg = if focused { c.context } else { c.chrome };
// On the terminal's background the context color is the terminal's own, so the
// keyboard cursor row takes the hunk header band instead.
let highlight = if app.terminal_background {
c.separator
} else {
c.context
};
let bg = if focused { highlight } else { c.chrome };
let y = area.y + 1 + offset as u16;
fill(
buf,
Expand Down
123 changes: 123 additions & 0 deletions src/render/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,3 +581,126 @@ fn file_marks_truncate_long_names_but_never_the_badge() {
]
);
}

/// A modified file with context, a replacement, a pure addition and a pure deletion.
const CONTEXT: &str = "diff --git a/src/lib.rs b/src/lib.rs
index 1111111..2222222 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,5 +1,5 @@
fn first() {}
-fn old() {}
+fn new() {}
fn middle() {}
-fn gone() {}
fn last() {}
+fn added() {}
diff --git a/README.md b/README.md
index 3333333..4444444 100644
--- a/README.md
+++ b/README.md
@@ -1 +1 @@
-old
+new
";

/// The rows of `buffer` whose text contains `text`.
fn rows_with(buffer: &Buffer, text: &str) -> Vec<u16> {
let Rect { width, height, .. } = buffer.area;
(0..height)
.filter(|&y| {
(0..width)
.map(|x| buffer[(x, y)].symbol())
.collect::<String>()
.contains(text)
})
.collect()
}

#[test]
fn terminal_background_leaves_base_surfaces_to_the_terminal_and_keeps_tints() {
for appearance in [Appearance::Dark, Appearance::Light] {
for split in [true, false] {
let mut app = review_in(CONTEXT, "context.patch", appearance);
if !split {
app.layout = Layout::Unified;
}
// Off by default: the theme paints every cell.
let theme = draw_buffer(&mut app, 160, 24, None);
assert!(
theme.content().iter().all(|cell| cell.bg != Color::Reset),
"{appearance:?}"
);
app.set_terminal_background(true).unwrap();
let buffer = draw_buffer(&mut app, 160, 24, None);
let c = app.colors.clone();
let width = buffer.area.width;
let cells = |y: u16| (0..width).map(move |x| (x, y));
// Plain context rows, empty rows below the diff, the sidebar, the file headers,
// the label row and the footer carry no background, and plain text no foreground.
let mut plain: Vec<u16> = rows_with(&buffer, "fn middle() {}");
plain.extend(rows_with(&buffer, "fn first() {}"));
plain.extend([0, 17, 18, 22, 23]);
for y in plain {
for cell in cells(y) {
assert_eq!(
buffer[cell].bg,
Color::Reset,
"{appearance:?} {split} {cell:?}"
);
}
}
let row = rows_with(&buffer, "fn middle() {}")[0];
let text = cells(row)
.find(|&cell| buffer[cell].symbol() == "m")
.unwrap();
assert_eq!(buffer[text].fg, Color::Reset);
// Changed lines and hunk headers keep their explicit tints.
for (text, bg) in [
("fn added() {}", c.add_bg),
("fn gone() {}", c.del_bg),
("@@ -1,5 +1,5 @@", c.separator),
] {
let row = rows_with(&buffer, text)[0];
assert!(
cells(row).any(|cell| buffer[cell].bg == bg) && bg != Color::Reset,
"{appearance:?} {split} {text}"
);
}
// The empty half of a split addition keeps its shading.
if split {
let row = rows_with(&buffer, "fn added() {}")[0];
assert!(cells(row).any(|cell| buffer[cell].bg == c.empty));
}
// Turning it off restores the theme.
app.set_terminal_background(false).unwrap();
let again = draw_buffer(&mut app, 160, 24, None);
assert_eq!(again, theme, "{appearance:?} {split}");
}
}
}

#[test]
fn terminal_background_highlights_the_files_cursor_and_survives_a_theme_toggle() {
let mut app = review(KINDS, "kinds.patch");
app.set_terminal_background(true).unwrap();
draw_buffer(&mut app, 160, 24, None);
app.files_command().unwrap();
let buffer = draw_buffer(&mut app, 160, 24, None);
let c = app.colors.clone();
let cursor = styled(&buffer, app.sidebar.area, ">*", "added.rs");
assert!(
cursor
.iter()
.all(|(_, bg)| *bg == c.separator && *bg != Color::Reset)
);
let other = styled(&buffer, app.sidebar.area, "modified.rs", "modified.rs");
assert!(
other
.iter()
.all(|(fg, bg)| (*fg, *bg) == (Color::Reset, Color::Reset))
);
app.toggle_theme().unwrap();
assert_eq!(app.colors.bg, Color::Reset);
assert_ne!(app.colors.add_bg, c.add_bg);
}
36 changes: 36 additions & 0 deletions src/theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,42 @@ pub fn load(appearance: Appearance) -> Result<(Colors, Theme)> {
Ok((colors, syntax))
}

/// The theme's colors for drawing on the terminal's own background and foreground.
///
/// The base surfaces (diff, plain context, sidebar, label row, footer) and plain text become
/// `Color::Reset`. The tints keep explicit colors from the `appearance` palette, which should
/// match the terminal: a dark palette on a dark terminal, a light one on a light terminal.
/// The terminal's background is not known and is often lighter or bluer than the theme's,
/// so hunk headers are mixed more strongly, and the
/// dark tints start from a slightly lighter base than #0a0a0a.
pub(crate) fn on_terminal(appearance: Appearance) -> Result<Colors> {
let colors = load(appearance)?.0;
let dark = appearance == Appearance::Dark;
let fg = colors.fg;
// Dark terminals are rarely as dark as the theme's #0a0a0a, so the dark tints start from
// a slightly lighter base and sit on #1e1e1e or #1e2230 as they do on black.
let base = if dark {
lab_mix(colors.bg, fg, 0.06)
} else {
colors.bg
};
let add_bg = lab_mix(base, colors.added, if dark { 0.22 } else { 0.12 });
let del_bg = lab_mix(base, colors.deleted, if dark { 0.22 } else { 0.12 });
Ok(Colors {
bg: Color::Reset,
fg: Color::Reset,
chrome: Color::Reset,
context: Color::Reset,
separator: lab_mix(base, fg, if dark { 0.16 } else { 0.09 }),
empty: lab_mix(base, fg, if dark { 0.12 } else { 0.10 }),
add_bg,
del_bg,
add_word: alpha_mix(add_bg, colors.added, if dark { 0.20 } else { 0.15 }),
del_word: alpha_mix(del_bg, colors.deleted, if dark { 0.20 } else { 0.15 }),
..colors
})
}

fn components(color: Color) -> (u8, u8, u8) {
let Color::Rgb(r, g, b) = color else {
unreachable!("theme colors are RGB")
Expand Down
Loading
Loading