Compare commits
5 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b0600fa44 | ||
|
|
6b365eea95 | ||
|
|
7b2431d4a8 | ||
|
|
e3970c813d | ||
|
|
2ec00031cd |
18 changed files with 1074 additions and 57 deletions
15
.github/dependabot.yml
vendored
15
.github/dependabot.yml
vendored
|
|
@ -4,10 +4,7 @@ updates:
|
|||
- package-ecosystem: "gomod"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "05:00"
|
||||
timezone: "America/New_York"
|
||||
interval: "monthly"
|
||||
labels:
|
||||
- "dependencies"
|
||||
commit-message:
|
||||
|
|
@ -25,10 +22,7 @@ updates:
|
|||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "05:00"
|
||||
timezone: "America/New_York"
|
||||
interval: "monthly"
|
||||
labels:
|
||||
- "dependencies"
|
||||
commit-message:
|
||||
|
|
@ -42,10 +36,7 @@ updates:
|
|||
- package-ecosystem: "docker"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
day: "monday"
|
||||
time: "05:00"
|
||||
timezone: "America/New_York"
|
||||
interval: "monthly"
|
||||
labels:
|
||||
- "dependencies"
|
||||
commit-message:
|
||||
|
|
|
|||
2
.github/workflows/build.yml
vendored
2
.github/workflows/build.yml
vendored
|
|
@ -22,4 +22,4 @@ jobs:
|
|||
ruleguard:
|
||||
uses: charmbracelet/meta/.github/workflows/ruleguard.yml@main
|
||||
with:
|
||||
go-version: stable
|
||||
go-version: "1.26"
|
||||
|
|
|
|||
4
.github/workflows/coverage.yml
vendored
4
.github/workflows/coverage.yml
vendored
|
|
@ -8,10 +8,10 @@ jobs:
|
|||
GO111MODULE: "on"
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v6
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version: stable
|
||||
|
||||
|
|
|
|||
4
.github/workflows/lint.yml
vendored
4
.github/workflows/lint.yml
vendored
|
|
@ -8,9 +8,9 @@ jobs:
|
|||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9.2.0
|
||||
uses: golangci/golangci-lint-action@v9.3.0
|
||||
with:
|
||||
# Optional: golangci-lint command line arguments.
|
||||
args: --issues-exit-code=0
|
||||
|
|
|
|||
10
go.mod
10
go.mod
|
|
@ -1,6 +1,6 @@
|
|||
module charm.land/glow/v3
|
||||
|
||||
go 1.26.5
|
||||
go 1.26.7
|
||||
|
||||
require (
|
||||
charm.land/bubbles/v2 v2.1.1
|
||||
|
|
@ -15,17 +15,19 @@ require (
|
|||
github.com/fsnotify/fsnotify v1.9.0
|
||||
github.com/mattn/go-runewidth v0.0.24
|
||||
github.com/mitchellh/go-homedir v1.1.0
|
||||
github.com/muesli/cancelreader v0.2.2
|
||||
github.com/muesli/gitcha v0.3.0
|
||||
github.com/muesli/go-app-paths v0.2.2
|
||||
github.com/muesli/mango-cobra v1.3.0
|
||||
github.com/muesli/reflow v0.3.0
|
||||
github.com/muesli/roff v0.1.0
|
||||
github.com/muesli/termenv v0.16.0
|
||||
github.com/rivo/uniseg v0.4.7
|
||||
github.com/sahilm/fuzzy v0.1.3
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/viper v1.21.0
|
||||
golang.org/x/sys v0.47.0
|
||||
golang.org/x/term v0.42.0
|
||||
golang.org/x/term v0.44.0
|
||||
golang.org/x/text v0.39.0
|
||||
mvdan.cc/sh/v3 v3.13.1
|
||||
)
|
||||
|
|
@ -53,11 +55,9 @@ require (
|
|||
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/muesli/mango v0.2.0 // indirect
|
||||
github.com/muesli/mango-pflag v0.1.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/sabhiram/go-gitignore v0.0.0-20180611051255-d3107576ba94 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
|
|
@ -70,7 +70,7 @@ require (
|
|||
github.com/yuin/goldmark-emoji v1.0.5 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 // indirect
|
||||
golang.org/x/net v0.53.0 // indirect
|
||||
golang.org/x/net v0.56.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
)
|
||||
|
|
|
|||
8
go.sum
8
go.sum
|
|
@ -161,15 +161,15 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
|||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 h1:LoYXNGAShUG3m/ehNk4iFctuhGX/+R1ZpfJ4/ia80JM=
|
||||
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI=
|
||||
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
|
||||
golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
|
||||
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
|
||||
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
|
|
|||
9
main.go
9
main.go
|
|
@ -311,6 +311,8 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error {
|
|||
return fmt.Errorf("unable to render markdown: %w", err)
|
||||
}
|
||||
|
||||
out = utils.ApplyTextSizing(out)
|
||||
|
||||
// display
|
||||
switch {
|
||||
case pager || cmd.Flags().Changed("pager"):
|
||||
|
|
@ -345,6 +347,9 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error {
|
|||
}
|
||||
|
||||
func runTUI(path string, content string) error {
|
||||
// detect text sizing support before bubbletea takes over the terminal
|
||||
_ = utils.TextSizingEnabled()
|
||||
|
||||
// Read environment to get debugging stuff
|
||||
cfg, err := env.ParseAs[ui.Config]()
|
||||
if err != nil {
|
||||
|
|
@ -364,7 +369,9 @@ func runTUI(path string, content string) error {
|
|||
cfg.PreserveNewLines = preserveNewLines
|
||||
|
||||
// Run Bubble Tea program
|
||||
if _, err := ui.NewProgram(cfg, content).Run(); err != nil {
|
||||
prog, cleanup := ui.NewProgram(cfg, content)
|
||||
defer cleanup()
|
||||
if _, err := prog.Run(); err != nil {
|
||||
return fmt.Errorf("unable to run tui program: %w", err)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -388,6 +388,8 @@ func glamourRender(m pagerModel, markdown string) (string, error) {
|
|||
|
||||
if isCode {
|
||||
out = strings.TrimSpace(out)
|
||||
} else {
|
||||
out = utils.ApplyTextSizing(out)
|
||||
}
|
||||
|
||||
// trim lines
|
||||
|
|
|
|||
43
ui/pager_test.go
Normal file
43
ui/pager_test.go
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
package ui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGlamourRenderTextSizing(t *testing.T) {
|
||||
t.Setenv("GLOW_TEXT_SIZING", "on")
|
||||
|
||||
common := &commonModel{
|
||||
cfg: Config{
|
||||
GlamourEnabled: true,
|
||||
GlamourStyle: "dark",
|
||||
GlamourMaxWidth: 80,
|
||||
},
|
||||
styles: newStyles(true),
|
||||
width: 80,
|
||||
height: 24,
|
||||
}
|
||||
m := newPagerModel(common)
|
||||
m.currentDocument = markdown{Note: "test.md"}
|
||||
m.setSize(80, 24)
|
||||
|
||||
out, err := glamourRender(m, "# Hello\n\n## World\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The dark style's H1 has a background color, which renders broken when
|
||||
// scaled, so it is left at normal size.
|
||||
if strings.Contains(out, "\x1b]66;s=3;") {
|
||||
t.Errorf("expected H1 with background to not be scaled, got %q", out)
|
||||
}
|
||||
if !strings.Contains(out, "Hello") {
|
||||
t.Errorf("expected H1 text in pager output, got %q", out)
|
||||
}
|
||||
if !strings.Contains(out, "\x1b]66;s=2;World\x1b\\") {
|
||||
t.Errorf("expected H2 at 2x scale in pager output, got %q", out)
|
||||
}
|
||||
if strings.Contains(out, "\x1b]6666;") {
|
||||
t.Errorf("expected no leftover markers in pager output, got %q", out)
|
||||
}
|
||||
}
|
||||
139
ui/rawpaint.go
Normal file
139
ui/rawpaint.go
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
package ui
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
// rawPainter paints frames directly to the terminal. It is used when kitty
|
||||
// text sizing support is detected: bubbletea's default renderer parses each
|
||||
// frame into a cell buffer which discards OSC 66 sequences along with their
|
||||
// payload text, so the program runs with [tea.WithoutRenderer] and this
|
||||
// painter drives the terminal instead.
|
||||
type rawPainter struct {
|
||||
w io.Writer
|
||||
tty *os.File
|
||||
state *term.State
|
||||
mouse bool
|
||||
done chan struct{}
|
||||
|
||||
mu sync.Mutex
|
||||
gen int
|
||||
painted int
|
||||
}
|
||||
|
||||
func newRawPainter(w io.Writer, tty *os.File, state *term.State, mouse bool) *rawPainter {
|
||||
return &rawPainter{w: w, tty: tty, state: state, mouse: mouse, done: make(chan struct{})}
|
||||
}
|
||||
|
||||
func (p *rawPainter) windowSize() tea.WindowSizeMsg {
|
||||
if p.tty != nil {
|
||||
if w, h, err := term.GetSize(int(p.tty.Fd())); err == nil && w > 0 && h > 0 {
|
||||
return tea.WindowSizeMsg{Width: w, Height: h}
|
||||
}
|
||||
}
|
||||
return tea.WindowSizeMsg{Width: 80, Height: 24}
|
||||
}
|
||||
|
||||
func (p *rawPainter) start() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
_, _ = io.WriteString(p.w, "\x1b[?1049h\x1b[?25l")
|
||||
if p.mouse {
|
||||
_, _ = io.WriteString(p.w, "\x1b[?1002h\x1b[?1006h")
|
||||
}
|
||||
}
|
||||
|
||||
func (p *rawPainter) stop() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.mouse {
|
||||
_, _ = io.WriteString(p.w, "\x1b[?1002l\x1b[?1006l")
|
||||
}
|
||||
_, _ = io.WriteString(p.w, "\x1b[?25h\x1b[?1049l")
|
||||
if p.tty != nil {
|
||||
if p.state != nil {
|
||||
_ = term.Restore(int(p.tty.Fd()), p.state)
|
||||
}
|
||||
_ = p.tty.Close()
|
||||
}
|
||||
select {
|
||||
case <-p.done:
|
||||
default:
|
||||
close(p.done)
|
||||
}
|
||||
}
|
||||
|
||||
// watchResize sends the initial window size to the program and reports
|
||||
// terminal resizes. Without a renderer bubbletea never initializes the tty,
|
||||
// so its own size reporting never happens.
|
||||
func (p *rawPainter) watchResize(prog *tea.Program) {
|
||||
ch := make(chan os.Signal, 1)
|
||||
winchNotify(ch)
|
||||
go func() {
|
||||
prog.Send(p.windowSize())
|
||||
for {
|
||||
select {
|
||||
case <-p.done:
|
||||
winchStop(ch)
|
||||
return
|
||||
case <-ch:
|
||||
prog.Send(p.windowSize())
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (p *rawPainter) paint(frame string) tea.Cmd {
|
||||
p.mu.Lock()
|
||||
p.gen++
|
||||
gen := p.gen
|
||||
p.mu.Unlock()
|
||||
|
||||
return func() tea.Msg {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if gen <= p.painted {
|
||||
return nil
|
||||
}
|
||||
p.painted = gen
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("\x1b[?2026h\x1b[H\x1b[2J")
|
||||
b.WriteString(strings.ReplaceAll(frame, "\n", "\r\n"))
|
||||
b.WriteString("\x1b[?2026l")
|
||||
_, _ = io.WriteString(p.w, b.String())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// paintModel wraps the root model, painting a frame after every processed
|
||||
// message. Bubbletea's renderer never calls View when it is disabled, so the
|
||||
// wrapper drives painting itself.
|
||||
type paintModel struct {
|
||||
inner tea.Model
|
||||
painter *rawPainter
|
||||
}
|
||||
|
||||
func (m paintModel) Init() tea.Cmd {
|
||||
m.painter.start()
|
||||
return tea.Batch(m.inner.Init(), m.painter.paint(m.inner.View().Content))
|
||||
}
|
||||
|
||||
func (m paintModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if ws, ok := msg.(tea.WindowSizeMsg); ok && (ws.Width <= 0 || ws.Height <= 0) {
|
||||
msg = m.painter.windowSize()
|
||||
}
|
||||
inner, cmd := m.inner.Update(msg)
|
||||
m.inner = inner
|
||||
return m, tea.Batch(cmd, m.painter.paint(inner.View().Content))
|
||||
}
|
||||
|
||||
func (m paintModel) View() tea.View {
|
||||
return m.inner.View()
|
||||
}
|
||||
107
ui/rawpaint_test.go
Normal file
107
ui/rawpaint_test.go
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
package ui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
)
|
||||
|
||||
func TestRawPainterPaint(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
p := &rawPainter{w: &buf}
|
||||
|
||||
stale := p.paint("stale frame")
|
||||
fresh := p.paint("fresh\nframe")
|
||||
|
||||
fresh()
|
||||
stale()
|
||||
|
||||
got := buf.String()
|
||||
if strings.Contains(got, "stale") {
|
||||
t.Errorf("stale frame was painted over a newer one: %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "\x1b[?2026h\x1b[H\x1b[2Jfresh\r\nframe\x1b[?2026l") {
|
||||
t.Errorf("unexpected frame format: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaintModelRendersDocument(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "test.md")
|
||||
if err := os.WriteFile(path, []byte("# Hello\n\nSome text here.\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg := Config{
|
||||
GlamourEnabled: true,
|
||||
GlamourStyle: "dark",
|
||||
GlamourMaxWidth: 80,
|
||||
Path: path,
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
painter := &rawPainter{w: &buf}
|
||||
var pm tea.Model = paintModel{inner: newModel(cfg, ""), painter: painter}
|
||||
|
||||
msgCh := make(chan tea.Msg, 64)
|
||||
var exec func(cmd tea.Cmd)
|
||||
exec = func(cmd tea.Cmd) {
|
||||
if cmd == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
switch msg := cmd().(type) {
|
||||
case tea.BatchMsg:
|
||||
for _, c := range msg {
|
||||
exec(c)
|
||||
}
|
||||
case nil:
|
||||
default:
|
||||
msgCh <- msg
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
exec(pm.Init())
|
||||
msgCh <- tea.WindowSizeMsg{Width: 80, Height: 24}
|
||||
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
// Frames are painted asynchronously by the paint command, so poll
|
||||
// the buffer instead of only checking after processed messages.
|
||||
painter.mu.Lock()
|
||||
done := strings.Contains(buf.String(), "Some text")
|
||||
painter.mu.Unlock()
|
||||
if done {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("timed out waiting for content; buf=%q", buf.String())
|
||||
}
|
||||
|
||||
select {
|
||||
case msg := <-msgCh:
|
||||
im, cmd := pm.Update(msg)
|
||||
pm = im
|
||||
exec(cmd)
|
||||
case <-time.After(5 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaintModelZeroSizeSubstitution(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
painter := &rawPainter{w: &buf}
|
||||
pm := paintModel{inner: newModel(Config{}, "body"), painter: painter}
|
||||
|
||||
im, _ := pm.Update(tea.WindowSizeMsg{Width: 0, Height: 0})
|
||||
m := im.(paintModel).inner.(model)
|
||||
if m.common.width != 80 || m.common.height != 24 {
|
||||
t.Errorf("expected fallback size 80x24, got %dx%d", m.common.width, m.common.height)
|
||||
}
|
||||
}
|
||||
32
ui/rawpaint_unix.go
Normal file
32
ui/rawpaint_unix.go
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
//go:build !windows
|
||||
|
||||
package ui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func openRawTerminal() (*os.File, *term.State, error) {
|
||||
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
state, err := term.MakeRaw(int(tty.Fd()))
|
||||
if err != nil {
|
||||
_ = tty.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return tty, state, nil
|
||||
}
|
||||
|
||||
func winchNotify(ch chan os.Signal) {
|
||||
signal.Notify(ch, syscall.SIGWINCH)
|
||||
}
|
||||
|
||||
func winchStop(ch chan os.Signal) {
|
||||
signal.Stop(ch)
|
||||
}
|
||||
16
ui/rawpaint_windows.go
Normal file
16
ui/rawpaint_windows.go
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
package ui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
func openRawTerminal() (*os.File, *term.State, error) {
|
||||
return nil, nil, errors.New("raw terminal is not supported on windows")
|
||||
}
|
||||
|
||||
func winchNotify(chan os.Signal) {}
|
||||
|
||||
func winchStop(chan os.Signal) {}
|
||||
36
ui/ui.go
36
ui/ui.go
|
|
@ -23,8 +23,9 @@ var markdownExtensions = []string{
|
|||
"*.md", "*.mdown", "*.mkdn", "*.mkd", "*.markdown",
|
||||
}
|
||||
|
||||
// NewProgram returns a new Tea program.
|
||||
func NewProgram(cfg Config, content string) *tea.Program {
|
||||
// NewProgram returns a new Tea program. The returned cleanup function
|
||||
// restores the terminal state and must be called after the program exits.
|
||||
func NewProgram(cfg Config, content string) (*tea.Program, func()) {
|
||||
log.Debug(
|
||||
"Starting glow",
|
||||
"glamour",
|
||||
|
|
@ -32,7 +33,21 @@ func NewProgram(cfg Config, content string) *tea.Program {
|
|||
)
|
||||
|
||||
m := newModel(cfg, content)
|
||||
return tea.NewProgram(m)
|
||||
|
||||
if utils.TextSizingEnabled() {
|
||||
if tty, state, err := openRawTerminal(); err == nil {
|
||||
painter := newRawPainter(os.Stdout, tty, state, cfg.EnableMouse)
|
||||
prog := tea.NewProgram(
|
||||
paintModel{inner: m, painter: painter},
|
||||
tea.WithoutRenderer(),
|
||||
tea.WithInput(tty),
|
||||
)
|
||||
painter.watchResize(prog)
|
||||
return prog, painter.stop
|
||||
}
|
||||
}
|
||||
|
||||
return tea.NewProgram(m), func() {}
|
||||
}
|
||||
|
||||
type errMsg struct{ err error }
|
||||
|
|
@ -153,6 +168,13 @@ func newModel(cfg Config, content string) tea.Model {
|
|||
Note: stripAbsolutePath(path, cwd),
|
||||
Modtime: info.ModTime(),
|
||||
}
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
log.Error("unable to read file", "file", path, "error", err)
|
||||
m.fatalErr = err
|
||||
return m
|
||||
}
|
||||
m.pager.currentDocument.Body = string(utils.RemoveFrontmatter(content))
|
||||
}
|
||||
|
||||
return m
|
||||
|
|
@ -165,13 +187,7 @@ func (m model) Init() tea.Cmd {
|
|||
case stateShowStash:
|
||||
cmds = append(cmds, findLocalFiles(*m.common))
|
||||
case stateShowDocument:
|
||||
content, err := os.ReadFile(m.common.cfg.Path)
|
||||
if err != nil {
|
||||
log.Error("unable to read file", "file", m.common.cfg.Path, "error", err)
|
||||
return func() tea.Msg { return errMsg{err} }
|
||||
}
|
||||
body := string(utils.RemoveFrontmatter(content))
|
||||
cmds = append(cmds, renderWithGlamour(m.pager, body))
|
||||
cmds = append(cmds, renderWithGlamour(m.pager, m.pager.currentDocument.Body))
|
||||
}
|
||||
|
||||
return tea.Batch(cmds...)
|
||||
|
|
|
|||
24
ui/ui_test.go
Normal file
24
ui/ui_test.go
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
package ui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewModelLoadsDocumentBody(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "test.md")
|
||||
if err := os.WriteFile(path, []byte("# Hello\n\nSome text here.\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
m := newModel(Config{Path: path}, "").(model)
|
||||
if m.state != stateShowDocument {
|
||||
t.Fatalf("expected stateShowDocument, got %s", m.state)
|
||||
}
|
||||
if !strings.Contains(m.pager.currentDocument.Body, "Some text") {
|
||||
t.Errorf("expected document body to be loaded, got %q", m.pager.currentDocument.Body)
|
||||
}
|
||||
}
|
||||
393
utils/textsize.go
Normal file
393
utils/textsize.go
Normal file
|
|
@ -0,0 +1,393 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"charm.land/glamour/v2/ansi"
|
||||
"github.com/muesli/cancelreader"
|
||||
"github.com/rivo/uniseg"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
const (
|
||||
osc66ST = "\x1b\\"
|
||||
osc66MaxPayload = 4000
|
||||
|
||||
markerPrefix = "\x1b]6666;"
|
||||
markerClose = markerPrefix + "0" + osc66ST
|
||||
)
|
||||
|
||||
var textSizingEnabled = sync.OnceValue(detectTextSizing)
|
||||
|
||||
// TextSizingEnabled reports whether the terminal supports kitty's text
|
||||
// sizing protocol (OSC 66), auto-detecting support on first call and caching
|
||||
// the result. Set GLOW_TEXT_SIZING to on/off to override detection.
|
||||
func TextSizingEnabled() bool {
|
||||
return textSizingEnabled()
|
||||
}
|
||||
|
||||
func detectTextSizing() bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv("GLOW_TEXT_SIZING"))) {
|
||||
case "0", "false", "off", "no":
|
||||
return false
|
||||
case "1", "true", "on", "yes":
|
||||
return true
|
||||
}
|
||||
|
||||
if !term.IsTerminal(int(os.Stdout.Fd())) {
|
||||
return false
|
||||
}
|
||||
if termEnv := os.Getenv("TERM"); termEnv == "" || termEnv == "dumb" {
|
||||
return false
|
||||
}
|
||||
|
||||
if supported, decisive := probeTextSizing(); decisive {
|
||||
return supported
|
||||
}
|
||||
|
||||
return os.Getenv("KITTY_WINDOW_ID") != "" ||
|
||||
os.Getenv("TERM_PROGRAM") == "kitty" ||
|
||||
strings.Contains(os.Getenv("TERM"), "kitty")
|
||||
}
|
||||
|
||||
var cprPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R`)
|
||||
|
||||
func probeTextSizing() (supported, decisive bool) {
|
||||
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return false, false
|
||||
}
|
||||
defer func() { _ = tty.Close() }()
|
||||
|
||||
fd := int(tty.Fd())
|
||||
oldState, err := term.MakeRaw(fd)
|
||||
if err != nil {
|
||||
return false, false
|
||||
}
|
||||
defer func() { _ = term.Restore(fd, oldState) }()
|
||||
|
||||
reader, err := cancelreader.NewReader(tty)
|
||||
if err != nil {
|
||||
return false, false
|
||||
}
|
||||
defer func() { _ = reader.Close() }()
|
||||
|
||||
if _, err := io.WriteString(tty, "\r\x1b[6n\x1b]66;w=2; \a\x1b[6n\r"); err != nil {
|
||||
return false, false
|
||||
}
|
||||
|
||||
timer := time.AfterFunc(800*time.Millisecond, func() { reader.Cancel() })
|
||||
defer timer.Stop()
|
||||
|
||||
var buf []byte
|
||||
tmp := make([]byte, 128)
|
||||
nextCol := func() (int, bool) {
|
||||
for {
|
||||
if loc := cprPattern.FindSubmatchIndex(buf); loc != nil {
|
||||
col, _ := strconv.Atoi(string(buf[loc[4]:loc[5]]))
|
||||
buf = buf[loc[1]:]
|
||||
return col, true
|
||||
}
|
||||
n, rerr := reader.Read(tmp)
|
||||
if n > 0 {
|
||||
buf = append(buf, tmp[:n]...)
|
||||
}
|
||||
if rerr != nil {
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
before, ok := nextCol()
|
||||
if !ok {
|
||||
return false, false
|
||||
}
|
||||
after, ok := nextCol()
|
||||
if !ok {
|
||||
return false, true
|
||||
}
|
||||
return after-before == 2, true
|
||||
}
|
||||
|
||||
func markerOpen(level int) string {
|
||||
return markerPrefix + strconv.Itoa(level) + osc66ST
|
||||
}
|
||||
|
||||
func markerLevel(s string) int {
|
||||
if !strings.HasPrefix(s, markerPrefix) {
|
||||
return -1
|
||||
}
|
||||
rest := s[len(markerPrefix):]
|
||||
if len(rest) < 1+len(osc66ST) || rest[0] < '0' || rest[0] > '9' || !strings.HasPrefix(rest[1:], osc66ST) {
|
||||
return -1
|
||||
}
|
||||
return int(rest[0] - '0')
|
||||
}
|
||||
|
||||
// AddHeadingSizeMarkers marks the heading styles of levels 1 to 3 in the
|
||||
// given style config so that ApplyTextSizing can find the rendered heading
|
||||
// text and scale it. Headings with a background color are left unmarked:
|
||||
// the background does not cover the scaled glyphs and renders broken.
|
||||
// The style config is modified in place; pass a copy if the original is
|
||||
// shared.
|
||||
func AddHeadingSizeMarkers(cfg *ansi.StyleConfig) {
|
||||
blocks := []struct {
|
||||
level int
|
||||
block *ansi.StyleBlock
|
||||
}{
|
||||
{1, &cfg.H1},
|
||||
{2, &cfg.H2},
|
||||
{3, &cfg.H3},
|
||||
}
|
||||
for _, b := range blocks {
|
||||
if b.block.BackgroundColor != nil {
|
||||
continue
|
||||
}
|
||||
prefix := b.block.Prefix
|
||||
if strings.HasPrefix(prefix, "#") {
|
||||
prefix = strings.TrimPrefix(strings.TrimLeft(prefix, "#"), " ")
|
||||
}
|
||||
b.block.Prefix = markerOpen(b.level) + prefix
|
||||
b.block.Suffix += markerClose
|
||||
}
|
||||
}
|
||||
|
||||
func headingRows(level int) int {
|
||||
if level == 1 {
|
||||
return 3
|
||||
}
|
||||
return 2
|
||||
}
|
||||
|
||||
// ApplyTextSizing replaces the heading markers inserted by
|
||||
// AddHeadingSizeMarkers with kitty text sizing (OSC 66) sequences: level 1
|
||||
// headings are scaled 3x, level 2 headings 2x, and level 3 headings 1.5x via
|
||||
// fractional scaling with a tight width so glyphs keep their natural width.
|
||||
// Output without markers is returned unchanged.
|
||||
func ApplyTextSizing(s string) string {
|
||||
if !strings.Contains(s, markerPrefix) {
|
||||
return s
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
for len(s) > 0 {
|
||||
i := strings.Index(s, markerPrefix)
|
||||
if i < 0 {
|
||||
b.WriteString(s)
|
||||
break
|
||||
}
|
||||
b.WriteString(s[:i])
|
||||
s = s[i:]
|
||||
|
||||
level := markerLevel(s)
|
||||
if level < 0 {
|
||||
b.WriteString(markerPrefix)
|
||||
s = s[len(markerPrefix):]
|
||||
continue
|
||||
}
|
||||
s = s[len(markerOpen(level)):]
|
||||
if level < 1 || level > 3 {
|
||||
continue
|
||||
}
|
||||
|
||||
end := strings.Index(s, markerClose)
|
||||
if end < 0 {
|
||||
b.WriteString(s)
|
||||
break
|
||||
}
|
||||
writeSizedSpan(&b, level, s[:end])
|
||||
s = s[end+len(markerClose):]
|
||||
b.WriteString(strings.Repeat("\n", headingRows(level)-1))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func writeSizedSpan(b *strings.Builder, level int, span string) {
|
||||
lines := strings.Split(span, "\n")
|
||||
for i, ln := range lines {
|
||||
if i > 0 {
|
||||
b.WriteString(strings.Repeat("\n", headingRows(level)))
|
||||
}
|
||||
writeSizedLine(b, level, ln, i > 0)
|
||||
}
|
||||
}
|
||||
|
||||
type segment struct {
|
||||
escape bool
|
||||
value string
|
||||
}
|
||||
|
||||
func writeSizedLine(b *strings.Builder, level int, ln string, continuation bool) {
|
||||
var segs []segment
|
||||
for len(ln) > 0 {
|
||||
i := strings.IndexByte(ln, '\x1b')
|
||||
if i < 0 {
|
||||
segs = append(segs, segment{value: ln})
|
||||
break
|
||||
}
|
||||
if i > 0 {
|
||||
segs = append(segs, segment{value: ln[:i]})
|
||||
ln = ln[i:]
|
||||
continue
|
||||
}
|
||||
seq := scanEscape(ln)
|
||||
segs = append(segs, segment{escape: true, value: seq})
|
||||
ln = ln[len(seq):]
|
||||
}
|
||||
|
||||
firstContent, lastContent := -1, -1
|
||||
for i, sg := range segs {
|
||||
if !sg.escape && strings.Trim(sg.value, " \t") != "" {
|
||||
if firstContent < 0 {
|
||||
firstContent = i
|
||||
}
|
||||
lastContent = i
|
||||
}
|
||||
}
|
||||
|
||||
for i, sg := range segs {
|
||||
if sg.escape || firstContent < 0 {
|
||||
b.WriteString(sg.value)
|
||||
continue
|
||||
}
|
||||
text := sg.value
|
||||
switch {
|
||||
case i < firstContent && continuation:
|
||||
b.WriteString(text)
|
||||
continue
|
||||
case i > lastContent:
|
||||
b.WriteString(text)
|
||||
continue
|
||||
}
|
||||
if i == firstContent && continuation {
|
||||
trimmed := strings.TrimLeft(text, " \t")
|
||||
b.WriteString(text[:len(text)-len(trimmed)])
|
||||
text = trimmed
|
||||
}
|
||||
var trail string
|
||||
if i == lastContent {
|
||||
trimmed := strings.TrimRight(text, " \t")
|
||||
trail = text[len(trimmed):]
|
||||
text = trimmed
|
||||
}
|
||||
if text != "" {
|
||||
b.WriteString(sizedChunk(level, text))
|
||||
}
|
||||
b.WriteString(trail)
|
||||
}
|
||||
}
|
||||
|
||||
func scanEscape(s string) string {
|
||||
if len(s) < 2 {
|
||||
return s
|
||||
}
|
||||
switch s[1] {
|
||||
case '[':
|
||||
for i := 2; i < len(s); i++ {
|
||||
if s[i] >= 0x40 && s[i] <= 0x7e {
|
||||
return s[:i+1]
|
||||
}
|
||||
}
|
||||
return s
|
||||
case ']':
|
||||
for i := 2; i < len(s); i++ {
|
||||
if s[i] == '\a' {
|
||||
return s[:i+1]
|
||||
}
|
||||
if s[i] == '\x1b' && i+1 < len(s) && s[i+1] == '\\' {
|
||||
return s[:i+2]
|
||||
}
|
||||
}
|
||||
return s
|
||||
default:
|
||||
i := 1
|
||||
for i < len(s) && s[i] >= 0x20 && s[i] <= 0x2f {
|
||||
i++
|
||||
}
|
||||
if i < len(s) {
|
||||
i++
|
||||
}
|
||||
return s[:i]
|
||||
}
|
||||
}
|
||||
|
||||
func sizedChunk(level int, text string) string {
|
||||
text = strings.Map(func(r rune) rune {
|
||||
if r < 0x20 || (r >= 0x7f && r <= 0x9f) {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, text)
|
||||
if text == "" {
|
||||
return ""
|
||||
}
|
||||
switch level {
|
||||
case 1:
|
||||
return osc66Chunks("s=3", text)
|
||||
case 2:
|
||||
return osc66Chunks("s=2", text)
|
||||
default:
|
||||
return osc66TightChunks(text)
|
||||
}
|
||||
}
|
||||
|
||||
func osc66Chunks(meta, text string) string {
|
||||
var b strings.Builder
|
||||
var chunk strings.Builder
|
||||
g := uniseg.NewGraphemes(text)
|
||||
for g.Next() {
|
||||
cluster := g.Str()
|
||||
if chunk.Len() > 0 && chunk.Len()+len(cluster) > osc66MaxPayload {
|
||||
writeOSC66(&b, meta, chunk.String())
|
||||
chunk.Reset()
|
||||
}
|
||||
chunk.WriteString(cluster)
|
||||
}
|
||||
if chunk.Len() > 0 {
|
||||
writeOSC66(&b, meta, chunk.String())
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func osc66TightChunks(text string) string {
|
||||
var b strings.Builder
|
||||
var chunk strings.Builder
|
||||
width := 0
|
||||
flush := func() {
|
||||
if chunk.Len() == 0 {
|
||||
return
|
||||
}
|
||||
w := (width*3 + 3) / 4
|
||||
writeOSC66(&b, fmt.Sprintf("s=2:n=3:d=4:w=%d", w), chunk.String())
|
||||
chunk.Reset()
|
||||
width = 0
|
||||
}
|
||||
g := uniseg.NewGraphemes(text)
|
||||
for g.Next() {
|
||||
cluster := g.Str()
|
||||
cw := uniseg.StringWidth(cluster)
|
||||
if width > 0 && width+cw > 4 {
|
||||
flush()
|
||||
}
|
||||
chunk.WriteString(cluster)
|
||||
width += cw
|
||||
}
|
||||
flush()
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func writeOSC66(b *strings.Builder, meta, text string) {
|
||||
b.WriteString("\x1b]66;")
|
||||
b.WriteString(meta)
|
||||
b.WriteByte(';')
|
||||
b.WriteString(text)
|
||||
b.WriteString(osc66ST)
|
||||
}
|
||||
222
utils/textsize_test.go
Normal file
222
utils/textsize_test.go
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"charm.land/glamour/v2"
|
||||
"charm.land/glamour/v2/styles"
|
||||
)
|
||||
|
||||
func renderPlainAndSized(t *testing.T, markdown string, wordWrap int) (string, string) {
|
||||
t.Helper()
|
||||
|
||||
cfg := styles.DarkStyleConfig
|
||||
// Headings with a background are not scaled, so drop the dark style's
|
||||
// H1 background to exercise H1 scaling.
|
||||
cfg.H1.BackgroundColor = nil
|
||||
|
||||
r, err := glamour.NewTermRenderer(
|
||||
glamour.WithStyles(cfg),
|
||||
glamour.WithWordWrap(wordWrap),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain, err := r.Render(markdown)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
AddHeadingSizeMarkers(&cfg)
|
||||
r, err = glamour.NewTermRenderer(
|
||||
glamour.WithStyles(cfg),
|
||||
glamour.WithWordWrap(wordWrap),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
marked, err := r.Render(markdown)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(marked, markerPrefix) {
|
||||
t.Fatal("rendered output does not contain heading markers")
|
||||
}
|
||||
|
||||
return plain, ApplyTextSizing(marked)
|
||||
}
|
||||
|
||||
func TestAddHeadingSizeMarkersSkipsBackground(t *testing.T) {
|
||||
cfg := styles.DarkStyleConfig
|
||||
AddHeadingSizeMarkers(&cfg)
|
||||
|
||||
if strings.Contains(cfg.H1.Prefix, markerPrefix) || strings.Contains(cfg.H1.Suffix, markerPrefix) {
|
||||
t.Errorf("expected H1 with background color to be left unmarked, got %q/%q", cfg.H1.Prefix, cfg.H1.Suffix)
|
||||
}
|
||||
if !strings.HasPrefix(cfg.H2.Prefix, markerOpen(2)) {
|
||||
t.Errorf("expected H2 to be marked, got %q", cfg.H2.Prefix)
|
||||
}
|
||||
if !strings.HasPrefix(cfg.H3.Prefix, markerOpen(3)) {
|
||||
t.Errorf("expected H3 to be marked, got %q", cfg.H3.Prefix)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTextSizingPassthrough(t *testing.T) {
|
||||
in := "hello \x1b[1mworld\x1b[0m"
|
||||
if got := ApplyTextSizing(in); got != in {
|
||||
t.Errorf("expected output unchanged, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTextSizingMalformedMarker(t *testing.T) {
|
||||
in := "a" + markerPrefix // truncated marker at end of string
|
||||
if got := ApplyTextSizing(in); got != in {
|
||||
t.Errorf("expected malformed marker preserved verbatim, got %q", got)
|
||||
}
|
||||
in = "a" + markerPrefix + "x" // non-digit level
|
||||
if got := ApplyTextSizing(in); got != in {
|
||||
t.Errorf("expected malformed marker preserved verbatim, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTextSizingLevels(t *testing.T) {
|
||||
_, sized := renderPlainAndSized(t, "# Hello\n\n## World\n\n### Third\n", 80)
|
||||
|
||||
if !strings.Contains(sized, "\x1b]66;s=3;Hello\x1b\\") {
|
||||
t.Errorf("expected H1 text at 3x scale, got %q", sized)
|
||||
}
|
||||
if !strings.Contains(sized, "\x1b]66;s=3; \x1b\\") {
|
||||
t.Errorf("expected H1 prefix space at 3x scale, got %q", sized)
|
||||
}
|
||||
if !strings.Contains(sized, "\x1b]66;s=2;World\x1b\\") {
|
||||
t.Errorf("expected H2 text at 2x scale, got %q", sized)
|
||||
}
|
||||
if !strings.Contains(sized, "\x1b]66;s=2:n=3:d=4:w=3;Thir\x1b\\") {
|
||||
t.Errorf("expected H3 chunks at tight 1.5x scale, got %q", sized)
|
||||
}
|
||||
if !strings.Contains(sized, "\x1b]66;s=2:n=3:d=4:w=1;d\x1b\\") {
|
||||
t.Errorf("expected H3 remainder chunk at tight 1.5x scale, got %q", sized)
|
||||
}
|
||||
if strings.Contains(sized, markerPrefix) {
|
||||
t.Errorf("expected all markers to be replaced, got %q", sized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTextSizingCompensationLines(t *testing.T) {
|
||||
plain, sized := renderPlainAndSized(t, "# Hello\n\n## World\n\n### Third\n\nparagraph\n", 80)
|
||||
|
||||
if diff := strings.Count(sized, "\n") - strings.Count(plain, "\n"); diff != 4 {
|
||||
t.Errorf("expected 4 extra newlines (2 for H1, 1 each for H2/H3), got %d", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTextSizingWrappedHeading(t *testing.T) {
|
||||
plain, sized := renderPlainAndSized(t, "# aaa bbb ccc\n\npara\n", 8)
|
||||
|
||||
plainLines := strings.Split(plain, "\n")
|
||||
sizedLines := strings.Split(sized, "\n")
|
||||
|
||||
plainHead := lineIndex(t, plainLines, "aaa")
|
||||
plainPara := lineIndex(t, plainLines, "para")
|
||||
sizedHead := lineIndex(t, sizedLines, "aaa")
|
||||
sizedPara := lineIndex(t, sizedLines, "para")
|
||||
|
||||
headLines := plainPara - plainHead - 1
|
||||
if headLines < 2 {
|
||||
t.Fatalf("expected heading to wrap, got %d line(s)", headLines)
|
||||
}
|
||||
if got, want := sizedPara-sizedHead, headLines*3+1; got != want {
|
||||
t.Errorf("expected wrapped heading to occupy %d rows, got %d", want, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyTextSizingNestedStyles(t *testing.T) {
|
||||
_, sized := renderPlainAndSized(t, "# Hello *World*\n", 80)
|
||||
|
||||
if !strings.Contains(sized, "\x1b]66;s=3;Hello \x1b\\") {
|
||||
t.Errorf("expected first chunk at 3x scale, got %q", sized)
|
||||
}
|
||||
if !strings.Contains(sized, "\x1b]66;s=3;World\x1b\\") {
|
||||
t.Errorf("expected emphasized chunk at 3x scale, got %q", sized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectTextSizingEnvOverride(t *testing.T) {
|
||||
t.Setenv("GLOW_TEXT_SIZING", "off")
|
||||
if detectTextSizing() {
|
||||
t.Error("expected detection to be disabled")
|
||||
}
|
||||
t.Setenv("GLOW_TEXT_SIZING", "on")
|
||||
if !detectTextSizing() {
|
||||
t.Error("expected detection to be forced on")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlamourStyleTextSizing(t *testing.T) {
|
||||
render := func(t *testing.T) string {
|
||||
t.Helper()
|
||||
r, err := glamour.NewTermRenderer(
|
||||
GlamourStyle(styles.DarkStyle, false),
|
||||
glamour.WithWordWrap(80),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := r.Render("# Hello\n\n## World\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
textSizingEnabled = sync.OnceValue(detectTextSizing)
|
||||
t.Setenv("GLOW_TEXT_SIZING", "off")
|
||||
if out := render(t); strings.Contains(out, markerPrefix) {
|
||||
t.Errorf("expected no heading markers when disabled, got %q", out)
|
||||
}
|
||||
|
||||
textSizingEnabled = sync.OnceValue(detectTextSizing)
|
||||
t.Setenv("GLOW_TEXT_SIZING", "on")
|
||||
out := render(t)
|
||||
if strings.Contains(out, markerOpen(1)) {
|
||||
t.Errorf("expected no H1 markers (background color), got %q", out)
|
||||
}
|
||||
if !strings.Contains(out, markerOpen(2)) {
|
||||
t.Errorf("expected H2 markers when enabled, got %q", out)
|
||||
}
|
||||
sized := ApplyTextSizing(out)
|
||||
if strings.Contains(sized, "\x1b]66;s=3;") {
|
||||
t.Errorf("expected no 3x scaling for H1, got %q", sized)
|
||||
}
|
||||
if !strings.Contains(sized, "\x1b]66;s=2;") {
|
||||
t.Errorf("expected OSC 66 sequences after ApplyTextSizing, got %q", sized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanEscape(t *testing.T) {
|
||||
tt := []struct{ in, want string }{
|
||||
{"\x1b[1;31mfoo", "\x1b[1;31m"},
|
||||
{"\x1b[0m", "\x1b[0m"},
|
||||
{"\x1b]66;s=2;hi\a rest", "\x1b]66;s=2;hi\a"},
|
||||
{"\x1b]6666;1\x1b\\x", "\x1b]6666;1\x1b\\"},
|
||||
{"\x1b(B", "\x1b(B"},
|
||||
}
|
||||
for _, tc := range tt {
|
||||
if got := scanEscape(tc.in); got != tc.want {
|
||||
t.Errorf("scanEscape(%q) = %q, want %q", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func lineIndex(t *testing.T, lines []string, substr string) int {
|
||||
t.Helper()
|
||||
for i, ln := range lines {
|
||||
if strings.Contains(ln, substr) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
t.Fatalf("no line contains %q", substr)
|
||||
return -1
|
||||
}
|
||||
|
|
@ -2,6 +2,8 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
|
|
@ -71,43 +73,66 @@ func IsMarkdownFile(filename string) bool {
|
|||
|
||||
// GlamourStyle returns a glamour.TermRendererOption based on the given style.
|
||||
func GlamourStyle(style string, isCode bool) glamour.TermRendererOption {
|
||||
return func(tr *glamour.TermRenderer) error {
|
||||
styleConfig, err := styleConfigFor(style, isCode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !isCode && TextSizingEnabled() {
|
||||
AddHeadingSizeMarkers(&styleConfig)
|
||||
}
|
||||
if err := glamour.WithStyles(styleConfig)(tr); err != nil {
|
||||
return fmt.Errorf("glamour: error applying styles: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func styleConfigFor(style string, isCode bool) (ansi.StyleConfig, error) {
|
||||
if !isCode {
|
||||
if style == "auto" {
|
||||
return glamour.WithStandardStyle("dark")
|
||||
style = styles.DarkStyle
|
||||
}
|
||||
return glamour.WithStylePath(style)
|
||||
if cfg, ok := styles.DefaultStyles[style]; ok {
|
||||
return *cfg, nil
|
||||
}
|
||||
return styleConfigFromFile(style)
|
||||
}
|
||||
|
||||
// If we are rendering a pure code block, we need to modify the style to
|
||||
// remove the indentation.
|
||||
|
||||
var styleConfig ansi.StyleConfig
|
||||
|
||||
switch style {
|
||||
case "auto":
|
||||
if lipgloss.HasDarkBackground(os.Stdin, os.Stdout) {
|
||||
styleConfig = styles.DarkStyleConfig
|
||||
style = styles.DarkStyle
|
||||
} else {
|
||||
styleConfig = styles.LightStyleConfig
|
||||
style = styles.LightStyle
|
||||
}
|
||||
case styles.DarkStyle:
|
||||
styleConfig = styles.DarkStyleConfig
|
||||
case styles.LightStyle:
|
||||
styleConfig = styles.LightStyleConfig
|
||||
case styles.PinkStyle:
|
||||
styleConfig = styles.PinkStyleConfig
|
||||
case styles.NoTTYStyle:
|
||||
styleConfig = styles.NoTTYStyleConfig
|
||||
case styles.DraculaStyle:
|
||||
styleConfig = styles.DraculaStyleConfig
|
||||
case styles.TokyoNightStyle:
|
||||
styleConfig = styles.DraculaStyleConfig
|
||||
style = styles.DraculaStyle
|
||||
case styles.DarkStyle, styles.LightStyle, styles.PinkStyle,
|
||||
styles.NoTTYStyle, styles.DraculaStyle:
|
||||
default:
|
||||
return glamour.WithStylesFromJSONFile(style)
|
||||
return styleConfigFromFile(style)
|
||||
}
|
||||
|
||||
styleConfig := *styles.DefaultStyles[style]
|
||||
|
||||
var margin uint
|
||||
styleConfig.CodeBlock.Margin = &margin
|
||||
|
||||
return glamour.WithStyles(styleConfig)
|
||||
return styleConfig, nil
|
||||
}
|
||||
|
||||
func styleConfigFromFile(path string) (ansi.StyleConfig, error) {
|
||||
jsonBytes, err := os.ReadFile(path) //nolint:gosec
|
||||
if err != nil {
|
||||
return ansi.StyleConfig{}, fmt.Errorf("glamour: error reading file: %w", err)
|
||||
}
|
||||
|
||||
var styleConfig ansi.StyleConfig
|
||||
if err := json.Unmarshal(jsonBytes, &styleConfig); err != nil {
|
||||
return ansi.StyleConfig{}, fmt.Errorf("glamour: error parsing style file: %w", err)
|
||||
}
|
||||
return styleConfig, nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue