diff --git a/nav.go b/nav.go index 4d90f1fb..2074029a 100644 --- a/nav.go +++ b/nav.go @@ -934,6 +934,17 @@ func (nav *nav) preview(path string, win *win, mode string) { if binary { lines = []string{"\033[7mbinary\033[0m"} } + + // The internal previewer reads raw file content which may contain + // escape sequences that corrupt the display or enable code execution + // (e.g. OSC 52 clipboard writes). Strip all control characters. + if len(gOpts.previewer) == 0 && !binary { + sixel = false + for i, l := range lines { + lines[i] = stripAllSequences(l) + } + } + reg.lines = lines reg.sixel = sixel } diff --git a/termseq.go b/termseq.go index 9ac87c0e..0afe9250 100644 --- a/termseq.go +++ b/termseq.go @@ -270,3 +270,15 @@ func applyOSC(body string, st tcell.Style) tcell.Style { return st } } + +// stripAllSequences removes all control characters from a string, keeping +// only printable characters and tabs. This is used to +// sanitize raw file content for the internal previewer. +func stripAllSequences(s string) string { + return strings.Map(func(r rune) rune { + if r >= 0x20 && r != 0x7F || r == '\t' { + return r + } + return -1 + }, s) +} diff --git a/ui.go b/ui.go index c747dc82..8ec5eff5 100644 --- a/ui.go +++ b/ui.go @@ -35,6 +35,12 @@ func (win *win) renew(w, h, x, y int) { win.w, win.h, win.x, win.y = w, h, x, y } +// isPrintable reports whether sequence is safe to display. +// It rejects C0 control characters (0x00-0x1F) and DEL (0x7F). +func isPrintable(gc string) bool { + return gc[0] >= 0x20 && gc[0] != 0x7F +} + // printLength returns the display width of s in terminal cells. // // It ignores supported terminal control sequences (see [readTermSequence]) @@ -55,7 +61,7 @@ func printLength(s string) int { if gc == "\t" { length += gOpts.tabstop - length%gOpts.tabstop - } else { + } else if isPrintable(gc) { length += w } } @@ -89,7 +95,7 @@ func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) t if gc == "\t" { w := gOpts.tabstop - (x+off+printLength(b.String()))%gOpts.tabstop b.WriteString(strings.Repeat(" ", w)) - } else if gc != "\r" && gc != "\n" { + } else if isPrintable(gc) { b.WriteString(gc) }