Skip to content

Commit

Permalink
Improving handling edgecases for removing symbols
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Oct 21, 2023
1 parent 0cbeb98 commit 715faf9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
17 changes: 11 additions & 6 deletions pkg/cli/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func (c *Content) RemoveSymbol() string {
c.pos--
symbol := c.text[c.pos]

lines := c.GetLinesAfterPosition(c.pos)
startCurrentLine, lines := c.GetLinesAfterPosition(c.pos)

buffer := c.text[:c.pos]

Expand All @@ -101,10 +101,15 @@ func (c *Content) RemoveSymbol() string {

c.text = buffer

if symbol != '\n' {
if c.pos == len(c.text) && symbol != '\n' {
return "\b \b"
}

if symbol != '\n' {
endCurrentLine := startCurrentLine + len(lines[0])
return LineClear + "\r" + string(c.text[startCurrentLine:endCurrentLine-1]) + "\r" + string(c.text[startCurrentLine:c.pos])
}

output := LineUp + LineClear + "\r" + lines[0]

for i := 1; i < len(lines); i++ {
Expand Down Expand Up @@ -173,19 +178,19 @@ func (c *Content) MoveToEnd() string {
return output
}

func (c *Content) GetLinesAfterPosition(pos int) []string {
func (c *Content) GetLinesAfterPosition(pos int) (startOfLine int, lines []string) {
if pos < 0 || pos > len(c.text) {
return []string{}
return 0, []string{}
}

startOfLine := lastIndexOf(c.text, pos, '\t')
startOfLine = lastIndexOf(c.text, pos, '\t')
if startOfLine == -1 {
startOfLine = 0
} else {
startOfLine++
}

return strings.Split(string(c.text[startOfLine:]), "\n")
return startOfLine, strings.Split(string(c.text[startOfLine:]), "\n")
}

func lastIndexOf(buffer []rune, pos int, search rune) int {
Expand Down
9 changes: 8 additions & 1 deletion pkg/cli/content_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,9 +264,16 @@ func TestContent_RemoveSymbol(t *testing.T) {
name: "remove symbol in the middle of the text",
input: "hello world",
pos: 6,
output: "\b \b",
output: "\x1b[2K\rhelloworld\rhello",
contentAfter: "helloworld",
},
{
name: "remove symbol in the middle of the multiline text",
input: "hello\nworld",
pos: 4,
output: "\x1b[2K\rhelo\rhel",
contentAfter: "helo\nworld",
},
{
name: "remove symbol at the beginning of the text",
input: "hello world",
Expand Down

0 comments on commit 715faf9

Please sign in to comment.