62159
Sy
symb / files
symb / internal / tui / editor / editing.go
2.4 KB
1package editor 2 3// --------------------------------------------------------------------------- 4// Editing operations 5// --------------------------------------------------------------------------- 6 7// InsertText inserts a multi-line string at the current cursor position. 8// Newlines are handled via insertNewline. No-op if ReadOnly. 9func (m *Model) InsertText(text string) { 10 if m.ReadOnly { 11 return 12 } 13 for _, r := range text { 14 switch r { 15 case '\n': 16 m.insertNewline() 17 case '\r': 18 // Skip carriage returns (normalize \r\n to \n) 19 default: 20 m.insertRune(r) 21 } 22 } 23} 24 25func (m *Model) insertRune(r rune) { 26 if m.ReadOnly { 27 return 28 } 29 line := m.currentLine() 30 newLine := make([]rune, 0, len(line)+1) 31 newLine = append(newLine, line[:m.col]...) 32 newLine = append(newLine, r) 33 newLine = append(newLine, line[m.col:]...) 34 m.lines[m.row] = newLine 35 m.col++ 36} 37 38func (m *Model) insertNewline() { 39 if m.ReadOnly { 40 return 41 } 42 line := m.currentLine() 43 after := make([]rune, len(line[m.col:])) 44 copy(after, line[m.col:]) 45 m.lines[m.row] = line[:m.col] 46 // Insert new line after current 47 newLines := make([][]rune, 0, len(m.lines)+1) 48 newLines = append(newLines, m.lines[:m.row+1]...) 49 newLines = append(newLines, after) 50 newLines = append(newLines, m.lines[m.row+1:]...) 51 m.lines = newLines 52 m.row++ 53 m.col = 0 54} 55 56func (m *Model) deleteBack() { 57 if m.ReadOnly { 58 return 59 } 60 if m.col > 0 { 61 line := m.currentLine() 62 m.lines[m.row] = append(line[:m.col-1], line[m.col:]...) 63 m.col-- 64 } else if m.row > 0 { 65 // Merge with previous line 66 prev := m.lines[m.row-1] 67 m.col = len(prev) 68 m.lines[m.row-1] = append(prev, m.currentLine()...) 69 m.lines = append(m.lines[:m.row], m.lines[m.row+1:]...) 70 m.row-- 71 } 72} 73 74func (m *Model) deleteForward() { 75 if m.ReadOnly { 76 return 77 } 78 line := m.currentLine() 79 if m.col < len(line) { 80 m.lines[m.row] = append(line[:m.col], line[m.col+1:]...) 81 } else if m.row < len(m.lines)-1 { 82 // Merge with next line 83 m.lines[m.row] = append(line, m.lines[m.row+1]...) 84 m.lines = append(m.lines[:m.row+1], m.lines[m.row+2:]...) 85 } 86} 87 88func (m *Model) tabIndent() { 89 if m.ReadOnly { 90 return 91 } 92 // Indent to match the leading whitespace of the line above. 93 indent := "\t" 94 if m.row > 0 { 95 above := m.lines[m.row-1] 96 indent = "" 97 for _, r := range above { 98 if r == ' ' || r == '\t' { 99 indent += string(r) 100 } else { 101 break 102 } 103 } 104 if indent == "" { 105 indent = "\t" 106 } 107 } 108 for _, r := range indent { 109 m.insertRune(r) 110 } 111}