feat(pager): add --soft-wrap option to gum pager

This commit is contained in:
Leon Stam 2022-12-06 17:40:53 +01:00 committed by Maas Lalani
parent b8dbcc3e82
commit e108bc4668
3 changed files with 24 additions and 1 deletions

View file

@ -34,6 +34,7 @@ func (o Options) Run() error {
content: o.Content,
showLineNumbers: o.ShowLineNumbers,
lineNumberStyle: o.LineNumberStyle.ToLipgloss(),
softWrap: o.SoftWrap,
}
_, err := tea.NewProgram(model, tea.WithAltScreen()).Run()
if err != nil {

View file

@ -10,4 +10,5 @@ type Options struct {
Content string `arg:"" optional:"" help:"Display content to scroll"`
ShowLineNumbers bool `help:"Show line numbers" default:"true"`
LineNumberStyle style.Styles `embed:"" prefix:"line-number." help:"Style the line numbers" set:"defaultForeground=237" envprefix:"GUM_PAGER_LINE_NUMBER_"`
SoftWrap bool `help:"Soft wrap lines" default:"false"`
}

View file

@ -19,6 +19,7 @@ type model struct {
helpStyle lipgloss.Style
showLineNumbers bool
lineNumberStyle lipgloss.Style
softWrap bool
}
func (m model) Init() tea.Cmd {
@ -32,12 +33,32 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.viewport.Width = msg.Width
textStyle := lipgloss.NewStyle().Width(m.viewport.Width)
var text strings.Builder
// Determine max width of a line
maxLineWidth := m.viewport.Width
if m.softWrap {
vpStyle := m.viewport.Style
maxLineWidth -= vpStyle.GetHorizontalBorderSize() + vpStyle.GetHorizontalMargins() + vpStyle.GetHorizontalPadding()
if m.showLineNumbers {
maxLineWidth -= len(" │ ")
}
}
for i, line := range strings.Split(m.content, "\n") {
line = strings.ReplaceAll(line, "\t", " ")
if m.showLineNumbers {
text.WriteString(m.lineNumberStyle.Render(fmt.Sprintf("%4d │ ", i+1)))
}
text.WriteString(textStyle.Render(runewidth.Truncate(line, m.viewport.Width, "")))
for m.softWrap && len(line) > maxLineWidth {
truncatedLine := runewidth.Truncate(line, maxLineWidth, "")
text.WriteString(textStyle.Render(truncatedLine))
text.WriteString("\n")
if m.showLineNumbers {
text.WriteString(m.lineNumberStyle.Render(" │ "))
}
line = strings.Replace(line, truncatedLine, "", 1)
}
text.WriteString(textStyle.Render(runewidth.Truncate(line, maxLineWidth, "")))
text.WriteString("\n")
}