Skip to content
Myr

pager.go

This file

Path

pager/pager.go

234 lines · 5.7 KiB · Go

Last changed by

chore: update to bubbletea v2 (#1112)Drew Smirnoffbefore adoptionf6dd28e

History of this file

Take it

1// Package pager provides a pager (similar to less) for the terminal.2//3// $ cat file.txt | gum pager4package pager56import (7	"fmt"8	"strings"910	"charm.land/bubbles/v2/help"11	"charm.land/bubbles/v2/key"12	"charm.land/bubbles/v2/textinput"13	"charm.land/bubbles/v2/viewport"14	tea "charm.land/bubbletea/v2"15	"charm.land/lipgloss/v2"16	"github.com/charmbracelet/x/ansi"17)1819type keymap struct {20	Home,21	End,22	Search,23	NextMatch,24	PrevMatch,25	Abort,26	Quit,27	ConfirmSearch,28	CancelSearch key.Binding29}3031// FullHelp implements help.KeyMap.32func (k keymap) FullHelp() [][]key.Binding {33	return nil34}3536// ShortHelp implements help.KeyMap.37func (k keymap) ShortHelp() []key.Binding {38	return []key.Binding{39		key.NewBinding(40			key.WithKeys("up", "down"),41			key.WithHelp("↓↑", "navigate"),42		),43		k.Quit,44		k.Search,45		k.NextMatch,46		k.PrevMatch,47	}48}4950func defaultKeymap() keymap {51	return keymap{52		Home: key.NewBinding(53			key.WithKeys("g", "home"),54			key.WithHelp("h", "home"),55		),56		End: key.NewBinding(57			key.WithKeys("G", "end"),58			key.WithHelp("G", "end"),59		),60		Search: key.NewBinding(61			key.WithKeys("/"),62			key.WithHelp("/", "search"),63		),64		PrevMatch: key.NewBinding(65			key.WithKeys("p", "N"),66			key.WithHelp("N", "previous match"),67		),68		NextMatch: key.NewBinding(69			key.WithKeys("n"),70			key.WithHelp("n", "next match"),71		),72		Abort: key.NewBinding(73			key.WithKeys("ctrl+c"),74			key.WithHelp("ctrl+c", "abort"),75		),76		Quit: key.NewBinding(77			key.WithKeys("q", "esc"),78			key.WithHelp("esc", "quit"),79		),80		ConfirmSearch: key.NewBinding(81			key.WithKeys("enter"),82			key.WithHelp("enter", "confirm"),83		),84		CancelSearch: key.NewBinding(85			key.WithKeys("ctrl+c", "ctrl+d", "esc"),86			key.WithHelp("ctrl+c", "cancel"),87		),88	}89}9091type model struct {92	content             string93	origContent         string94	viewport            viewport.Model95	help                help.Model96	showLineNumbers     bool97	lineNumberStyle     lipgloss.Style98	softWrap            bool99	search              search100	matchStyle          lipgloss.Style101	matchHighlightStyle lipgloss.Style102	maxWidth            int103	keymap              keymap104}105106func (m model) Init() tea.Cmd { return nil }107108func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {109	switch msg := msg.(type) {110	case tea.WindowSizeMsg:111		m.processText(msg)112	case tea.KeyPressMsg:113		return m.keyHandler(msg)114	}115116	m.keymap.PrevMatch.SetEnabled(m.search.query != nil)117	m.keymap.NextMatch.SetEnabled(m.search.query != nil)118119	var cmd tea.Cmd120	m.search.input, cmd = m.search.input.Update(msg)121	return m, cmd122}123124func (m *model) helpView() string {125	return m.help.View(m.keymap)126}127128func (m *model) processText(msg tea.WindowSizeMsg) {129	m.viewport.SetHeight(msg.Height - lipgloss.Height(m.helpView()))130	m.viewport.SetWidth(msg.Width)131	textStyle := lipgloss.NewStyle().Width(m.viewport.Width())132	var text strings.Builder133134	// Determine max width of a line.135	m.maxWidth = m.viewport.Width()136	if m.softWrap {137		vpStyle := m.viewport.Style138		m.maxWidth -= vpStyle.GetHorizontalBorderSize() + vpStyle.GetHorizontalMargins() + vpStyle.GetHorizontalPadding()139		if m.showLineNumbers {140			m.maxWidth -= lipgloss.Width("     │ ")141		}142	}143144	for i, line := range strings.Split(m.content, "\n") {145		line = strings.ReplaceAll(line, "\t", "    ")146		if m.showLineNumbers {147			text.WriteString(m.lineNumberStyle.Render(fmt.Sprintf("%4d │ ", i+1)))148		}149		idx := 0150		if w := ansi.StringWidth(line); m.softWrap && w > m.maxWidth {151			for w > idx {152				if m.showLineNumbers && idx != 0 {153					text.WriteString(m.lineNumberStyle.Render("     │ "))154				}155				truncatedLine := ansi.Cut(line, idx, m.maxWidth+idx)156				idx += m.maxWidth157				text.WriteString(textStyle.Render(truncatedLine))158				text.WriteString("\n")159			}160		} else {161			text.WriteString(textStyle.Render(line))162			text.WriteString("\n")163		}164	}165166	diffHeight := m.viewport.Height() - lipgloss.Height(text.String())167	if diffHeight > 0 && m.showLineNumbers {168		remainingLines := "   ~ │ " + strings.Repeat("\n   ~ │ ", diffHeight-1)169		text.WriteString(m.lineNumberStyle.Render(remainingLines))170	}171	m.viewport.SetContent(text.String())172}173174const heightOffset = 2175176func (m model) keyHandler(msg tea.KeyPressMsg) (model, tea.Cmd) {177	km := m.keymap178	var cmd tea.Cmd179	if m.search.active {180		switch {181		case key.Matches(msg, km.ConfirmSearch):182			if m.search.input.Value() != "" {183				m.content = m.origContent184				m.search.Execute(&m)185186				// Trigger a view update to highlight the found matches.187				m.search.NextMatch(&m)188				m.processText(tea.WindowSizeMsg{Height: m.viewport.Height() + heightOffset, Width: m.viewport.Width()})189			} else {190				m.search.Done()191			}192		case key.Matches(msg, km.CancelSearch):193			m.search.Done()194		default:195			m.search.input, cmd = m.search.input.Update(msg)196		}197	} else {198		switch {199		case key.Matches(msg, km.Home):200			m.viewport.GotoTop()201		case key.Matches(msg, km.End):202			m.viewport.GotoBottom()203		case key.Matches(msg, km.Search):204			m.search.Begin()205			return m, textinput.Blink206		case key.Matches(msg, km.PrevMatch):207			m.search.PrevMatch(&m)208			m.processText(tea.WindowSizeMsg{Height: m.viewport.Height() + heightOffset, Width: m.viewport.Width()})209		case key.Matches(msg, km.NextMatch):210			m.search.NextMatch(&m)211			m.processText(tea.WindowSizeMsg{Height: m.viewport.Height() + heightOffset, Width: m.viewport.Width()})212		case key.Matches(msg, km.Quit):213			return m, tea.Quit214		case key.Matches(msg, km.Abort):215			return m, tea.Interrupt216		}217		m.viewport, cmd = m.viewport.Update(msg)218	}219220	return m, cmd221}222223func (m model) View() tea.View {224	v := tea.NewView("")225	v.AltScreen = true226	v.ReportFocus = true227	if m.search.active {228		v.SetContent(m.viewport.View() + "\n " + m.search.input.View())229		return v230	}231232	v.SetContent(m.viewport.View() + "\n" + m.helpView())233	return v234}