Implement builtin support for sixel images, allow combining with text (#2109)

* Add function for reading lines in file

* Implement sixel drawing

* Remove sixel option

* Fix linting error
This commit is contained in:
Joe Lim authored and GitHub committed 2025-08-25 22:19:14 +10:00
1 parent aba73884e3
commit 13da770af6
11 files changed
+190 -99

No files matched your search

+1 -3
View File
@@ -450,9 +450,7 @@ func (app *app) loop() {
if err == nil { if err == nil {
if r.path == curr.path { if r.path == curr.path {
app.ui.regPrev = r app.ui.regPrev = r
if gOpts.sixel { app.ui.sxScreen.forceClear = true
app.ui.sxScreen.forceClear = true
}
} }
} }
-5
View File
@@ -200,7 +200,6 @@ The following options can be used to customize the behavior of lf:
shellflag string (default '-c' for Unix and '/c' for Windows) shellflag string (default '-c' for Unix and '/c' for Windows)
shellopts []string (default '') shellopts []string (default '')
showbinds bool (default true) showbinds bool (default true)
sixel bool (default false)
smartcase bool (default true) smartcase bool (default true)
smartdia bool (default false) smartdia bool (default false)
sortby string (default 'natural') sortby string (default 'natural')
@@ -994,10 +993,6 @@ List of shell options to pass to the shell executable.
Show bindings associated with pressed keys. Show bindings associated with pressed keys.
## sixel (bool) (default false)
Render sixel images in preview.
## smartcase (bool) (default true) ## smartcase (bool) (default true)
Override `ignorecase` option when the pattern contains an uppercase character. Override `ignorecase` option when the pattern contains an uppercase character.
-5
View File
@@ -190,7 +190,6 @@ The following options can be used to customize the behavior of lf:
shellflag string (default '-c' for Unix and '/c' for Windows) shellflag string (default '-c' for Unix and '/c' for Windows)
shellopts []string (default '') shellopts []string (default '')
showbinds bool (default true) showbinds bool (default true)
sixel bool (default false)
smartcase bool (default true) smartcase bool (default true)
smartdia bool (default false) smartdia bool (default false)
sortby string (default 'natural') sortby string (default 'natural')
@@ -1080,10 +1079,6 @@ showbinds (bool) (default true)
Show bindings associated with pressed keys. Show bindings associated with pressed keys.
sixel (bool) (default false)
Render sixel images in preview.
smartcase (bool) (default true) smartcase (bool) (default true)
Override ignorecase option when the pattern contains an uppercase Override ignorecase option when the pattern contains an uppercase
+6 -18
View File
@@ -92,10 +92,7 @@ func (e *setExpr) eval(app *app, args []string) {
err = applyBoolOpt(&gOpts.drawbox, e) err = applyBoolOpt(&gOpts.drawbox, e)
if err == nil { if err == nil {
app.ui.renew() app.ui.renew()
if app.nav.height != app.ui.wins[0].h { clear(app.nav.regCache)
app.nav.height = app.ui.wins[0].h
clear(app.nav.regCache)
}
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "hidden", "nohidden", "hidden!": case "hidden", "nohidden", "hidden!":
@@ -148,10 +145,8 @@ func (e *setExpr) eval(app *app, args []string) {
err = errors.New("preview: 'ratios' should consist of at least two numbers before enabling 'preview'") err = errors.New("preview: 'ratios' should consist of at least two numbers before enabling 'preview'")
} }
if err == nil { if err == nil {
if gOpts.sixel {
app.ui.sxScreen.forceClear = true
}
gOpts.preview = preview gOpts.preview = preview
app.ui.sxScreen.forceClear = true
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "relativenumber", "norelativenumber", "relativenumber!": case "relativenumber", "norelativenumber", "relativenumber!":
@@ -166,11 +161,9 @@ func (e *setExpr) eval(app *app, args []string) {
err = applyBoolOpt(&gOpts.roundbox, e) err = applyBoolOpt(&gOpts.roundbox, e)
case "showbinds", "noshowbinds", "showbinds!": case "showbinds", "noshowbinds", "showbinds!":
err = applyBoolOpt(&gOpts.showbinds, e) err = applyBoolOpt(&gOpts.showbinds, e)
// DEPRECATED: remove after r38 is released
case "sixel", "nosixel", "sixel!": case "sixel", "nosixel", "sixel!":
err = applyBoolOpt(&gOpts.sixel, e) app.ui.echoerr("option 'sixel' has been removed as it is now enabled by default")
clear(app.nav.regCache)
app.ui.sxScreen.forceClear = true
app.ui.loadFile(app, true)
case "smartcase", "nosmartcase", "smartcase!": case "smartcase", "nosmartcase", "smartcase!":
err = applyBoolOpt(&gOpts.smartcase, e) err = applyBoolOpt(&gOpts.smartcase, e)
if err == nil { if err == nil {
@@ -355,9 +348,7 @@ func (e *setExpr) eval(app *app, args []string) {
} }
gOpts.ratios = rats gOpts.ratios = rats
app.ui.wins = getWins(app.ui.screen) app.ui.wins = getWins(app.ui.screen)
if gOpts.sixel { clear(app.nav.regCache)
clear(app.nav.regCache)
}
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
case "rulerfmt": case "rulerfmt":
gOpts.rulerfmt = e.val gOpts.rulerfmt = e.val
@@ -1352,13 +1343,10 @@ func (e *callExpr) eval(app *app, args []string) {
app.nav.height = app.ui.wins[0].h app.nav.height = app.ui.wins[0].h
clear(app.nav.regCache) clear(app.nav.regCache)
} }
if gOpts.sixel {
clear(app.nav.regCache)
app.ui.sxScreen.forceClear = true
}
for _, dir := range app.nav.dirs { for _, dir := range app.nav.dirs {
dir.boundPos(app.nav.height) dir.boundPos(app.nav.height)
} }
app.ui.sxScreen.forceClear = true
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
onRedraw(app) onRedraw(app)
case "load": case "load":
-3
View File
@@ -205,7 +205,6 @@ shell string (default \(aqsh\(aq for Unix and \(aqcmd\(aq for Win
shellflag string (default \(aq\-c\(aq for Unix and \(aq/c\(aq for Windows) shellflag string (default \(aq\-c\(aq for Unix and \(aq/c\(aq for Windows)
shellopts []string (default \(aq\(aq) shellopts []string (default \(aq\(aq)
showbinds bool (default true) showbinds bool (default true)
sixel bool (default false)
smartcase bool (default true) smartcase bool (default true)
smartdia bool (default false) smartdia bool (default false)
sortby string (default \(aqnatural\(aq) sortby string (default \(aqnatural\(aq)
@@ -944,8 +943,6 @@ Command line flag used to pass shell commands.
List of shell options to pass to the shell executable. List of shell options to pass to the shell executable.
.SS showbinds (bool) (default true) .SS showbinds (bool) (default true)
Show bindings associated with pressed keys. Show bindings associated with pressed keys.
.SS sixel (bool) (default false)
Render sixel images in preview.
.SS smartcase (bool) (default true) .SS smartcase (bool) (default true)
Override \f[CR]ignorecase\f[R] option when the pattern contains an Override \f[CR]ignorecase\f[R] option when the pattern contains an
uppercase character. uppercase character.
+68
View File
@@ -2,6 +2,7 @@ package main
import ( import (
"bufio" "bufio"
"bytes"
"fmt" "fmt"
"io" "io"
"io/fs" "io/fs"
@@ -421,6 +422,73 @@ func stripAnsi(s string) string {
return b.String() return b.String()
} }
// This function reads lines from a file to be displayed as a preview.
// The number of lines to read is capped since files can be very large.
// Lines are split on `\n` characters, and `\r` characters are discarded.
// Sixel images are also detected and stored as separate lines.
// The presence of a null byte outside a sixel image indicates a binary file.
func readLines(reader io.ByteReader, maxLines int) (lines []string, binary bool, sixel bool) {
var buf bytes.Buffer
var last byte
inSixel := false
for {
b, err := reader.ReadByte()
if err != nil {
if buf.Len() > 0 {
lines = append(lines, buf.String())
}
return
}
if inSixel {
buf.WriteByte(b)
if b == '\\' && last == '\033' {
lines = append(lines, buf.String())
buf.Reset()
if len(lines) >= maxLines {
return
}
inSixel = false
}
} else {
switch {
case b == 0:
return nil, true, false
case b == '\033':
// withhold as it could be the start of a sixel image
case b == 'P' && last == '\033':
if buf.Len() > 0 {
lines = append(lines, buf.String())
buf.Reset()
if len(lines) >= maxLines {
return
}
}
buf.WriteByte(last)
buf.WriteByte(b)
inSixel = true
sixel = true
case last == '\033':
// not a sixel image
buf.WriteByte(last)
buf.WriteByte(b)
case b == '\r':
case b == '\n':
lines = append(lines, buf.String())
buf.Reset()
if len(lines) >= maxLines {
return
}
default:
buf.WriteByte(b)
}
}
last = b
}
}
// We don't need no generic code // We don't need no generic code
// We don't need no type control // We don't need no type control
// No dark templates in compiler // No dark templates in compiler
+52
View File
@@ -443,3 +443,55 @@ func TestStripAnsi(t *testing.T) {
} }
} }
} }
func TestReadLines(t *testing.T) {
tests := []struct {
s string
maxLines int
lines []string
binary bool
sixel bool
}{
{"", 10, nil, false, false},
{"\r", 10, nil, false, false},
{"\r\n", 10, []string{""}, false, false},
{"\r\r\n", 10, []string{""}, false, false},
{"\n\n", 10, []string{"", ""}, false, false},
{"foo", 10, []string{"foo"}, false, false},
{"foo\n", 10, []string{"foo"}, false, false},
{"foo\r\n", 10, []string{"foo"}, false, false},
{"foo\nbar", 10, []string{"foo", "bar"}, false, false},
{"foo\nbar\n", 10, []string{"foo", "bar"}, false, false},
{"foo\r\nbar", 10, []string{"foo", "bar"}, false, false},
{"foo\r\nbar\r\n", 10, []string{"foo", "bar"}, false, false},
{"\033[31mfoo\033[0m", 10, []string{"\033[31mfoo\033[0m"}, false, false},
{"\000", 10, nil, true, false},
{"foo\r\n\000\r\nbar\r\n", 10, nil, true, false},
{"\033P\033\\", 10, []string{"\033P\033\\"}, false, true},
{"\033Pq\"1;1;1;1#0@\033\\", 10, []string{"\033Pq\"1;1;1;1#0@\033\\"}, false, true},
{"\033P\000\033\\", 10, []string{"\033P\000\033\\"}, false, true},
{"\033P\n\033\\", 10, []string{"\033P\n\033\\"}, false, true},
{"\033P\r\n\033\\", 10, []string{"\033P\r\n\033\\"}, false, true},
{"\033P\033\\\033P\033\\", 10, []string{"\033P\033\\", "\033P\033\\"}, false, true},
{"foo\033P\033\\bar", 10, []string{"foo", "\033P\033\\", "bar"}, false, true},
{"foo\033P\033\\bar\033P\033\\baz", 10, []string{"foo", "\033P\033\\", "bar", "\033P\033\\", "baz"}, false, true},
{"foo\nbar\nbaz", 2, []string{"foo", "bar"}, false, false},
{"foo\nbar\nbaz\n", 2, []string{"foo", "bar"}, false, false},
{"foo\nbar\033P\033\\", 2, []string{"foo", "bar"}, false, false},
{"foo\nbar\nbaz", 3, []string{"foo", "bar", "baz"}, false, false},
{"foo\nbar\nbaz\n", 3, []string{"foo", "bar", "baz"}, false, false},
{"foo\nbar\033P\033\\", 3, []string{"foo", "bar", "\033P\033\\"}, false, true},
}
for _, test := range tests {
lines, binary, sixel := readLines(strings.NewReader(test.s), test.maxLines)
if !reflect.DeepEqual(lines, test.lines) || binary != test.binary || sixel != test.sixel {
t.Errorf(
"at input (%q, %v) expected (%#v, %v, %v) but got (%#v, %v, %v)",
test.s, test.maxLines,
test.lines, test.binary, test.sixel,
lines, binary, sixel,
)
}
}
}
+5 -37
View File
@@ -12,7 +12,6 @@ import (
"path/filepath" "path/filepath"
"reflect" "reflect"
"regexp" "regexp"
"slices"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
@@ -914,43 +913,12 @@ func (nav *nav) preview(path string, win *win) {
reader = bufio.NewReader(f) reader = bufio.NewReader(f)
} }
if gOpts.sixel { lines, binary, sixel := readLines(reader, win.h)
prefix, err := reader.Peek(2) if binary {
if err == nil && string(prefix) == gSixelBegin { lines = []string{"\033[7mbinary\033[0m"}
b, err := io.ReadAll(reader)
if err != nil {
log.Printf("loading sixel: %s", err)
}
str := string(b)
reg.sixel = &str
return
}
}
// bufio.Scanner can't handle files containing long lines if they exceed the
// size of its internal buffer
line := []byte{}
for len(reg.lines) < win.h {
bytes, isPrefix, err := reader.ReadLine()
if err != nil {
if len(line) > 0 {
reg.lines = append(reg.lines, string(line))
}
break
}
if slices.Contains(bytes, 0) {
reg.lines = []string{"\033[7mbinary\033[0m"}
return
}
line = append(line, bytes...)
if !isPrefix {
reg.lines = append(reg.lines, string(line))
line = []byte{}
}
} }
reg.lines = lines
reg.sixel = sixel
} }
func (nav *nav) loadReg(path string, volatile bool) *reg { func (nav *nav) loadReg(path string, volatile bool) *reg {
-2
View File
@@ -98,7 +98,6 @@ var gOpts struct {
shellflag string shellflag string
shellopts []string shellopts []string
showbinds bool showbinds bool
sixel bool
smartcase bool smartcase bool
smartdia bool smartdia bool
sortby sortMethod sortby sortMethod
@@ -267,7 +266,6 @@ func init() {
gOpts.shellflag = gDefaultShellFlag gOpts.shellflag = gDefaultShellFlag
gOpts.shellopts = nil gOpts.shellopts = nil
gOpts.showbinds = true gOpts.showbinds = true
gOpts.sixel = false
gOpts.smartcase = true gOpts.smartcase = true
gOpts.smartdia = false gOpts.smartdia = false
gOpts.sortby = naturalSort gOpts.sortby = naturalSort
+49 -20
View File
@@ -6,12 +6,11 @@ import (
"log" "log"
"os" "os"
"strconv" "strconv"
"strings"
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
) )
const gSixelBegin = "\033P"
type sixelScreen struct { type sixelScreen struct {
lastFile string lastFile string
lastWin win lastWin win
@@ -29,7 +28,7 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return return
} }
if reg.sixel == nil { if !reg.sixel {
sxs.lastFile = "" sxs.lastFile = ""
return return
} }
@@ -40,26 +39,56 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return return
} }
matches := reSixelSize.FindStringSubmatch(*reg.sixel) y := win.y
if matches == nil { var b strings.Builder
log.Printf("sixel: failed to get image size")
return
}
iw, _ := strconv.Atoi(matches[1])
ih, _ := strconv.Atoi(matches[2])
if os.Getenv("TMUX") != "" { for _, line := range reg.lines {
// tmux rounds the image height up to a multiple of 6, so we if !strings.HasPrefix(line, "\033P") {
// need to do the same to avoid overwriting the image, as tmux if y >= win.y+win.h {
// would remove the image if we touched it. break
ih = (ih + 5) / 6 * 6 }
screen.LockRegion(win.x, y, printLength(line), 1, true)
fmt.Fprintf(&b, "\033[%d;%dH", y+1, win.x+1)
b.WriteString(line)
y += 1
continue
}
matches := reSixelSize.FindStringSubmatch(line)
if matches == nil {
log.Printf("sixel: failed to get image size")
continue
}
iw, _ := strconv.Atoi(matches[1])
ih, _ := strconv.Atoi(matches[2])
if os.Getenv("TMUX") != "" {
// tmux rounds the image height up to a multiple of 6, so we
// need to do the same to avoid overwriting the image, as tmux
// would remove the image if we touched it.
ih = (ih + 5) / 6 * 6
}
sw := (iw + cw - 1) / cw
sh := (ih + ch - 1) / ch
if y+sh-1 >= win.y+win.h {
break
}
screen.LockRegion(win.x, y, sw, sh, true)
fmt.Fprintf(&b, "\033[%d;%dH", y+1, win.x+1)
b.WriteString(line)
y += sh
} }
screen.LockRegion(win.x, win.y, (iw+cw-1)/cw, (ih+ch-1)/ch, true) fmt.Fprint(os.Stderr, "\033[?2026h") // Begin synchronized update
fmt.Fprint(os.Stderr, "\0337") // Save cursor position fmt.Fprint(os.Stderr, "\0337") // Save cursor position
fmt.Fprintf(os.Stderr, "\033[%d;%dH", win.y+1, win.x+1) // Move cursor to position fmt.Fprint(os.Stderr, b.String()) // Write data
fmt.Fprint(os.Stderr, *reg.sixel) // Print sixel fmt.Fprint(os.Stderr, "\0338") // Restore cursor position
fmt.Fprint(os.Stderr, "\0338") // Restore cursor position fmt.Fprint(os.Stderr, "\033[?2026l") // End synchronized update
sxs.lastFile = reg.path sxs.lastFile = reg.path
sxs.lastWin = *win sxs.lastWin = *win
+9 -6
View File
@@ -270,12 +270,14 @@ func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs
return return
} }
for i, l := range reg.lines { if !reg.sixel {
if i > win.h-1 { for i, l := range reg.lines {
break if i > win.h-1 {
} break
}
st = win.print(screen, 2, i, st, l) st = win.print(screen, 2, i, st, l)
}
} }
sxs.printSixel(win, screen, reg) sxs.printSixel(win, screen, reg)
@@ -768,7 +770,7 @@ type reg struct {
loadTime time.Time loadTime time.Time
path string path string
lines []string lines []string
sixel *string sixel bool
} }
func (ui *ui) loadFile(app *app, volatile bool) { func (ui *ui) loadFile(app *app, volatile bool) {
@@ -1572,6 +1574,7 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
return &callExpr{"cd", []string{dir.path}, 1} return &callExpr{"cd", []string{dir.path}, 1}
} }
case *tcell.EventResize: case *tcell.EventResize:
clear(nav.regCache)
return &callExpr{"redraw", nil, 1} return &callExpr{"redraw", nil, 1}
case *tcell.EventError: case *tcell.EventError:
log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When()) log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When())