@@ -0,0 +1,1550 @@
1+// Package textarea provides a multi-line text input component for Bubble Tea
2+// applications with syntax highlighting support.
3+//
4+// This is a custom textarea based on charmbracelet/bubbles/textarea
5+// (https://github.com/charmbracelet/bubbles/blob/master/textarea/textarea.go)
6+// extended with Chroma syntax highlighting support.
7+//
8+// Key modifications:
9+// - Added Language field to enable syntax highlighting
10+// - Added highlightLine() method using Chroma for tokenization and formatting
11+// - Modified View() method to apply highlighting before rendering
12+// - Integrated with internal/constants for configurable theme selection
13+package textarea
14+
15+import (
16+ "crypto/sha256"
17+ "fmt"
18+ "strconv"
19+ "strings"
20+ "unicode"
21+
22+ "github.com/alecthomas/chroma/v2"
23+ "github.com/alecthomas/chroma/v2/formatters"
24+ "github.com/alecthomas/chroma/v2/lexers"
25+ "github.com/alecthomas/chroma/v2/styles"
26+ "github.com/atotto/clipboard"
27+ "github.com/charmbracelet/bubbles/cursor"
28+ "github.com/charmbracelet/bubbles/key"
29+ "github.com/charmbracelet/bubbles/runeutil"
30+ "github.com/charmbracelet/bubbles/textarea/memoization"
31+ "github.com/charmbracelet/bubbles/viewport"
32+ tea "github.com/charmbracelet/bubbletea"
33+ "github.com/charmbracelet/lipgloss"
34+ "github.com/charmbracelet/x/ansi"
35+ rw "github.com/mattn/go-runewidth"
36+ "github.com/rivo/uniseg"
37+ "github.com/xonecas/smith/internal/constants"
38+)
39+
40+const (
41+ minHeight = 1
42+ defaultHeight = 6
43+ defaultWidth = 40
44+ defaultCharLimit = 0 // no limit
45+ defaultMaxHeight = 99
46+ defaultMaxWidth = 500
47+
48+ // XXX: in v2, make max lines dynamic and default max lines configurable.
49+ maxLines = 10000
50+)
51+
52+// Internal messages for clipboard operations.
53+type (
54+ pasteMsg string
55+ pasteErrMsg struct{ error }
56+)
57+
58+// KeyMap is the key bindings for different actions within the textarea.
59+type KeyMap struct {
60+ CharacterBackward key.Binding
61+ CharacterForward key.Binding
62+ DeleteAfterCursor key.Binding
63+ DeleteBeforeCursor key.Binding
64+ DeleteCharacterBackward key.Binding
65+ DeleteCharacterForward key.Binding
66+ DeleteWordBackward key.Binding
67+ DeleteWordForward key.Binding
68+ InsertNewline key.Binding
69+ LineEnd key.Binding
70+ LineNext key.Binding
71+ LinePrevious key.Binding
72+ LineStart key.Binding
73+ Paste key.Binding
74+ WordBackward key.Binding
75+ WordForward key.Binding
76+ InputBegin key.Binding
77+ InputEnd key.Binding
78+
79+ UppercaseWordForward key.Binding
80+ LowercaseWordForward key.Binding
81+ CapitalizeWordForward key.Binding
82+
83+ TransposeCharacterBackward key.Binding
84+}
85+
86+// DefaultKeyMap is the default set of key bindings for navigating and acting
87+// upon the textarea.
88+var DefaultKeyMap = KeyMap{
89+ CharacterForward: key.NewBinding(key.WithKeys("right", "ctrl+f"), key.WithHelp("right", "character forward")),
90+ CharacterBackward: key.NewBinding(key.WithKeys("left", "ctrl+b"), key.WithHelp("left", "character backward")),
91+ WordForward: key.NewBinding(key.WithKeys("alt+right", "alt+f"), key.WithHelp("alt+right", "word forward")),
92+ WordBackward: key.NewBinding(key.WithKeys("alt+left", "alt+b"), key.WithHelp("alt+left", "word backward")),
93+ LineNext: key.NewBinding(key.WithKeys("down", "ctrl+n"), key.WithHelp("down", "next line")),
94+ LinePrevious: key.NewBinding(key.WithKeys("up", "ctrl+p"), key.WithHelp("up", "previous line")),
95+ DeleteWordBackward: key.NewBinding(key.WithKeys("alt+backspace", "ctrl+w"), key.WithHelp("alt+backspace", "delete word backward")),
96+ DeleteWordForward: key.NewBinding(key.WithKeys("alt+delete", "alt+d"), key.WithHelp("alt+delete", "delete word forward")),
97+ DeleteAfterCursor: key.NewBinding(key.WithKeys("ctrl+k"), key.WithHelp("ctrl+k", "delete after cursor")),
98+ DeleteBeforeCursor: key.NewBinding(key.WithKeys("ctrl+u"), key.WithHelp("ctrl+u", "delete before cursor")),
99+ InsertNewline: key.NewBinding(key.WithKeys("enter", "ctrl+m"), key.WithHelp("enter", "insert newline")),
100+ DeleteCharacterBackward: key.NewBinding(key.WithKeys("backspace", "ctrl+h"), key.WithHelp("backspace", "delete character backward")),
101+ DeleteCharacterForward: key.NewBinding(key.WithKeys("delete", "ctrl+d"), key.WithHelp("delete", "delete character forward")),
102+ LineStart: key.NewBinding(key.WithKeys("home", "ctrl+a"), key.WithHelp("home", "line start")),
103+ LineEnd: key.NewBinding(key.WithKeys("end", "ctrl+e"), key.WithHelp("end", "line end")),
104+ Paste: key.NewBinding(key.WithKeys("ctrl+v"), key.WithHelp("ctrl+v", "paste")),
105+ InputBegin: key.NewBinding(key.WithKeys("alt+<", "ctrl+home"), key.WithHelp("alt+<", "input begin")),
106+ InputEnd: key.NewBinding(key.WithKeys("alt+>", "ctrl+end"), key.WithHelp("alt+>", "input end")),
107+
108+ CapitalizeWordForward: key.NewBinding(key.WithKeys("alt+c"), key.WithHelp("alt+c", "capitalize word forward")),
109+ LowercaseWordForward: key.NewBinding(key.WithKeys("alt+l"), key.WithHelp("alt+l", "lowercase word forward")),
110+ UppercaseWordForward: key.NewBinding(key.WithKeys("alt+u"), key.WithHelp("alt+u", "uppercase word forward")),
111+
112+ TransposeCharacterBackward: key.NewBinding(key.WithKeys("ctrl+t"), key.WithHelp("ctrl+t", "transpose character backward")),
113+}
114+
115+// LineInfo is a helper for keeping track of line information regarding
116+// soft-wrapped lines.
117+type LineInfo struct {
118+ // Width is the number of columns in the line.
119+ Width int
120+ // CharWidth is the number of characters in the line to account for
121+ // double-width runes.
122+ CharWidth int
123+ // Height is the number of rows in the line.
124+ Height int
125+ // StartColumn is the index of the first column of the line.
126+ StartColumn int
127+ // ColumnOffset is the number of columns that the cursor is offset from the
128+ // start of the line.
129+ ColumnOffset int
130+ // RowOffset is the number of rows that the cursor is offset from the start
131+ // of the line.
132+ RowOffset int
133+ // CharOffset is the number of characters that the cursor is offset
134+ // from the start of the line. This will generally be equivalent to
135+ // ColumnOffset, but will be different there are double-width runes before
136+ // the cursor.
137+ CharOffset int
138+}
139+
140+// Style that will be applied to the text area.
141+//
142+// Style can be applied to focused and unfocused states to change the styles
143+// depending on the focus state.
144+//
145+// For an introduction to styling with Lip Gloss see:
146+// https://github.com/charmbracelet/lipgloss
147+type Style struct {
148+ Base lipgloss.Style
149+ CursorLine lipgloss.Style
150+ CursorLineNumber lipgloss.Style
151+ EndOfBuffer lipgloss.Style
152+ LineNumber lipgloss.Style
153+ Placeholder lipgloss.Style
154+ Prompt lipgloss.Style
155+ Text lipgloss.Style
156+}
157+
158+func (s Style) computedCursorLine() lipgloss.Style {
159+ return s.CursorLine.Inherit(s.Base).Inline(true)
160+}
161+
162+func (s Style) computedCursorLineNumber() lipgloss.Style {
163+ return s.CursorLineNumber.
164+ Inherit(s.CursorLine).
165+ Inherit(s.Base).
166+ Inline(true)
167+}
168+
169+func (s Style) computedEndOfBuffer() lipgloss.Style {
170+ return s.EndOfBuffer.Inherit(s.Base).Inline(true)
171+}
172+
173+func (s Style) computedLineNumber() lipgloss.Style {
174+ return s.LineNumber.Inherit(s.Base).Inline(true)
175+}
176+
177+func (s Style) computedPlaceholder() lipgloss.Style {
178+ return s.Placeholder.Inherit(s.Base).Inline(true)
179+}
180+
181+func (s Style) computedPrompt() lipgloss.Style {
182+ return s.Prompt.Inherit(s.Base).Inline(true)
183+}
184+
185+func (s Style) computedText() lipgloss.Style {
186+ return s.Text.Inherit(s.Base).Inline(true)
187+}
188+
189+// line is the input to the text wrapping function. This is stored in a struct
190+// so that it can be hashed and memoized.
191+type line struct {
192+ runes []rune
193+ width int
194+}
195+
196+// Hash returns a hash of the line.
197+func (w line) Hash() string {
198+ v := fmt.Sprintf("%s:%d", string(w.runes), w.width)
199+ return fmt.Sprintf("%x", sha256.Sum256([]byte(v)))
200+}
201+
202+// Model is the Bubble Tea model for this text area element.
203+type Model struct {
204+ Err error
205+
206+ // General settings.
207+ cache *memoization.MemoCache[line, [][]rune]
208+
209+ // Prompt is printed at the beginning of each line.
210+ //
211+ // When changing the value of Prompt after the model has been
212+ // initialized, ensure that SetWidth() gets called afterwards.
213+ //
214+ // See also SetPromptFunc().
215+ Prompt string
216+
217+ // Placeholder is the text displayed when the user
218+ // hasn't entered anything yet.
219+ Placeholder string
220+
221+ // ShowLineNumbers, if enabled, causes line numbers to be printed
222+ // after the prompt.
223+ ShowLineNumbers bool
224+
225+ // EndOfBufferCharacter is displayed at the end of the input.
226+ EndOfBufferCharacter rune
227+
228+ // KeyMap encodes the keybindings recognized by the widget.
229+ KeyMap KeyMap
230+
231+ // Styling. FocusedStyle and BlurredStyle are used to style the textarea in
232+ // focused and blurred states.
233+ FocusedStyle Style
234+ BlurredStyle Style
235+ // style is the current styling to use.
236+ // It is used to abstract the differences in focus state when styling the
237+ // model, since we can simply assign the set of styles to this variable
238+ // when switching focus states.
239+ style *Style
240+
241+ // Cursor is the text area cursor.
242+ Cursor cursor.Model
243+
244+ // CharLimit is the maximum number of characters this input element will
245+ // accept. If 0 or less, there's no limit.
246+ CharLimit int
247+
248+ // MaxHeight is the maximum height of the text area in rows. If 0 or less,
249+ // there's no limit.
250+ MaxHeight int
251+
252+ // MaxWidth is the maximum width of the text area in columns. If 0 or less,
253+ // there's no limit.
254+ MaxWidth int
255+
256+ // If promptFunc is set, it replaces Prompt as a generator for
257+ // prompt strings at the beginning of each line.
258+ promptFunc func(line int) string
259+
260+ // promptWidth is the width of the prompt.
261+ promptWidth int
262+
263+ // width is the maximum number of characters that can be displayed at once.
264+ // If 0 or less this setting is ignored.
265+ width int
266+
267+ // height is the maximum number of lines that can be displayed at once. It
268+ // essentially treats the text field like a vertically scrolling viewport
269+ // if there are more lines than the permitted height.
270+ height int
271+
272+ // Underlying text value.
273+ value [][]rune
274+
275+ // focus indicates whether user input focus should be on this input
276+ // component. When false, ignore keyboard input and hide the cursor.
277+ focus bool
278+
279+ // Cursor column.
280+ col int
281+
282+ // Cursor row.
283+ row int
284+
285+ // Last character offset, used to maintain state when the cursor is moved
286+ // vertically such that we can maintain the same navigating position.
287+ lastCharOffset int
288+
289+ // viewport is the vertically-scrollable viewport of the multi-line text
290+ // input.
291+ viewport *viewport.Model
292+
293+ // rune sanitizer for input.
294+ rsan runeutil.Sanitizer
295+
296+ // Language for syntax highlighting (e.g., "go", "python", "javascript")
297+ // If empty, no syntax highlighting is applied.
298+ Language string
299+}
300+
301+// New creates a new model with default settings.
302+func New() Model {
303+ vp := viewport.New(0, 0)
304+ vp.KeyMap = viewport.KeyMap{}
305+ cur := cursor.New()
306+
307+ focusedStyle, blurredStyle := DefaultStyles()
308+
309+ m := Model{
310+ CharLimit: defaultCharLimit,
311+ MaxHeight: defaultMaxHeight,
312+ MaxWidth: defaultMaxWidth,
313+ Prompt: lipgloss.ThickBorder().Left + " ",
314+ style: &blurredStyle,
315+ FocusedStyle: focusedStyle,
316+ BlurredStyle: blurredStyle,
317+ cache: memoization.NewMemoCache[line, [][]rune](maxLines),
318+ EndOfBufferCharacter: ' ',
319+ ShowLineNumbers: true,
320+ Cursor: cur,
321+ KeyMap: DefaultKeyMap,
322+
323+ value: make([][]rune, minHeight, maxLines),
324+ focus: false,
325+ col: 0,
326+ row: 0,
327+
328+ viewport: &vp,
329+ }
330+
331+ m.SetHeight(defaultHeight)
332+ m.SetWidth(defaultWidth)
333+
334+ return m
335+}
336+
337+// DefaultStyles returns the default styles for focused and blurred states for
338+// the textarea.
339+func DefaultStyles() (Style, Style) {
340+ focused := Style{
341+ Base: lipgloss.NewStyle(),
342+ CursorLine: lipgloss.NewStyle().Background(lipgloss.AdaptiveColor{Light: "255", Dark: "0"}),
343+ CursorLineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "240"}),
344+ EndOfBuffer: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "254", Dark: "0"}),
345+ LineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
346+ Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
347+ Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
348+ Text: lipgloss.NewStyle(),
349+ }
350+ blurred := Style{
351+ Base: lipgloss.NewStyle(),
352+ CursorLine: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "245", Dark: "7"}),
353+ CursorLineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
354+ EndOfBuffer: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "254", Dark: "0"}),
355+ LineNumber: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "249", Dark: "7"}),
356+ Placeholder: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
357+ Prompt: lipgloss.NewStyle().Foreground(lipgloss.Color("7")),
358+ Text: lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "245", Dark: "7"}),
359+ }
360+
361+ return focused, blurred
362+}
363+
364+// SetValue sets the value of the text input.
365+func (m *Model) SetValue(s string) {
366+ m.Reset()
367+ m.InsertString(s)
368+}
369+
370+// InsertString inserts a string at the cursor position.
371+func (m *Model) InsertString(s string) {
372+ m.insertRunesFromUserInput([]rune(s))
373+}
374+
375+// InsertRune inserts a rune at the cursor position.
376+func (m *Model) InsertRune(r rune) {
377+ m.insertRunesFromUserInput([]rune{r})
378+}
379+
380+// insertRunesFromUserInput inserts runes at the current cursor position.
381+func (m *Model) insertRunesFromUserInput(runes []rune) {
382+ // Clean up any special characters in the input provided by the
383+ // clipboard. This avoids bugs due to e.g. tab characters and
384+ // whatnot.
385+ runes = m.san().Sanitize(runes)
386+
387+ if m.CharLimit > 0 {
388+ availSpace := m.CharLimit - m.Length()
389+ // If the char limit's been reached, cancel.
390+ if availSpace <= 0 {
391+ return
392+ }
393+ // If there's not enough space to paste the whole thing cut the pasted
394+ // runes down so they'll fit.
395+ if availSpace < len(runes) {
396+ runes = runes[:availSpace]
397+ }
398+ }
399+
400+ // Split the input into lines.
401+ var lines [][]rune
402+ lstart := 0
403+ for i := 0; i < len(runes); i++ {
404+ if runes[i] == '\n' {
405+ // Queue a line to become a new row in the text area below.
406+ // Beware to clamp the max capacity of the slice, to ensure no
407+ // data from different rows get overwritten when later edits
408+ // will modify this line.
409+ lines = append(lines, runes[lstart:i:i])
410+ lstart = i + 1
411+ }
412+ }
413+ if lstart <= len(runes) {
414+ // The last line did not end with a newline character.
415+ // Take it now.
416+ lines = append(lines, runes[lstart:])
417+ }
418+
419+ // Obey the maximum line limit.
420+ if maxLines > 0 && len(m.value)+len(lines)-1 > maxLines {
421+ allowedHeight := max(0, maxLines-len(m.value)+1)
422+ lines = lines[:allowedHeight]
423+ }
424+
425+ if len(lines) == 0 {
426+ // Nothing left to insert.
427+ return
428+ }
429+
430+ // Save the remainder of the original line at the current
431+ // cursor position.
432+ tail := make([]rune, len(m.value[m.row][m.col:]))
433+ copy(tail, m.value[m.row][m.col:])
434+
435+ // Paste the first line at the current cursor position.
436+ m.value[m.row] = append(m.value[m.row][:m.col], lines[0]...)
437+ m.col += len(lines[0])
438+
439+ if numExtraLines := len(lines) - 1; numExtraLines > 0 {
440+ // Add the new lines.
441+ // We try to reuse the slice if there's already space.
442+ var newGrid [][]rune
443+ if cap(m.value) >= len(m.value)+numExtraLines {
444+ // Can reuse the extra space.
445+ newGrid = m.value[:len(m.value)+numExtraLines]
446+ } else {
447+ // No space left; need a new slice.
448+ newGrid = make([][]rune, len(m.value)+numExtraLines)
449+ copy(newGrid, m.value[:m.row+1])
450+ }
451+ // Add all the rows that were after the cursor in the original
452+ // grid at the end of the new grid.
453+ copy(newGrid[m.row+1+numExtraLines:], m.value[m.row+1:])
454+ m.value = newGrid
455+ // Insert all the new lines in the middle.
456+ for _, l := range lines[1:] {
457+ m.row++
458+ m.value[m.row] = l
459+ m.col = len(l)
460+ }
461+ }
462+
463+ // Finally add the tail at the end of the last line inserted.
464+ m.value[m.row] = append(m.value[m.row], tail...)
465+
466+ m.SetCursor(m.col)
467+}
468+
469+// Value returns the value of the text input.
470+func (m Model) Value() string {
471+ if m.value == nil {
472+ return ""
473+ }
474+
475+ var v strings.Builder
476+ for _, l := range m.value {
477+ v.WriteString(string(l))
478+ v.WriteByte('\n')
479+ }
480+
481+ return strings.TrimSuffix(v.String(), "\n")
482+}
483+
484+// Length returns the number of characters currently in the text input.
485+func (m *Model) Length() int {
486+ var l int
487+ for _, row := range m.value {
488+ l += uniseg.StringWidth(string(row))
489+ }
490+ // We add len(m.value) to include the newline characters.
491+ return l + len(m.value) - 1
492+}
493+
494+// LineCount returns the number of lines that are currently in the text input.
495+func (m *Model) LineCount() int {
496+ return len(m.value)
497+}
498+
499+// Line returns the line position.
500+func (m Model) Line() int {
501+ return m.row
502+}
503+
504+// CursorDown moves the cursor down by one line.
505+// Returns whether or not the cursor blink should be reset.
506+func (m *Model) CursorDown() {
507+ li := m.LineInfo()
508+ charOffset := max(m.lastCharOffset, li.CharOffset)
509+ m.lastCharOffset = charOffset
510+
511+ if li.RowOffset+1 >= li.Height && m.row < len(m.value)-1 {
512+ m.row++
513+ m.col = 0
514+ } else {
515+ // Move the cursor to the start of the next line so that we can get
516+ // the line information. We need to add 2 columns to account for the
517+ // trailing space wrapping.
518+ const trailingSpace = 2
519+ m.col = min(li.StartColumn+li.Width+trailingSpace, len(m.value[m.row])-1)
520+ }
521+
522+ nli := m.LineInfo()
523+ m.col = nli.StartColumn
524+
525+ if nli.Width <= 0 {
526+ return
527+ }
528+
529+ offset := 0
530+ for offset < charOffset {
531+ if m.row >= len(m.value) || m.col >= len(m.value[m.row]) || offset >= nli.CharWidth-1 {
532+ break
533+ }
534+ offset += rw.RuneWidth(m.value[m.row][m.col])
535+ m.col++
536+ }
537+}
538+
539+// CursorUp moves the cursor up by one line.
540+func (m *Model) CursorUp() {
541+ li := m.LineInfo()
542+ charOffset := max(m.lastCharOffset, li.CharOffset)
543+ m.lastCharOffset = charOffset
544+
545+ if li.RowOffset <= 0 && m.row > 0 {
546+ m.row--
547+ m.col = len(m.value[m.row])
548+ } else {
549+ // Move the cursor to the end of the previous line.
550+ // This can be done by moving the cursor to the start of the line and
551+ // then subtracting 2 to account for the trailing space we keep on
552+ // soft-wrapped lines.
553+ const trailingSpace = 2
554+ m.col = li.StartColumn - trailingSpace
555+ }
556+
557+ nli := m.LineInfo()
558+ m.col = nli.StartColumn
559+
560+ if nli.Width <= 0 {
561+ return
562+ }
563+
564+ offset := 0
565+ for offset < charOffset {
566+ if m.col >= len(m.value[m.row]) || offset >= nli.CharWidth-1 {
567+ break
568+ }
569+ offset += rw.RuneWidth(m.value[m.row][m.col])
570+ m.col++
571+ }
572+}
573+
574+// SetCursor moves the cursor to the given position. If the position is
575+// out of bounds the cursor will be moved to the start or end accordingly.
576+func (m *Model) SetCursor(col int) {
577+ m.col = clamp(col, 0, len(m.value[m.row]))
578+ // Any time that we move the cursor horizontally we need to reset the last
579+ // offset so that the horizontal position when navigating is adjusted.
580+ m.lastCharOffset = 0
581+}
582+
583+// CursorStart moves the cursor to the start of the input field.
584+func (m *Model) CursorStart() {
585+ m.SetCursor(0)
586+}
587+
588+// CursorEnd moves the cursor to the end of the input field.
589+func (m *Model) CursorEnd() {
590+ m.SetCursor(len(m.value[m.row]))
591+}
592+
593+// Focused returns the focus state on the model.
594+func (m Model) Focused() bool {
595+ return m.focus
596+}
597+
598+// Focus sets the focus state on the model. When the model is in focus it can
599+// receive keyboard input and the cursor will be hidden.
600+func (m *Model) Focus() tea.Cmd {
601+ m.focus = true
602+ m.style = &m.FocusedStyle
603+ return m.Cursor.Focus()
604+}
605+
606+// Blur removes the focus state on the model. When the model is blurred it can
607+// not receive keyboard input and the cursor will be hidden.
608+func (m *Model) Blur() {
609+ m.focus = false
610+ m.style = &m.BlurredStyle
611+ m.Cursor.Blur()
612+}
613+
614+// Reset sets the input to its default state with no input.
615+func (m *Model) Reset() {
616+ m.value = make([][]rune, minHeight, maxLines)
617+ m.col = 0
618+ m.row = 0
619+ m.viewport.GotoTop()
620+ m.SetCursor(0)
621+}
622+
623+// san initializes or retrieves the rune sanitizer.
624+func (m *Model) san() runeutil.Sanitizer {
625+ if m.rsan == nil {
626+ // Textinput has all its input on a single line so collapse
627+ // newlines/tabs to single spaces.
628+ m.rsan = runeutil.NewSanitizer()
629+ }
630+ return m.rsan
631+}
632+
633+// deleteBeforeCursor deletes all text before the cursor. Returns whether or
634+// not the cursor blink should be reset.
635+func (m *Model) deleteBeforeCursor() {
636+ m.value[m.row] = m.value[m.row][m.col:]
637+ m.SetCursor(0)
638+}
639+
640+// deleteAfterCursor deletes all text after the cursor. Returns whether or not
641+// the cursor blink should be reset. If input is masked delete everything after
642+// the cursor so as not to reveal word breaks in the masked input.
643+func (m *Model) deleteAfterCursor() {
644+ m.value[m.row] = m.value[m.row][:m.col]
645+ m.SetCursor(len(m.value[m.row]))
646+}
647+
648+// transposeLeft exchanges the runes at the cursor and immediately
649+// before. No-op if the cursor is at the beginning of the line. If
650+// the cursor is not at the end of the line yet, moves the cursor to
651+// the right.
652+func (m *Model) transposeLeft() {
653+ if m.col == 0 || len(m.value[m.row]) < 2 {
654+ return
655+ }
656+ if m.col >= len(m.value[m.row]) {
657+ m.SetCursor(m.col - 1)
658+ }
659+ m.value[m.row][m.col-1], m.value[m.row][m.col] = m.value[m.row][m.col], m.value[m.row][m.col-1]
660+ if m.col < len(m.value[m.row]) {
661+ m.SetCursor(m.col + 1)
662+ }
663+}
664+
665+// deleteWordLeft deletes the word left to the cursor. Returns whether or not
666+// the cursor blink should be reset.
667+func (m *Model) deleteWordLeft() {
668+ if m.col == 0 || len(m.value[m.row]) == 0 {
669+ return
670+ }
671+
672+ // Linter note: it's critical that we acquire the initial cursor position
673+ // here prior to altering it via SetCursor() below. As such, moving this
674+ // call into the corresponding if clause does not apply here.
675+ oldCol := m.col
676+
677+ m.SetCursor(m.col - 1)
678+ for unicode.IsSpace(m.value[m.row][m.col]) {
679+ if m.col <= 0 {
680+ break
681+ }
682+ // ignore series of whitespace before cursor
683+ m.SetCursor(m.col - 1)
684+ }
685+
686+ for m.col > 0 {
687+ if !unicode.IsSpace(m.value[m.row][m.col]) {
688+ m.SetCursor(m.col - 1)
689+ } else {
690+ if m.col > 0 {
691+ // keep the previous space
692+ m.SetCursor(m.col + 1)
693+ }
694+ break
695+ }
696+ }
697+
698+ if oldCol > len(m.value[m.row]) {
699+ m.value[m.row] = m.value[m.row][:m.col]
700+ } else {
701+ m.value[m.row] = append(m.value[m.row][:m.col], m.value[m.row][oldCol:]...)
702+ }
703+}
704+
705+// deleteWordRight deletes the word right to the cursor.
706+func (m *Model) deleteWordRight() {
707+ if m.col >= len(m.value[m.row]) || len(m.value[m.row]) == 0 {
708+ return
709+ }
710+
711+ oldCol := m.col
712+
713+ for m.col < len(m.value[m.row]) && unicode.IsSpace(m.value[m.row][m.col]) {
714+ // ignore series of whitespace after cursor
715+ m.SetCursor(m.col + 1)
716+ }
717+
718+ for m.col < len(m.value[m.row]) {
719+ if !unicode.IsSpace(m.value[m.row][m.col]) {
720+ m.SetCursor(m.col + 1)
721+ } else {
722+ break
723+ }
724+ }
725+
726+ if m.col > len(m.value[m.row]) {
727+ m.value[m.row] = m.value[m.row][:oldCol]
728+ } else {
729+ m.value[m.row] = append(m.value[m.row][:oldCol], m.value[m.row][m.col:]...)
730+ }
731+
732+ m.SetCursor(oldCol)
733+}
734+
735+// characterRight moves the cursor one character to the right.
736+func (m *Model) characterRight() {
737+ if m.col < len(m.value[m.row]) {
738+ m.SetCursor(m.col + 1)
739+ } else {
740+ if m.row < len(m.value)-1 {
741+ m.row++
742+ m.CursorStart()
743+ }
744+ }
745+}
746+
747+// characterLeft moves the cursor one character to the left.
748+// If insideLine is set, the cursor is moved to the last
749+// character in the previous line, instead of one past that.
750+func (m *Model) characterLeft(insideLine bool) {
751+ if m.col == 0 && m.row != 0 {
752+ m.row--
753+ m.CursorEnd()
754+ if !insideLine {
755+ return
756+ }
757+ }
758+ if m.col > 0 {
759+ m.SetCursor(m.col - 1)
760+ }
761+}
762+
763+// wordLeft moves the cursor one word to the left. Returns whether or not the
764+// cursor blink should be reset. If input is masked, move input to the start
765+// so as not to reveal word breaks in the masked input.
766+func (m *Model) wordLeft() {
767+ for {
768+ m.characterLeft(true /* insideLine */)
769+ if m.col < len(m.value[m.row]) && !unicode.IsSpace(m.value[m.row][m.col]) {
770+ break
771+ }
772+ }
773+
774+ for m.col > 0 {
775+ if unicode.IsSpace(m.value[m.row][m.col-1]) {
776+ break
777+ }
778+ m.SetCursor(m.col - 1)
779+ }
780+}
781+
782+// wordRight moves the cursor one word to the right. Returns whether or not the
783+// cursor blink should be reset. If the input is masked, move input to the end
784+// so as not to reveal word breaks in the masked input.
785+func (m *Model) wordRight() {
786+ m.doWordRight(func(int, int) { /* nothing */ })
787+}
788+
789+func (m *Model) doWordRight(fn func(charIdx int, pos int)) {
790+ // Skip spaces forward.
791+ for m.col >= len(m.value[m.row]) || unicode.IsSpace(m.value[m.row][m.col]) {
792+ if m.row == len(m.value)-1 && m.col == len(m.value[m.row]) {
793+ // End of text.
794+ break
795+ }
796+ m.characterRight()
797+ }
798+
799+ charIdx := 0
800+ for m.col < len(m.value[m.row]) {
801+ if unicode.IsSpace(m.value[m.row][m.col]) {
802+ break
803+ }
804+ fn(charIdx, m.col)
805+ m.SetCursor(m.col + 1)
806+ charIdx++
807+ }
808+}
809+
810+// uppercaseRight changes the word to the right to uppercase.
811+func (m *Model) uppercaseRight() {
812+ m.doWordRight(func(_ int, i int) {
813+ m.value[m.row][i] = unicode.ToUpper(m.value[m.row][i])
814+ })
815+}
816+
817+// lowercaseRight changes the word to the right to lowercase.
818+func (m *Model) lowercaseRight() {
819+ m.doWordRight(func(_ int, i int) {
820+ m.value[m.row][i] = unicode.ToLower(m.value[m.row][i])
821+ })
822+}
823+
824+// capitalizeRight changes the word to the right to title case.
825+func (m *Model) capitalizeRight() {
826+ m.doWordRight(func(charIdx int, i int) {
827+ if charIdx == 0 {
828+ m.value[m.row][i] = unicode.ToTitle(m.value[m.row][i])
829+ }
830+ })
831+}
832+
833+// LineInfo returns the number of characters from the start of the
834+// (soft-wrapped) line and the (soft-wrapped) line width.
835+func (m Model) LineInfo() LineInfo {
836+ grid := m.memoizedWrap(m.value[m.row], m.width)
837+
838+ // Find out which line we are currently on. This can be determined by the
839+ // m.col and counting the number of runes that we need to skip.
840+ var counter int
841+ for i, line := range grid {
842+ // We've found the line that we are on
843+ if counter+len(line) == m.col && i+1 < len(grid) {
844+ // We wrap around to the next line if we are at the end of the
845+ // previous line so that we can be at the very beginning of the row
846+ return LineInfo{
847+ CharOffset: 0,
848+ ColumnOffset: 0,
849+ Height: len(grid),
850+ RowOffset: i + 1,
851+ StartColumn: m.col,
852+ Width: len(grid[i+1]),
853+ CharWidth: uniseg.StringWidth(string(line)),
854+ }
855+ }
856+
857+ if counter+len(line) >= m.col {
858+ return LineInfo{
859+ CharOffset: uniseg.StringWidth(string(line[:max(0, m.col-counter)])),
860+ ColumnOffset: m.col - counter,
861+ Height: len(grid),
862+ RowOffset: i,
863+ StartColumn: counter,
864+ Width: len(line),
865+ CharWidth: uniseg.StringWidth(string(line)),
866+ }
867+ }
868+
869+ counter += len(line)
870+ }
871+ return LineInfo{}
872+}
873+
874+// repositionView repositions the view of the viewport based on the defined
875+// scrolling behavior.
876+func (m *Model) repositionView() {
877+ minimum := m.viewport.YOffset
878+ maximum := minimum + m.viewport.Height - 1
Cut short: this commit's diff is over 1000 lines.