chore: import official kitty sources from upstream

Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
BlackAngelTV committed 2026-11-04 11:35:59 +01:00
commit 3d174c45a4
1134 files changed
+433629

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
def syntax_aliases(x: str) -> dict[str, str]:
ans = {}
for x in x.split():
k, _, v = x.partition(':')
ans[k] = v
return ans
+402
View File
@@ -0,0 +1,402 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"crypto/md5"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"unicode/utf8"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
var path_name_map, remote_dirs map[string]string
var mimetypes_cache, data_cache, hash_cache *utils.LRUCache[string, string]
var size_cache *utils.LRUCache[string, int64]
var lines_cache *utils.LRUCache[string, []string]
var light_highlighted_lines_cache *utils.LRUCache[string, []string]
var dark_highlighted_lines_cache *utils.LRUCache[string, []string]
var is_text_cache *utils.LRUCache[string, bool]
func init_caches() {
path_name_map = make(map[string]string, 32)
remote_dirs = make(map[string]string, 32)
const sz = 4096
size_cache = utils.NewLRUCache[string, int64](sz)
mimetypes_cache = utils.NewLRUCache[string, string](sz)
data_cache = utils.NewLRUCache[string, string](sz)
is_text_cache = utils.NewLRUCache[string, bool](sz)
lines_cache = utils.NewLRUCache[string, []string](sz)
light_highlighted_lines_cache = utils.NewLRUCache[string, []string](sz)
dark_highlighted_lines_cache = utils.NewLRUCache[string, []string](sz)
hash_cache = utils.NewLRUCache[string, string](sz)
}
func add_remote_dir(val string) {
x := filepath.Base(val)
idx := strings.LastIndex(x, "-")
if idx > -1 {
x = x[idx+1:]
} else {
x = ""
}
remote_dirs[val] = x
}
func mimetype_for_path(path string) string {
return mimetypes_cache.MustGetOrCreate(path, func(path string) string {
mt := utils.GuessMimeTypeWithFileSystemAccess(path)
if mt == "" {
mt = "application/octet-stream"
}
if utils.KnownTextualMimes[mt] {
if _, a, found := strings.Cut(mt, "/"); found {
mt = "text/" + a
}
}
return mt
})
}
func data_for_path(path string) (string, error) {
return data_cache.GetOrCreate(path, func(path string) (string, error) {
ans, err := os.ReadFile(path)
return utils.UnsafeBytesToString(ans), err
})
}
func size_for_path(path string) (int64, error) {
return size_cache.GetOrCreate(path, func(path string) (int64, error) {
s, err := os.Stat(path)
if err != nil {
return 0, err
}
return s.Size(), nil
})
}
func is_image(path string) bool {
return strings.HasPrefix(mimetype_for_path(path), "image/")
}
func is_path_text(path string) bool {
return is_text_cache.MustGetOrCreate(path, func(path string) bool {
if is_image(path) {
return false
}
s1, err := os.Stat(path)
if err == nil {
s2, err := os.Stat("/dev/null")
if err == nil && os.SameFile(s1, s2) {
return false
}
}
d, err := data_for_path(path)
if err != nil {
return false
}
return utf8.ValidString(d)
})
}
func hash_for_path(path string) (string, error) {
return hash_cache.GetOrCreate(path, func(path string) (string, error) {
ans, err := data_for_path(path)
if err != nil {
return "", err
}
hash := md5.Sum(utils.UnsafeStringToBytes(ans))
return utils.UnsafeBytesToString(hash[:]), err
})
}
func text_to_lines(text string) []string {
lines := make([]string, 0, 512)
splitlines_like_git(text, false, func(line string) { lines = append(lines, line) })
return lines
}
func sanitize(text string) string { return utils.ReplaceControlCodes(text, conf.Replace_tab_by, "\n") }
func lines_for_path(path string) ([]string, error) {
return lines_cache.GetOrCreate(path, func(path string) ([]string, error) {
ans, err := data_for_path(path)
if err != nil {
return nil, err
}
return text_to_lines(sanitize(ans)), nil
})
}
func highlighted_lines_for_path(path string) ([]string, error) {
plain_lines, err := lines_for_path(path)
if err != nil {
return nil, err
}
var ans []string
var found bool
if use_light_colors {
ans, found = light_highlighted_lines_cache.Get(path)
} else {
ans, found = dark_highlighted_lines_cache.Get(path)
}
if found && len(ans) == len(plain_lines) {
return ans, nil
}
return plain_lines, nil
}
type Collection struct {
changes, renames, type_map map[string]string
adds, removes *utils.Set[string]
all_paths []string
paths_to_highlight *utils.Set[string]
added_count, removed_count int
}
func (self *Collection) add_change(left, right string) {
self.changes[left] = right
self.all_paths = append(self.all_paths, left)
self.paths_to_highlight.Add(left)
self.paths_to_highlight.Add(right)
self.type_map[left] = `diff`
}
func (self *Collection) add_rename(left, right string) {
self.renames[left] = right
self.all_paths = append(self.all_paths, left)
self.type_map[left] = `rename`
}
func (self *Collection) add_add(right string) {
self.adds.Add(right)
self.all_paths = append(self.all_paths, right)
self.paths_to_highlight.Add(right)
self.type_map[right] = `add`
if is_path_text(right) {
num, _ := lines_for_path(right)
self.added_count += len(num)
}
}
func (self *Collection) add_removal(left string) {
self.removes.Add(left)
self.all_paths = append(self.all_paths, left)
self.paths_to_highlight.Add(left)
self.type_map[left] = `removal`
if is_path_text(left) {
num, _ := lines_for_path(left)
self.removed_count += len(num)
}
}
func (self *Collection) finalize() {
utils.StableSortWithKey(self.all_paths, func(path string) string {
return path_name_map[path]
})
}
func (self *Collection) Len() int { return len(self.all_paths) }
func (self *Collection) Items() int { return len(self.all_paths) }
func (self *Collection) Apply(f func(path, typ, changed_path string) error) error {
for _, path := range self.all_paths {
typ := self.type_map[path]
changed_path := ""
switch typ {
case "diff":
changed_path = self.changes[path]
case "rename":
changed_path = self.renames[path]
}
if err := f(path, typ, changed_path); err != nil {
return err
}
}
return nil
}
func allowed(path string, patterns ...string) bool {
name := filepath.Base(path)
for _, pat := range patterns {
if matched, err := filepath.Match(pat, name); err == nil && matched {
return false
}
}
return true
}
func remote_hostname(path string) (string, string) {
for q, val := range remote_dirs {
if strings.HasPrefix(path, q) {
return q, val
}
}
return "", ""
}
func resolve_remote_name(path, defval string) string {
remote_dir, rh := remote_hostname(path)
if remote_dir != "" && rh != "" {
r, err := filepath.Rel(remote_dir, path)
if err == nil {
return rh + ":" + r
}
}
return defval
}
func walk(base string, patterns []string, names *utils.Set[string], pmap, path_name_map map[string]string) error {
base, err := filepath.Abs(base)
if err != nil {
return err
}
return filepath.WalkDir(base, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
is_allowed := allowed(path, patterns...)
if !is_allowed {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if d.IsDir() {
return nil
}
path, err = filepath.Abs(path)
if err != nil {
return err
}
name, err := filepath.Rel(base, path)
if err != nil {
return err
}
if name != "." {
path_name_map[path] = name
names.Add(name)
pmap[name] = path
}
return nil
})
}
func (self *Collection) collect_files(left, right string) error {
left_names, right_names := utils.NewSet[string](16), utils.NewSet[string](16)
left_path_map, right_path_map := make(map[string]string, 16), make(map[string]string, 16)
err := walk(left, conf.Ignore_name, left_names, left_path_map, path_name_map)
if err != nil {
return err
}
if err = walk(right, conf.Ignore_name, right_names, right_path_map, path_name_map); err != nil {
return err
}
common_names := left_names.Intersect(right_names)
changed_names := utils.NewSet[string](common_names.Len())
for n := range common_names.Iterable() {
ld, err := data_for_path(left_path_map[n])
var rd string
if err == nil {
rd, err = data_for_path(right_path_map[n])
}
if err != nil {
return err
}
if ld != rd {
changed_names.Add(n)
self.add_change(left_path_map[n], right_path_map[n])
} else {
if lstat, err := os.Stat(left_path_map[n]); err == nil {
if rstat, err := os.Stat(right_path_map[n]); err == nil {
if lstat.Mode() != rstat.Mode() {
// identical files with only a mode change
changed_names.Add(n)
self.add_change(left_path_map[n], right_path_map[n])
}
}
}
}
}
removed := left_names.Subtract(common_names)
added := right_names.Subtract(common_names)
ahash, rhash := make(map[string]string, added.Len()), make(map[string]string, removed.Len())
for a := range added.Iterable() {
ahash[a], err = hash_for_path(right_path_map[a])
if err != nil {
return err
}
}
for r := range removed.Iterable() {
rhash[r], err = hash_for_path(left_path_map[r])
if err != nil {
return err
}
}
for name, rh := range rhash {
found := false
for n, ah := range ahash {
if ah == rh {
ld, _ := data_for_path(left_path_map[name])
rd, _ := data_for_path(right_path_map[n])
if ld == rd {
self.add_rename(left_path_map[name], right_path_map[n])
added.Discard(n)
found = true
break
}
}
}
if !found {
self.add_removal(left_path_map[name])
}
}
for name := range added.Iterable() {
self.add_add(right_path_map[name])
}
return nil
}
func create_collection(left, right string) (ans *Collection, err error) {
ans = &Collection{
changes: make(map[string]string),
renames: make(map[string]string),
type_map: make(map[string]string),
adds: utils.NewSet[string](32),
removes: utils.NewSet[string](32),
paths_to_highlight: utils.NewSet[string](32),
all_paths: make([]string, 0, 32),
}
left_stat, err := os.Stat(left)
if err != nil {
return nil, err
}
if left_stat.IsDir() {
err = ans.collect_files(left, right)
if err != nil {
return nil, err
}
} else {
pl, err := filepath.Abs(left)
if err != nil {
return nil, err
}
pr, err := filepath.Abs(right)
if err != nil {
return nil, err
}
path_name_map[pl] = resolve_remote_name(pl, left)
path_name_map[pr] = resolve_remote_name(pr, right)
ans.add_change(pl, pr)
}
ans.finalize()
return ans, err
}
+54
View File
@@ -0,0 +1,54 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func TestDiffCollectWalk(t *testing.T) {
tdir := t.TempDir()
j := func(x ...string) string { return filepath.Join(append([]string{tdir}, x...)...) }
_ = os.MkdirAll(j("a", "b"), 0o700)
_ = os.WriteFile(j("a/b/c"), nil, 0o600)
_ = os.WriteFile(j("b"), nil, 0o600)
_ = os.WriteFile(j("d"), nil, 0o600)
_ = os.WriteFile(j("e"), nil, 0o600)
_ = os.WriteFile(j("#d#"), nil, 0o600)
_ = os.WriteFile(j("e~"), nil, 0o600)
_ = os.MkdirAll(j("f"), 0o700)
_ = os.WriteFile(j("f/g"), nil, 0o600)
_ = os.WriteFile(j("h space"), nil, 0o600)
expected_names := utils.NewSetWithItems("d", "e", "f/g", "h space")
expected_pmap := map[string]string{
"d": j("d"),
"e": j("e"),
"f/g": j("f/g"),
"h space": j("h space"),
}
names := utils.NewSet[string](16)
pmap := make(map[string]string, 16)
if err := walk(tdir, []string{"*~", "#*#", "b"}, names, pmap, map[string]string{}); err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(
utils.Sort(expected_names.AsSlice(), strings.Compare),
utils.Sort(names.AsSlice(), strings.Compare),
); diff != "" {
t.Fatal(diff)
}
if diff := cmp.Diff(expected_pmap, pmap); diff != "" {
t.Fatal(diff)
}
}
+261
View File
@@ -0,0 +1,261 @@
// Copied from the Go stdlib, with modifications.
//https://github.com/golang/go/raw/master/src/internal/diff/diff.go
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package diff
import (
"bytes"
"fmt"
"sort"
"strings"
)
// A pair is a pair of values tracked for both the x and y side of a diff.
// It is typically a pair of line indexes.
type pair struct{ x, y int }
// Diff returns an anchored diff of the two texts old and new
// in the “unified diff” format. If old and new are identical,
// Diff returns a nil slice (no output).
//
// Unix diff implementations typically look for a diff with
// the smallest number of lines inserted and removed,
// which can in the worst case take time quadratic in the
// number of lines in the texts. As a result, many implementations
// either can be made to run for a long time or cut off the search
// after a predetermined amount of work.
//
// In contrast, this implementation looks for a diff with the
// smallest number of “unique” lines inserted and removed,
// where unique means a line that appears just once in both old and new.
// We call this an “anchored diff” because the unique lines anchor
// the chosen matching regions. An anchored diff is usually clearer
// than a standard diff, because the algorithm does not try to
// reuse unrelated blank lines or closing braces.
// The algorithm also guarantees to run in O(n log n) time
// instead of the standard O(n²) time.
//
// Some systems call this approach a “patience diff,” named for
// the “patience sorting” algorithm, itself named for a solitaire card game.
// We avoid that name for two reasons. First, the name has been used
// for a few different variants of the algorithm, so it is imprecise.
// Second, the name is frequently interpreted as meaning that you have
// to wait longer (to be patient) for the diff, meaning that it is a slower algorithm,
// when in fact the algorithm is faster than the standard one.
func Diff(oldName, old, newName, new string, num_of_context_lines int) []byte {
if old == new {
return nil
}
x := lines(old)
y := lines(new)
// Print diff header.
var out bytes.Buffer
fmt.Fprintf(&out, "diff %s %s\n", oldName, newName)
fmt.Fprintf(&out, "--- %s\n", oldName)
fmt.Fprintf(&out, "+++ %s\n", newName)
// Loop over matches to consider,
// expanding each match to include surrounding lines,
// and then printing diff chunks.
// To avoid setup/teardown cases outside the loop,
// tgs returns a leading {0,0} and trailing {len(x), len(y)} pair
// in the sequence of matches.
var (
done pair // printed up to x[:done.x] and y[:done.y]
chunk pair // start lines of current chunk
count pair // number of lines from each side in current chunk
ctext []string // lines for current chunk
)
for _, m := range tgs(x, y) {
if m.x < done.x {
// Already handled scanning forward from earlier match.
continue
}
// Expand matching lines as far possible,
// establishing that x[start.x:end.x] == y[start.y:end.y].
// Note that on the first (or last) iteration we may (or definitey do)
// have an empty match: start.x==end.x and start.y==end.y.
start := m
for start.x > done.x && start.y > done.y && x[start.x-1] == y[start.y-1] {
start.x--
start.y--
}
end := m
for end.x < len(x) && end.y < len(y) && x[end.x] == y[end.y] {
end.x++
end.y++
}
// Emit the mismatched lines before start into this chunk.
// (No effect on first sentinel iteration, when start = {0,0}.)
for _, s := range x[done.x:start.x] {
ctext = append(ctext, "-"+s)
count.x++
}
for _, s := range y[done.y:start.y] {
ctext = append(ctext, "+"+s)
count.y++
}
// If we're not at EOF and have too few common lines,
// the chunk includes all the common lines and continues.
C := num_of_context_lines // number of context lines
if (end.x < len(x) || end.y < len(y)) &&
(end.x-start.x < C || (len(ctext) > 0 && end.x-start.x < 2*C)) {
for _, s := range x[start.x:end.x] {
ctext = append(ctext, " "+s)
count.x++
count.y++
}
done = end
continue
}
// End chunk with common lines for context.
if len(ctext) > 0 {
n := min(end.x-start.x, C)
for _, s := range x[start.x : start.x+n] {
ctext = append(ctext, " "+s)
count.x++
count.y++
}
done = pair{start.x + n, start.y + n}
// Format and emit chunk.
// Convert line numbers to 1-indexed.
// Special case: empty file shows up as 0,0 not 1,0.
if count.x > 0 {
chunk.x++
}
if count.y > 0 {
chunk.y++
}
fmt.Fprintf(&out, "@@ -%d,%d +%d,%d @@\n", chunk.x, count.x, chunk.y, count.y)
for _, s := range ctext {
out.WriteString(s)
}
count.x = 0
count.y = 0
ctext = ctext[:0]
}
// If we reached EOF, we're done.
if end.x >= len(x) && end.y >= len(y) {
break
}
// Otherwise start a new chunk.
chunk = pair{end.x - C, end.y - C}
for _, s := range x[chunk.x:end.x] {
ctext = append(ctext, " "+s)
count.x++
count.y++
}
done = end
}
return out.Bytes()
}
// lines returns the lines in the file x, including newlines.
// If the file does not end in a newline, one is supplied
// along with a warning about the missing newline.
func lines(x string) []string {
l := strings.SplitAfter(x, "\n")
if l[len(l)-1] == "" {
l = l[:len(l)-1]
} else {
// Treat last line as having a message about the missing newline attached,
// using the same text as BSD/GNU diff (including the leading backslash).
l[len(l)-1] += "\n\\ No newline at end of file\n"
}
return l
}
// tgs returns the pairs of indexes of the longest common subsequence
// of unique lines in x and y, where a unique line is one that appears
// once in x and once in y.
//
// The longest common subsequence algorithm is as described in
// Thomas G. Szymanski, “A Special Case of the Maximal Common
// Subsequence Problem,” Princeton TR #170 (January 1975),
// available at https://research.swtch.com/tgs170.pdf.
func tgs(x, y []string) []pair {
// Count the number of times each string appears in a and b.
// We only care about 0, 1, many, counted as 0, -1, -2
// for the x side and 0, -4, -8 for the y side.
// Using negative numbers now lets us distinguish positive line numbers later.
m := make(map[string]int)
for _, s := range x {
if c := m[s]; c > -2 {
m[s] = c - 1
}
}
for _, s := range y {
if c := m[s]; c > -8 {
m[s] = c - 4
}
}
// Now unique strings can be identified by m[s] = -1+-4.
//
// Gather the indexes of those strings in x and y, building:
// xi[i] = increasing indexes of unique strings in x.
// yi[i] = increasing indexes of unique strings in y.
// inv[i] = index j such that x[xi[i]] = y[yi[j]].
var xi, yi, inv []int
for i, s := range y {
if m[s] == -1+-4 {
m[s] = len(yi)
yi = append(yi, i)
}
}
for i, s := range x {
if j, ok := m[s]; ok && j >= 0 {
xi = append(xi, i)
inv = append(inv, j)
}
}
// Apply Algorithm A from Szymanski's paper.
// In those terms, A = J = inv and B = [0, n).
// We add sentinel pairs {0,0}, and {len(x),len(y)}
// to the returned sequence, to help the processing loop.
J := inv
n := len(xi)
T := make([]int, n)
L := make([]int, n)
for i := range T {
T[i] = n + 1
}
for i := range n {
k := sort.Search(n, func(k int) bool {
return T[k] >= J[i]
})
T[k] = J[i]
L[i] = k + 1
}
k := 0
for _, v := range L {
if k < v {
k = v
}
}
seq := make([]pair, 2+k)
seq[1+k] = pair{len(x), len(y)} // sentinel at end
lastj := n
for i := n - 1; i >= 0; i-- {
if L[i] == k && J[i] < lastj {
seq[k] = pair{xi[i], yi[J[i]]}
k--
}
}
seq[0] = pair{0, 0} // sentinel at start
return seq
}
+51
View File
@@ -0,0 +1,51 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"fmt"
"os"
"sync"
"github.com/kovidgoyal/kitty/tools/highlight"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/images"
)
var _ = fmt.Print
var _ = os.WriteFile
type prefer_light_colors bool
func (s prefer_light_colors) StyleName() string {
return utils.IfElse(bool(s), conf.Pygments_style, conf.Dark_pygments_style)
}
func (s prefer_light_colors) UseLightColors() bool { return bool(s) }
func (s prefer_light_colors) SyntaxAliases() map[string]string { return conf.Syntax_aliases }
func (s prefer_light_colors) TextForPath(path string) (string, error) { return data_for_path(path) }
var highlighter = sync.OnceValue(func() highlight.Highlighter {
return highlight.NewHighlighter(sanitize)
})
func highlight_all(paths []string, light bool) {
ctx := images.Context{}
srd := prefer_light_colors(light)
if err := ctx.SafeParallel(0, len(paths), func(nums <-chan int) {
for i := range nums {
path := paths[i]
raw, err := highlighter().HighlightFile(path, &srd)
if err != nil {
continue
}
if light {
light_highlighted_lines_cache.Set(path, text_to_lines(raw))
} else {
dark_highlighted_lines_cache.Set(path, text_to_lines(raw))
}
}
}); err != nil {
panic(err)
}
}
+241
View File
@@ -0,0 +1,241 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"archive/tar"
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/kovidgoyal/kitty/kittens/ssh"
"github.com/kovidgoyal/kitty/tools/cli"
"github.com/kovidgoyal/kitty/tools/config"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
func load_config(opts *Options) (ans *Config, err error) {
ans = NewConfig()
p := config.ConfigParser{LineHandler: ans.Parse}
err = p.LoadConfig("diff.conf", opts.Config, opts.Override)
if err != nil {
return nil, err
}
ans.KeyboardShortcuts = config.ResolveShortcuts(ans.KeyboardShortcuts)
return ans, nil
}
var conf *Config
var opts *Options
var lp *loop.Loop
var temp_files []string
func resolve_path(path string) (ans string, is_dir bool, err error) {
var s fs.FileInfo
if s, err = os.Stat(path); err != nil {
return
} else {
if s.Mode()&fs.ModeNamedPipe != 0 {
var src, dest *os.File
if src, err = os.Open(path); err != nil {
return
}
defer src.Close()
if dest, err = os.CreateTemp("", fmt.Sprintf("*-pipe-%s", filepath.Base(path))); err != nil {
return
}
defer dest.Close()
temp_files = append(temp_files, dest.Name())
if _, err = io.Copy(dest, src); err != nil {
return
}
return dest.Name(), false, nil
} else {
return path, s.IsDir(), nil
}
}
}
func get_ssh_file(hostname, rpath string) (string, error) {
tdir, err := os.MkdirTemp("", "*-"+hostname)
if err != nil {
return "", err
}
add_remote_dir(tdir)
is_abs := strings.HasPrefix(rpath, "/")
for strings.HasPrefix(rpath, "/") {
rpath = rpath[1:]
}
cmd := []string{ssh.SSHExe(), hostname, "tar", "--dereference", "--create", "--file", "-"}
if is_abs {
cmd = append(cmd, "-C", "/")
}
cmd = append(cmd, rpath)
c := exec.Command(cmd[0], cmd[1:]...)
c.Stdin, c.Stderr = os.Stdin, os.Stderr
stdout, err := c.Output()
if err != nil {
return "", fmt.Errorf("Failed to ssh into remote host %s to get file %s with error: %w", hostname, rpath, err)
}
tf := tar.NewReader(bytes.NewReader(stdout))
count, err := utils.ExtractAllFromTar(tf, tdir, utils.TarExtractOptions{DontPreserveSuidAndSgid: true})
if err != nil {
return "", fmt.Errorf("Failed to untar data from remote host %s to get file %s with error: %w", hostname, rpath, err)
}
ans := filepath.Join(tdir, rpath)
if _, err = os.Lstat(ans); err == nil {
// The archive contains rpath itself, which is either the requested
// file or directory
return ans, nil
} else if !errors.Is(err, fs.ErrNotExist) {
return "", err
}
// rpath was expanded by the remote shell, for example, ~/file, so
// look for the single file in the archive
if count == 1 {
if err = filepath.WalkDir(tdir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
ans = path
return fs.SkipAll
}
return nil
}); err != nil {
return "", err
}
}
return ans, nil
}
func get_remote_file(path string) (string, error) {
if strings.HasPrefix(path, "ssh:") {
parts := strings.SplitN(path, ":", 3)
if len(parts) == 3 {
return get_ssh_file(parts[1], parts[2])
}
}
return path, nil
}
func main(_ *cli.Command, opts_ *Options, args []string) (rc int, err error) {
opts = opts_
conf, err = load_config(opts)
if err != nil {
return 1, err
}
if len(args) != 2 {
return 1, fmt.Errorf("You must specify exactly two files/directories to compare")
}
if err = set_diff_command(conf.Diff_cmd); err != nil {
return 1, err
}
switch conf.Color_scheme {
case Color_scheme_light:
use_light_colors = true
case Color_scheme_dark:
use_light_colors = false
case Color_scheme_auto:
use_light_colors = false
}
init_caches()
defer func() {
for tdir := range remote_dirs {
// Directories extracted from the remote host can be read-only.
// This is best effort cleanup of a temp dir, so errors are ignored.
_ = filepath.WalkDir(tdir, func(path string, d fs.DirEntry, err error) error {
if err == nil && d.IsDir() {
_ = os.Chmod(path, 0o700)
}
return nil
})
os.RemoveAll(tdir)
}
}()
left, err := get_remote_file(args[0])
if err != nil {
return 1, err
}
right, err := get_remote_file(args[1])
if err != nil {
return 1, err
}
defer func() {
for _, path := range temp_files {
os.Remove(path)
}
}()
var left_is_dir, right_is_dir bool
if left, left_is_dir, err = resolve_path(left); err != nil {
return 1, err
}
if right, right_is_dir, err = resolve_path(right); err != nil {
return 1, err
}
if left_is_dir != right_is_dir {
return 1, fmt.Errorf("The items to be diffed should both be either directories or files. Comparing a directory to a file is not valid.'")
}
lp, err = loop.New()
loop.MouseTrackingMode(lp, loop.BUTTONS_AND_DRAG_MOUSE_TRACKING)
if err != nil {
return 1, err
}
lp.ColorSchemeChangeNotifications()
h := Handler{left: left, right: right, lp: lp}
lp.OnInitialize = func() (string, error) {
lp.SetCursorVisible(false)
lp.SetCursorShape(loop.BAR_CURSOR, true)
lp.AllowLineWrapping(false)
lp.SetWindowTitle(fmt.Sprintf("%s vs. %s", left, right))
lp.QueryCapabilities()
h.initialize()
return "", nil
}
lp.OnCapabilitiesReceived = func(tc loop.TerminalCapabilities) error {
if !tc.KeyboardProtocol {
return fmt.Errorf("This terminal does not support the kitty keyboard protocol, or you are running inside a terminal multiplexer that is blocking querying for kitty keyboard protocol support. The diff kitten cannot function without it.")
}
h.on_capabilities_received(tc)
return nil
}
lp.OnWakeup = h.on_wakeup
lp.OnFinalize = func() string {
lp.SetCursorVisible(true)
lp.SetCursorShape(loop.BLOCK_CURSOR, true)
h.finalize()
return ""
}
lp.OnResize = h.on_resize
lp.OnKeyEvent = h.on_key_event
lp.OnText = h.on_text
lp.OnMouseEvent = h.on_mouse_event
err = lp.Run()
if err != nil {
return 1, err
}
ds := lp.DeathSignalName()
if ds != "" {
fmt.Println("Killed by signal: ", ds)
lp.KillIfSignalled()
return 1, nil
}
return
}
func EntryPoint(parent *cli.Command) {
create_cmd(parent, main)
}
+442
View File
@@ -0,0 +1,442 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import sys
from functools import partial
from kitty.conf.types import Definition
from kitty.constants import appname
from kitty.simple_cli_definitions import CONFIG_HELP, CompletionSpec
def main(args: list[str]) -> None:
raise SystemExit('Must be run as kitten diff')
definition = Definition(
'!kittens.diff',
)
agr = definition.add_group
egr = definition.end_group
opt = definition.add_option
map = definition.add_map
mma = definition.add_mouse_map
# diff {{{
agr('diff', 'Diffing')
opt(
'syntax_aliases',
'pyj:py pyi:py recipe:py',
ctype='strdict_ _:',
option_type='syntax_aliases',
long_text="""
File extension aliases for syntax highlight. For example, to syntax highlight
:file:`file.xyz` as :file:`file.abc` use a setting of :code:`xyz:abc`.
Multiple aliases must be separated by spaces.
""",
)
opt('num_context_lines', '3', option_type='positive_int', long_text='The number of lines of context to show around each change.')
opt(
'diff_cmd',
'auto',
long_text="""
The diff command to use. Must contain the placeholder :code:`_CONTEXT_` which
will be replaced by the number of lines of context. A few special values are allowed:
:code:`auto` will automatically pick an available diff implementation. :code:`builtin`
will use the anchored diff algorithm from the Go standard library. :code:`git` will
use the git command to do the diffing. :code:`diff` will use the diff command to
do the diffing.
""",
)
opt('replace_tab_by', '\\x20\\x20\\x20\\x20', option_type='python_string', long_text='The string to replace tabs with. Default is to use four spaces.')
opt(
'+ignore_name',
'',
ctype='string',
add_to_default=False,
long_text="""
A glob pattern that is matched against only the filename of files and directories. Matching
files and directories are ignored when scanning the filesystem to look for files to diff.
Can be specified multiple times to use multiple patterns. For example::
ignore_name .git
ignore_name *~
ignore_name *.pyc
""",
)
opt(
'mark_moved_lines',
'yes',
option_type='to_bool',
long_text="""
Highlight lines that are moved, that is removed from the left and added to the right
differently, using the :opt:`moved_bg` color.""",
)
opt(
'word_diff_mode',
'words',
choices=('words', 'central'),
long_text="""
The algorithm to use for highlighting which parts of changed lines differ.
When set to :code:`words`, changed words in each changed line are highlighted.
When set to :code:`central`, the central changed region of each changed line is
highlighted at the byte level. The :code:`words` mode is generally more useful
as it shows exactly which words changed. Note that the :code:`words` mode
only applies when a changed chunk has equal numbers of added and removed lines.
""",
)
opt(
'word_regex',
r'[^\s\p{P}]+',
long_text="""
The regular expression used to define a word when :opt:`word_diff_mode` is
:code:`words`. The default value matches any run of non-whitespace and
non-punctuation characters. The expression must be a valid Go regular expression.
If an invalid expression is provided, diff will fail with an error.
""",
)
opt(
'sticky_header',
'yes',
option_type='to_bool',
long_text="""
When scrolled past the header of a file, keep the file's name and separator
pinned to the top of the screen.
""",
)
egr() # }}}
# colors {{{
agr('colors', 'Colors')
opt(
'color_scheme',
'auto',
choices=('auto', 'light', 'dark'),
long_text="""
Whether to use the light or dark colors. The default of :code:`auto` means
to follow the parent terminal color scheme. Note that the actual colors used
for dark schemes are set by the :code:`dark_*` settings below and the non-prefixed
settings are used for light colors.
""",
)
opt(
'pygments_style',
'default',
long_text="""
The pygments color scheme to use for syntax highlighting. See :link:`pygments
builtin styles <https://pygments.org/styles/>` for a list of schemes. Note that
this **does not** change the colors used for diffing,
only the colors used for syntax highlighting. To change the general colors use the settings below.
This sets the colors used for light color schemes, use :opt:`dark_pygments_style` to change the
colors for dark color schemes.
""",
)
opt(
'dark_pygments_style',
'github-dark',
long_text="""
The pygments color scheme to use for syntax highlighting with dark colors. See :link:`pygments
builtin styles <https://pygments.org/styles/>` for a list of schemes. Note that
this **does not** change the colors used for diffing,
only the colors used for syntax highlighting. To change the general colors use the settings below.
This sets the colors used for dark color schemes, use :opt:`pygments_style` to change the
colors for light color schemes.""",
)
opt('foreground', 'black', option_type='to_color', long_text='Basic colors')
opt('dark_foreground', '#f8f8f2', option_type='to_color')
dark_bg = '#212830'
opt(
'background',
'white',
option_type='to_color',
)
opt(
'dark_background',
dark_bg,
option_type='to_color',
)
opt('title_fg', 'black', option_type='to_color', long_text='Title colors')
opt('dark_title_fg', 'white', option_type='to_color')
opt(
'title_bg',
'white',
option_type='to_color',
)
opt(
'dark_title_bg',
dark_bg,
option_type='to_color',
)
opt('margin_bg', '#fafbfc', option_type='to_color', long_text='Margin colors')
opt('dark_margin_bg', dark_bg, option_type='to_color')
opt('margin_fg', '#aaaaaa', option_type='to_color')
opt('dark_margin_fg', '#aaaaaa', option_type='to_color')
opt('removed_bg', '#ffeef0', option_type='to_color', long_text='Removed text backgrounds')
opt('dark_removed_bg', '#352c33', option_type='to_color')
opt('highlight_removed_bg', '#fdb8c0', option_type='to_color')
opt('dark_highlight_removed_bg', '#5c3539', option_type='to_color')
opt('removed_margin_bg', '#ffdce0', option_type='to_color')
opt('dark_removed_margin_bg', '#5c3539', option_type='to_color')
opt('added_bg', '#e6ffed', option_type='to_color', long_text='Added text backgrounds')
opt('dark_added_bg', '#263834', option_type='to_color')
opt('highlight_added_bg', '#acf2bd', option_type='to_color')
opt('dark_highlight_added_bg', '#31503d', option_type='to_color')
opt('added_margin_bg', '#cdffd8', option_type='to_color')
opt('dark_added_margin_bg', '#31503d', option_type='to_color')
opt('moved_bg', '#fffde7', option_type='to_color', long_text='Moved text backgrounds (same text that was removed in one place and added in another)')
opt('dark_moved_bg', '#003333', option_type='to_color')
opt('moved_margin_bg', '#fff3b0', option_type='to_color')
opt('dark_moved_margin_bg', '#00495b', option_type='to_color')
opt('filler_bg', '#fafbfc', option_type='to_color', long_text='Filler (empty) line background')
opt('dark_filler_bg', '#262c36', option_type='to_color')
opt('margin_filler_bg', 'none', option_type='to_color_or_none', long_text='Filler (empty) line background in margins, defaults to the filler background')
opt('dark_margin_filler_bg', 'none', option_type='to_color_or_none')
opt('hunk_margin_bg', '#dbedff', option_type='to_color', long_text='Hunk header colors')
opt('dark_hunk_margin_bg', '#0c2d6b', option_type='to_color')
opt('hunk_bg', '#f1f8ff', option_type='to_color')
opt('dark_hunk_bg', '#253142', option_type='to_color')
opt('search_bg', '#444', option_type='to_color', long_text='Highlighting')
opt('dark_search_bg', '#2c599c', option_type='to_color')
opt('search_fg', 'white', option_type='to_color')
opt('dark_search_fg', 'white', option_type='to_color')
opt('select_bg', '#b4d5fe', option_type='to_color')
opt('dark_select_bg', '#2c599c', option_type='to_color')
opt('select_fg', 'black', option_type='to_color_or_none')
opt('dark_select_fg', 'white', option_type='to_color_or_none')
egr() # }}}
# shortcuts {{{
agr('shortcuts', 'Keyboard shortcuts')
map(
'Quit',
'quit --allow-fallback=shifted,ascii q quit',
)
map(
'Quit',
'quit esc quit',
)
map(
'Scroll down',
'scroll_down --allow-fallback=shifted,ascii j scroll_by 1',
)
map(
'Scroll down',
'scroll_down down scroll_by 1',
)
map(
'Scroll up',
'scroll_up --allow-fallback=shifted,ascii k scroll_by -1',
)
map(
'Scroll up',
'scroll_up up scroll_by -1',
)
map(
'Scroll to top',
'scroll_top home scroll_to start',
)
map(
'Scroll to bottom',
'scroll_bottom end scroll_to end',
)
map(
'Scroll to next page',
'scroll_page_down page_down scroll_to next-page',
)
map(
'Scroll to next page',
'scroll_page_down space scroll_to next-page',
)
map(
'Scroll to next page',
'scroll_page_down --allow-fallback=shifted,ascii ctrl+f scroll_to next-page',
)
map(
'Scroll to previous page',
'scroll_page_up page_up scroll_to prev-page',
)
map(
'Scroll to previous page',
'scroll_page_up --allow-fallback=shifted,ascii ctrl+b scroll_to prev-page',
)
map(
'Scroll down half page',
'scroll_half_page_down --allow-fallback=shifted,ascii ctrl+d scroll_to next-half-page',
)
map(
'Scroll up half page',
'scroll_half_page_up --allow-fallback=shifted,ascii ctrl+u scroll_to prev-half-page',
)
map(
'Scroll to next change',
'next_change --allow-fallback=shifted,ascii n scroll_to next-change',
)
map(
'Scroll to previous change',
'prev_change --allow-fallback=shifted,ascii p scroll_to prev-change',
)
map(
'Scroll to next file',
'next_file --allow-fallback=shifted,ascii shift+j scroll_to next-file',
)
map(
'Scroll to previous file',
'prev_file --allow-fallback=shifted,ascii shift+k scroll_to prev-file',
)
map(
'Show all context',
'all_context --allow-fallback=shifted,ascii a change_context all',
)
map(
'Show default context',
'default_context = change_context default',
)
map(
'Increase context',
'increase_context + change_context 5',
)
map(
'Decrease context',
'decrease_context - change_context -5',
)
map(
'Search forward',
'search_forward / start_search regex forward',
)
map(
'Search backward',
'search_backward ? start_search regex backward',
)
map(
'Scroll to next search match',
'next_match . scroll_to next-match',
)
map(
'Scroll to next search match',
'next_match > scroll_to next-match',
)
map(
'Scroll to previous search match',
'prev_match , scroll_to prev-match',
)
map(
'Scroll to previous search match',
'prev_match < scroll_to prev-match',
)
map(
'Search forward (no regex)',
'search_forward_simple --allow-fallback=shifted,ascii f start_search substring forward',
)
map(
'Search backward (no regex)',
'search_backward_simple --allow-fallback=shifted,ascii b start_search substring backward',
)
map('Copy selection to clipboard', 'copy_to_clipboard --allow-fallback=shifted,ascii y copy_to_clipboard')
map(
'Copy selection to clipboard or exit if no selection is present',
'copy_to_clipboard_or_exit --allow-fallback=shifted,ascii ctrl+c copy_to_clipboard_or_exit',
)
egr() # }}}
OPTIONS = partial(
"""\
--context
type=int
default=-1
Number of lines of context to show between changes. Negative values use the
number set in :file:`diff.conf`.
--config
type=list
completion=type:file ext:conf group:"Config files" kwds:none,NONE
{config_help}
--override -o
type=list
Override individual configuration options, can be specified multiple times.
Syntax: :italic:`name=value`. For example: :italic:`-o background=gray`
""".format,
config_help=CONFIG_HELP.format(conf_name='diff', appname=appname),
)
help_text = 'Show a side-by-side diff of the specified files/directories. You can also use :italic:`ssh:hostname:remote-file-path` to diff remote files.'
usage = 'file_or_directory_left file_or_directory_right'
if __name__ == '__main__':
main(sys.argv)
elif __name__ == '__doc__':
from kitty.guess_mime_type import text_mimes
cd = sys.cli_docs # type: ignore
cd['usage'] = usage
cd['options'] = OPTIONS
cd['help_text'] = help_text
cd['short_desc'] = 'Pretty, side-by-side diffing of files and images'
mimes = ' '.join(f'mime:{x}' for x in ('text/*', 'image/*') + tuple(text_mimes))
cd['args_completion'] = CompletionSpec.from_string(f'type:file {mimes} group:"Text and image files"')
elif __name__ == '__conf__':
sys.options_definition = definition # type: ignore
+227
View File
@@ -0,0 +1,227 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"fmt"
"math"
"strconv"
"strings"
"sync"
"github.com/kovidgoyal/kitty"
"github.com/kovidgoyal/kitty/tools/config"
"github.com/kovidgoyal/kitty/tools/tty"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type KittyOpts struct {
Wheel_scroll_multiplier float64
Copy_on_select bool
}
func read_relevant_kitty_opts() KittyOpts {
ans := KittyOpts{Wheel_scroll_multiplier: kitty.KittyConfigDefaults.Wheel_scroll_multiplier}
handle_line := func(key, val string) error {
switch key {
case "wheel_scroll_multiplier":
v, err := strconv.ParseFloat(val, 64)
if err == nil {
ans.Wheel_scroll_multiplier = v
}
case "copy_on_select":
ans.Copy_on_select = strings.ToLower(val) == "clipboard"
}
return nil
}
config.ReadKittyConfig(handle_line)
return ans
}
var RelevantKittyOpts = sync.OnceValue(func() KittyOpts {
return read_relevant_kitty_opts()
})
func (self *Handler) handle_wheel_event(up bool) {
amt := int(math.Round(RelevantKittyOpts().Wheel_scroll_multiplier))
if amt == 0 {
amt = 1
}
if up {
amt *= -1
}
_ = self.dispatch_action(`scroll_by`, strconv.Itoa(amt))
}
type line_pos struct {
min_x, max_x int
y ScrollPos
}
func (self *line_pos) MinX() int { return self.min_x }
func (self *line_pos) MaxX() int { return self.max_x }
func (self *line_pos) Equal(other tui.LinePos) bool {
if o, ok := other.(*line_pos); ok {
return self.y == o.y
}
return false
}
func (self *line_pos) LessThan(other tui.LinePos) bool {
if o, ok := other.(*line_pos); ok {
return self.y.Less(o.y)
}
return false
}
func (self *Handler) line_pos_from_pos(x int, pos ScrollPos) *line_pos {
ans := line_pos{min_x: self.logical_lines.margin_size, y: pos}
available_cols := self.logical_lines.columns / 2
if x >= available_cols {
ans.min_x += available_cols
ans.max_x = utils.Max(ans.min_x, ans.min_x+self.logical_lines.ScreenLineAt(pos).right.wcswidth()-1)
} else {
ans.max_x = utils.Max(ans.min_x, ans.min_x+self.logical_lines.ScreenLineAt(pos).left.wcswidth()-1)
}
return &ans
}
func (self *Handler) start_mouse_selection(ev *loop.MouseEvent) {
available_cols := self.logical_lines.columns / 2
if ev.Cell.Y >= self.screen_size.num_lines || ev.Cell.X < self.logical_lines.margin_size || (ev.Cell.X >= available_cols && ev.Cell.X < available_cols+self.logical_lines.margin_size) {
return
}
pos := self.scroll_pos
self.logical_lines.IncrementScrollPosBy(&pos, ev.Cell.Y)
ll := self.logical_lines.At(pos.logical_line)
if ll.line_type == EMPTY_LINE || ll.line_type == IMAGE_LINE {
return
}
self.mouse_selection.StartNewSelection(ev, self.line_pos_from_pos(ev.Cell.X, pos), 0, self.screen_size.num_lines-1, self.screen_size.cell_width, self.screen_size.cell_height)
}
func (self *Handler) drag_scroll_tick(timer_id loop.IdType) error {
return self.mouse_selection.DragScrollTick(timer_id, self.lp, self.drag_scroll_tick, func(amt int, ev *loop.MouseEvent) error {
if self.scroll_lines(amt) != 0 {
self.do_update_mouse_selection(ev)
self.draw_screen()
}
return nil
})
}
var debugprintln = tty.DebugPrintln
func (self *Handler) update_mouse_selection(ev *loop.MouseEvent) {
if !self.mouse_selection.IsActive() {
return
}
if self.mouse_selection.OutOfVerticalBounds(ev) {
self.mouse_selection.DragScroll(ev, self.lp, self.drag_scroll_tick)
return
}
if self.do_update_mouse_selection(ev) {
self.draw_screen()
}
}
func (self *Handler) do_update_mouse_selection(ev *loop.MouseEvent) (changed bool) {
pos := self.scroll_pos
y := ev.Cell.Y
y = utils.Max(0, utils.Min(y, self.screen_size.num_lines-1))
self.logical_lines.IncrementScrollPosBy(&pos, y)
x := self.mouse_selection.StartLine().MinX()
return self.mouse_selection.Update(ev, self.line_pos_from_pos(x, pos))
}
func (self *Handler) clear_mouse_selection() {
self.mouse_selection.Clear()
}
func (self *Handler) text_for_current_mouse_selection() string {
if self.mouse_selection.IsEmpty() {
return ""
}
text := make([]byte, 0, 2048)
start_pos, end_pos := *self.mouse_selection.StartLine().(*line_pos), *self.mouse_selection.EndLine().(*line_pos)
// if start is after end, swap them
if end_pos.y.Less(start_pos.y) {
start_pos, end_pos = end_pos, start_pos
}
start, end := start_pos.y, end_pos.y
is_left := start_pos.min_x == self.logical_lines.margin_size
line_for_pos := func(pos ScrollPos) string {
if is_left {
return self.logical_lines.ScreenLineAt(pos).left.marked_up_text
}
return self.logical_lines.ScreenLineAt(pos).right.marked_up_text
}
for pos, prev_ll_idx := start, start.logical_line; pos.Less(end) || pos == end; {
ll := self.logical_lines.At(pos.logical_line)
var line string
switch ll.line_type {
case EMPTY_LINE:
case IMAGE_LINE:
if pos.screen_line < ll.image_lines_offset {
line = line_for_pos(pos)
}
default:
line = line_for_pos(pos)
}
line = wcswidth.StripEscapeCodes(line)
s, e := self.mouse_selection.LineBounds(self.line_pos_from_pos(start_pos.min_x, pos))
s -= start_pos.min_x
e -= start_pos.min_x
line = wcswidth.TruncateToVisualLength(line, e+1)
if s > 0 {
prefix := wcswidth.TruncateToVisualLength(line, s)
line = line[len(prefix):]
}
// TODO: look at the original line from the source and handle leading tabs as per it
if pos.logical_line > prev_ll_idx {
line = "\n" + line
}
prev_ll_idx = pos.logical_line
if line != "" {
text = append(text, line...)
}
if self.logical_lines.IncrementScrollPosBy(&pos, 1) == 0 {
break
}
}
return utils.UnsafeBytesToString(text)
}
func (self *Handler) finish_mouse_selection(ev *loop.MouseEvent) {
if !self.mouse_selection.IsActive() {
return
}
self.update_mouse_selection(ev)
self.mouse_selection.Finish()
text := self.text_for_current_mouse_selection()
if text != "" {
if RelevantKittyOpts().Copy_on_select {
self.lp.CopyTextToClipboard(text)
} else {
self.lp.CopyTextToPrimarySelection(text)
}
}
}
func (self *Handler) add_mouse_selection_to_line(line_pos ScrollPos, y int) string {
if self.mouse_selection.IsEmpty() {
return ""
}
selection_sgr := format_as_sgr.selection
x := self.mouse_selection.StartLine().MinX()
return self.mouse_selection.LineFormatSuffix(self.line_pos_from_pos(x, line_pos), selection_sgr[2:len(selection_sgr)-1], y)
}
+655
View File
@@ -0,0 +1,655 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"bytes"
"errors"
"fmt"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
parallel "github.com/kovidgoyal/go-parallel"
"github.com/kovidgoyal/kitty/tools/simdstring"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/images"
"github.com/kovidgoyal/kitty/tools/utils/shlex"
)
var _ = fmt.Print
const GIT_DIFF = `git diff --no-color --no-ext-diff --exit-code -U_CONTEXT_ --no-index --`
const DIFF_DIFF = `diff -p -U _CONTEXT_ --`
var diff_cmd []string
var GitExe = sync.OnceValue(func() string {
return utils.FindExe("git")
})
var DiffExe = sync.OnceValue(func() string {
return utils.FindExe("diff")
})
func find_differ() {
if GitExe() != "git" && exec.Command(GitExe(), "--help").Run() == nil {
diff_cmd, _ = shlex.Split(GIT_DIFF)
} else if DiffExe() != "diff" && exec.Command(DiffExe(), "--help").Run() == nil {
diff_cmd, _ = shlex.Split(DIFF_DIFF)
} else {
diff_cmd = []string{}
}
}
func set_diff_command(q string) error {
switch q {
case "auto":
find_differ()
case "builtin", "":
diff_cmd = []string{}
case "diff":
diff_cmd, _ = shlex.Split(DIFF_DIFF)
case "git":
diff_cmd, _ = shlex.Split(GIT_DIFF)
default:
c, err := shlex.Split(q)
if err != nil {
return err
}
diff_cmd = c
}
return nil
}
// Region represents a highlighted byte range within a line.
type Region struct{ offset, size int }
// Center holds the highlighted regions for the left (removed) and right (added) sides of a changed line pair.
type Center struct {
left_regions []Region
right_regions []Region
}
type Chunk struct {
is_context bool
left_start, right_start int
left_count, right_count int
centers []Center
}
func (self *Chunk) add_line() {
self.right_count++
}
func (self *Chunk) remove_line() {
self.left_count++
}
func (self *Chunk) context_line() {
self.left_count++
self.right_count++
}
// changed_center computes the central changed region of left/right at the byte level.
func changed_center(left, right string) (ans Center) {
if len(left) > 0 && len(right) > 0 {
ll, rl := len(left), len(right)
ml := utils.Min(ll, rl)
offset := 0
for ; offset < ml && left[offset] == right[offset]; offset++ {
}
suffix_count := 0
for ; suffix_count < ml && left[ll-1-suffix_count] == right[rl-1-suffix_count]; suffix_count++ {
}
left_size := ll - suffix_count - offset
right_size := rl - suffix_count - offset
if left_size > 0 {
ans.left_regions = []Region{{offset: offset, size: left_size}}
}
if right_size > 0 {
ans.right_regions = []Region{{offset: offset, size: right_size}}
}
}
return
}
var word_regexp = sync.OnceValues(func() (*regexp.Regexp, error) {
pattern := `\S+`
if conf != nil && conf.Word_regex != "" {
pattern = conf.Word_regex
}
return regexp.Compile(pattern)
})
// The LCS table in word_diff_center needs one cell per pair of words between
// the first and last changed word, so lines where that span is longer than
// this fall back to changed_center.
const max_word_diff_words = 2048
// word_diff_center computes highlighted regions for changed words between left and right.
func word_diff_center(left, right string, re *regexp.Regexp) Center {
left_matches := re.FindAllStringIndex(left, -1)
right_matches := re.FindAllStringIndex(right, -1)
// Changed words are only highlighted when they pair up by position, which
// is impossible when the word counts differ, so skip the LCS in that case.
if len(left_matches) != len(right_matches) {
return changed_center(left, right)
}
type word struct {
text string
offset int
size int
}
left_words := make([]word, len(left_matches))
right_words := make([]word, len(right_matches))
for i, m := range left_matches {
left_words[i] = word{text: left[m[0]:m[1]], offset: m[0], size: m[1] - m[0]}
}
for i, m := range right_matches {
right_words[i] = word{text: right[m[0]:m[1]], offset: m[0], size: m[1] - m[0]}
}
// Strip common prefix and suffix words so LCS only runs on the differing middle.
prefix := 0
for prefix < len(left_words) && prefix < len(right_words) && left_words[prefix].text == right_words[prefix].text {
prefix++
}
suffix := 0
for suffix < len(left_words)-prefix && suffix < len(right_words)-prefix &&
left_words[len(left_words)-1-suffix].text == right_words[len(right_words)-1-suffix].text {
suffix++
}
lw := left_words[prefix : len(left_words)-suffix]
rw := right_words[prefix : len(right_words)-suffix]
m, n := len(lw), len(rw)
if max(m, n) > max_word_diff_words {
return changed_center(left, right)
}
// LCS dynamic programming table
dp := make([][]int32, m+1)
for i := range dp {
dp[i] = make([]int32, n+1)
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if lw[i-1].text == rw[j-1].text {
dp[i][j] = dp[i-1][j-1] + 1
} else if dp[i-1][j] > dp[i][j-1] {
dp[i][j] = dp[i-1][j]
} else {
dp[i][j] = dp[i][j-1]
}
}
}
// Backtrack to find changed words within the middle slice.
left_changed := make([]bool, m)
right_changed := make([]bool, n)
i, j := m, n
for i > 0 && j > 0 {
if lw[i-1].text == rw[j-1].text {
i--
j--
} else if dp[i-1][j] > dp[i][j-1] {
left_changed[i-1] = true
i--
} else {
right_changed[j-1] = true
j--
}
}
for i > 0 {
left_changed[i-1] = true
i--
}
for j > 0 {
right_changed[j-1] = true
j--
}
// Remap changed flags to absolute indices within the full words arrays.
left_changed_abs := make([]bool, len(left_words))
right_changed_abs := make([]bool, len(right_words))
for k, c := range left_changed {
left_changed_abs[prefix+k] = c
}
for k, c := range right_changed {
right_changed_abs[prefix+k] = c
}
// Verify that every changed word at index i has a corresponding changed
// word at the same index i on the other side. If any position is changed
// on exactly one side, the lines differ in word count and it makes more
// sense to highlight the single changed central region of the whole line.
max_idx := max(len(left_words), len(right_words))
for idx := range max_idx {
lc := idx < len(left_words) && left_changed_abs[idx]
rc := idx < len(right_words) && right_changed_abs[idx]
if lc != rc {
return changed_center(left, right)
}
}
// All changed words are positionally paired. Apply character-level
// prefix/suffix trimming to each pair so only the differing central bytes
// are highlighted.
var ans Center
for idx := range left_words {
if !left_changed_abs[idx] {
continue
}
lword := left_words[idx]
rword := right_words[idx]
lt := left[lword.offset : lword.offset+lword.size]
rt := right[rword.offset : rword.offset+rword.size]
ll, rl := len(lt), len(rt)
ml := min(ll, rl)
cpfx := 0
for cpfx < ml && lt[cpfx] == rt[cpfx] {
cpfx++
}
csfx := 0
for csfx < ml-cpfx && lt[ll-1-csfx] == rt[rl-1-csfx] {
csfx++
}
lsize := ll - cpfx - csfx
rsize := rl - cpfx - csfx
if lsize > 0 {
ans.left_regions = append(ans.left_regions, Region{offset: lword.offset + cpfx, size: lsize})
}
if rsize > 0 {
ans.right_regions = append(ans.right_regions, Region{offset: rword.offset + cpfx, size: rsize})
}
}
return ans
}
func (self *Chunk) finalize(_ []string, _ []string) {
// Center computation is performed in parallel by Patch.compute_centers
}
type Hunk struct {
left_start, left_count int
right_start, right_count int
title string
added_count, removed_count int
chunks []*Chunk
current_chunk *Chunk
largest_line_number int
}
func (self *Hunk) new_chunk(is_context bool) *Chunk {
left_start, right_start := self.left_start, self.right_start
if len(self.chunks) > 0 {
c := self.chunks[len(self.chunks)-1]
left_start = c.left_start + c.left_count
right_start = c.right_start + c.right_count
}
return &Chunk{is_context: is_context, left_start: left_start, right_start: right_start}
}
func (self *Hunk) ensure_diff_chunk() {
if self.current_chunk == nil || self.current_chunk.is_context {
if self.current_chunk != nil {
self.chunks = append(self.chunks, self.current_chunk)
}
self.current_chunk = self.new_chunk(false)
}
}
func (self *Hunk) ensure_context_chunk() {
if self.current_chunk == nil || !self.current_chunk.is_context {
if self.current_chunk != nil {
self.chunks = append(self.chunks, self.current_chunk)
}
self.current_chunk = self.new_chunk(true)
}
}
func (self *Hunk) add_line() {
self.ensure_diff_chunk()
self.current_chunk.add_line()
self.added_count++
}
func (self *Hunk) remove_line() {
self.ensure_diff_chunk()
self.current_chunk.remove_line()
self.removed_count++
}
func (self *Hunk) context_line() {
self.ensure_context_chunk()
self.current_chunk.context_line()
}
func (self *Hunk) finalize(left_lines, right_lines []string) error {
if self.current_chunk != nil {
self.chunks = append(self.chunks, self.current_chunk)
}
// Sanity check
c := self.chunks[len(self.chunks)-1]
if c.left_start+c.left_count != self.left_start+self.left_count {
return fmt.Errorf("Left side line mismatch %d != %d", c.left_start+c.left_count, self.left_start+self.left_count)
}
if c.right_start+c.right_count != self.right_start+self.right_count {
return fmt.Errorf("Right side line mismatch %d != %d", c.right_start+c.right_count, self.right_start+self.right_count)
}
for _, c := range self.chunks {
c.finalize(left_lines, right_lines)
}
return nil
}
type Patch struct {
all_hunks []*Hunk
largest_line_number, added_count, removed_count int
left_moved_lines, right_moved_lines *utils.Set[int]
}
func (self *Patch) Len() int { return len(self.all_hunks) }
func splitlines_like_git(raw string, strip_trailing_lines bool, process_line func(string)) {
sz := len(raw)
if strip_trailing_lines {
for sz > 0 && (raw[sz-1] == '\n' || raw[sz-1] == '\r') {
sz--
}
}
start := 0
for i := 0; i < sz; i++ {
switch raw[i] {
case '\n':
process_line(raw[start:i])
start = i + 1
case '\r':
process_line(raw[start:i])
start = i + 1
if start < sz && raw[start] == '\n' {
i++
start++
}
}
}
if start < sz {
process_line(raw[start:sz])
}
}
func parse_range(x string) (start, count int) {
s, c, found := strings.Cut(x, ",")
start, _ = strconv.Atoi(s)
if start < 0 {
start = -start
}
count = 1
if found {
count, _ = strconv.Atoi(c)
}
return
}
func parse_hunk_header(line string) *Hunk {
parts := strings.SplitN(line, "@@", 3)
linespec := strings.TrimSpace(parts[1])
title := ""
if len(parts) == 3 {
title = strings.TrimSpace(parts[2])
}
left, right, _ := strings.Cut(linespec, " ")
ls, lc := parse_range(left)
rs, rc := parse_range(right)
return &Hunk{
title: title, left_start: ls - 1, left_count: lc, right_start: rs - 1, right_count: rc,
largest_line_number: utils.Max(ls-1+lc, rs-1+rc),
}
}
func (self *Patch) compute_centers(left_lines, right_lines []string) error {
word_mode := conf != nil && conf.Word_diff_mode == Word_diff_mode_words
var re *regexp.Regexp
if word_mode {
var err error
re, err = word_regexp()
if err != nil {
return fmt.Errorf("Failed to compile word_regex %q: %w", conf.Word_regex, err)
}
}
type pair struct {
chunk *Chunk
idx int
}
var pairs []pair
for _, hunk := range self.all_hunks {
for _, chunk := range hunk.chunks {
if !chunk.is_context && chunk.left_count == chunk.right_count {
for i := 0; i < chunk.left_count; i++ {
pairs = append(pairs, pair{chunk, i})
}
}
}
}
if len(pairs) == 0 {
return nil
}
centers := make([]Center, len(pairs))
if err := parallel.Run_in_parallel_over_range(0, func(start, end int) {
for i := start; i < end; i++ {
p := pairs[i]
left := left_lines[p.chunk.left_start+p.idx]
right := right_lines[p.chunk.right_start+p.idx]
if word_mode {
centers[i] = word_diff_center(left, right, re)
} else {
centers[i] = changed_center(left, right)
}
}
}, 0, len(pairs)); err != nil {
return err
}
ci := 0
for _, hunk := range self.all_hunks {
for _, chunk := range hunk.chunks {
if !chunk.is_context && chunk.left_count == chunk.right_count {
chunk.centers = centers[ci : ci+chunk.left_count]
ci += chunk.left_count
}
}
}
return nil
}
// Use SIMD to efficiently find non-blank lines: a line is non-blank if it
// contains at least one character that is not a space or tab.
func is_non_blank(text string) bool {
return simdstring.NotIndexByte2String(text, ' ', '\t') >= 0
}
func (self *Patch) detect_moved_lines(left_lines, right_lines []string) {
// Build maps from line text to lists of line numbers for removed and added lines.
removed := make(map[string][]int, len(left_lines)) // text -> left line numbers
added := make(map[string][]int, len(right_lines)) // text -> right line numbers
for _, hunk := range self.all_hunks {
for _, chunk := range hunk.chunks {
if !chunk.is_context {
for i := 0; i < chunk.left_count; i++ {
lnum := chunk.left_start + i
text := left_lines[lnum]
if is_non_blank(text) {
removed[text] = append(removed[text], lnum)
}
}
for i := 0; i < chunk.right_count; i++ {
rnum := chunk.right_start + i
text := right_lines[rnum]
if is_non_blank(text) {
added[text] = append(added[text], rnum)
}
}
}
}
}
// Lines that appear in both removed and added sets are moved lines. When a
// line appears multiple times on each side, only min(left_count,
// right_count) occurrences are marked as moved.
self.left_moved_lines = utils.NewSet[int]()
self.right_moved_lines = utils.NewSet[int]()
for text, lnums := range removed {
if rnums, ok := added[text]; ok {
count := min(len(lnums), len(rnums))
for _, lnum := range lnums[:count] {
self.left_moved_lines.Add(lnum)
}
for _, rnum := range rnums[:count] {
self.right_moved_lines.Add(rnum)
}
}
}
}
func parse_patch(raw string, left_lines, right_lines []string) (ans *Patch, err error) {
ans = &Patch{all_hunks: make([]*Hunk, 0, 32)}
var current_hunk *Hunk
splitlines_like_git(raw, true, func(line string) {
if strings.HasPrefix(line, "@@ ") {
current_hunk = parse_hunk_header(line)
ans.all_hunks = append(ans.all_hunks, current_hunk)
} else if current_hunk != nil {
var ch byte
if len(line) > 0 {
ch = line[0]
}
switch ch {
case '+':
current_hunk.add_line()
case '-':
current_hunk.remove_line()
case '\\':
default:
current_hunk.context_line()
}
}
})
for _, h := range ans.all_hunks {
err = h.finalize(left_lines, right_lines)
if err != nil {
return
}
ans.added_count += h.added_count
ans.removed_count += h.removed_count
}
if len(ans.all_hunks) > 0 {
ans.largest_line_number = ans.all_hunks[len(ans.all_hunks)-1].largest_line_number
}
err = ans.compute_centers(left_lines, right_lines)
if err == nil && conf.Mark_moved_lines {
ans.detect_moved_lines(left_lines, right_lines)
}
return
}
func run_diff(file1, file2 string, num_of_context_lines int) (ok, is_different bool, patch string, err error) {
// we resolve symlinks because git diff does not follow symlinks, while diff
// does. We want consistent behavior, also for integration with git difftool
// we always want symlinks to be followed.
path1, err := filepath.EvalSymlinks(file1)
if err != nil {
return
}
path2, err := filepath.EvalSymlinks(file2)
if err != nil {
return
}
if len(diff_cmd) == 0 {
data1, err := data_for_path(path1)
if err != nil {
return false, false, "", err
}
data2, err := data_for_path(path2)
if err != nil {
return false, false, "", err
}
patchb := Diff(path1, data1, path2, data2, num_of_context_lines)
if patchb == nil {
return true, false, "", nil
}
return true, len(patchb) > 0, utils.UnsafeBytesToString(patchb), nil
} else {
context := strconv.Itoa(num_of_context_lines)
cmd := utils.Map(func(x string) string {
return strings.ReplaceAll(x, "_CONTEXT_", context)
}, diff_cmd)
cmd = append(cmd, path1, path2)
c := exec.Command(cmd[0], cmd[1:]...)
stdout, stderr := bytes.Buffer{}, bytes.Buffer{}
c.Stdout, c.Stderr = &stdout, &stderr
err = c.Run()
if err != nil {
var e *exec.ExitError
if errors.As(err, &e) && e.ExitCode() == 1 {
return true, true, stdout.String(), nil
}
return false, false, stderr.String(), err
}
return true, false, stdout.String(), nil
}
}
func do_diff(file1, file2 string, context_count int) (ans *Patch, err error) {
ok, _, raw, err := run_diff(file1, file2, context_count)
if !ok {
return nil, fmt.Errorf("Failed to diff %s vs. %s with errors:\n%s", file1, file2, raw)
}
if err != nil {
return
}
left_lines, err := lines_for_path(file1)
if err != nil {
return
}
right_lines, err := lines_for_path(file2)
if err != nil {
return
}
ans, err = parse_patch(raw, left_lines, right_lines)
return
}
type diff_job struct{ file1, file2 string }
func diff(jobs []diff_job, context_count int) (ans map[string]*Patch, err error) {
ans = make(map[string]*Patch)
ctx := images.Context{}
type result struct {
file1, file2 string
err error
patch *Patch
}
results := make(chan result, len(jobs))
if err := ctx.SafeParallel(0, len(jobs), func(nums <-chan int) {
for i := range nums {
job := jobs[i]
r := result{file1: job.file1, file2: job.file2}
r.patch, r.err = do_diff(job.file1, job.file2, context_count)
results <- r
}
}); err != nil {
panic(err)
}
close(results)
for r := range results {
if r.err != nil {
return nil, r.err
}
ans[r.file1] = r.patch
}
return ans, nil
}
+159
View File
@@ -0,0 +1,159 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"regexp"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
var region_eq = cmpopts.EquateComparable(Region{})
func TestWordDiffCenter(t *testing.T) {
re := regexp.MustCompile(`\S+`)
many_words := strings.Repeat("a ", 100000)
too_many_words := strings.Repeat("a ", max_word_diff_words)
type tc struct {
left, right string
left_regions []Region
right_regions []Region
}
tests := []tc{
{
// word count equal, single substitution at index 1 → positional pair
// "quick" vs "slow": no common chars → full words
left: "the quick brown fox", right: "the slow brown fox",
left_regions: []Region{{4, 5}},
right_regions: []Region{{4, 4}},
},
{
left: "hello world", right: "hello world",
left_regions: nil,
right_regions: nil,
},
{
// word count equal, single substitution at index 1 → positional pair
// "bar" vs "qux": no common chars → full words
left: "foo bar baz", right: "foo qux baz",
left_regions: []Region{{4, 3}},
right_regions: []Region{{4, 3}},
},
{
// left has 3 words, right has 4 → word counts differ with unmatched
// changed words → fall back to changed_center
// changed_center gives: offset=4 (common "aaa "), suffix="ccc"(4)
// left_size=3 ("bbb"), right_size=7 ("xxx yyy")
left: "aaa bbb ccc", right: "aaa xxx yyy ccc",
left_regions: []Region{{4, 3}},
right_regions: []Region{{4, 7}},
},
{
// word on left deleted: unmatched changed word → fall back to changed_center
// changed_center: prefix="aaa "(4), suffix=" ccc ddd"(8)
// left_size=3 ("bbb"), right_size=-1 → nil
left: "aaa bbb ccc ddd", right: "aaa ccc ddd",
left_regions: []Region{{4, 3}},
right_regions: nil,
},
{
// word counts equal, single substitution at index 3 → positional pair
// "fox" vs "cat": no common chars → full words
left: "the quick brown fox over the lazy dog", right: "the quick brown cat over the lazy dog",
left_regions: []Region{{16, 3}},
right_regions: []Region{{16, 3}},
},
{
// single word, positional pair with common char prefix "version" (7)
left: "version1",
right: "version2",
left_regions: []Region{{7, 1}},
right_regions: []Region{{7, 1}},
},
{
// positional pair at index 1, char prefix="prefix"(6), suffix="suffix"(6)
// word at offset 7 → highlight offset 13, size 2
left: "update prefixABsuffix done",
right: "update prefixCDsuffix done",
left_regions: []Region{{13, 2}},
right_regions: []Region{{13, 2}},
},
{
// equal word count, multiple positional pairs (all words changed)
// each pair has no common chars → full-word regions
left: "aaa bbb ccc", right: "xxx yyy zzz",
left_regions: []Region{{0, 3}, {4, 3}, {8, 3}},
right_regions: []Region{{0, 3}, {4, 3}, {8, 3}},
},
{
// pure insertion on right side → unmatched changed word → fall back to changed_center
// changed_center finds common prefix "aaa bbb ccc" (11 bytes) and suffix "";
// left_size=0 (nil), right_size=4 (" ddd" inserted at the end)
left: "aaa bbb ccc", right: "aaa bbb ccc ddd",
left_regions: nil,
right_regions: []Region{{11, 4}},
},
{
// very long line, word counts differ → changed_center without
// running the LCS over 100000 words
left: many_words, right: "x " + many_words + "y",
left_regions: []Region{{0, len(many_words)}},
right_regions: []Region{{0, len(many_words) + 3}},
},
{
// word counts equal, but more than max_word_diff_words words
// between the first and last changed word → changed_center
left: "x " + too_many_words + "y", right: "X " + too_many_words + "Y",
left_regions: []Region{{0, len(too_many_words) + 3}},
right_regions: []Region{{0, len(too_many_words) + 3}},
},
{
// more than max_word_diff_words words, but the changed ones are
// close together → still diffed by word
left: too_many_words + "x a y", right: too_many_words + "X a Y",
left_regions: []Region{{len(too_many_words), 1}, {len(too_many_words) + 4, 1}},
right_regions: []Region{{len(too_many_words), 1}, {len(too_many_words) + 4, 1}},
},
}
for _, tc := range tests {
c := word_diff_center(tc.left, tc.right, re)
if diff := cmp.Diff(tc.left_regions, c.left_regions, region_eq); diff != "" {
t.Errorf("word_diff_center(%q, %q) left_regions mismatch: %s", tc.left, tc.right, diff)
}
if diff := cmp.Diff(tc.right_regions, c.right_regions, region_eq); diff != "" {
t.Errorf("word_diff_center(%q, %q) right_regions mismatch: %s", tc.left, tc.right, diff)
}
}
}
func TestChangedCenter(t *testing.T) {
type tc struct {
left, right string
left_regions []Region
right_regions []Region
}
tests := []tc{
{
left: "the quick brown fox", right: "the slow brown fox",
left_regions: []Region{{4, 5}},
right_regions: []Region{{4, 4}},
},
{
left: "hello world", right: "hello world",
left_regions: nil,
right_regions: nil,
},
}
for _, tc := range tests {
c := changed_center(tc.left, tc.right)
if diff := cmp.Diff(tc.left_regions, c.left_regions, region_eq); diff != "" {
t.Errorf("changed_center(%q, %q) left_regions mismatch: %s", tc.left, tc.right, diff)
}
if diff := cmp.Diff(tc.right_regions, c.right_regions, region_eq); diff != "" {
t.Errorf("changed_center(%q, %q) right_regions mismatch: %s", tc.left, tc.right, diff)
}
}
}
+886
View File
@@ -0,0 +1,886 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"errors"
"fmt"
"math"
"os"
"sort"
"strconv"
"strings"
"github.com/kovidgoyal/kitty/tools/tui/graphics"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/tui/sgr"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/style"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type LineType int
const (
TITLE_LINE LineType = iota
CHANGE_LINE
CONTEXT_LINE
HUNK_TITLE_LINE
IMAGE_LINE
EMPTY_LINE
)
type Reference struct {
path string
linenum int // 1 based
}
type HalfScreenLine struct {
marked_up_margin_text string
marked_up_text string
is_filler bool
is_moved bool
cached_wcswidth int
}
func (self *HalfScreenLine) wcswidth() int {
if self.cached_wcswidth == 0 && self.marked_up_text != "" {
self.cached_wcswidth = wcswidth.Stringwidth(self.marked_up_text)
}
return self.cached_wcswidth
}
type ScreenLine struct {
left, right HalfScreenLine
}
type LogicalLine struct {
line_type LineType
screen_lines []*ScreenLine
is_full_width bool
is_change_start bool
left_reference, right_reference Reference
left_image, right_image struct {
key string
count int
}
image_lines_offset int
}
func (self *LogicalLine) render_screen_line(n int, lp *loop.Loop, margin_size, columns int) {
if n >= len(self.screen_lines) || n < 0 {
return
}
sl := self.screen_lines[n]
available_cols := columns/2 - margin_size
if self.is_full_width {
available_cols = columns - margin_size
}
left_margin := place_in(sl.left.marked_up_margin_text, margin_size)
left_text := place_in(sl.left.marked_up_text, available_cols)
if sl.left.is_filler {
left_margin = format_as_sgr.margin_filler + left_margin
left_text = format_as_sgr.filler + left_text
} else if sl.left.is_moved {
left_margin = format_as_sgr.moved_margin + left_margin
left_text = format_as_sgr.moved + left_text
} else {
switch self.line_type {
case CHANGE_LINE, IMAGE_LINE:
left_margin = format_as_sgr.removed_margin + left_margin
left_text = format_as_sgr.removed + left_text
case HUNK_TITLE_LINE:
left_margin = format_as_sgr.hunk_margin + left_margin
left_text = format_as_sgr.hunk + left_text
case TITLE_LINE:
default:
left_margin = format_as_sgr.margin + left_margin
}
}
lp.QueueWriteString(left_margin + "\x1b[m")
lp.QueueWriteString(left_text)
if self.is_full_width {
return
}
right_margin := place_in(sl.right.marked_up_margin_text, margin_size)
right_text := place_in(sl.right.marked_up_text, available_cols)
if sl.right.is_filler {
right_margin = format_as_sgr.margin_filler + right_margin
right_text = format_as_sgr.filler + right_text
} else if sl.right.is_moved {
right_margin = format_as_sgr.moved_margin + right_margin
right_text = format_as_sgr.moved + right_text
} else {
switch self.line_type {
case CHANGE_LINE, IMAGE_LINE:
right_margin = format_as_sgr.added_margin + right_margin
right_text = format_as_sgr.added + right_text
case HUNK_TITLE_LINE:
right_margin = format_as_sgr.hunk_margin + right_margin
right_text = format_as_sgr.hunk + right_text
case TITLE_LINE:
default:
right_margin = format_as_sgr.margin + right_margin
}
}
lp.QueueWriteString("\x1b[m\r")
lp.MoveCursorHorizontally(available_cols + margin_size)
lp.QueueWriteString(right_margin + "\x1b[m")
lp.QueueWriteString(right_text)
}
func (self *LogicalLine) IncrementScrollPosBy(pos *ScrollPos, amt int) (delta int) {
if len(self.screen_lines) > 0 {
npos := utils.Max(0, utils.Min(pos.screen_line+amt, len(self.screen_lines)-1))
delta = npos - pos.screen_line
pos.screen_line = npos
}
return
}
func fit_in(text string, count int) string {
truncated := wcswidth.TruncateToVisualLength(text, count)
if len(truncated) >= len(text) {
return text
}
if count > 1 {
truncated = wcswidth.TruncateToVisualLength(text, count-1)
}
return truncated + `…`
}
func fill_in(text string, sz int) string {
w := wcswidth.Stringwidth(text)
if w < sz {
text += strings.Repeat(` `, (sz - w))
}
return text
}
func place_in(text string, sz int) string {
return fill_in(fit_in(text, sz), sz)
}
var format_as_sgr struct {
title, margin, added, removed, added_margin, removed_margin, filler, margin_filler, hunk_margin, hunk, selection, search, moved, moved_margin string
}
var statusline_format, added_count_format, removed_count_format, message_format func(...any) string
var use_light_colors bool = false
type ResolvedColors struct {
Added_bg style.RGBA
Added_margin_bg style.RGBA
Background style.RGBA
Filler_bg style.RGBA
Foreground style.RGBA
Highlight_added_bg style.RGBA
Highlight_removed_bg style.RGBA
Hunk_bg style.RGBA
Hunk_margin_bg style.RGBA
Margin_bg style.RGBA
Margin_fg style.RGBA
Margin_filler_bg style.NullableColor
Moved_bg style.RGBA
Moved_margin_bg style.RGBA
Removed_bg style.RGBA
Removed_margin_bg style.RGBA
Search_bg style.RGBA
Search_fg style.RGBA
Select_bg style.RGBA
Select_fg style.NullableColor
Title_bg style.RGBA
Title_fg style.RGBA
}
var resolved_colors ResolvedColors
func create_formatters() {
rc := &resolved_colors
if !use_light_colors {
rc.Added_bg = conf.Dark_added_bg
rc.Added_margin_bg = conf.Dark_added_margin_bg
rc.Background = conf.Dark_background
rc.Filler_bg = conf.Dark_filler_bg
rc.Foreground = conf.Dark_foreground
rc.Highlight_added_bg = conf.Dark_highlight_added_bg
rc.Highlight_removed_bg = conf.Dark_highlight_removed_bg
rc.Hunk_bg = conf.Dark_hunk_bg
rc.Hunk_margin_bg = conf.Dark_hunk_margin_bg
rc.Margin_bg = conf.Dark_margin_bg
rc.Margin_fg = conf.Dark_margin_fg
rc.Margin_filler_bg = conf.Dark_margin_filler_bg
rc.Moved_bg = conf.Dark_moved_bg
rc.Moved_margin_bg = conf.Dark_moved_margin_bg
rc.Removed_bg = conf.Dark_removed_bg
rc.Removed_margin_bg = conf.Dark_removed_margin_bg
rc.Search_bg = conf.Dark_search_bg
rc.Search_fg = conf.Dark_search_fg
rc.Select_bg = conf.Dark_select_bg
rc.Select_fg = conf.Dark_select_fg
rc.Title_bg = conf.Dark_title_bg
rc.Title_fg = conf.Dark_title_fg
} else {
rc.Added_bg = conf.Added_bg
rc.Added_margin_bg = conf.Added_margin_bg
rc.Background = conf.Background
rc.Filler_bg = conf.Filler_bg
rc.Foreground = conf.Foreground
rc.Highlight_added_bg = conf.Highlight_added_bg
rc.Highlight_removed_bg = conf.Highlight_removed_bg
rc.Hunk_bg = conf.Hunk_bg
rc.Hunk_margin_bg = conf.Hunk_margin_bg
rc.Margin_bg = conf.Margin_bg
rc.Margin_fg = conf.Margin_fg
rc.Margin_filler_bg = conf.Margin_filler_bg
rc.Moved_bg = conf.Moved_bg
rc.Moved_margin_bg = conf.Moved_margin_bg
rc.Removed_bg = conf.Removed_bg
rc.Removed_margin_bg = conf.Removed_margin_bg
rc.Search_bg = conf.Search_bg
rc.Search_fg = conf.Search_fg
rc.Select_bg = conf.Select_bg
rc.Select_fg = conf.Select_fg
rc.Title_bg = conf.Title_bg
rc.Title_fg = conf.Title_fg
}
ctx := style.Context{AllowEscapeCodes: true}
only_open := func(x string) string {
ans := ctx.SprintFunc(x)("|")
ans, _, _ = strings.Cut(ans, "|")
return ans
}
format_as_sgr.filler = only_open("bg=" + rc.Filler_bg.AsRGBSharp())
if rc.Margin_filler_bg.IsSet {
format_as_sgr.margin_filler = only_open("bg=" + rc.Margin_filler_bg.Color.AsRGBSharp())
} else {
format_as_sgr.margin_filler = only_open("bg=" + rc.Filler_bg.AsRGBSharp())
}
format_as_sgr.added = only_open("bg=" + rc.Added_bg.AsRGBSharp())
format_as_sgr.added_margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Added_margin_bg.AsRGBSharp()))
format_as_sgr.removed = only_open("bg=" + rc.Removed_bg.AsRGBSharp())
format_as_sgr.removed_margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Removed_margin_bg.AsRGBSharp()))
format_as_sgr.moved = only_open("bg=" + rc.Moved_bg.AsRGBSharp())
format_as_sgr.moved_margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Moved_margin_bg.AsRGBSharp()))
format_as_sgr.title = only_open(fmt.Sprintf("fg=%s bg=%s bold", rc.Title_fg.AsRGBSharp(), rc.Title_bg.AsRGBSharp()))
format_as_sgr.margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Margin_bg.AsRGBSharp()))
format_as_sgr.hunk = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Hunk_bg.AsRGBSharp()))
format_as_sgr.hunk_margin = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Margin_fg.AsRGBSharp(), rc.Hunk_margin_bg.AsRGBSharp()))
format_as_sgr.search = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Search_fg.AsRGBSharp(), rc.Search_bg.AsRGBSharp()))
statusline_format = ctx.SprintFunc(fmt.Sprintf("fg=%s", rc.Margin_fg.AsRGBSharp()))
added_count_format = ctx.SprintFunc(fmt.Sprintf("fg=%s", rc.Highlight_added_bg.AsRGBSharp()))
removed_count_format = ctx.SprintFunc(fmt.Sprintf("fg=%s", rc.Highlight_removed_bg.AsRGBSharp()))
message_format = ctx.SprintFunc("bold")
if rc.Select_fg.IsSet {
format_as_sgr.selection = only_open(fmt.Sprintf("fg=%s bg=%s", rc.Select_fg.Color.AsRGBSharp(), rc.Select_bg.AsRGBSharp()))
} else {
format_as_sgr.selection = only_open("bg=" + rc.Select_bg.AsRGBSharp())
}
}
func center_span(ltype string, offset, size int) *sgr.Span {
ans := sgr.NewSpan(offset, size)
switch ltype {
case "add":
ans.SetBackground(resolved_colors.Highlight_added_bg).SetClosingBackground(resolved_colors.Added_bg)
case "remove":
ans.SetBackground(resolved_colors.Highlight_removed_bg).SetClosingBackground(resolved_colors.Removed_bg)
}
return ans
}
func title_lines(left_path, right_path string, columns, margin_size int, ans []*LogicalLine) []*LogicalLine {
left_name, right_name := path_name_map[left_path], path_name_map[right_path]
available_cols := columns/2 - margin_size
ll := LogicalLine{
line_type: TITLE_LINE,
left_reference: Reference{path: left_path}, right_reference: Reference{path: right_path},
}
sl := ScreenLine{}
if right_name != "" && right_name != left_name {
sl.left.marked_up_text = format_as_sgr.title + fit_in(sanitize(left_name), available_cols)
sl.right.marked_up_text = format_as_sgr.title + fit_in(sanitize(right_name), available_cols)
} else {
sl.left.marked_up_text = format_as_sgr.title + fit_in(sanitize(left_name), columns-margin_size)
ll.is_full_width = true
}
l2 := ll
l2.line_type = EMPTY_LINE
ll.screen_lines = append(ll.screen_lines, &sl)
sl2 := ScreenLine{}
sl2.left.marked_up_margin_text = "\x1b[m" + strings.Repeat("━", margin_size)
sl2.left.marked_up_text = strings.Repeat("━", columns-margin_size)
l2.is_full_width = true
l2.screen_lines = append(l2.screen_lines, &sl2)
return append(ans, &ll, &l2)
}
type LogicalLines struct {
lines []*LogicalLine
title_line_indices []int // sorted indices of TITLE_LINEs in lines -- used for sticky_header
margin_size, columns int
}
func (self *LogicalLines) At(i int) *LogicalLine { return self.lines[i] }
func (self *LogicalLines) TitleLineIdxFor(line_idx int) int {
if len(self.title_line_indices) == 0 || line_idx < 0 {
return -1
}
// first title index > line_idx, so the one before it is our answer
i := sort.SearchInts(self.title_line_indices, line_idx+1)
if i == 0 {
return -1
}
return self.title_line_indices[i-1]
}
func (self *LogicalLines) ScreenLineAt(pos ScrollPos) *ScreenLine {
if pos.logical_line < len(self.lines) && pos.logical_line >= 0 {
line := self.lines[pos.logical_line]
if pos.screen_line < len(line.screen_lines) && pos.screen_line >= 0 {
return self.lines[pos.logical_line].screen_lines[pos.screen_line]
}
}
return nil
}
func (self *LogicalLines) Len() int { return len(self.lines) }
func (self *LogicalLines) NumScreenLinesTo(a ScrollPos) (ans int) {
return self.Minus(a, ScrollPos{})
}
// a - b in terms of number of screen lines between the positions
func (self *LogicalLines) Minus(a, b ScrollPos) (delta int) {
if a.logical_line == b.logical_line {
return a.screen_line - b.screen_line
}
amt := 1
if a.Less(b) {
amt = -1
} else {
a, b = b, a
}
for i := a.logical_line; i < utils.Min(len(self.lines), b.logical_line+1); i++ {
line := self.lines[i]
switch i {
case a.logical_line:
delta += utils.Max(0, len(line.screen_lines)-a.screen_line)
case b.logical_line:
delta += b.screen_line
default:
delta += len(line.screen_lines)
}
}
return delta * amt
}
func (self *LogicalLines) IncrementScrollPosBy(pos *ScrollPos, amt int) (delta int) {
if pos.logical_line < 0 || pos.logical_line >= len(self.lines) || amt == 0 {
return
}
one := 1
if amt < 0 {
one = -1
}
for amt != 0 {
line := self.lines[pos.logical_line]
d := line.IncrementScrollPosBy(pos, amt)
if d == 0 {
nlp := pos.logical_line + one
if nlp < 0 || nlp >= len(self.lines) {
break
}
pos.logical_line = nlp
if one > 0 {
pos.screen_line = 0
} else {
pos.screen_line = len(self.lines[nlp].screen_lines) - 1
}
delta += one
amt -= one
} else {
amt -= d
delta += d
}
}
return
}
func human_readable(size int64) string {
divisor, suffix := 1, "B"
for i, candidate := range []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"} {
if size < (1 << ((i + 1) * 10)) {
divisor, suffix = (1 << (i * 10)), candidate
break
}
}
fs := float64(size) / float64(divisor)
s := strconv.FormatFloat(fs, 'f', 2, 64)
if idx := strings.Index(s, "."); idx > -1 {
s = s[:idx+2]
}
if strings.HasSuffix(s, ".0") || strings.HasSuffix(s, ".00") {
idx := strings.IndexByte(s, '.')
s = s[:idx]
}
return s + " " + suffix
}
func image_lines(left_path, right_path string, screen_size screen_size, margin_size int, image_size graphics.Size, ans []*LogicalLine) ([]*LogicalLine, error) {
columns := screen_size.columns
available_cols := columns/2 - margin_size
ll, err := first_binary_line(left_path, right_path, columns, margin_size, func(path string) (string, error) {
sz, err := size_for_path(path)
if err != nil {
return "", err
}
text := fmt.Sprintf("Size: %s", human_readable(sz))
res := image_collection.ResolutionOf(path)
if res.Width > -1 {
text = fmt.Sprintf("Dimensions: %dx%d %s", res.Width, res.Height, text)
}
return text, nil
})
if err != nil {
return nil, err
}
ll.image_lines_offset = len(ll.screen_lines)
do_side := func(path string) []string {
if path == "" {
return nil
}
sz, err := image_collection.GetSizeIfAvailable(path, image_size)
if err == nil {
count := int(math.Ceil(float64(sz.Height) / float64(screen_size.cell_height)))
return utils.Repeat("", count)
}
if errors.Is(err, graphics.ErrNotFound) {
return splitlines("Loading image...", available_cols)
}
return splitlines(fmt.Sprintf("%s", err), available_cols)
}
left_lines := do_side(left_path)
if ll.left_image.count = len(left_lines); ll.left_image.count > 0 {
ll.left_image.key = left_path
}
right_lines := do_side(right_path)
if ll.right_image.count = len(right_lines); ll.right_image.count > 0 {
ll.right_image.key = right_path
}
for i := 0; i < utils.Max(len(left_lines), len(right_lines)); i++ {
sl := ScreenLine{}
if i < len(left_lines) {
sl.left.marked_up_text = left_lines[i]
} else {
sl.left.is_filler = true
}
if i < len(right_lines) {
sl.right.marked_up_text = right_lines[i]
} else {
sl.right.is_filler = true
}
ll.screen_lines = append(ll.screen_lines, &sl)
}
ll.line_type = IMAGE_LINE
return append(ans, ll), nil
}
func first_binary_line(left_path, right_path string, columns, margin_size int, renderer func(path string) (string, error)) (*LogicalLine, error) {
available_cols := columns/2 - margin_size
ll := LogicalLine{
is_change_start: true, line_type: CHANGE_LINE,
left_reference: Reference{path: left_path}, right_reference: Reference{path: right_path},
}
if left_path == "" {
line, err := renderer(right_path)
if err != nil {
return nil, err
}
for _, x := range splitlines(line, available_cols) {
sl := ScreenLine{}
sl.right.marked_up_text = x
sl.left.is_filler = true
ll.screen_lines = append(ll.screen_lines, &sl)
}
} else if right_path == "" {
line, err := renderer(left_path)
if err != nil {
return nil, err
}
for _, x := range splitlines(line, available_cols) {
sl := ScreenLine{}
sl.right.is_filler = true
sl.left.marked_up_text = x
ll.screen_lines = append(ll.screen_lines, &sl)
}
} else {
l, err := renderer(left_path)
if err != nil {
return nil, err
}
r, err := renderer(right_path)
if err != nil {
return nil, err
}
left_lines, right_lines := splitlines(l, available_cols), splitlines(r, available_cols)
for i := 0; i < utils.Max(len(left_lines), len(right_lines)); i++ {
sl := ScreenLine{}
if i < len(left_lines) {
sl.left.marked_up_text = left_lines[i]
}
if i < len(right_lines) {
sl.right.marked_up_text = right_lines[i]
}
ll.screen_lines = append(ll.screen_lines, &sl)
}
}
return &ll, nil
}
func binary_lines(left_path, right_path string, columns, margin_size int, ans []*LogicalLine) (ans2 []*LogicalLine, err error) {
ll, err := first_binary_line(left_path, right_path, columns, margin_size, func(path string) (string, error) {
sz, err := size_for_path(path)
if err != nil {
return "", err
}
return fmt.Sprintf("Binary file: %s", human_readable(sz)), nil
})
if err != nil {
return nil, err
}
return append(ans, ll), nil
}
type DiffData struct {
left_path, right_path string
available_cols, margin_size int
left_lines, right_lines []string
left_moved_lines *utils.Set[int]
right_moved_lines *utils.Set[int]
}
func hunk_title(hunk *Hunk) string {
return fmt.Sprintf("@@ -%d,%d +%d,%d @@ %s", hunk.left_start+1, hunk.left_count, hunk.right_start+1, hunk.right_count, hunk.title)
}
func lines_for_context_chunk(data *DiffData, _ int, chunk *Chunk, _ int, ans []*LogicalLine) []*LogicalLine {
for i := 0; i < chunk.left_count; i++ {
left_line_number := chunk.left_start + i
right_line_number := chunk.right_start + i
ll := LogicalLine{line_type: CONTEXT_LINE,
left_reference: Reference{path: data.left_path, linenum: left_line_number + 1},
right_reference: Reference{path: data.right_path, linenum: right_line_number + 1},
}
left_line_number_s := strconv.Itoa(left_line_number + 1)
right_line_number_s := strconv.Itoa(right_line_number + 1)
for _, text := range splitlines(data.left_lines[left_line_number], data.available_cols) {
left_line := HalfScreenLine{marked_up_margin_text: left_line_number_s, marked_up_text: text}
right_line := left_line
if right_line_number_s != left_line_number_s {
right_line = HalfScreenLine{marked_up_margin_text: right_line_number_s, marked_up_text: text}
}
ll.screen_lines = append(ll.screen_lines, &ScreenLine{left_line, right_line})
left_line_number_s, right_line_number_s = "", ""
}
ans = append(ans, &ll)
}
return ans
}
func splitlines(text string, width int) []string {
return style.WrapTextAsLines(text, width, style.WrapOptions{})
}
func render_half_line(line_number int, line, ltype string, available_cols int, center Center, is_moved bool, ans []HalfScreenLine) []HalfScreenLine {
var regions []Region
if ltype == "remove" {
regions = center.left_regions
} else {
regions = center.right_regions
}
if len(regions) > 0 {
spans := make([]*sgr.Span, len(regions))
for i, r := range regions {
spans[i] = center_span(ltype, r.offset, r.size)
}
line = sgr.InsertFormatting(line, spans...)
}
lnum := strconv.Itoa(line_number + 1)
for _, sc := range splitlines(line, available_cols) {
ans = append(ans, HalfScreenLine{marked_up_margin_text: lnum, marked_up_text: sc, is_moved: is_moved})
lnum = ""
}
return ans
}
func lines_for_diff_chunk(data *DiffData, _ int, chunk *Chunk, _ int, ans []*LogicalLine) []*LogicalLine {
common := utils.Min(chunk.left_count, chunk.right_count)
ll, rl := make([]HalfScreenLine, 0, 32), make([]HalfScreenLine, 0, 32)
for i := 0; i < utils.Max(chunk.left_count, chunk.right_count); i++ {
ll, rl = ll[:0], rl[:0]
var center Center
left_lnum, right_lnum := 0, 0
if i < len(chunk.centers) {
center = chunk.centers[i]
}
if i < chunk.left_count {
left_lnum = chunk.left_start + i
left_is_moved := data.left_moved_lines != nil && data.left_moved_lines.Has(left_lnum)
ll = render_half_line(left_lnum, data.left_lines[left_lnum], "remove", data.available_cols, center, left_is_moved, ll)
left_lnum++
}
if i < chunk.right_count {
right_lnum = chunk.right_start + i
right_is_moved := data.right_moved_lines != nil && data.right_moved_lines.Has(right_lnum)
rl = render_half_line(right_lnum, data.right_lines[right_lnum], "add", data.available_cols, center, right_is_moved, rl)
right_lnum++
}
if i < common {
extra := len(ll) - len(rl)
if extra < 0 {
ll = append(ll, utils.Repeat(HalfScreenLine{}, -extra)...)
} else if extra > 0 {
rl = append(rl, utils.Repeat(HalfScreenLine{}, extra)...)
}
} else {
if len(ll) > 0 {
rl = append(rl, utils.Repeat(HalfScreenLine{is_filler: true}, len(ll))...)
} else if len(rl) > 0 {
ll = append(ll, utils.Repeat(HalfScreenLine{is_filler: true}, len(rl))...)
}
}
logline := LogicalLine{
line_type: CHANGE_LINE, is_change_start: i == 0,
left_reference: Reference{path: data.left_path, linenum: left_lnum},
right_reference: Reference{path: data.left_path, linenum: right_lnum},
}
for l := 0; l < len(ll); l++ {
logline.screen_lines = append(logline.screen_lines, &ScreenLine{left: ll[l], right: rl[l]})
}
ans = append(ans, &logline)
}
return ans
}
func lines_for_diff(left_path string, right_path string, patch *Patch, columns, margin_size int, ans []*LogicalLine) (result []*LogicalLine, err error) {
ht := LogicalLine{
line_type: HUNK_TITLE_LINE,
left_reference: Reference{path: left_path}, right_reference: Reference{path: right_path},
is_full_width: true,
}
if patch.Len() == 0 {
txt := "The files are identical"
if lstat, err := os.Stat(left_path); err == nil {
if rstat, err := os.Stat(right_path); err == nil {
if lstat.Mode() != rstat.Mode() {
txt = fmt.Sprintf("Mode changed: %s to %s", lstat.Mode(), rstat.Mode())
}
}
}
for _, line := range splitlines(txt, columns-margin_size) {
sl := ScreenLine{}
sl.left.marked_up_text = line
ht.screen_lines = append(ht.screen_lines, &sl)
}
ht.line_type = EMPTY_LINE
ht.is_full_width = true
return append(ans, &ht), nil
}
available_cols := columns/2 - margin_size
data := DiffData{
left_path: left_path, right_path: right_path, available_cols: available_cols, margin_size: margin_size,
left_moved_lines: patch.left_moved_lines, right_moved_lines: patch.right_moved_lines,
}
if left_path != "" {
data.left_lines, err = highlighted_lines_for_path(left_path)
if err != nil {
return
}
}
if right_path != "" {
data.right_lines, err = highlighted_lines_for_path(right_path)
if err != nil {
return
}
}
for hunk_num, hunk := range patch.all_hunks {
htl := ht
htl.left_reference.linenum = hunk.left_start + 1
htl.right_reference.linenum = hunk.right_start + 1
for _, line := range splitlines(hunk_title(hunk), columns-margin_size) {
sl := ScreenLine{}
sl.left.marked_up_text = line
htl.screen_lines = append(htl.screen_lines, &sl)
}
ans = append(ans, &htl)
for cnum, chunk := range hunk.chunks {
if chunk.is_context {
ans = lines_for_context_chunk(&data, hunk_num, chunk, cnum, ans)
} else {
ans = lines_for_diff_chunk(&data, hunk_num, chunk, cnum, ans)
}
}
}
return ans, nil
}
func all_lines(path string, columns, margin_size int, is_add bool, ans []*LogicalLine) ([]*LogicalLine, error) {
available_cols := columns/2 - margin_size
ltype := `add`
ll := LogicalLine{line_type: CHANGE_LINE}
if !is_add {
ltype = `remove`
ll.left_reference.path = path
} else {
ll.right_reference.path = path
}
lines, err := highlighted_lines_for_path(path)
if err != nil {
return nil, err
}
var msg_lines []string
if is_add {
msg_lines = splitlines(`This file was added`, available_cols)
} else {
msg_lines = splitlines(`This file was removed`, available_cols)
}
for line_number, line := range lines {
hlines := make([]HalfScreenLine, 0, 8)
hlines = render_half_line(line_number, line, ltype, available_cols, Center{}, false, hlines)
l := ll
if is_add {
l.right_reference.linenum = line_number + 1
} else {
l.left_reference.linenum = line_number + 1
}
l.is_change_start = line_number == 0
for i, hl := range hlines {
sl := ScreenLine{}
if is_add {
sl.right = hl
if len(msg_lines) > 0 {
sl.left.marked_up_text = msg_lines[i]
sl.left.is_filler = true
msg_lines = msg_lines[1:]
} else {
sl.left.is_filler = true
}
} else {
sl.left = hl
if len(msg_lines) > 0 {
sl.right.marked_up_text = msg_lines[i]
sl.right.is_filler = true
msg_lines = msg_lines[1:]
} else {
sl.right.is_filler = true
}
}
l.screen_lines = append(l.screen_lines, &sl)
}
ans = append(ans, &l)
}
return ans, nil
}
func rename_lines(path, other_path string, columns, margin_size int, ans []*LogicalLine) ([]*LogicalLine, error) {
ll := LogicalLine{
left_reference: Reference{path: path}, right_reference: Reference{path: other_path},
line_type: CHANGE_LINE, is_change_start: true, is_full_width: true}
for _, line := range splitlines(fmt.Sprintf(`The file %s was renamed to %s`, sanitize(path_name_map[path]), sanitize(path_name_map[other_path])), columns-margin_size) {
sl := ScreenLine{}
sl.right.marked_up_text = line
ll.screen_lines = append(ll.screen_lines, &sl)
}
return append(ans, &ll), nil
}
func render(collection *Collection, diff_map map[string]*Patch, screen_size screen_size, largest_line_number int, image_size graphics.Size) (result *LogicalLines, err error) {
margin_size := utils.Max(3, len(strconv.Itoa(largest_line_number))+1)
ans := make([]*LogicalLine, 0, 1024)
var title_line_indices []int
track_titles := conf != nil && conf.Sticky_header
columns := screen_size.columns
err = collection.Apply(func(path, item_type, changed_path string) error {
if track_titles {
title_line_indices = append(title_line_indices, len(ans))
}
ans = title_lines(path, changed_path, columns, margin_size, ans)
defer func() {
ans = append(ans, &LogicalLine{line_type: EMPTY_LINE, screen_lines: []*ScreenLine{{}}})
}()
is_binary := !is_path_text(path)
if !is_binary && item_type == `diff` && !is_path_text(changed_path) {
is_binary = true
}
is_img := is_binary && is_image(path) || (item_type == `diff` && is_image(changed_path))
_ = is_img
switch item_type {
case "diff":
if is_binary {
if is_img {
ans, err = image_lines(path, changed_path, screen_size, margin_size, image_size, ans)
} else {
ans, err = binary_lines(path, changed_path, columns, margin_size, ans)
}
} else {
ans, err = lines_for_diff(path, changed_path, diff_map[path], columns, margin_size, ans)
}
if err != nil {
return err
}
case "add":
if is_binary {
if is_img {
ans, err = image_lines("", path, screen_size, margin_size, image_size, ans)
} else {
ans, err = binary_lines("", path, columns, margin_size, ans)
}
} else {
ans, err = all_lines(path, columns, margin_size, true, ans)
}
if err != nil {
return err
}
case "removal":
if is_binary {
if is_img {
ans, err = image_lines(path, "", screen_size, margin_size, image_size, ans)
} else {
ans, err = binary_lines(path, "", columns, margin_size, ans)
}
} else {
ans, err = all_lines(path, columns, margin_size, false, ans)
}
if err != nil {
return err
}
case "rename":
ans, err = rename_lines(path, changed_path, columns, margin_size, ans)
if err != nil {
return err
}
default:
return fmt.Errorf("Unknown change type: %#v", item_type)
}
return nil
})
var ll []*LogicalLine
if len(ans) > 1 {
ll = ans[:len(ans)-1]
} else {
// Having am empty list of lines causes panics later on
ll = []*LogicalLine{{line_type: EMPTY_LINE, screen_lines: []*ScreenLine{{}}}}
}
return &LogicalLines{lines: ll, title_line_indices: title_line_indices, margin_size: margin_size, columns: columns}, err
}
+150
View File
@@ -0,0 +1,150 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"fmt"
"regexp"
"slices"
"strings"
"sync"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/utils/images"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type Search struct {
pat *regexp.Regexp
matches map[ScrollPos][]Span
}
func (self *Search) Len() int { return len(self.matches) }
func (self *Search) find_matches_in_lines(clean_lines []string, origin int, send_result func(screen_line, offset, size int)) {
lengths := utils.Map(func(x string) int { return len(x) }, clean_lines)
offsets := make([]int, len(clean_lines))
cell_lengths := utils.Map(wcswidth.Stringwidth, clean_lines)
cell_offsets := make([]int, len(clean_lines))
for i := range clean_lines {
if i > 0 {
offsets[i] = offsets[i-1] + lengths[i-1]
cell_offsets[i] = cell_offsets[i-1] + cell_lengths[i-1]
}
}
joined_text := strings.Join(clean_lines, "")
matches := self.pat.FindAllStringIndex(joined_text, -1)
pos := 0
find_pos := func(start int) int {
for i := pos; i < len(clean_lines); i++ {
if start < offsets[i]+lengths[i] {
pos = i
return pos
}
}
return -1
}
for _, m := range matches {
start, end := m[0], m[1]
total_size := end - start
if total_size < 1 {
continue
}
start_line := find_pos(start)
if start_line > -1 {
end_line := find_pos(end - 1)
if end_line > -1 {
for i := start_line; i <= end_line; i++ {
cell_start := 0
if i == start_line {
byte_offset := start - offsets[i]
cell_start = wcswidth.Stringwidth(clean_lines[i][:byte_offset])
}
cell_end := cell_lengths[i]
if i == end_line {
byte_offset := end - offsets[i]
cell_end = wcswidth.Stringwidth(clean_lines[i][:byte_offset])
}
send_result(i, origin+cell_start, cell_end-cell_start)
}
}
}
}
}
func (self *Search) find_matches_in_line(line *LogicalLine, margin_size, cols int, send_result func(screen_line, offset, size int)) {
half_width := cols / 2
right_offset := half_width + margin_size
left_clean_lines, right_clean_lines := make([]string, len(line.screen_lines)), make([]string, len(line.screen_lines))
for i, sl := range line.screen_lines {
if line.is_full_width {
left_clean_lines[i] = wcswidth.StripEscapeCodes(sl.left.marked_up_text)
} else {
left_clean_lines[i] = wcswidth.StripEscapeCodes(sl.left.marked_up_text)
right_clean_lines[i] = wcswidth.StripEscapeCodes(sl.right.marked_up_text)
}
}
self.find_matches_in_lines(left_clean_lines, margin_size, send_result)
self.find_matches_in_lines(right_clean_lines, right_offset, send_result)
}
func (self *Search) Has(pos ScrollPos) bool {
return len(self.matches[pos]) > 0
}
type Span struct{ start, end int }
func (self *Search) search(logical_lines *LogicalLines) {
margin_size := logical_lines.margin_size
cols := logical_lines.columns
self.matches = make(map[ScrollPos][]Span)
ctx := images.Context{}
mutex := sync.Mutex{}
if err := ctx.SafeParallel(0, logical_lines.Len(), func(nums <-chan int) {
for i := range nums {
line := logical_lines.At(i)
if line.line_type == EMPTY_LINE || line.line_type == IMAGE_LINE {
continue
}
self.find_matches_in_line(line, margin_size, cols, func(screen_line, offset, size int) {
if size > 0 {
mutex.Lock()
defer mutex.Unlock()
pos := ScrollPos{i, screen_line}
self.matches[pos] = append(self.matches[pos], Span{offset, offset + size - 1})
}
})
}
}); err != nil {
panic(err)
}
for _, spans := range self.matches {
slices.SortFunc(spans, func(a, b Span) int { return a.start - b.start })
}
}
func (self *Search) markup_line(pos ScrollPos, y int) string {
spans := self.matches[pos]
if spans == nil {
return ""
}
sgr := format_as_sgr.search[2:]
sgr = sgr[:len(sgr)-1]
ans := make([]byte, 0, 32)
for _, span := range spans {
ans = append(ans, tui.FormatPartOfLine(sgr, span.start, span.end, y)...)
}
return utils.UnsafeBytesToString(ans)
}
func do_search(pat *regexp.Regexp, logical_lines *LogicalLines) *Search {
ans := &Search{pat: pat, matches: make(map[ScrollPos][]Span)}
ans.search(logical_lines)
return ans
}
+39
View File
@@ -0,0 +1,39 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"regexp"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestDiffSearchFindMatches(t *testing.T) {
wrapped := []string{"abc def ", "ghi rows"}
for _, tc := range []struct {
pat string
lines []string
origin int
expected [][3]int
}{
{"foo", []string{"x := foo"}, 0, [][3]int{{0, 5, 3}}},
{"o", []string{"foo"}, 0, [][3]int{{0, 1, 1}, {0, 2, 1}}},
{"rows", wrapped, 0, [][3]int{{1, 4, 4}}},
{"def ghi", wrapped, 0, [][3]int{{0, 4, 4}, {1, 0, 3}}},
{"def ", wrapped, 0, [][3]int{{0, 4, 4}}},
{"foo", []string{"日本 foo"}, 0, [][3]int{{0, 5, 3}}},
{"foo", []string{"x := foo"}, 7, [][3]int{{0, 12, 3}}},
} {
s := &Search{pat: regexp.MustCompile(tc.pat)}
var actual [][3]int
s.find_matches_in_lines(tc.lines, tc.origin, func(screen_line, offset, size int) {
if size > 0 {
actual = append(actual, [3]int{screen_line, offset, size})
}
})
if diff := cmp.Diff(tc.expected, actual); diff != "" {
t.Errorf("Unexpected matches for %#v in %#v:\n%s", tc.pat, tc.lines, diff)
}
}
}
+804
View File
@@ -0,0 +1,804 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package diff
import (
"fmt"
"regexp"
"strconv"
"strings"
"github.com/kovidgoyal/kitty/tools/config"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/graphics"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/tui/readline"
"github.com/kovidgoyal/kitty/tools/utils"
"github.com/kovidgoyal/kitty/tools/wcswidth"
)
var _ = fmt.Print
type ResultType int
const (
COLLECTION ResultType = iota
DIFF
HIGHLIGHT
IMAGE_LOAD
IMAGE_RESIZE
)
type ScrollPos struct {
logical_line, screen_line int
}
func (self ScrollPos) Less(other ScrollPos) bool {
return self.logical_line < other.logical_line || (self.logical_line == other.logical_line && self.screen_line < other.screen_line)
}
func (self ScrollPos) Add(other ScrollPos) ScrollPos {
return ScrollPos{self.logical_line + other.logical_line, self.screen_line + other.screen_line}
}
type AsyncResult struct {
err error
rtype ResultType
collection *Collection
diff_map map[string]*Patch
page_size graphics.Size
}
var image_collection *graphics.ImageCollection
type screen_size struct{ rows, columns, num_lines, cell_width, cell_height int }
type Handler struct {
async_results chan AsyncResult
mouse_selection tui.MouseSelection
image_count int
shortcut_tracker config.ShortcutTracker
left, right string
collection *Collection
diff_map map[string]*Patch
logical_lines *LogicalLines
terminal_capabilities_received bool
lp *loop.Loop
current_context_count, original_context_count int
added_count, removed_count int
screen_size screen_size
scroll_pos, max_scroll_pos ScrollPos
restore_position *ScrollPos
inputting_command bool
statusline_message string
rl *readline.Readline
current_search *Search
current_search_is_regex, current_search_is_backward bool
largest_line_number int
images_resized_to graphics.Size
}
func (self *Handler) calculate_statistics() {
self.added_count, self.removed_count = self.collection.added_count, self.collection.removed_count
self.largest_line_number = 0
for _, patch := range self.diff_map {
self.added_count += patch.added_count
self.removed_count += patch.removed_count
self.largest_line_number = utils.Max(patch.largest_line_number, self.largest_line_number)
}
}
func (self *Handler) update_screen_size(sz loop.ScreenSize) {
self.screen_size.rows = int(sz.HeightCells)
self.screen_size.columns = int(sz.WidthCells)
self.screen_size.num_lines = self.screen_size.rows - 1
self.screen_size.cell_height = int(sz.CellHeight)
self.screen_size.cell_width = int(sz.CellWidth)
}
func (self *Handler) on_escape_code(etype loop.EscapeCodeType, payload []byte) error {
switch etype {
case loop.APC:
gc := graphics.GraphicsCommandFromAPC(payload)
if gc != nil {
if !image_collection.HandleGraphicsCommand(gc) {
self.draw_screen()
}
}
}
return nil
}
func (self *Handler) finalize() {
image_collection.Finalize(self.lp)
}
func set_terminal_colors(lp *loop.Loop) {
create_formatters()
lp.SetDefaultColor(loop.FOREGROUND, resolved_colors.Foreground)
lp.SetDefaultColor(loop.CURSOR, resolved_colors.Foreground)
lp.SetDefaultColor(loop.BACKGROUND, resolved_colors.Background)
lp.SetDefaultColor(loop.SELECTION_BG, resolved_colors.Select_bg)
if resolved_colors.Select_fg.IsSet {
lp.SetDefaultColor(loop.SELECTION_FG, resolved_colors.Select_fg.Color)
}
}
func (self *Handler) on_capabilities_received(tc loop.TerminalCapabilities) {
var use_dark_colors bool
prev := use_light_colors
switch conf.Color_scheme {
case Color_scheme_auto:
use_dark_colors = tc.ColorPreference != loop.LIGHT_COLOR_PREFERENCE
case Color_scheme_light:
use_dark_colors = false
case Color_scheme_dark:
use_dark_colors = true
}
use_light_colors = !use_dark_colors
if use_light_colors != prev && (light_highlight_started || dark_highlight_started) {
self.highlight_all()
}
set_terminal_colors(self.lp)
self.terminal_capabilities_received = true
self.draw_screen()
}
func (self *Handler) on_color_scheme_change(cp loop.ColorPreference) error {
if conf.Color_scheme != Color_scheme_auto {
return nil
}
light := cp == loop.LIGHT_COLOR_PREFERENCE
if use_light_colors != light {
use_light_colors = light
set_terminal_colors(self.lp)
self.highlight_all()
self.draw_screen()
}
return nil
}
func (self *Handler) initialize() {
self.rl = readline.New(self.lp, readline.RlInit{DontMarkPrompts: true, Prompt: "/"})
self.lp.OnEscapeCode = self.on_escape_code
self.lp.OnColorSchemeChange = self.on_color_scheme_change
image_collection = graphics.NewImageCollection()
self.current_context_count = opts.Context
if self.current_context_count < 0 {
self.current_context_count = int(conf.Num_context_lines)
}
sz, _ := self.lp.ScreenSize()
self.update_screen_size(sz)
self.original_context_count = self.current_context_count
self.async_results = make(chan AsyncResult, 32)
go func() {
self.lp.RecoverFromPanicInGoRoutine()
r := AsyncResult{}
r.collection, r.err = create_collection(self.left, self.right)
self.async_results <- r
self.lp.WakeupMainThread()
}()
self.draw_screen()
}
func (self *Handler) generate_diff() {
self.diff_map = nil
jobs := make([]diff_job, 0, 32)
_ = self.collection.Apply(func(path, typ, changed_path string) error {
if typ == "diff" {
if is_path_text(path) && is_path_text(changed_path) {
jobs = append(jobs, diff_job{path, changed_path})
}
}
return nil
})
go func() {
self.lp.RecoverFromPanicInGoRoutine()
r := AsyncResult{rtype: DIFF}
r.diff_map, r.err = diff(jobs, self.current_context_count)
self.async_results <- r
self.lp.WakeupMainThread()
}()
}
func (self *Handler) on_wakeup() error {
var r AsyncResult
for {
select {
case r = <-self.async_results:
if r.err != nil {
return r.err
}
r.err = self.handle_async_result(r)
if r.err != nil {
return r.err
}
default:
return nil
}
}
}
var dark_highlight_started bool
var light_highlight_started bool
func (self *Handler) highlight_all() {
if (use_light_colors && light_highlight_started) || (!use_light_colors && dark_highlight_started) {
return
}
if use_light_colors {
light_highlight_started = true
} else {
dark_highlight_started = true
}
text_files := utils.Filter(self.collection.paths_to_highlight.AsSlice(), is_path_text)
go func() {
self.lp.RecoverFromPanicInGoRoutine()
r := AsyncResult{rtype: HIGHLIGHT}
highlight_all(text_files, use_light_colors)
self.async_results <- r
self.lp.WakeupMainThread()
}()
}
func (self *Handler) load_all_images() {
_ = self.collection.Apply(func(path, item_type, changed_path string) error {
if path != "" && is_image(path) {
image_collection.AddPaths(path)
self.image_count++
}
if changed_path != "" && is_image(changed_path) {
image_collection.AddPaths(changed_path)
self.image_count++
}
return nil
})
if self.image_count > 0 {
image_collection.Initialize(self.lp)
go func() {
self.lp.RecoverFromPanicInGoRoutine()
r := AsyncResult{rtype: IMAGE_LOAD}
image_collection.LoadAll()
self.async_results <- r
self.lp.WakeupMainThread()
}()
}
}
func (self *Handler) resize_all_images_if_needed() {
if self.logical_lines == nil {
return
}
margin_size := self.logical_lines.margin_size
columns := self.logical_lines.columns
available_cols := columns/2 - margin_size
sz := graphics.Size{
Width: available_cols * self.screen_size.cell_width,
Height: self.screen_size.num_lines * 2 * self.screen_size.cell_height,
}
if sz != self.images_resized_to && self.image_count > 0 {
go func() {
self.lp.RecoverFromPanicInGoRoutine()
image_collection.ResizeForPageSize(sz.Width, sz.Height)
r := AsyncResult{rtype: IMAGE_RESIZE, page_size: sz}
self.async_results <- r
self.lp.WakeupMainThread()
}()
}
}
func (self *Handler) rerender_diff() error {
if self.diff_map != nil && self.collection != nil && self.terminal_capabilities_received {
err := self.render_diff()
if err != nil {
return err
}
self.draw_screen()
}
return nil
}
func (self *Handler) handle_async_result(r AsyncResult) error {
switch r.rtype {
case COLLECTION:
self.collection = r.collection
self.generate_diff()
self.highlight_all()
self.load_all_images()
case DIFF:
if !self.terminal_capabilities_received {
go func() {
self.async_results <- r
self.lp.WakeupMainThread()
}()
return nil
}
self.diff_map = r.diff_map
self.calculate_statistics()
self.clear_mouse_selection()
err := self.render_diff()
if err != nil {
return err
}
self.scroll_pos = ScrollPos{}
if self.restore_position != nil {
self.scroll_pos = *self.restore_position
if self.max_scroll_pos.Less(self.scroll_pos) {
self.scroll_pos = self.max_scroll_pos
}
self.restore_position = nil
}
self.draw_screen()
case IMAGE_RESIZE:
self.images_resized_to = r.page_size
return self.rerender_diff()
case IMAGE_LOAD, HIGHLIGHT:
return self.rerender_diff()
}
return nil
}
func (self *Handler) on_resize(old_size, new_size loop.ScreenSize) error {
self.clear_mouse_selection()
self.update_screen_size(new_size)
if self.diff_map != nil && self.collection != nil && self.terminal_capabilities_received {
err := self.render_diff()
if err != nil {
return err
}
if self.max_scroll_pos.Less(self.scroll_pos) {
self.scroll_pos = self.max_scroll_pos
}
}
self.draw_screen()
return nil
}
func (self *Handler) render_diff() (err error) {
if self.screen_size.columns < 8 {
return fmt.Errorf("Screen too narrow, need at least 8 columns")
}
if self.screen_size.rows < 2 {
return fmt.Errorf("Screen too short, need at least 2 rows")
}
self.logical_lines, err = render(self.collection, self.diff_map, self.screen_size, self.largest_line_number, self.images_resized_to)
if err != nil {
return err
}
last := self.logical_lines.Len() - 1
self.max_scroll_pos.logical_line = last
if last > -1 {
self.max_scroll_pos.screen_line = len(self.logical_lines.At(last).screen_lines) - 1
} else {
self.max_scroll_pos.screen_line = 0
}
self.logical_lines.IncrementScrollPosBy(&self.max_scroll_pos, -self.screen_size.num_lines+1)
if self.current_search != nil {
self.current_search.search(self.logical_lines)
}
return nil
}
func (self *Handler) draw_image(key string, _, starting_row int) {
image_collection.PlaceImageSubRect(self.lp, key, self.images_resized_to, 0, self.screen_size.cell_height*starting_row, -1, -1)
}
func (self *Handler) draw_image_pair(ll *LogicalLine, starting_row int) {
if ll.left_image.key == "" && ll.right_image.key == "" {
return
}
defer self.lp.QueueWriteString("\r")
if ll.left_image.key != "" {
self.lp.QueueWriteString("\r")
self.lp.MoveCursorHorizontally(self.logical_lines.margin_size)
self.draw_image(ll.left_image.key, ll.left_image.count, starting_row)
}
if ll.right_image.key != "" {
self.lp.QueueWriteString("\r")
self.lp.MoveCursorHorizontally(self.logical_lines.margin_size + self.logical_lines.columns/2)
self.draw_image(ll.right_image.key, ll.right_image.count, starting_row)
}
}
func (self *Handler) draw_screen() {
self.lp.StartAtomicUpdate()
defer self.lp.EndAtomicUpdate()
if self.image_count > 0 {
self.resize_all_images_if_needed()
image_collection.DeleteAllVisiblePlacements(self.lp)
}
lp.MoveCursorTo(1, 1)
lp.ClearToEndOfScreen()
if self.logical_lines == nil || self.diff_map == nil || self.collection == nil || !self.terminal_capabilities_received {
lp.Println(`Calculating diff, please wait...`)
return
}
pos := self.scroll_pos
seen_images := utils.NewSet[int]()
num_written := 0
if conf != nil && conf.Sticky_header {
num_written = self.draw_sticky_header(&pos)
}
for ; num_written < self.screen_size.num_lines; num_written++ {
ll := self.logical_lines.At(pos.logical_line)
if ll == nil || self.logical_lines.ScreenLineAt(pos) == nil {
num_written--
} else {
is_image := ll.line_type == IMAGE_LINE
ll.render_screen_line(pos.screen_line, lp, self.logical_lines.margin_size, self.logical_lines.columns)
if is_image && !seen_images.Has(pos.logical_line) && pos.screen_line >= ll.image_lines_offset {
seen_images.Add(pos.logical_line)
self.draw_image_pair(ll, pos.screen_line-ll.image_lines_offset)
}
if self.current_search != nil {
if mkp := self.current_search.markup_line(pos, num_written); mkp != "" {
lp.QueueWriteString(mkp)
}
}
if mkp := self.add_mouse_selection_to_line(pos, num_written); mkp != "" {
lp.QueueWriteString(mkp)
}
lp.MoveCursorVertically(1)
lp.QueueWriteString("\x1b[m\r")
}
if self.logical_lines.IncrementScrollPosBy(&pos, 1) == 0 {
break
}
}
self.draw_status_line()
}
func (self *Handler) draw_sticky_header(pos *ScrollPos) int {
title_idx := self.logical_lines.TitleLineIdxFor(pos.logical_line)
if title_idx < 0 {
return 0
}
// If the next line is a different file's TITLE_LINE, skip sticky so the
// real title flows into view naturally instead of being consumed.
next := pos.logical_line + 1
if next < self.logical_lines.Len() && self.logical_lines.At(next).line_type == TITLE_LINE && next != title_idx {
return 0
}
// file title
self.logical_lines.At(title_idx).render_screen_line(0, self.lp, self.logical_lines.margin_size, self.logical_lines.columns)
self.lp.MoveCursorVertically(1)
self.lp.QueueWriteString("\x1b[m\r")
self.logical_lines.IncrementScrollPosBy(pos, 1)
// separator
self.logical_lines.At(title_idx+1).render_screen_line(0, self.lp, self.logical_lines.margin_size, self.logical_lines.columns)
self.lp.MoveCursorVertically(1)
self.lp.QueueWriteString("\x1b[m\r")
self.logical_lines.IncrementScrollPosBy(pos, 1)
return 2
}
func (self *Handler) draw_status_line() {
if self.logical_lines == nil || self.diff_map == nil {
return
}
self.lp.MoveCursorTo(1, self.screen_size.rows)
self.lp.ClearToEndOfLine()
self.lp.SetCursorVisible(self.inputting_command)
if self.inputting_command {
self.rl.RedrawNonAtomic()
} else if self.statusline_message != "" {
self.lp.QueueWriteString(message_format(wcswidth.TruncateToVisualLength(sanitize(self.statusline_message), self.screen_size.columns)))
} else {
num := self.logical_lines.NumScreenLinesTo(self.scroll_pos)
den := self.logical_lines.NumScreenLinesTo(self.max_scroll_pos)
var frac int
if den > 0 {
frac = int((float64(num) * 100.0) / float64(den))
}
sp := statusline_format(fmt.Sprintf("%d%%", frac))
var counts string
if self.current_search == nil {
counts = added_count_format(strconv.Itoa(self.added_count)) + statusline_format(`,`) + removed_count_format(strconv.Itoa(self.removed_count))
} else {
counts = statusline_format(fmt.Sprintf("%d matches", self.current_search.Len()))
}
suffix := counts + " " + sp
prefix := statusline_format(":")
filler := strings.Repeat(" ", utils.Max(0, self.screen_size.columns-wcswidth.Stringwidth(prefix)-wcswidth.Stringwidth(suffix)))
self.lp.QueueWriteString(prefix + filler + suffix)
}
}
func (self *Handler) on_text(text string, a, b bool) error {
if self.inputting_command {
defer self.draw_status_line()
return self.rl.OnText(text, a, b)
}
if self.statusline_message != "" {
self.statusline_message = ""
self.draw_status_line()
return nil
}
return nil
}
func (self *Handler) do_search(query string) {
self.current_search = nil
if len(query) < 2 {
return
}
if !self.current_search_is_regex {
query = regexp.QuoteMeta(query)
}
pat, err := regexp.Compile(`(?i)` + query)
if err != nil {
self.statusline_message = fmt.Sprintf("Bad regex: %s", err)
self.lp.Beep()
return
}
self.current_search = do_search(pat, self.logical_lines)
if self.current_search.Len() == 0 {
self.current_search = nil
self.statusline_message = fmt.Sprintf("No matches for: %#v", query)
self.lp.Beep()
} else {
if self.scroll_to_next_match(false, true) {
self.draw_screen()
} else {
self.lp.Beep()
}
}
}
func (self *Handler) on_key_event(ev *loop.KeyEvent) error {
if self.inputting_command {
defer self.draw_status_line()
if ev.MatchesPressOrRepeat("esc") {
self.inputting_command = false
ev.Handled = true
return nil
}
if ev.MatchesPressOrRepeat("enter") {
self.inputting_command = false
ev.Handled = true
self.do_search(self.rl.AllText())
self.draw_screen()
return nil
}
return self.rl.OnKeyEvent(ev)
}
if self.statusline_message != "" {
if ev.Type != loop.RELEASE {
ev.Handled = true
self.statusline_message = ""
self.draw_status_line()
}
return nil
}
if self.current_search != nil && ev.MatchesPressOrRepeat("esc") {
self.current_search = nil
self.draw_screen()
return nil
}
ac := self.shortcut_tracker.Match(ev, conf.KeyboardShortcuts)
if ac != nil {
ev.Handled = true
return self.dispatch_action(ac.Name, ac.Args)
}
return nil
}
func (self *Handler) scroll_lines(amt int) (delta int) {
before := self.scroll_pos
delta = self.logical_lines.IncrementScrollPosBy(&self.scroll_pos, amt)
if delta > 0 && self.max_scroll_pos.Less(self.scroll_pos) {
self.scroll_pos = self.max_scroll_pos
delta = self.logical_lines.Minus(self.scroll_pos, before)
}
return
}
func (self *Handler) scroll_to_next_change(backwards bool) bool {
if backwards {
for i := self.scroll_pos.logical_line - 1; i >= 0; i-- {
line := self.logical_lines.At(i)
if line.is_change_start {
self.scroll_pos = ScrollPos{i, 0}
return true
}
}
} else {
for i := self.scroll_pos.logical_line + 1; i < self.logical_lines.Len(); i++ {
line := self.logical_lines.At(i)
if line.is_change_start {
self.scroll_pos = ScrollPos{i, 0}
return true
}
}
}
return false
}
func (self *Handler) scroll_to_next_file(backwards bool) bool {
if backwards {
for i := self.scroll_pos.logical_line - 1; i >= 0; i-- {
line := self.logical_lines.At(i)
if line.line_type == TITLE_LINE {
self.scroll_pos = ScrollPos{i, 0}
return true
}
}
} else {
for i := self.scroll_pos.logical_line + 1; i < self.logical_lines.Len(); i++ {
line := self.logical_lines.At(i)
if line.line_type == TITLE_LINE {
self.scroll_pos = ScrollPos{i, 0}
return true
}
}
}
return false
}
func (self *Handler) scroll_to_next_match(backwards, include_current_match bool) bool {
if self.current_search == nil {
return false
}
if self.current_search_is_backward {
backwards = !backwards
}
offset, delta := 1, 1
if include_current_match {
offset = 0
}
if backwards {
offset *= -1
delta *= -1
}
pos := self.scroll_pos
if offset != 0 && self.logical_lines.IncrementScrollPosBy(&pos, offset) == 0 {
return false
}
for {
if self.current_search.Has(pos) {
self.scroll_pos = pos
self.draw_screen()
return true
}
if self.logical_lines.IncrementScrollPosBy(&pos, delta) == 0 || self.max_scroll_pos.Less(pos) {
break
}
}
return false
}
func (self *Handler) change_context_count(val int) bool {
val = utils.Max(0, val)
if val == self.current_context_count {
return false
}
self.current_context_count = val
p := self.scroll_pos
self.restore_position = &p
self.clear_mouse_selection()
self.generate_diff()
self.draw_screen()
return true
}
func (self *Handler) start_search(is_regex, is_backward bool) {
if self.inputting_command {
self.lp.Beep()
return
}
self.inputting_command = true
self.current_search_is_regex = is_regex
self.current_search_is_backward = is_backward
self.rl.SetText(``)
self.draw_status_line()
}
func (self *Handler) dispatch_action(name, args string) error {
switch name {
case `quit`:
self.lp.Quit(0)
case `copy_to_clipboard`:
text := self.text_for_current_mouse_selection()
if text == "" {
self.lp.Beep()
} else {
self.lp.CopyTextToClipboard(text)
}
case `copy_to_clipboard_or_exit`:
text := self.text_for_current_mouse_selection()
if text == "" {
self.lp.Quit(0)
} else {
self.lp.CopyTextToClipboard(text)
}
case `scroll_by`:
if args == "" {
args = "1"
}
amt, err := strconv.Atoi(args)
if err == nil {
if self.scroll_lines(amt) == 0 {
self.lp.Beep()
} else {
self.draw_screen()
}
} else {
self.lp.Beep()
}
case `scroll_to`:
done := false
switch {
case strings.Contains(args, "file"):
done = self.scroll_to_next_file(strings.Contains(args, `prev`))
case strings.Contains(args, `change`):
done = self.scroll_to_next_change(strings.Contains(args, `prev`))
case strings.Contains(args, `match`):
done = self.scroll_to_next_match(strings.Contains(args, `prev`), false)
case strings.Contains(args, `page`):
amt := self.screen_size.num_lines
if strings.Contains(args, `half`) {
amt = amt / 2
}
if strings.Contains(args, `prev`) {
amt *= -1
}
done = self.scroll_lines(amt) != 0
default:
npos := ScrollPos{}
if strings.Contains(args, `end`) {
npos = self.max_scroll_pos
}
done = npos != self.scroll_pos
self.scroll_pos = npos
}
if done {
self.draw_screen()
} else {
self.lp.Beep()
}
case `change_context`:
new_ctx := self.current_context_count
switch args {
case `all`:
new_ctx = 100000
case `default`:
new_ctx = self.original_context_count
default:
delta, _ := strconv.Atoi(args)
new_ctx += delta
}
if !self.change_context_count(new_ctx) {
self.lp.Beep()
}
case `start_search`:
if self.diff_map != nil && self.logical_lines != nil {
a, b, _ := strings.Cut(args, " ")
self.start_search(config.StringToBool(a), config.StringToBool(b))
}
}
return nil
}
func (self *Handler) on_mouse_event(ev *loop.MouseEvent) error {
if self.logical_lines == nil {
return nil
}
if ev.Event_type == loop.MOUSE_PRESS && ev.Buttons&(loop.MOUSE_WHEEL_UP|loop.MOUSE_WHEEL_DOWN) != 0 {
self.handle_wheel_event(ev.Buttons&(loop.MOUSE_WHEEL_UP) != 0)
return nil
}
if ev.Event_type == loop.MOUSE_PRESS && ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
self.start_mouse_selection(ev)
return nil
}
if ev.Event_type == loop.MOUSE_MOVE {
self.update_mouse_selection(ev)
return nil
}
if ev.Event_type == loop.MOUSE_RELEASE && ev.Buttons&loop.LEFT_MOUSE_BUTTON != 0 {
self.finish_mouse_selection(ev)
return nil
}
return nil
}