From 6f737ad19c0e5d7688bac25c90938f7d747eee81 Mon Sep 17 00:00:00 2001 From: Matt Low Date: Sun, 17 Mar 2024 00:25:42 +0000 Subject: [PATCH] tui: handle text wrapping ourselves, add ctrl+w wrap toggle Gets rid of those pesky trailing characters --- pkg/tui/tui.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/pkg/tui/tui.go b/pkg/tui/tui.go index 7f9153c..56b043e 100644 --- a/pkg/tui/tui.go +++ b/pkg/tui/tui.go @@ -23,6 +23,7 @@ import ( "github.com/charmbracelet/bubbles/viewport" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/muesli/reflow/wordwrap" ) type focusState int @@ -59,6 +60,7 @@ type model struct { // ui state focus focusState + wrap bool // whether message content is wrapped to viewport width status string // a general status message highlightCache []string // a cache of syntax highlighted message content messageOffsets []int @@ -156,6 +158,9 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } case "ctrl+p": m.persistence = !m.persistence + case "ctrl+w": + m.wrap = !m.wrap + m.updateContent() case "q": if m.focus != focusInput { return m, tea.Quit @@ -403,6 +408,7 @@ func initialModel(ctx *lmcli.Context, convShortname string) model { replyChan: make(chan models.Message), replyChunkChan: make(chan string), + wrap: true, selectedMessage: -1, } @@ -696,7 +702,7 @@ func (m *model) setMessageContents(i int, content string) { func (m *model) updateContent() { atBottom := m.content.AtBottom() - m.content.SetContent(conversationStyle.Render(m.conversationView())) + m.content.SetContent(m.conversationView()) if atBottom { // if we were at bottom before the update, scroll with the output m.content.GotoBottom() @@ -757,8 +763,15 @@ func (m *model) conversationView() string { } else { highlighted = m.highlightCache[i] } - contents := messageStyle.Width(m.content.Width).Render(highlighted) - sb.WriteString(contents) + var contents string + if m.wrap { + wrapWidth := m.content.Width - messageStyle.GetHorizontalPadding() - 2 + wrapped := wordwrap.String(highlighted, wrapWidth) + contents = wrapped + } else { + contents = highlighted + } + sb.WriteString(messageStyle.Width(0).Render(contents)) lineCnt += lipgloss.Height(contents) } @@ -767,7 +780,7 @@ func (m *model) conversationView() string { lineCnt += 1 } } - return sb.String() + return conversationStyle.Render(sb.String()) } func Launch(ctx *lmcli.Context, convShortname string) error {