From cb835acf7d56db9aabefb7b5bfef5739734abd08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB=20=D0=A1=D1=8B=D1=81?= =?UTF-8?q?=D0=BE=D0=B5=D0=B2?= Date: Sun, 22 Oct 2023 11:20:11 +0800 Subject: [PATCH] Improve stability of request editor --- pkg/cli/content.go | 25 ++++++++++--------------- pkg/cli/content_test.go | 13 ++++++++++--- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/pkg/cli/content.go b/pkg/cli/content.go index 1cf6aa8..d31b7c4 100644 --- a/pkg/cli/content.go +++ b/pkg/cli/content.go @@ -112,18 +112,18 @@ func (c *Content) RemoveSymbol() string { } output := LineUp + LineClear + "\r" + lines[0] + moveUp := "" for i := 1; i < len(lines); i++ { output += lines[i] + "\n" + LineClear + "\r" + moveUp += LineUp } - // Move cursor back to position - for i := 1; i < len(lines); i++ { - output += LineUp + if moveUp != "" { + output += moveUp + output += "\r" + lines[0] } - output += "\r" + lines[0] - return output } @@ -159,7 +159,6 @@ func (c *Content) InsertSymbol(symbol rune) string { } output := "" - for i := 0; i < len(lines); i++ { output += LineClear + "\r" + lines[i] if i < len(lines)-1 { @@ -167,12 +166,12 @@ func (c *Content) InsertSymbol(symbol rune) string { } } - // Move cursor back to position - for i := 2; i < len(lines); i++ { - output += LineUp + moveUp := "" + for i := 1; i < len(lines)-1; i++ { + moveUp += LineUp } - output += "\r" + output += moveUp + "\r" return output } @@ -189,11 +188,7 @@ func (c *Content) MoveToEnd() string { } func (c *Content) GetLinesAfterPosition(pos int) (startOfLine int, lines []string) { - if pos < 0 || pos > len(c.text) { - return 0, []string{} - } - - startOfLine = lastIndexOf(c.text, pos, '\t') + startOfLine = lastIndexOf(c.text, pos-1, '\n') if startOfLine == -1 { startOfLine = 0 } else { diff --git a/pkg/cli/content_test.go b/pkg/cli/content_test.go index 037249d..e3f6542 100644 --- a/pkg/cli/content_test.go +++ b/pkg/cli/content_test.go @@ -306,7 +306,7 @@ func TestContent_RemoveSymbol(t *testing.T) { name: "remove newline symbol at the end of the text", input: "hello\nworld\n", pos: 12, - output: "\x1b[1A\x1b[2K\rhelloworld\n\x1b[2K\r\n\x1b[2K\r\x1b[1A\x1b[1A\rhello", + output: "\x1b[1A\x1b[2K\rworld\n\x1b[2K\r\x1b[1A\rworld", contentAfter: "hello\nworld", }, { @@ -398,8 +398,6 @@ func TestContent_InsertSymbol(t *testing.T) { posAfter: 12, }, { - // This test is not really correct, but it is how it works now - // TODO: fix this test name: "insert newline at the begginning", input: "hello\nworld", symbol: '\n', @@ -408,6 +406,15 @@ func TestContent_InsertSymbol(t *testing.T) { contentAfter: "\nhello\nworld", posAfter: 1, }, + { + name: "insert newline in a row", + input: "h\n\nello\nworld", + symbol: '\n', + pos: 2, + output: "\x1b[2K\r\n\x1b[2K\r\n\x1b[2K\rello\n\x1b[2K\rworld\x1b[1A\x1b[1A\r", + contentAfter: "h\n\n\nello\nworld", + posAfter: 3, + }, } for _, tt := range tests {