* Add delta --tui: an embedded gitu fork
delta --tui (alias --gitu) runs the delta-gitu fork of gitu with this executable as its diff
renderer.
* Let feature keys start from what the user's config enables now, at any width
delta --tui told gitu once, at startup, which features were in force at the starting width. So a
change to git config during the session was missed. With side-by-side = 140 in a narrower terminal,
S forced side-by-side on instead of disabling the user's rule, and L disabled the line numbers that
side-by-side brings in as a default, which were not in effect, so no press of L changed anything.
Now gitu asks, each time it needs to know, which features the user's config enables. delta reads
the git config again and settles its options as if every minimum width were met, without asking
the terminal anything. It counts only the features the user names (in --features, DELTA_FEATURES,
a flag, a features list, or an option in git config), which it now records as it gathers features,
and not those a builtin feature brings in as defaults.
cargo test test_gitu_is_told
* Test that delta --tui gives gitu the git config delta reads, for gitu to offer themes from
gitu offered themes from git config as it opens it, which can differ from delta's: with
GIT_CONFIG_GLOBAL set, choosing a theme in the picker changed nothing, with no error.
cargo test test_gitu_reads_the_git_config
* Give gitu the git config delta reads, so its theme picker offers only themes delta can find
delta --tui now tells gitu how delta opens git config, shared with GitConfig::try_create. With
GIT_CONFIG_GLOBAL set, delta finds no themes there today, so gitu says none are defined instead of
offering themes that change nothing.
cargo test test_gitu_reads_the_git_config
* delta-gitu v0.1.14
* Document H for the feature list, space to toggle in it, + and - for context, and every feature offered by default
The manual described - for the list and + for the +/- markers, and a default list without the
user's own features.
* Document shell commands, search as you type and its history, and stat rows of patches asked for with --stat
The TUI page did not cover shell commands bound to keys, said search moved
only on enter, left / out of the prompt histories, and did not say how a patch
asked for with --stat, or git log --stat, is shown.
* Document views, and H's columns for features, commands and views
Views, git commands of the user's opened from a key with what is under the
cursor, were not documented, and H was described as one list with commands
marked $.
* Document {command}, the git command the screen is showing, in views and commands
* Document that shell commands get the width and features the TUI draws with
* delta-gitu v0.1.15
* Stop recording which features the user names, to merge main, whose gathering code replaced the code it was built on
#2330 rewrote the gathering of features that 83df1902 recorded the user's features in. Until that
is redone on the new code, delta --tui counts a feature that a builtin feature brings in as a
default, such as side-by-side's line-numbers, as enabled by the user's config, and two tests say so.
cargo test test_gitu_is_told
* Test that a builtin feature named in a features list is in effect
Since #2330, features = raw, color-only, diff-highlight or diff-so-fancy in git config had no
effect: a style feature does not set an option of its own name, so its own option counted as off,
and the feature was left out. In 0.20.1, each gave the same output as its flag.
cargo test a_builtin_feature_named_in_a_features_list
* Leave out a builtin feature only when its own option is set to off, so features = diff-so-fancy works again
#2330 left out a builtin feature whose own option was not on, counting an option that nothing sets
as off. A style feature such as raw, color-only, diff-highlight or diff-so-fancy does not set an
option of its own name, so naming it in a features list in git config had no effect. Now a feature
is left out only when something sets its option to off.
Rendering with every theme in themes.gitconfig, with each switch and style feature set in [delta],
given as a flag, or named in a features list, on three diffs: against #2330, only the 240 cases
that name a style feature in a features list differ; against 0.20.1, those 240 are the same again.
cargo test a_builtin_feature_named_in_a_features_list
* Record again which features the user names, on main's gathering code, for delta --tui
As features are gathered, each now comes either from the user (--features, DELTA_FEATURES, a flag, a
features list, or an option in git config) or as a builtin feature's default, as side-by-side
brings in line-numbers. gather_features returns the features the user names with the rest of what
it gathers, and delta --tui counts only those as enabled by the user's config, as 83df1902 did on
the gathering code that main replaced.
Rendering with every theme in themes.gitconfig, with each switch and style feature set in [delta],
given as a flag, or named in a features list, on three diffs, is unchanged by this commit.
cargo test test_gitu_is_told
* Don't require --pager, add --tui to CLI, update manual and docs
* delta-gitu v0.1.16
* Say that start-folded folds every patch, as the fork now does
* delta-gitu v0.1.17
* Test that delta --tui says where delta's options go when given them, and that --tui must come first
* Tell a user who gives delta's options to delta --tui, or puts --tui after them, where delta's options go
* delta-gitu v0.1.18
14 KiB
The purpose of delta is to transform input received from git, diff, git blame, grep, etc to produce visually appealing output, including by syntax highlighting code.
Initialization
Delta reads user options from [delta] sections in .gitconfig, and from the command line.
Input
Delta reads from stdin, hence one can do e.g. git diff | delta.
Note that when git's stdout is sent to a pipe, (a) git does not emit ANSI color escape sequences unless --color=always, and (b) git does not start its own pager process.
Users typically configure git to use delta as its pager. In that case, git sends its stdout to delta behind the scenes (with ANSI color escape sequences), without the user needing to pipe it explicitly.
Parsing the input
Delta parses input using a state machine in which
the states correspond to semantically distinct sections of the input (e.g. HunkMinus means that we are in a removed line in a diff hunk).
The core dispatching loop is here.
pub fn delta<I>(lines: ByteLines<I>, writer: &mut dyn Write, config: &Config) -> std::io::Result<()>
where
I: BufRead,
{
StateMachine::new(writer, config).consume(lines)
}
pub enum State {
DiffHeader(DiffType),
HunkHeader(DiffType, ParsedHunkHeader, String, String),
HunkZero(DiffType, Option<String>),
HunkMinus(DiffType, Option<String>),
HunkPlus(DiffType, Option<String>),
Unknown,
}
impl<'a> StateMachine<'a> {
fn consume<I>(&mut self, mut lines: ByteLines<I>) -> std::io::Result<()>
where
I: BufRead,
{
while let Some(Ok(raw_line_bytes)) = lines.next() {
self.ingest_line(raw_line_bytes);
// Every method named handle_* must return std::io::Result<bool>.
// The bool indicates whether the line has been handled by that
// method (in which case no subsequent handlers are permitted to
// handle it).
let _ = self.handle_commit_meta_header_line()?
|| self.handle_diff_stat_line()?
|| self.handle_hunk_header_line()?
|| self.handle_hunk_line()?
|| self.emit_line_unchanged()?;
}
self.painter.paint_buffered_minus_and_plus_lines();
Ok(())
}
}
Output
Delta creates a child pager process (less) and writes its output to the stdin of the pager process.
Delta's navigate feature is implemented by constructing an appropriate regex and passing it as an argument to less.
Core utility data structures
-
config::ConfigThis is a struct with many fields corresponding to all user options and miscellaneous other useful things. It might be possible to store it globally, but currently the code passes references to it around the call stack. -
paint::PainterThis struct holds the syntax highlighter, and a writable output stream (connected to the stdin of the childlessprocess). It also holds two line buffers: one to store all the removed ("minus") lines encountered in a single diff hunk, and one to hold the added ("plus") lines.
Handling diff hunk lines
Here we will follow one code path in detail: handling diff hunk lines (removed/unchanged/added). This is the most important, and most complex, code path.
Recall that git diff output contains multiple diff "hunks". A hunk is a sequence of diff lines describing the changes among some lines of code that are close together in the same file. A git diff may have many hunks, from multiple files (and therefore multiple languages). Within a hunk, there are sequences of consecutive removed and/or added lines ("subhunks"), separated by unchanged lines. (The term "hunk" is standard; the term "subhunk" is specific to delta.)
The handler function that is called when delta process a hunk line is handle_hunk_line.
This function stores the line in a buffer (one buffer for minus lines and one for plus lines): the processing work is not done until we get to the end of the subhunk.
Now, we are at the end of a subhunk, and we have a sequence of minus lines, and a sequence of plus lines.
![]() |
Delta processes a subhunk (paint_minus_and_plus_lines) as follows:
|
|
-
Compute syntax (foreground) styles for the subhunk
We call the syntect library to compute syntax highlighting styles for each of the minus lines, and each of the plus lines, if the minus/plus styles specify syntax highlighting. The language used for syntax-highlighting is determined by the filename in the diff. For a single line, the result is an array of
(style, substring)pairs. Each pair specifies the foreground (text) color to be applied to a substring of the line (for example, a language keyword, or a string literal). -
Compute diff (background) styles for the subhunk
Again, the call yields, for each line, an array of
(style, substring)pairs. Each pair represents foreground and background colors to be applied to a substring of the line, as specified by delta's*-styleoptions.In order to compute the array of style sections, the call has to (1) infer the correct alignment of minus and plus lines, and (2) for each such "homologous pair", infer the edit operations that transformed the minus line into the plus line (see within-line-diff-algorithm).
For example, for a minus line, we may have inferred that the line has a homologous plus line, and that a word has been deleted. By default, delta applies a bright red background color to such a word and lets the foreground color be determined by the terminal emulator default foreground color (
minus-emph-style = normal "#901011"). On the other hand, for an added word, delta by default applies a bright green background color, and specifies that the foreground color should come from the syntax highlighting styles (plus-emph-style = syntax "#006000"). -
Process subhunk lines for side-by-side or unified output
At this point we have a collection of lines corresponding to a subhunk and, for each line, a specification of how syntax styles and diff styles are applied to substrings of the line. These data structures are processed differently according to whether unified or side-by-side diff display has been requested.
-
Superimpose syntax and diff styles for a line
Before we can output a line of code we need to take the two arrays of
(style, substring)pairs and compute a single output array of(style, substring)pairs, such that the output array represents the diff styles, but with foreground colors taken from the syntax highlighting, where appropriate. The call is here (superimpose_style_sections). -
Output a line with styles converted to ANSI color escape sequences
The
stylestructs that delta uses are implemented by theansi_termlibrary. Individual substrings are painted with their assigned style, and concatenated to form a utf-8 string containing ANSI color escape sequences.
Within-line diff algorithm
There is currently only one within-line diff algorithm implemented. This considers all possible pairings for a given line and for each one, computes the minimum number of edit operations between the candidate pair. The inferred pairing is the one with the smallest edit distance. (The number of comparisons is constrained by the possible interleavings, and furthermore a greedy heuristic is used, so that the number of comparisons is not quadratic).
Features
Delta features such as line-numbers, side-by-side, diff-so-fancy, etc can be considered to consist of (a) some feature-specific implementation code, and (b) a collection of key-value pairs specifying the values that certain delta options should take if that feature is enabled.
Accordingly, each such "feature" is implemented by a separate module under src/features/.
Each of these modules must export a function named make_feature whose job is to return key-value pairs for updating the user options.
Common terms used in the code
minus |
a removed line in a diff hunk (i.e. the lines starting with -) |
zero |
an unchanged line in a diff hunk |
plus |
an added line in a diff hunk (i.e. the lines starting with +) |
style |
a struct specifying foreground colors, background colors, and other attributes such as boldness, derived from ANSI sequences |
style_sections |
an array of (style, section) tuples |
paint |
to take a string without ANSI color sequences and return a new one with ANSI color sequences |
hunk |
a diff hunk |
subhunk |
a consecutive sequence of minus and/or plus lines, without any zero line |
TUI mode (delta --tui)
delta --tui runs gitu, from the delta-gitu crate (a fork of gitu), inside the delta process (src/subcommands/gitu.rs). It sets the running delta binary as gitu's diff renderer. delta is still a one-pass filter: gitu runs it as a child process for each diff it draws.
- Rows carry patch identity. gitu starts delta with
OSC1717=V1. delta then writes an OSC 1717 record on each row it draws: file header, hunk header, diff line (with its type and old and new line numbers) and commit (src/features/diff_line_metadata.rs). The records are invisible in a terminal. gitu parses the patch itself and uses the records to map each rendered row to a line of the patch, so it can navigate, fold and stage whatever delta's layout (side-by-side, line numbers, no+/-markers). Staging builds a patch from the selected lines and passes it togit apply. - gitu runs git's command again. git does not tell its pager what command it ran. gitu finds the git process in the process tree, as delta does to find the calling process, and runs that command itself, in the directory git ran it, without reading what git piped. It runs it again after each change, so
:accepts only read-only git commands. The command decides which operations are offered:git diffcan stage,git diff --cachedcan unstage, and a diff involving a commit can be applied and reversed. - Streaming. gitu passes git's output to delta as a shell pipeline would. It draws the first screen from what delta has drawn so far, cut back to whole hunks, and rebuilds the view when delta finishes.
- Features. gitu passes the features turned on in the session as
DELTA_FEATURES=+name ..., which delta adds to the user's config. - Stat rows. delta draws a file's header before it reads the file's hunks, so it cannot draw a
--statrow in place of the header. gitu counts stat rows from the patch and lays them out as git does.
