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 r.path == curr.path {
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)
shellopts []string (default '')
showbinds bool (default true)
sixel bool (default false)
smartcase bool (default true)
smartdia bool (default false)
sortby string (default 'natural')
@@ -994,10 +993,6 @@ List of shell options to pass to the shell executable.
Show bindings associated with pressed keys.
## sixel (bool) (default false)
Render sixel images in preview.
## smartcase (bool) (default true)
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)
shellopts []string (default '')
showbinds bool (default true)
sixel bool (default false)
smartcase bool (default true)
smartdia bool (default false)
sortby string (default 'natural')
@@ -1080,10 +1079,6 @@ showbinds (bool) (default true)
Show bindings associated with pressed keys.
sixel (bool) (default false)
Render sixel images in preview.
smartcase (bool) (default true)
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)
if err == nil {
app.ui.renew()
if app.nav.height != app.ui.wins[0].h {
app.nav.height = app.ui.wins[0].h
clear(app.nav.regCache)
}
clear(app.nav.regCache)
app.ui.loadFile(app, true)
}
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'")
}
if err == nil {
if gOpts.sixel {
app.ui.sxScreen.forceClear = true
}
gOpts.preview = preview
app.ui.sxScreen.forceClear = true
app.ui.loadFile(app, true)
}
case "relativenumber", "norelativenumber", "relativenumber!":
@@ -166,11 +161,9 @@ func (e *setExpr) eval(app *app, args []string) {
err = applyBoolOpt(&gOpts.roundbox, e)
case "showbinds", "noshowbinds", "showbinds!":
err = applyBoolOpt(&gOpts.showbinds, e)
// DEPRECATED: remove after r38 is released
case "sixel", "nosixel", "sixel!":
err = applyBoolOpt(&gOpts.sixel, e)
clear(app.nav.regCache)
app.ui.sxScreen.forceClear = true
app.ui.loadFile(app, true)
app.ui.echoerr("option 'sixel' has been removed as it is now enabled by default")
case "smartcase", "nosmartcase", "smartcase!":
err = applyBoolOpt(&gOpts.smartcase, e)
if err == nil {
@@ -355,9 +348,7 @@ func (e *setExpr) eval(app *app, args []string) {
}
gOpts.ratios = rats
app.ui.wins = getWins(app.ui.screen)
if gOpts.sixel {
clear(app.nav.regCache)
}
clear(app.nav.regCache)
app.ui.loadFile(app, true)
case "rulerfmt":
gOpts.rulerfmt = e.val
@@ -1352,13 +1343,10 @@ func (e *callExpr) eval(app *app, args []string) {
app.nav.height = app.ui.wins[0].h
clear(app.nav.regCache)
}
if gOpts.sixel {
clear(app.nav.regCache)
app.ui.sxScreen.forceClear = true
}
for _, dir := range app.nav.dirs {
dir.boundPos(app.nav.height)
}
app.ui.sxScreen.forceClear = true
app.ui.loadFile(app, true)
onRedraw(app)
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)
shellopts []string (default \(aq\(aq)
showbinds bool (default true)
sixel bool (default false)
smartcase bool (default true)
smartdia bool (default false)
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.
.SS showbinds (bool) (default true)
Show bindings associated with pressed keys.
.SS sixel (bool) (default false)
Render sixel images in preview.
.SS smartcase (bool) (default true)
Override \f[CR]ignorecase\f[R] option when the pattern contains an
uppercase character.
+68
View File
@@ -2,6 +2,7 @@ package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/fs"
@@ -421,6 +422,73 @@ func stripAnsi(s string) 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 type control
// 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"
"reflect"
"regexp"
"slices"
"sort"
"strconv"
"strings"
@@ -914,43 +913,12 @@ func (nav *nav) preview(path string, win *win) {
reader = bufio.NewReader(f)
}
if gOpts.sixel {
prefix, err := reader.Peek(2)
if err == nil && string(prefix) == gSixelBegin {
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{}
}
lines, binary, sixel := readLines(reader, win.h)
if binary {
lines = []string{"\033[7mbinary\033[0m"}
}
reg.lines = lines
reg.sixel = sixel
}
func (nav *nav) loadReg(path string, volatile bool) *reg {
-2
View File
@@ -98,7 +98,6 @@ var gOpts struct {
shellflag string
shellopts []string
showbinds bool
sixel bool
smartcase bool
smartdia bool
sortby sortMethod
@@ -267,7 +266,6 @@ func init() {
gOpts.shellflag = gDefaultShellFlag
gOpts.shellopts = nil
gOpts.showbinds = true
gOpts.sixel = false
gOpts.smartcase = true
gOpts.smartdia = false
gOpts.sortby = naturalSort
+49 -20
View File
@@ -6,12 +6,11 @@ import (
"log"
"os"
"strconv"
"strings"
"github.com/gdamore/tcell/v2"
)
const gSixelBegin = "\033P"
type sixelScreen struct {
lastFile string
lastWin win
@@ -29,7 +28,7 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return
}
if reg.sixel == nil {
if !reg.sixel {
sxs.lastFile = ""
return
}
@@ -40,26 +39,56 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return
}
matches := reSixelSize.FindStringSubmatch(*reg.sixel)
if matches == nil {
log.Printf("sixel: failed to get image size")
return
}
iw, _ := strconv.Atoi(matches[1])
ih, _ := strconv.Atoi(matches[2])
y := win.y
var b strings.Builder
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
for _, line := range reg.lines {
if !strings.HasPrefix(line, "\033P") {
if y >= win.y+win.h {
break
}
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, "\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, *reg.sixel) // Print sixel
fmt.Fprint(os.Stderr, "\0338") // Restore cursor position
fmt.Fprint(os.Stderr, "\033[?2026h") // Begin synchronized update
fmt.Fprint(os.Stderr, "\0337") // Save cursor position
fmt.Fprint(os.Stderr, b.String()) // Write data
fmt.Fprint(os.Stderr, "\0338") // Restore cursor position
fmt.Fprint(os.Stderr, "\033[?2026l") // End synchronized update
sxs.lastFile = reg.path
sxs.lastWin = *win
+9 -6
View File
@@ -270,12 +270,14 @@ func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs
return
}
for i, l := range reg.lines {
if i > win.h-1 {
break
}
if !reg.sixel {
for i, l := range reg.lines {
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)
@@ -768,7 +770,7 @@ type reg struct {
loadTime time.Time
path string
lines []string
sixel *string
sixel 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}
}
case *tcell.EventResize:
clear(nav.regCache)
return &callExpr{"redraw", nil, 1}
case *tcell.EventError:
log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When())